@turbobase/cli 1.37.0 → 1.38.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 +482 -183
- package/dist/turbobase.js +465 -166
- 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 zb=Object.create;var Ui=Object.defineProperty;var Bb=Object.getOwnPropertyDescriptor;var Fb=Object.getOwnPropertyNames;var Hb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yd=(t,e)=>{for(var r in e)Ui(t,r,{get:e[r],enumerable:!0})},Vb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fb(e))!Kb.call(t,o)&&o!==r&&Ui(t,o,{get:()=>e[o],enumerable:!(n=Bb(e,o))||n.enumerable});return t};var Xd=(t,e,r)=>(r=t!=null?zb(Hb(t)):{},Vb(e||!t||!t.__esModule?Ui(r,"default",{value:t,enumerable:!0}):r,t));function ur(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var gn=j(()=>{});import{z as pr}from"zod";function Eo(t){let e=Mi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function qi(t,e){let r=Mi.safeParse(t);if(!r.success)throw new Kt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Zd.test(e))throw new Kt('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Zd.test(n))throw new Kt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Qd,eu,Mi,Kt,Zd,tu=j(()=>{Qd=pr.object({type:pr.literal("connection"),source_system:pr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:pr.string().min(1).max(200).optional()}),eu=pr.discriminatedUnion("type",[Qd]),Mi=pr.object({inputs:pr.array(eu).optional()}).passthrough(),Kt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Zd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Po,zi=j(()=>{Po=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Fe}from"zod";var Bi,ru,nu=j(()=>{gn();zi();Bi=Fe.object({id:Fe.string().min(1,"hook id must be non-empty"),recordType:Fe.union([Fe.string().min(1),Fe.array(Fe.string().min(1)).min(1),Fe.literal("*")]),event:Fe.enum(Po),source:Fe.string().min(1).optional(),when:Fe.unknown().optional(),run:Fe.unknown(),failClosed:Fe.boolean().optional(),timeoutMs:Fe.number().int().positive().optional(),description:Fe.string().optional(),systemReserved:Fe.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"})}),ru=ur({kind:"hook",schema:Bi,factoryName:"defineHook"})});var ou=j(()=>{nu();zi()});var Ao,Fi=j(()=>{Ao=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var su,Jb,iu,Hi,au,lu=j(()=>{gn();Fi();su=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),Jb=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(su).min(1,"reads[].columns must name at least one column"),by:ge.array(su).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),iu=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Hi=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Ao),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:iu.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:iu,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(Jb).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((d,p)=>{typeof d.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&d.to?.source&&r.from.source===d.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"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.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"})}),au=ur({kind:"conduit",schema:Hi,factoryName:"defineConduit"})});var cu=j(()=>{lu();Fi()});import{z as $e}from"zod";var Ki,du,uu=j(()=>{gn();Ki=$e.object({id:$e.string().min(1,"process id must be non-empty"),input:$e.object({type:$e.literal("object"),properties:$e.record($e.unknown()).optional(),required:$e.array($e.string()).optional()}).passthrough(),steps:$e.array($e.object({id:$e.string().min(1,"step id must be non-empty"),recordType:$e.string().min(1,"step.recordType must be non-empty"),awaitSource:$e.boolean().optional(),build:$e.unknown(),description:$e.string().optional()})).min(1,"a process needs at least one step"),eachRow:$e.object({outstanding:$e.unknown(),key:$e.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:$e.enum(["stop","rollback"]).optional(),description:$e.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),du=ur({kind:"process",schema:Ki,factoryName:"defineProcess"})});var pu=j(()=>{});var hu=j(()=>{uu();pu()});async function sw(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function Oo(t,e={}){return(e.transform??sw)(t)}var Vi=j(()=>{});function Gi(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 mu(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Wi(t){return`${mu(t.source)}${mu(t.recordType)}`}function iw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function aw(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 Ji(t){let e=Wi(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
4
|
+
var Xb=Object.create;var qi=Object.defineProperty;var Zb=Object.getOwnPropertyDescriptor;var Qb=Object.getOwnPropertyNames;var ew=Object.getPrototypeOf,tw=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Qd=(t,e)=>{for(var r in e)qi(t,r,{get:e[r],enumerable:!0})},rw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qb(e))!tw.call(t,o)&&o!==r&&qi(t,o,{get:()=>e[o],enumerable:!(n=Zb(e,o))||n.enumerable});return t};var eu=(t,e,r)=>(r=t!=null?Xb(ew(t)):{},rw(e||!t||!t.__esModule?qi(r,"default",{value:t,enumerable:!0}):r,t));function ur(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var gn=j(()=>{});import{z as pr}from"zod";function Po(t){let e=zi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Bi(t,e){let r=zi.safeParse(t);if(!r.success)throw new Kt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(tu.test(e))throw new Kt('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(tu.test(n))throw new Kt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var ru,nu,zi,Kt,tu,ou=j(()=>{ru=pr.object({type:pr.literal("connection"),source_system:pr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:pr.string().min(1).max(200).optional()}),nu=pr.discriminatedUnion("type",[ru]),zi=pr.object({inputs:pr.array(nu).optional()}).passthrough(),Kt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};tu=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ao,Fi=j(()=>{Ao=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Fe}from"zod";var Hi,su,iu=j(()=>{gn();Fi();Hi=Fe.object({id:Fe.string().min(1,"hook id must be non-empty"),recordType:Fe.union([Fe.string().min(1),Fe.array(Fe.string().min(1)).min(1),Fe.literal("*")]),event:Fe.enum(Ao),source:Fe.string().min(1).optional(),when:Fe.unknown().optional(),run:Fe.unknown(),failClosed:Fe.boolean().optional(),timeoutMs:Fe.number().int().positive().optional(),description:Fe.string().optional(),systemReserved:Fe.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"})}),su=ur({kind:"hook",schema:Hi,factoryName:"defineHook"})});var au=j(()=>{iu();Fi()});var Co,Ki=j(()=>{Co=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var lu,sw,cu,Vi,du,uu=j(()=>{gn();Ki();lu=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),sw=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(lu).min(1,"reads[].columns must name at least one column"),by:ge.array(lu).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),cu=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Vi=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Co),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:cu.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:cu,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(sw).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((d,p)=>{typeof d.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&d.to?.source&&r.from.source===d.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"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.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"})}),du=ur({kind:"conduit",schema:Vi,factoryName:"defineConduit"})});var pu=j(()=>{uu();Ki()});import{z as ye}from"zod";function mu(t,e,r){let n=e;(typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function hw(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{mu(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let l=o.get(a);l!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${l} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var hu,uw,pw,Gi,fu,gu=j(()=>{gn();hu={id:ye.string().min(1,"step id must be non-empty"),recordType:ye.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:ye.boolean().optional(),update:ye.object({step:ye.string().min(1,"update.step must name an earlier step").optional(),pgRowId:ye.unknown().optional(),externalId:ye.unknown().optional(),expectedSyncVersion:ye.unknown().optional()}).optional(),when:ye.unknown().optional(),rollback:ye.enum(["undo","keep"]).optional(),build:ye.unknown(),description:ye.string().optional()},uw=ye.object(hu),pw=ye.object({...hu,forEach:ye.object({input:ye.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:ye.array(uw).optional()}),Gi=ye.object({id:ye.string().min(1,"process id must be non-empty"),input:ye.object({type:ye.literal("object"),properties:ye.record(ye.unknown()).optional(),required:ye.array(ye.string()).optional()}).passthrough(),steps:ye.array(pw).min(1,"a process needs at least one step"),eachRow:ye.object({outstanding:ye.unknown(),key:ye.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:ye.enum(["stop","rollback"]).optional(),description:ye.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?hw(e,a,i):mu(e,s,["steps",i]),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});fu=ur({kind:"process",schema:Gi,factoryName:"defineProcess"})});var yu=j(()=>{});var bu=j(()=>{gu();yu()});async function bw(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function No(t,e={}){return(e.transform??bw)(t)}var Wi=j(()=>{});function Ji(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 wu(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Yi(t){return`${wu(t.source)}${wu(t.recordType)}`}function ww(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function vw(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 Xi(t){let e=Yi(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
5
5
|
* ${r.join(`
|
|
6
6
|
* `)}
|
|
7
7
|
*/`;if(t.columns.length===0)return`${n}
|
|
8
8
|
export interface ${e} {
|
|
9
9
|
// no columns introspected
|
|
10
10
|
[key: string]: unknown;
|
|
11
|
-
}`;let o=t.columns.map(s=>{let i=
|
|
12
|
-
${
|
|
11
|
+
}`;let o=t.columns.map(s=>{let i=Ji(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${vw(s)} */
|
|
12
|
+
${ww(s.name)}${a}: ${i}${l};`});return`${n}
|
|
13
13
|
export interface ${e} {
|
|
14
14
|
${o.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function Lo(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Xi).join(`
|
|
17
17
|
|
|
18
|
-
`)}function
|
|
19
|
-
`)}var
|
|
18
|
+
`)}function vu(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function _w(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Zi(t){let e=vu(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${_w(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
|
|
19
|
+
`)}var Qi=j(()=>{});function Sw(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function _u(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function hr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Sw(t.baseUrl),n=await _u(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Lo(n),s=[kw,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Zi(n)];if(!t.recordsOnly){let i=await _u(r.openapi,t.token,e),a=await No(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
|
|
20
20
|
|
|
21
21
|
`)+`
|
|
22
|
-
`}var
|
|
23
|
-
`)});var
|
|
24
|
-
`,{mode:384})}async function
|
|
25
|
-
`)}function
|
|
26
|
-
`)}function Do(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(d=>new Promise(p=>setTimeout(p,d))),s=e.now??(()=>Date.now()),i=e.onWait??bw,a=e.onGiveUp??ww;return async(d,p)=>{let f=s(),_=0;for(;;){let y=await t(d,p);if(y.status!==503||p&&!yw(p.body))return y;let k=r-(s()-f),{maintenance:R,delayMs:$,error:P}=await gw(y,s());if(!R)return y;if(k<=0)return _>0&&a({waitedMs:s()-f,attempts:_,host:_u(d),error:P}),y;let I=$??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,k),_+=1,i({attempt:_,delayMs:I,remainingMs:k,host:_u(d),error:P}),await o(I)}}}var oa=j(()=>{});function Su(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function vw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function ku(t){let e=Su(t);return typeof t=="string"&&vw(e)?_w:e.slice(0,200)}function Tu(t,e){return na(t,e)}function xu(t){return t instanceof Q&&Tu(t.status,t.body)}function kw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Ru(t){return t.replace(/\/+$/,"")}function sa(t=process.env){let e=(t[Cr]??"").trim(),r=(t[Uo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ia(t){let e;try{e=new URL(t)}catch{return`${Cr} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Cr} 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,_w,Sw,q,Cr,Uo,wn,mt=j(()=>{oa();Q=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};_w="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Sw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Ru(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Do(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(kw()){let d=Su(a);throw new Q(`${e} ${r} \u2192 ${s.status}${d?`: ${d}`:""}`,s.status,a)}if(Tu(s.status,a))throw new Q(Sw,s.status,a);let l=ku(a);throw new Q(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Cr="TURBOBASE_REGISTRY_URL",Uo="TURBOBASE_REGISTRY_TOKEN";wn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Ru(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=ku(a);throw new Q(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as Tw,statSync as xw}from"node:fs";import{resolve as Mo,sep as $u}from"node:path";function Eu(t){if($w.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Pw(t,e,r){let n=Mo(e,r),o=Mo(t);if(n!==o&&!n.startsWith(o+$u))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+$u)&&Tw(i)&&xw(i).isFile())return i;return null}function Pu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Eu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=Pw(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Cw(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Ew,loader:"js"}))}}}function Cw(t){let e=t.startsWith("node:")?t.slice(5):t;return Aw.has(e.split("/")[0])}function Au(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 Cu(){try{return(await import("esbuild")).build}catch(t){throw Au("esbuild",t)}}async function Iw(){try{return(await import("isolated-vm")).default}catch(t){throw Au("isolated-vm",t)}}async function Bo(t,e={}){let r=await Cu(),n=e.resolveDir?Mo(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Pu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new qo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function aa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Cu(),n=Mo(e),o=Pu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Eu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let d=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new qo(d||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function vn(t,e,r={}){let n=r.timeoutMs??zo,o=r.memoryLimitMb??Rw,s=r.member??"run",i={patches:[],logs:[]},a=await Iw(),l=new a.Isolate({memoryLimit:o});try{let d=await l.createContext(),p=d.global,f=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.rejection||(i.rejection=F)}),_=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),y=new a.Callback(Y=>{let F=JSON.parse(String(Y));i.logs.push(F)}),k=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),R=r.query,$=new a.Reference(async Y=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(Y)))});await p.set("__tb_reject",f),await p.set("__tb_patch",_),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Ow(e)));let P=Lw(t,s,r.stepIndex??0,!!r.query),D=await(await l.compileScript(P)).run(d,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Ow(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 Nw(t){return`
|
|
22
|
+
`}var kw,Su=j(()=>{Wi();Qi();Qi();Wi();kw=["/**"," * 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 ea=j(()=>{gn();ou();au();pu();bu();Su()});import{homedir as Tw}from"node:os";import{join as ku}from"node:path";import{promises as ta}from"node:fs";function rt(t){return t.trim().replace(/\/+$/,"")}function jo(){let t=process.env.TURBOBASE_HOME??ku(Tw(),".turbobase");return{dir:t,file:ku(t,"credentials")}}function Tu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function yn(){let{file:t}=jo(),e;try{let s=await ta.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,l]of Object.entries(r.tenants))Tu(l)&&(s[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))Tu(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:xw(n),tenants:n}}function xw(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function ra(t){let{dir:e,file:r}=jo();await ta.mkdir(e,{recursive:!0,mode:448}),await ta.writeFile(r,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384})}async function xu(t){let e=rt(t.baseUrl),r=await yn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await ra(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ht(t){let e=await yn();if(t){let s=rt(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Do(t){let e=rt(t),r=await yn(),n=r.tenants[e];return n?(r.active=e,await ra(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function na(t){let e=await yn(),r=t?rt(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await ra(e),r}async function Ot(){let t=await yn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var bn=j(()=>{});function sa(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function Rw(t){if(t)try{return JSON.parse(t)}catch{return t}}function $w(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function Ew(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function Pw(t,e){let r=$w(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=Rw(n),s=sa(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??Ew(n),error:i}}function Aw(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 Ru(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 oa(t){return`${Math.round(t/1e3)}s`}function Cw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${oa(t.delayMs)} before retrying (${oa(t.remainingMs)} of the retry budget left).
|
|
25
|
+
`)}function Iw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${oa(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
|
|
26
|
+
`)}function Uo(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(d=>new Promise(p=>setTimeout(p,d))),s=e.now??(()=>Date.now()),i=e.onWait??Cw,a=e.onGiveUp??Iw;return async(d,p)=>{let g=s(),S=0;for(;;){let y=await t(d,p);if(y.status!==503||p&&!Aw(p.body))return y;let k=r-(s()-g),{maintenance:R,delayMs:$,error:P}=await Pw(y,s());if(!R)return y;if(k<=0)return S>0&&a({waitedMs:s()-g,attempts:S,host:Ru(d),error:P}),y;let I=$??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,k),S+=1,i({attempt:S,delayMs:I,remainingMs:k,host:Ru(d),error:P}),await o(I)}}}var ia=j(()=>{});function $u(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function Ow(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function Eu(t){let e=$u(t);return typeof t=="string"&&Ow(e)?Nw:e.slice(0,200)}function Pu(t,e){return sa(t,e)}function Au(t){return t instanceof Q&&Pu(t.status,t.body)}function jw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Cu(t){return t.replace(/\/+$/,"")}function aa(t=process.env){let e=(t[Cr]??"").trim(),r=(t[Mo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function la(t){let e;try{e=new URL(t)}catch{return`${Cr} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${Cr} 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,Nw,Lw,q,Cr,Mo,wn,mt=j(()=>{ia();Q=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Nw="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Lw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Cu(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Uo(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(jw()){let d=$u(a);throw new Q(`${e} ${r} \u2192 ${s.status}${d?`: ${d}`:""}`,s.status,a)}if(Pu(s.status,a))throw new Q(Lw,s.status,a);let l=Eu(a);throw new Q(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Cr="TURBOBASE_REGISTRY_URL",Mo="TURBOBASE_REGISTRY_TOKEN";wn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Cu(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=Eu(a);throw new Q(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as Dw,statSync as Uw}from"node:fs";import{resolve as qo,sep as Iu}from"node:path";function Ou(t){if(qw.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Bw(t,e,r){let n=qo(e,r),o=qo(t);if(n!==o&&!n.startsWith(o+Iu))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Iu)&&Dw(i)&&Uw(i).isFile())return i;return null}function Nu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Ou(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=Bw(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Hw(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:zw,loader:"js"}))}}}function Hw(t){let e=t.startsWith("node:")?t.slice(5):t;return Fw.has(e.split("/")[0])}function Lu(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 ju(){try{return(await import("esbuild")).build}catch(t){throw Lu("esbuild",t)}}async function Kw(){try{return(await import("isolated-vm")).default}catch(t){throw Lu("isolated-vm",t)}}async function Fo(t,e={}){let r=await ju(),n=e.resolveDir?qo(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Nu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new zo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function ca(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await ju(),n=qo(e),o=Nu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Ou(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let d=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new zo(d||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function vn(t,e,r={}){let n=r.timeoutMs??Bo,o=r.memoryLimitMb??Mw,s=r.member??"run",i={patches:[],logs:[]},a=await Kw(),l=new a.Isolate({memoryLimit:o});try{let d=await l.createContext(),p=d.global,g=new a.Callback(Y=>{let H=JSON.parse(String(Y));i.rejection||(i.rejection=H)}),S=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),y=new a.Callback(Y=>{let H=JSON.parse(String(Y));i.logs.push(H)}),k=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),R=r.query,$=new a.Reference(async Y=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(Y)))});await p.set("__tb_reject",g),await p.set("__tb_patch",S),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Vw(e)));let P=Ww(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),D=await(await l.compileScript(P)).run(d,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Vw(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 Gw(t){return`
|
|
27
27
|
"use strict";
|
|
28
28
|
(async () => {
|
|
29
29
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -46,7 +46,7 @@ ${o.join(`
|
|
|
46
46
|
__tb_result(JSON.stringify(out == null ? null : String(out)));
|
|
47
47
|
return undefined;
|
|
48
48
|
})()
|
|
49
|
-
`}function
|
|
49
|
+
`}function Ww(t,e,r,n,o=!1){return e==="build"?Yw(t,n):e==="prompt"?Jw(t,n):e==="outstanding"?Gw(t):`
|
|
50
50
|
"use strict";
|
|
51
51
|
(async () => {
|
|
52
52
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -88,7 +88,7 @@ ${o.join(`
|
|
|
88
88
|
canonicalStatus(args) {
|
|
89
89
|
return String((args && args.raw) || '').trim().toLowerCase();
|
|
90
90
|
},
|
|
91
|
-
${
|
|
91
|
+
${o?`async query(q) {
|
|
92
92
|
const json = await __tb_query.apply(undefined, [String(q)], {
|
|
93
93
|
arguments: { copy: true },
|
|
94
94
|
result: { promise: true, copy: true },
|
|
@@ -127,7 +127,52 @@ ${o.join(`
|
|
|
127
127
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
|
|
128
128
|
return ${e==="when"?"out":"undefined"};
|
|
129
129
|
})()
|
|
130
|
-
`}function
|
|
130
|
+
`}function Jw(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
|
|
131
|
+
"use strict";
|
|
132
|
+
(async () => {
|
|
133
|
+
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
134
|
+
const __tb_process = __tb_ctx.process || {};
|
|
135
|
+
const ctx = {
|
|
136
|
+
input: __tb_process.input,
|
|
137
|
+
runId: __tb_process.runId,
|
|
138
|
+
steps: __tb_process.steps || {},
|
|
139
|
+
row: __tb_process.row == null ? undefined : __tb_process.row,
|
|
140
|
+
item: __tb_process.item == null ? undefined : __tb_process.item,
|
|
141
|
+
index: __tb_process.index == null ? undefined : __tb_process.index,
|
|
142
|
+
async query(q) {
|
|
143
|
+
const json = await __tb_query.apply(undefined, [String(q)], {
|
|
144
|
+
arguments: { copy: true },
|
|
145
|
+
result: { promise: true, copy: true },
|
|
146
|
+
});
|
|
147
|
+
return JSON.parse(json);
|
|
148
|
+
},
|
|
149
|
+
log(level, message, meta) {
|
|
150
|
+
__tb_log(JSON.stringify({ level, message, meta }));
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// ---- bundled extension module (IIFE assigns __tb_extension_module) ----
|
|
155
|
+
${t}
|
|
156
|
+
|
|
157
|
+
const def = (typeof __tb_extension_module !== 'undefined' && __tb_extension_module)
|
|
158
|
+
? __tb_extension_module.default
|
|
159
|
+
: undefined;
|
|
160
|
+
if (!def || typeof def !== 'object') {
|
|
161
|
+
throw new Error('extension bundle has no default export (use export default defineProcess({...}))');
|
|
162
|
+
}
|
|
163
|
+
const __tb_path = ${r};
|
|
164
|
+
let step = Array.isArray(def.steps) ? def.steps[__tb_path[0]] : undefined;
|
|
165
|
+
if (step && __tb_path.length > 1) {
|
|
166
|
+
step = Array.isArray(step.steps) ? step.steps[__tb_path[1]] : undefined;
|
|
167
|
+
}
|
|
168
|
+
if (!step || !step.ai || typeof step.ai.prompt !== 'function') {
|
|
169
|
+
throw new Error('process step ' + __tb_path.join('.') + ' has no ai.prompt() function');
|
|
170
|
+
}
|
|
171
|
+
const out = await step.ai.prompt(ctx);
|
|
172
|
+
__tb_result(String(out == null ? '' : out));
|
|
173
|
+
return undefined;
|
|
174
|
+
})()
|
|
175
|
+
`}function Yw(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
|
|
131
176
|
"use strict";
|
|
132
177
|
(async () => {
|
|
133
178
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -138,8 +183,11 @@ ${o.join(`
|
|
|
138
183
|
steps: __tb_process.steps || {},
|
|
139
184
|
// turbobase-dev#1730: the source row this pass is migrating. Undefined
|
|
140
185
|
// rather than null for an ordinary chain, so a step reading it sees
|
|
141
|
-
// exactly what the documented ProcessStepContext says it sees.
|
|
186
|
+
// exactly what the documented ProcessStepContext says it sees. Same
|
|
187
|
+
// rule for the repeated group's element and its position.
|
|
142
188
|
row: __tb_process.row == null ? undefined : __tb_process.row,
|
|
189
|
+
item: __tb_process.item == null ? undefined : __tb_process.item,
|
|
190
|
+
index: __tb_process.index == null ? undefined : __tb_process.index,
|
|
143
191
|
async query(q) {
|
|
144
192
|
const json = await __tb_query.apply(undefined, [String(q)], {
|
|
145
193
|
arguments: { copy: true },
|
|
@@ -161,45 +209,71 @@ ${o.join(`
|
|
|
161
209
|
if (!def || typeof def !== 'object') {
|
|
162
210
|
throw new Error('extension bundle has no default export (use export default defineProcess({...}))');
|
|
163
211
|
}
|
|
164
|
-
|
|
212
|
+
// The PATH, not an index: a step-list entry may be a repeated group
|
|
213
|
+
// carrying nested steps, so the first number picks the entry and the
|
|
214
|
+
// second \u2014 when there is one \u2014 picks the step inside it.
|
|
215
|
+
const __tb_path = ${r};
|
|
216
|
+
let step = Array.isArray(def.steps) ? def.steps[__tb_path[0]] : undefined;
|
|
217
|
+
if (step && __tb_path.length > 1) {
|
|
218
|
+
step = Array.isArray(step.steps) ? step.steps[__tb_path[1]] : undefined;
|
|
219
|
+
}
|
|
165
220
|
if (!step || typeof step.build !== 'function') {
|
|
166
|
-
throw new Error('process step
|
|
221
|
+
throw new Error('process step ' + __tb_path.join('.') + ' has no build() function');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// A \`when\` that returns false declines the step and \`build\` is never
|
|
225
|
+
// called. A \`when\` that THROWS propagates, because an author whose
|
|
226
|
+
// condition is broken is not an author saying no.
|
|
227
|
+
if (typeof step.when === 'function' && !(await step.when(ctx))) {
|
|
228
|
+
__tb_result(JSON.stringify({ declined: true }));
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// The dynamic halves of an \`update\` address. \`update.step\` is static
|
|
233
|
+
// and is read on the host, off the definition, where the rollback can
|
|
234
|
+
// read it too.
|
|
235
|
+
const address = {};
|
|
236
|
+
if (step.update && typeof step.update === 'object') {
|
|
237
|
+
for (const key of ['pgRowId', 'externalId', 'expectedSyncVersion']) {
|
|
238
|
+
if (typeof step.update[key] === 'function') address[key] = await step.update[key](ctx);
|
|
239
|
+
}
|
|
167
240
|
}
|
|
241
|
+
|
|
168
242
|
const out = await step.build(ctx);
|
|
169
|
-
__tb_result(JSON.stringify(out == null ? null : out));
|
|
243
|
+
__tb_result(JSON.stringify({ declined: out == null, address: address, write: out == null ? null : out }));
|
|
170
244
|
return undefined;
|
|
171
245
|
})()
|
|
172
|
-
`}var
|
|
246
|
+
`}var Bo,Mw,qw,zw,zo,Fw,Ho=j(()=>{Bo=200,Mw=16,qw=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"]);zw=`
|
|
173
247
|
export const defineHook = (def) => def;
|
|
174
248
|
export const defineConduit = (def) => def;
|
|
175
249
|
export const defineProcess = (def) => def;
|
|
176
250
|
export default defineHook;
|
|
177
|
-
`;
|
|
251
|
+
`;zo=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Fw=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 da}from"node:fs";import{join as Xw}from"node:path";function Zw(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 Qw(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await vn(t,Zw(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Ko(t,e,r={}){let n=await Fo(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await Qw(n,e[s],`sample[${s}]`));return o}async function _n(t){let e;try{e=await da.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await da.readFile(Xw(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Sn(t){return da.readFile(t,"utf8")}var ua=j(()=>{Ho()});function We(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Hv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
|
|
178
252
|
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
179
253
|
run: (ctx) => {
|
|
180
254
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
181
255
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
182
|
-
},`,a="custom";else if(n==="require-field"){let
|
|
256
|
+
},`,a="custom";else if(n==="require-field"){let S=t.field;if(!S)throw new Je("require-field template needs --field=<name>");i=`
|
|
183
257
|
run: (ctx) => {
|
|
184
|
-
const v = ctx.payload[${JSON.stringify(
|
|
258
|
+
const v = ctx.payload[${JSON.stringify(S)}];
|
|
185
259
|
if (v === undefined || v === null || v === '') {
|
|
186
260
|
ctx.reject({
|
|
187
261
|
code: 'MANDATORY_FIELD_MISSING',
|
|
188
|
-
field: ${JSON.stringify(
|
|
189
|
-
message: ${JSON.stringify(`${
|
|
262
|
+
field: ${JSON.stringify(S)},
|
|
263
|
+
message: ${JSON.stringify(`${S} is required`)},
|
|
190
264
|
});
|
|
191
265
|
}
|
|
192
|
-
},`,a=`require-field-${
|
|
266
|
+
},`,a=`require-field-${S}`}else if(n==="enforce-format"){let S=t.field;if(!S)throw new Je("enforce-format template needs --field=<name>");if(!t.regex)throw new Je("enforce-format template needs --regex=<pattern>");i=`
|
|
193
267
|
run: (ctx) => {
|
|
194
|
-
const v = ctx.payload[${JSON.stringify(
|
|
268
|
+
const v = ctx.payload[${JSON.stringify(S)}];
|
|
195
269
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
196
270
|
ctx.reject({
|
|
197
271
|
code: 'INVALID_FORMAT',
|
|
198
|
-
field: ${JSON.stringify(
|
|
199
|
-
message: ${JSON.stringify(`${
|
|
272
|
+
field: ${JSON.stringify(S)},
|
|
273
|
+
message: ${JSON.stringify(`${S} does not match expected format`)},
|
|
200
274
|
});
|
|
201
275
|
}
|
|
202
|
-
},`,a=`enforce-format-${
|
|
276
|
+
},`,a=`enforce-format-${S}`}else throw new Je(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${We(t.regex).slice(0,24)}`:""}`,p=`/**
|
|
203
277
|
* ${t.description??`${a} on ${e}.${r}`}
|
|
204
278
|
*
|
|
205
279
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
@@ -212,7 +286,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
212
286
|
recordType: ${JSON.stringify(e)},
|
|
213
287
|
event: ${JSON.stringify(r)},${s}${i}
|
|
214
288
|
});
|
|
215
|
-
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function
|
|
289
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function Kv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Je("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Je("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Je(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${We(r)}2${We(n)}:${We(e)}`,l=`/**
|
|
216
290
|
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
|
|
217
291
|
*
|
|
218
292
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -255,7 +329,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
255
329
|
},
|
|
256
330
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
257
331
|
});
|
|
258
|
-
`;return{relativePath:`conduits/${We(r)}-${We(e)}-to-${We(n)}-${We(o)}.ts`,content:l}}function
|
|
332
|
+
`;return{relativePath:`conduits/${We(r)}-${We(e)}-to-${We(n)}-${We(o)}.ts`,content:l}}function Vv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Je(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${We(e)}-then-${We(r)}`:We(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
|
|
259
333
|
{
|
|
260
334
|
id: ${JSON.stringify(We(r))},
|
|
261
335
|
recordType: ${JSON.stringify(r)},
|
|
@@ -304,7 +378,7 @@ export default defineProcess({
|
|
|
304
378
|
],
|
|
305
379
|
onFailure: ${JSON.stringify(n)},
|
|
306
380
|
});
|
|
307
|
-
`;return{relativePath:`processes/${o}.ts`,content:l}}function Rt(t,e){let r=
|
|
381
|
+
`;return{relativePath:`processes/${o}.ts`,content:l}}function Rt(t,e){let r=Gv[t];if(!r)throw new Je(`unknown extension kind '${t}'. Scaffoldable kinds: ${gp.join(", ")}.`);return r(e)}var gp,Je,Gv,Xo=j(()=>{gp=["hook","conduit","process"];Je=class extends Error{};Gv={hook:Hv,conduit:Kv,process:Vv}});var Na,La=j(()=>{Na=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function pk(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function hk(t){return Vh[pk(t)%Vh.length]}function mk(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function Gh(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Wh(t,e){let[r,n]=hk(t),o=Gh(mk(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Gh(e)}">
|
|
308
382
|
<defs>
|
|
309
383
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
310
384
|
<stop offset="0" stop-color="${r}"/>
|
|
@@ -314,9 +388,9 @@ export default defineProcess({
|
|
|
314
388
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
315
389
|
<text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
|
|
316
390
|
</svg>
|
|
317
|
-
`}var
|
|
318
|
-
`}function
|
|
319
|
-
`}function
|
|
391
|
+
`}var Vh,Jh=j(()=>{Vh=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var um={};Qd(um,{CN_UTIL:()=>tm,COMPONENTS_JSON:()=>em,MAIN_TSX:()=>nm,STYLES_CSS:()=>om,TSCONFIG:()=>Qh,TURBOBASE_CLIENT:()=>Yh,UI_BADGE:()=>am,UI_BUTTON:()=>sm,UI_CARD:()=>im,UI_INPUT:()=>cm,UI_LABEL:()=>dm,UI_TABLE:()=>lm,indexHtml:()=>rm,instanceOriginFromEnv:()=>kk,packageJson:()=>Xh,scaffoldAppFiles:()=>xk,starterApp:()=>Rk,viteConfig:()=>Zh});function yk(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function bk(t){let e={name:yk(t.title,gk)},r=(t.description??"").trim().slice(0,fk);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Na},JSON.stringify(e,null,2)+`
|
|
392
|
+
`}function Xh(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:wk},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)}
|
|
393
|
+
`}function Sk(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 kk(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Zh(t,e={}){let r=Sk(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
320
394
|
import { fileURLToPath, URL } from 'node:url';
|
|
321
395
|
import react from '@vitejs/plugin-react';
|
|
322
396
|
// Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
|
|
@@ -335,8 +409,8 @@ import tailwindcss from '@tailwindcss/vite';
|
|
|
335
409
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
336
410
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
337
411
|
// them at boot; restart the dev server after changing one).
|
|
338
|
-
const TENANT = process.env.SUPABASE_URL || '${r??
|
|
339
|
-
const API = process.env.TURBOBASE_API_URL || '${r??
|
|
412
|
+
const TENANT = process.env.SUPABASE_URL || '${r??vk}'; // /rest + the Realtime WS
|
|
413
|
+
const API = process.env.TURBOBASE_API_URL || '${r??_k}'; // /v1, /auth, /login, /_app
|
|
340
414
|
|
|
341
415
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
342
416
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -374,7 +448,7 @@ export default defineConfig({
|
|
|
374
448
|
},
|
|
375
449
|
build: { outDir: 'dist' },
|
|
376
450
|
});
|
|
377
|
-
`}function
|
|
451
|
+
`}function rm(t){return`<!doctype html>
|
|
378
452
|
<html lang="en">
|
|
379
453
|
<head>
|
|
380
454
|
<meta charset="UTF-8" />
|
|
@@ -387,7 +461,7 @@ export default defineConfig({
|
|
|
387
461
|
<script type="module" src="/src/main.tsx"></script>
|
|
388
462
|
</body>
|
|
389
463
|
</html>
|
|
390
|
-
`}function
|
|
464
|
+
`}function xk(t){return{"package.json":Xh(t.slug),"vite.config.ts":Zh(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":Tk,"tsconfig.json":Qh,"index.html":rm(t.title),"public/turbobase.json":bk(t),"public/favicon.svg":Wh(t.slug,t.title),"src/main.tsx":nm,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Yh,"src/styles.css":om,"components.json":em,"src/lib/utils.ts":tm,"src/components/ui/button.tsx":sm,"src/components/ui/card.tsx":im,"src/components/ui/badge.tsx":am,"src/components/ui/table.tsx":lm,"src/components/ui/input.tsx":cm,"src/components/ui/label.tsx":dm,"README.md":`# ${t.title}
|
|
391
465
|
|
|
392
466
|
\`\`\`sh
|
|
393
467
|
npm install
|
|
@@ -408,7 +482,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
408
482
|
|
|
409
483
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
410
484
|
live access token and is gitignored \u2014 keep it that way.
|
|
411
|
-
`}}function
|
|
485
|
+
`}}function Rk(t){return`import React from 'react';
|
|
412
486
|
import { Loader2, Trash2 } from 'lucide-react';
|
|
413
487
|
|
|
414
488
|
import { select, write, del } from '@/lib/turbobase';
|
|
@@ -633,7 +707,7 @@ export default function App() {
|
|
|
633
707
|
</main>
|
|
634
708
|
);
|
|
635
709
|
}
|
|
636
|
-
`}var
|
|
710
|
+
`}var fk,gk,Yh,On,wk,vk,_k,Tk,Qh,em,tm,nm,om,sm,im,am,lm,cm,dm,pm=j(()=>{Jh();La();fk=200,gk=60;Yh=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
637
711
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
638
712
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
639
713
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -1087,6 +1161,44 @@ export async function del(
|
|
|
1087
1161
|
return (await res.json()) as { deleted: boolean; enqueued: boolean };
|
|
1088
1162
|
}
|
|
1089
1163
|
|
|
1164
|
+
/** One row of the \`file\` record type, as PostgREST hands it to you. Only the two
|
|
1165
|
+
* fields fileUrl() needs are listed; your row carries the rest. */
|
|
1166
|
+
export interface TurbobaseFileRow {
|
|
1167
|
+
external_id: string;
|
|
1168
|
+
/** Which connected account the file is on. Always present on a mirrored row. */
|
|
1169
|
+
connection_id?: string;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/** The Turbobase URL that SERVES a mirrored file \u2014 the string to put in an
|
|
1173
|
+
* \`<img src>\`, a \`<video src>\`, an \`<a href>\`, or a field on another record.
|
|
1174
|
+
*
|
|
1175
|
+
* Same-origin and relative, so the browser sends the session cookie it already
|
|
1176
|
+
* has. Nobody is sent to the storage account and nobody needs their own access
|
|
1177
|
+
* to it: the instance fetches the bytes with the connection's credential and
|
|
1178
|
+
* decides who may see them from Turbobase permissions.
|
|
1179
|
+
*
|
|
1180
|
+
* An allowlisted type (raster images, video, audio, PDF) is served inline, so
|
|
1181
|
+
* it renders in place. Anything else arrives as a download. Pass
|
|
1182
|
+
* \`{ download: true }\` to force a download for any type.
|
|
1183
|
+
*
|
|
1184
|
+
* THIS IS THE LINK TO STORE. If a record points at a file \u2014 a custom field, a
|
|
1185
|
+
* note, your own table \u2014 save THIS string, never the storage account's URL. It
|
|
1186
|
+
* has no host and no version marker in it, so it keeps working after the file
|
|
1187
|
+
* is replaced, and it names the connection, so it opens for every user who may
|
|
1188
|
+
* read the file rather than only the ones whose session defaults to that
|
|
1189
|
+
* account.
|
|
1190
|
+
*
|
|
1191
|
+
* TAKES THE ROW, not an id, on purpose: the connection is the part a hand-built
|
|
1192
|
+
* path leaves out, and leaving it out is what breaks the link on an instance
|
|
1193
|
+
* with two accounts of the same kind connected. */
|
|
1194
|
+
export function fileUrl(row: TurbobaseFileRow, opts: { download?: boolean } = {}): string {
|
|
1195
|
+
const query = new URLSearchParams();
|
|
1196
|
+
if (row.connection_id !== undefined) query.set('connection', row.connection_id);
|
|
1197
|
+
if (opts.download) query.set('download', '1');
|
|
1198
|
+
const q = query.toString();
|
|
1199
|
+
return \`/v1/data/file/\${encodeURIComponent(row.external_id)}/content\${q === '' ? '' : '?' + q}\`;
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1090
1202
|
/** One sub-result from batch(): its own status, so a 429/5xx on one query does
|
|
1091
1203
|
* not fail the others. \`ok\` is status 2xx; \`rows\` is the parsed body on
|
|
1092
1204
|
* success (undefined on failure \u2014 read \`status\`/\`error\`). */
|
|
@@ -1663,7 +1775,192 @@ export async function selectPage<T = unknown>(
|
|
|
1663
1775
|
}
|
|
1664
1776
|
return { rows, nextCursor };
|
|
1665
1777
|
}
|
|
1666
|
-
|
|
1778
|
+
|
|
1779
|
+
// ---------------------------------------------------------------------------
|
|
1780
|
+
// This app's own slug, which three of the calls below have to send.
|
|
1781
|
+
// ---------------------------------------------------------------------------
|
|
1782
|
+
|
|
1783
|
+
/** This app's slug, read off the mount path Vite was built with.
|
|
1784
|
+
*
|
|
1785
|
+
* \`base\` is \`/a/<slug>/\` in vite.config.ts \u2014 it has to be, because assets are
|
|
1786
|
+
* requested absolutely \u2014 so the slug is already in the bundle and nothing has
|
|
1787
|
+
* to be configured twice. Every call below takes an \`app\` override for the one
|
|
1788
|
+
* case this cannot answer: a bundle served from somewhere other than its own
|
|
1789
|
+
* mount path.
|
|
1790
|
+
*
|
|
1791
|
+
* THROWS RATHER THAN ANSWERING EMPTY. An empty slug reaches the instance as a
|
|
1792
|
+
* missing \`app\`, which answers \`400 app_required\` \u2014 a refusal about a field
|
|
1793
|
+
* the caller never typed, in a call they did not know carried it. Saying it
|
|
1794
|
+
* here names the fix instead. */
|
|
1795
|
+
export function appSlug(): string {
|
|
1796
|
+
const base = (import.meta as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? '/';
|
|
1797
|
+
// \`/a/<slug>/\` is the base of a hand-run \`npm run build\`. A bundle built by
|
|
1798
|
+
// \`turbobase apps deploy\` has \`/_tb/app-assets/<build-id>/\` instead \u2014 the
|
|
1799
|
+
// build is named, not the mount path, so one set of bytes can be previewed
|
|
1800
|
+
// and promoted \u2014 and reading THAT as a slug sends a build id the instance
|
|
1801
|
+
// does not know as an app. So the base is used only when it IS a mount path,
|
|
1802
|
+
// and otherwise the document's own path answers, which is \`/a/<slug>/\u2026\` (or
|
|
1803
|
+
// \`/a/<slug>-preview-<id>/\u2026\`) for every served bundle.
|
|
1804
|
+
const fromBase = /^\\/a\\/([^/]+)\\/?$/.exec(base)?.[1] ?? '';
|
|
1805
|
+
const path = (globalThis as { location?: { pathname?: string } }).location?.pathname ?? '';
|
|
1806
|
+
const fromPath = /^\\/a\\/([^/]+)/.exec(path)?.[1] ?? '';
|
|
1807
|
+
// A preview spends its app's allowance, so its handle is not part of the slug.
|
|
1808
|
+
const slug = decodeURIComponent(fromBase || fromPath).replace(/-preview-[0-9a-f]{24}$/, '');
|
|
1809
|
+
if (slug === '') {
|
|
1810
|
+
throw new Error(
|
|
1811
|
+
'turbobase: could not work out this app\\'s slug from the bundle\\'s base path (' +
|
|
1812
|
+
JSON.stringify(base) +
|
|
1813
|
+
'). vite.config.ts normally sets base to "/a/<slug>/". Pass the slug explicitly, ' +
|
|
1814
|
+
'e.g. askModel({ prompt, app: "my-app" }).',
|
|
1815
|
+
);
|
|
1816
|
+
}
|
|
1817
|
+
return slug;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// ---------------------------------------------------------------------------
|
|
1821
|
+
// The instance's model \u2014 ONE PROMPT IN, ONE ANSWER OUT.
|
|
1822
|
+
//
|
|
1823
|
+
// A passthrough: none of the platform's skills, grounding or system prompt is
|
|
1824
|
+
// added on the way out, so what the model answers is an answer to YOUR prompt.
|
|
1825
|
+
// You pick a TIER ('fast' | 'chat' | \u2026) rather than a model id, because which
|
|
1826
|
+
// model a tier resolves to \u2014 and what it costs \u2014 is the instance's decision.
|
|
1827
|
+
//
|
|
1828
|
+
// WHO MAY CALL IT. Your app's own screens may, under the session cookie the
|
|
1829
|
+
// user already holds. A TOKEN must carry \`ai:invoke\`, which is opt-in and in no
|
|
1830
|
+
// token kind's defaults, so a token minted before this release answers 403.
|
|
1831
|
+
//
|
|
1832
|
+
// WHAT IT COSTS. Every call is metered against your app's allowance and
|
|
1833
|
+
// recorded with the calling user, so a customer can see which of their people
|
|
1834
|
+
// spent it. The instance limits tokens per minute, per call and per day, and a
|
|
1835
|
+
// refusal arrives as TurbobaseAiLimitError carrying \`retryAfterMs\` when waiting
|
|
1836
|
+
// would clear it. The limits are checked BEFORE the model is asked, so a
|
|
1837
|
+
// refused call costs nothing.
|
|
1838
|
+
// ---------------------------------------------------------------------------
|
|
1839
|
+
|
|
1840
|
+
/** Thrown when the model proxy refuses on a LIMIT rather than on your input.
|
|
1841
|
+
* \`retryAfterMs\` is null when waiting changes nothing \u2014 a prompt over the
|
|
1842
|
+
* per-call ceiling, or a tier the instance does not allow. */
|
|
1843
|
+
export class TurbobaseAiLimitError extends Error {
|
|
1844
|
+
constructor(
|
|
1845
|
+
message: string,
|
|
1846
|
+
readonly limit: string,
|
|
1847
|
+
readonly retryAfterMs: number | null,
|
|
1848
|
+
) {
|
|
1849
|
+
super(message);
|
|
1850
|
+
this.name = 'TurbobaseAiLimitError';
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
|
|
1854
|
+
export interface AskModelResult {
|
|
1855
|
+
text: string;
|
|
1856
|
+
/** Which model the tier resolved to, for your own logging. Never send it back. */
|
|
1857
|
+
model: string;
|
|
1858
|
+
tier: string;
|
|
1859
|
+
usage: { inputTokens: number; outputTokens: number };
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
/** Ask the instance's model one question. */
|
|
1863
|
+
export async function askModel(args: {
|
|
1864
|
+
prompt: string;
|
|
1865
|
+
/** Defaults to 'fast'. The instance decides which tiers an app may reach. */
|
|
1866
|
+
tier?: string;
|
|
1867
|
+
/** Ceiling on the ANSWER's length. Not a spend commitment. */
|
|
1868
|
+
maxTokens?: number;
|
|
1869
|
+
/** Defaults to \`appSlug()\`. */
|
|
1870
|
+
app?: string;
|
|
1871
|
+
}): Promise<AskModelResult> {
|
|
1872
|
+
const res = await req('/v1/ai/complete', {
|
|
1873
|
+
method: 'POST',
|
|
1874
|
+
headers: { 'content-type': 'application/json' },
|
|
1875
|
+
// \`app\` IS REQUIRED BY THE ROUTE and is the one field a caller would expect
|
|
1876
|
+
// to be optional: the allowance and the usage row are both per app, so a
|
|
1877
|
+
// call naming none is a call nobody can attribute, bound or bill.
|
|
1878
|
+
body: JSON.stringify({
|
|
1879
|
+
prompt: args.prompt,
|
|
1880
|
+
tier: args.tier ?? 'fast',
|
|
1881
|
+
app: args.app ?? appSlug(),
|
|
1882
|
+
...(args.maxTokens !== undefined ? { maxTokens: args.maxTokens } : {}),
|
|
1883
|
+
}),
|
|
1884
|
+
});
|
|
1885
|
+
if (!res.ok) {
|
|
1886
|
+
const body = (await res.json().catch(() => ({}))) as {
|
|
1887
|
+
error?: string;
|
|
1888
|
+
limit?: string;
|
|
1889
|
+
message?: string;
|
|
1890
|
+
retryAfterMs?: number | null;
|
|
1891
|
+
};
|
|
1892
|
+
if (res.status === 429 || body.error === 'ai_tier_not_allowed') {
|
|
1893
|
+
throw new TurbobaseAiLimitError(
|
|
1894
|
+
body.message ?? 'the instance refused this call on a model limit',
|
|
1895
|
+
body.limit ?? body.error ?? 'unknown',
|
|
1896
|
+
body.retryAfterMs ?? null,
|
|
1897
|
+
);
|
|
1898
|
+
}
|
|
1899
|
+
throw new Error(readErrorFromBody(res.status, JSON.stringify(body)));
|
|
1900
|
+
}
|
|
1901
|
+
return (await res.json()) as AskModelResult;
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
/** The same call under the name the issue and the adopt note use:
|
|
1905
|
+
* \`ai.complete({ prompt, tier })\`. One function, two spellings \u2014 \`ai\` is the
|
|
1906
|
+
* namespace an app author reaches for, \`askModel\` the flat import. */
|
|
1907
|
+
export const ai = { complete: askModel } as const;
|
|
1908
|
+
|
|
1909
|
+
// ---------------------------------------------------------------------------
|
|
1910
|
+
// Processes \u2014 background work the instance performs, not the browser.
|
|
1911
|
+
//
|
|
1912
|
+
// A process is deployed with \`turbobase ext deploy\` and runs under the signed-in
|
|
1913
|
+
// user's own identity, so every record it writes goes through the same hooks,
|
|
1914
|
+
// guardrails and row-level security a write from this app does. INVOKE RETURNS A
|
|
1915
|
+
// TICKET, not an outcome: close the tab and the run carries on.
|
|
1916
|
+
// ---------------------------------------------------------------------------
|
|
1917
|
+
|
|
1918
|
+
export interface ProcessRun {
|
|
1919
|
+
runId: string;
|
|
1920
|
+
processId: string;
|
|
1921
|
+
state: 'queued' | 'running' | 'committed' | 'failed' | 'rolled_back' | 'cancelled';
|
|
1922
|
+
/** Why it ended as it did \u2014 names the failing step, the switch or the limit. */
|
|
1923
|
+
reason: string | null;
|
|
1924
|
+
startedAt: string | null;
|
|
1925
|
+
finishedAt: string | null;
|
|
1926
|
+
/** Units of work the run did not get to. Null on a process that is not an \`eachRow\`. */
|
|
1927
|
+
outstanding: number | null;
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/** Start a process. Answers a run id; watch it with \`processRun\`. */
|
|
1931
|
+
export async function invokeProcess(
|
|
1932
|
+
processId: string,
|
|
1933
|
+
input: unknown = {},
|
|
1934
|
+
): Promise<{ runId: string }> {
|
|
1935
|
+
const res = await req(\`/v1/processes/\${encodeURIComponent(processId)}?mode=async\`, {
|
|
1936
|
+
method: 'POST',
|
|
1937
|
+
headers: { 'content-type': 'application/json' },
|
|
1938
|
+
body: JSON.stringify(input),
|
|
1939
|
+
});
|
|
1940
|
+
if (!res.ok) throw await writeError(res, processId);
|
|
1941
|
+
return (await res.json()) as { runId: string };
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
/** One run and its step ledger. Someone else's run is indistinguishable from one
|
|
1945
|
+
* that never existed \u2014 an administrator sees every run. */
|
|
1946
|
+
export async function processRun<T = { run: ProcessRun; steps: unknown[] }>(
|
|
1947
|
+
runId: string,
|
|
1948
|
+
): Promise<T> {
|
|
1949
|
+
const res = await req(\`/v1/processes/runs/\${encodeURIComponent(runId)}\`);
|
|
1950
|
+
if (!res.ok) throw await writeError(res, 'process run');
|
|
1951
|
+
return (await res.json()) as T;
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
/** Stop one run. It finishes the step it is on and starts no more, so what has
|
|
1955
|
+
* already gone upstream stays \u2014 this is a stop, not an undo. */
|
|
1956
|
+
export async function cancelProcessRun(runId: string): Promise<{ cancelled: boolean }> {
|
|
1957
|
+
const res = await req(\`/v1/processes/runs/\${encodeURIComponent(runId)}/cancel\`, {
|
|
1958
|
+
method: 'POST',
|
|
1959
|
+
});
|
|
1960
|
+
if (!res.ok) throw await writeError(res, 'process run');
|
|
1961
|
+
return (await res.json()) as { cancelled: boolean };
|
|
1962
|
+
}
|
|
1963
|
+
`,On="src/types.ts",wk=`turbobase project types -o ${On} || node -e "if(require('node:fs').existsSync('${On}')){console.error('turbobase: could not refresh ${On} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${On} 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 ${On}');process.exit(1)}"`;vk="http://localhost:54331",_k="http://localhost:4100";Tk=`node_modules/
|
|
1667
1964
|
dist/
|
|
1668
1965
|
build/
|
|
1669
1966
|
|
|
@@ -1675,9 +1972,9 @@ build/
|
|
|
1675
1972
|
!.env.example
|
|
1676
1973
|
|
|
1677
1974
|
.DS_Store
|
|
1678
|
-
`,
|
|
1679
|
-
`,
|
|
1680
|
-
`,
|
|
1975
|
+
`,Qh=`${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)}
|
|
1976
|
+
`,em=`${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)}
|
|
1977
|
+
`,tm=`import { clsx, type ClassValue } from 'clsx';
|
|
1681
1978
|
import { twMerge } from 'tailwind-merge';
|
|
1682
1979
|
|
|
1683
1980
|
/**
|
|
@@ -1691,7 +1988,7 @@ import { twMerge } from 'tailwind-merge';
|
|
|
1691
1988
|
export function cn(...inputs: ClassValue[]) {
|
|
1692
1989
|
return twMerge(clsx(inputs));
|
|
1693
1990
|
}
|
|
1694
|
-
`;
|
|
1991
|
+
`;nm=`import React from 'react';
|
|
1695
1992
|
import { createRoot } from 'react-dom/client';
|
|
1696
1993
|
import App from './App';
|
|
1697
1994
|
import './styles.css';
|
|
@@ -1701,7 +1998,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1701
1998
|
<App />
|
|
1702
1999
|
</React.StrictMode>,
|
|
1703
2000
|
);
|
|
1704
|
-
`,
|
|
2001
|
+
`,om=`@import 'tailwindcss';
|
|
1705
2002
|
@import 'tw-animate-css';
|
|
1706
2003
|
|
|
1707
2004
|
/* Inter, self-hosted \u2014 the design system's font.
|
|
@@ -1789,7 +2086,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1789
2086
|
transition-duration: 0.01ms !important;
|
|
1790
2087
|
}
|
|
1791
2088
|
}
|
|
1792
|
-
`,
|
|
2089
|
+
`,sm=`import * as React from 'react';
|
|
1793
2090
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1794
2091
|
|
|
1795
2092
|
import { cn } from '@/lib/utils';
|
|
@@ -1829,7 +2126,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
|
1829
2126
|
Button.displayName = 'Button';
|
|
1830
2127
|
|
|
1831
2128
|
export { Button, buttonVariants };
|
|
1832
|
-
`,
|
|
2129
|
+
`,im=`import * as React from 'react';
|
|
1833
2130
|
|
|
1834
2131
|
import { cn } from '@/lib/utils';
|
|
1835
2132
|
|
|
@@ -1867,7 +2164,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
|
|
|
1867
2164
|
CardContent.displayName = 'CardContent';
|
|
1868
2165
|
|
|
1869
2166
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
|
1870
|
-
`,
|
|
2167
|
+
`,am=`import * as React from 'react';
|
|
1871
2168
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1872
2169
|
|
|
1873
2170
|
import { cn } from '@/lib/utils';
|
|
@@ -1902,7 +2199,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
|
|
1902
2199
|
}
|
|
1903
2200
|
|
|
1904
2201
|
export { Badge, badgeVariants };
|
|
1905
|
-
`,
|
|
2202
|
+
`,lm=`import * as React from 'react';
|
|
1906
2203
|
|
|
1907
2204
|
import { cn } from '@/lib/utils';
|
|
1908
2205
|
|
|
@@ -1961,7 +2258,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
|
|
|
1961
2258
|
TableCell.displayName = 'TableCell';
|
|
1962
2259
|
|
|
1963
2260
|
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
|
1964
|
-
`,
|
|
2261
|
+
`,cm=`import * as React from 'react';
|
|
1965
2262
|
|
|
1966
2263
|
import { cn } from '@/lib/utils';
|
|
1967
2264
|
|
|
@@ -1981,7 +2278,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
|
|
|
1981
2278
|
Input.displayName = 'Input';
|
|
1982
2279
|
|
|
1983
2280
|
export { Input };
|
|
1984
|
-
`,
|
|
2281
|
+
`,dm=`import * as React from 'react';
|
|
1985
2282
|
|
|
1986
2283
|
import { cn } from '@/lib/utils';
|
|
1987
2284
|
|
|
@@ -1998,51 +2295,53 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
|
|
|
1998
2295
|
Label.displayName = 'Label';
|
|
1999
2296
|
|
|
2000
2297
|
export { Label };
|
|
2001
|
-
`});import*as
|
|
2002
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function om(t){return t.description}function sm(t){if($t(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fr(t){if($t(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Nn=j(()=>{});import*as c from"zod/v4";function Sm(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function km(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ka,im,Zt,ps,Ae,am,lm,SN,uk,pk,Va,tt,Ln,cm,je,it,at,De,hs,dm,Ga,um,pm,Wa,jn,K,Ja,hm,mm,kN,ms,hk,fs,mk,Dn,Hr,fm,fk,gk,yk,bk,wk,vk,Ya,_k,Sk,Xa,gs,kk,Tk,ys,xk,Un,Mn,Rk,qn,Kr,$k,zn,bs,ws,vs,TN,_s,Ss,ks,gm,ym,bm,Za,wm,Bn,Vr,vm,Ek,Ts,Pk,xs,Ak,Qa,Ck,Rs,Ik,Ok,Nk,Lk,jk,Dk,Uk,Mk,qk,zk,$s,Bk,Fk,Es,el,tl,rl,Hk,Kk,Vk,nl,Gk,Wk,Jk,Yk,Xk,_m,Ps,Zk,As,xN,Qk,Gr,eT,RN,Fn,tT,ol,rT,nT,oT,sT,iT,aT,lT,us,cT,dT,uT,Hn,sl,pT,hT,mT,fT,gT,yT,bT,wT,vT,_T,ST,kT,TT,xT,RT,$T,ET,PT,Wr,AT,CT,IT,Cs,OT,NT,LT,il,jT,$N,EN,PN,AN,CN,IN,z,Ha,Jr=j(()=>{Ka="2025-11-25",im=[Ka,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",ps="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),am=c.union([c.string(),c.number().int()]),lm=c.string(),SN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),uk=c.object({ttl:c.number().optional()}),pk=c.object({taskId:c.string()}),Va=c.looseObject({progressToken:am.optional(),[Zt]:pk.optional()}),tt=c.object({_meta:Va.optional()}),Ln=tt.extend({task:uk.optional()}),cm=t=>Ln.safeParse(t).success,je=c.object({method:c.string(),params:tt.loose().optional()}),it=c.object({_meta:Va.optional()}),at=c.object({method:c.string(),params:it.loose().optional()}),De=c.looseObject({_meta:Va.optional()}),hs=c.union([c.string(),c.number().int()]),dm=c.object({jsonrpc:c.literal(ps),id:hs,...je.shape}).strict(),Ga=t=>dm.safeParse(t).success,um=c.object({jsonrpc:c.literal(ps),...at.shape}).strict(),pm=t=>um.safeParse(t).success,Wa=c.object({jsonrpc:c.literal(ps),id:hs,result:De}).strict(),jn=t=>Wa.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={}));Ja=c.object({jsonrpc:c.literal(ps),id:hs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),hm=t=>Ja.safeParse(t).success,mm=c.union([dm,um,Wa,Ja]),kN=c.union([Wa,Ja]),ms=De.strict(),hk=it.extend({requestId:hs.optional(),reason:c.string().optional()}),fs=at.extend({method:c.literal("notifications/cancelled"),params:hk}),mk=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Dn=c.object({icons:c.array(mk).optional()}),Hr=c.object({name:c.string(),title:c.string().optional()}),fm=Hr.extend({...Hr.shape,...Dn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),fk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),gk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:fk.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),yk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),bk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),wk=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:gk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:yk.optional(),extensions:c.record(c.string(),Ae).optional()}),vk=tt.extend({protocolVersion:c.string(),capabilities:wk,clientInfo:fm}),Ya=je.extend({method:c.literal("initialize"),params:vk}),_k=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:bk.optional(),extensions:c.record(c.string(),Ae).optional()}),Sk=De.extend({protocolVersion:c.string(),capabilities:_k,serverInfo:fm,instructions:c.string().optional()}),Xa=at.extend({method:c.literal("notifications/initialized"),params:it.optional()}),gs=je.extend({method:c.literal("ping"),params:tt.optional()}),kk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Tk=c.object({...it.shape,...kk.shape,progressToken:am}),ys=at.extend({method:c.literal("notifications/progress"),params:Tk}),xk=tt.extend({cursor:lm.optional()}),Un=je.extend({params:xk.optional()}),Mn=De.extend({nextCursor:lm.optional()}),Rk=c.enum(["working","input_required","completed","failed","cancelled"]),qn=c.object({taskId:c.string(),status:Rk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Kr=De.extend({task:qn}),$k=it.merge(qn),zn=at.extend({method:c.literal("notifications/tasks/status"),params:$k}),bs=je.extend({method:c.literal("tasks/get"),params:tt.extend({taskId:c.string()})}),ws=De.merge(qn),vs=je.extend({method:c.literal("tasks/result"),params:tt.extend({taskId:c.string()})}),TN=De.loose(),_s=Un.extend({method:c.literal("tasks/list")}),Ss=Mn.extend({tasks:c.array(qn)}),ks=je.extend({method:c.literal("tasks/cancel"),params:tt.extend({taskId:c.string()})}),gm=De.merge(qn),ym=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),bm=ym.extend({text:c.string()}),Za=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wm=ym.extend({blob:Za}),Bn=c.enum(["user","assistant"]),Vr=c.object({audience:c.array(Bn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),vm=c.object({...Hr.shape,...Dn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ek=c.object({...Hr.shape,...Dn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Ts=Un.extend({method:c.literal("resources/list")}),Pk=Mn.extend({resources:c.array(vm)}),xs=Un.extend({method:c.literal("resources/templates/list")}),Ak=Mn.extend({resourceTemplates:c.array(Ek)}),Qa=tt.extend({uri:c.string()}),Ck=Qa,Rs=je.extend({method:c.literal("resources/read"),params:Ck}),Ik=De.extend({contents:c.array(c.union([bm,wm]))}),Ok=at.extend({method:c.literal("notifications/resources/list_changed"),params:it.optional()}),Nk=Qa,Lk=je.extend({method:c.literal("resources/subscribe"),params:Nk}),jk=Qa,Dk=je.extend({method:c.literal("resources/unsubscribe"),params:jk}),Uk=it.extend({uri:c.string()}),Mk=at.extend({method:c.literal("notifications/resources/updated"),params:Uk}),qk=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),zk=c.object({...Hr.shape,...Dn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(qk)),_meta:c.optional(c.looseObject({}))}),$s=Un.extend({method:c.literal("prompts/list")}),Bk=Mn.extend({prompts:c.array(zk)}),Fk=tt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Es=je.extend({method:c.literal("prompts/get"),params:Fk}),el=c.object({type:c.literal("text"),text:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),tl=c.object({type:c.literal("image"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),rl=c.object({type:c.literal("audio"),data:Za,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hk=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()}),Kk=c.object({type:c.literal("resource"),resource:c.union([bm,wm]),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Vk=vm.extend({type:c.literal("resource_link")}),nl=c.union([el,tl,rl,Vk,Kk]),Gk=c.object({role:Bn,content:nl}),Wk=De.extend({description:c.string().optional(),messages:c.array(Gk)}),Jk=at.extend({method:c.literal("notifications/prompts/list_changed"),params:it.optional()}),Yk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Xk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),_m=c.object({...Hr.shape,...Dn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Yk.optional(),execution:Xk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ps=Un.extend({method:c.literal("tools/list")}),Zk=Mn.extend({tools:c.array(_m)}),As=De.extend({content:c.array(nl).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),xN=As.or(De.extend({toolResult:c.unknown()})),Qk=Ln.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Gr=je.extend({method:c.literal("tools/call"),params:Qk}),eT=at.extend({method:c.literal("notifications/tools/list_changed"),params:it.optional()}),RN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Fn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),tT=tt.extend({level:Fn}),ol=je.extend({method:c.literal("logging/setLevel"),params:tT}),rT=it.extend({level:Fn,logger:c.string().optional(),data:c.unknown()}),nT=at.extend({method:c.literal("notifications/message"),params:rT}),oT=c.object({name:c.string().optional()}),sT=c.object({hints:c.array(oT).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()}),iT=c.object({mode:c.enum(["auto","required","none"]).optional()}),aT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(nl).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),lT=c.discriminatedUnion("type",[el,tl,rl]),us=c.discriminatedUnion("type",[el,tl,rl,Hk,aT]),cT=c.object({role:Bn,content:c.union([us,c.array(us)]),_meta:c.record(c.string(),c.unknown()).optional()}),dT=Ln.extend({messages:c.array(cT),modelPreferences:sT.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:Ae.optional(),tools:c.array(_m).optional(),toolChoice:iT.optional()}),uT=je.extend({method:c.literal("sampling/createMessage"),params:dT}),Hn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Bn,content:lT}),sl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Bn,content:c.union([us,c.array(us)])}),pT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),hT=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()}),mT=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()}),fT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),gT=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()}),yT=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()}),bT=c.union([fT,gT]),wT=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()}),vT=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()}),_T=c.union([wT,vT]),ST=c.union([yT,bT,_T]),kT=c.union([ST,pT,hT,mT]),TT=Ln.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),kT),required:c.array(c.string()).optional()})}),xT=Ln.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),RT=c.union([TT,xT]),$T=je.extend({method:c.literal("elicitation/create"),params:RT}),ET=it.extend({elicitationId:c.string()}),PT=at.extend({method:c.literal("notifications/elicitation/complete"),params:ET}),Wr=De.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())}),AT=c.object({type:c.literal("ref/resource"),uri:c.string()}),CT=c.object({type:c.literal("ref/prompt"),name:c.string()}),IT=tt.extend({ref:c.union([CT,AT]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Cs=je.extend({method:c.literal("completion/complete"),params:IT});OT=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),NT=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),LT=je.extend({method:c.literal("roots/list"),params:tt.optional()}),il=De.extend({roots:c.array(NT)}),jT=at.extend({method:c.literal("notifications/roots/list_changed"),params:it.optional()}),$N=c.union([gs,Ya,Cs,ol,Es,$s,Ts,xs,Rs,Lk,Dk,Gr,Ps,bs,vs,_s,ks]),EN=c.union([fs,ys,Xa,jT,zn]),PN=c.union([ms,Hn,sl,Wr,il,ws,Ss,Kr]),AN=c.union([gs,uT,$T,LT,bs,vs,_s,ks]),CN=c.union([fs,ys,nT,Mk,Ok,eT,Jk,zn,PT]),IN=c.union([ms,Sk,OT,Wk,Bk,Pk,Ak,Ik,As,Zk,ws,Ss,Kr]),z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===K.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ha(o.elicitations,r)}return new t(e,r,n)}},Ha=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Tm=j(()=>{});var Rm,xm,$m,Is=j(()=>{Rm=Symbol("Let zodToJsonSchema decide on which parser to use"),xm={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"},$m=t=>typeof t=="string"?{...xm,name:t}:{...xm,...t}});var Em,al=j(()=>{Is();Em=t=>{let e=$m(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function ll(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,ll(t,e,n,o)}var er=j(()=>{});var Os,Ns=j(()=>{Os=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Os(e,t.currentPath):e.join("/")}}var lt=j(()=>{Ns()});import{ZodFirstPartyTypeKind as DT}from"zod/v3";function Pm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==DT.ZodAny&&(r.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var cl=j(()=>{er();Pe()});function Am(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var dl=j(()=>{er()});function Cm(){return{type:"boolean"}}var ul=j(()=>{});function Ls(t,e){return X(t.type._def,e)}var js=j(()=>{Pe()});var Im,pl=j(()=>{Pe();Im=(t,e)=>X(t.innerType._def,e)});function hl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>hl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return UT(t,e)}}var UT,ml=j(()=>{er();UT=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Om(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var fl=j(()=>{Pe()});function Nm(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):ke(e)}var gl=j(()=>{Pe();lt()});function Lm(t){return{type:"string",enum:Array.from(t.values)}}var yl=j(()=>{});function jm(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(MT(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var MT,bl=j(()=>{Pe();MT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Dm(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var wl=j(()=>{});function Ds(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":bt(r,"email",n.message,e);break;case"format:idn-email":bt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,yt.email,n.message,e);break}break;case"url":bt(r,"uri",n.message,e);break;case"uuid":bt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,yt.cuid,n.message,e);break;case"cuid2":He(r,yt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${_l(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${_l(n.value,e)}$`),n.message,e);break;case"datetime":bt(r,"date-time",n.message,e);break;case"date":bt(r,"date",n.message,e);break;case"time":bt(r,"time",n.message,e);break;case"duration":bt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(_l(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&bt(r,"ipv4",n.message,e),n.version!=="v4"&&bt(r,"ipv6",n.message,e);break}case"base64url":He(r,yt.base64url,n.message,e);break;case"jwt":He(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,yt.ipv6Cidr,n.message,e);break}case"emoji":He(r,yt.emoji(),n.message,e);break;case"ulid":{He(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,yt.base64,n.message,e);break}}break}case"nanoid":He(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function _l(t,e){return e.patternStrategy==="escape"?zT(t):t}function zT(t){let e="";for(let r=0;r<t.length;r++)qT.has(t[r])||(e+="\\"),e+=t[r];return e}function bt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Um(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",Um(e,n),r,n)}function Um(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
2298
|
+
`});import*as hm from"zod/v3";import*as gr from"zod/v4-mini";function $t(t){return!!t._zod}function yr(t){let e=Object.values(t);if(e.length===0)return gr.object({});let r=e.every($t),n=e.every(o=>!$t(o));if(r)return gr.object(t);if(n)return hm.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yt(t,e){return $t(t)?gr.safeParse(t,e):t.safeParse(e)}async function us(t,e){return $t(t)?await gr.safeParseAsync(t,e):await t.safeParseAsync(e)}function Xt(t){if(!t)return;let e;if($t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Br(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return yr(t)}}if($t(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function $k(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ps(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 ${$k(e.path)}`:e.message).join(`
|
|
2299
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function mm(t){return t.description}function fm(t){if($t(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fr(t){if($t(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Nn=j(()=>{});import*as c from"zod/v4";function Im(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Om(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Wa,gm,Zt,ms,Ae,ym,bm,qN,Ek,Pk,Ja,tt,Ln,wm,je,it,at,De,fs,vm,Ya,_m,Sm,Xa,jn,K,Za,km,Tm,zN,gs,Ak,ys,Ck,Dn,Hr,xm,Ik,Ok,Nk,Lk,jk,Dk,Qa,Uk,Mk,el,bs,qk,zk,ws,Bk,Un,Mn,Fk,qn,Kr,Hk,zn,vs,_s,Ss,BN,ks,Ts,xs,Rm,$m,Em,tl,Pm,Bn,Vr,Am,Kk,Rs,Vk,$s,Gk,rl,Wk,Es,Jk,Yk,Xk,Zk,Qk,eT,tT,rT,nT,oT,Ps,sT,iT,As,nl,ol,sl,aT,lT,cT,il,dT,uT,pT,hT,mT,Cm,Cs,fT,Is,FN,gT,Gr,yT,HN,Fn,bT,al,wT,vT,_T,ST,kT,TT,xT,hs,RT,$T,ET,Hn,ll,PT,AT,CT,IT,OT,NT,LT,jT,DT,UT,MT,qT,zT,BT,FT,HT,KT,VT,Wr,GT,WT,JT,Os,YT,XT,ZT,cl,QT,KN,VN,GN,WN,JN,YN,z,Ga,Jr=j(()=>{Wa="2025-11-25",gm=[Wa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",ms="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ym=c.union([c.string(),c.number().int()]),bm=c.string(),qN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Ek=c.object({ttl:c.number().optional()}),Pk=c.object({taskId:c.string()}),Ja=c.looseObject({progressToken:ym.optional(),[Zt]:Pk.optional()}),tt=c.object({_meta:Ja.optional()}),Ln=tt.extend({task:Ek.optional()}),wm=t=>Ln.safeParse(t).success,je=c.object({method:c.string(),params:tt.loose().optional()}),it=c.object({_meta:Ja.optional()}),at=c.object({method:c.string(),params:it.loose().optional()}),De=c.looseObject({_meta:Ja.optional()}),fs=c.union([c.string(),c.number().int()]),vm=c.object({jsonrpc:c.literal(ms),id:fs,...je.shape}).strict(),Ya=t=>vm.safeParse(t).success,_m=c.object({jsonrpc:c.literal(ms),...at.shape}).strict(),Sm=t=>_m.safeParse(t).success,Xa=c.object({jsonrpc:c.literal(ms),id:fs,result:De}).strict(),jn=t=>Xa.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={}));Za=c.object({jsonrpc:c.literal(ms),id:fs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),km=t=>Za.safeParse(t).success,Tm=c.union([vm,_m,Xa,Za]),zN=c.union([Xa,Za]),gs=De.strict(),Ak=it.extend({requestId:fs.optional(),reason:c.string().optional()}),ys=at.extend({method:c.literal("notifications/cancelled"),params:Ak}),Ck=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Dn=c.object({icons:c.array(Ck).optional()}),Hr=c.object({name:c.string(),title:c.string().optional()}),xm=Hr.extend({...Hr.shape,...Dn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Ik=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Ok=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Ik.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),Nk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),Lk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),jk=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:Ok.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Nk.optional(),extensions:c.record(c.string(),Ae).optional()}),Dk=tt.extend({protocolVersion:c.string(),capabilities:jk,clientInfo:xm}),Qa=je.extend({method:c.literal("initialize"),params:Dk}),Uk=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:Lk.optional(),extensions:c.record(c.string(),Ae).optional()}),Mk=De.extend({protocolVersion:c.string(),capabilities:Uk,serverInfo:xm,instructions:c.string().optional()}),el=at.extend({method:c.literal("notifications/initialized"),params:it.optional()}),bs=je.extend({method:c.literal("ping"),params:tt.optional()}),qk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),zk=c.object({...it.shape,...qk.shape,progressToken:ym}),ws=at.extend({method:c.literal("notifications/progress"),params:zk}),Bk=tt.extend({cursor:bm.optional()}),Un=je.extend({params:Bk.optional()}),Mn=De.extend({nextCursor:bm.optional()}),Fk=c.enum(["working","input_required","completed","failed","cancelled"]),qn=c.object({taskId:c.string(),status:Fk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Kr=De.extend({task:qn}),Hk=it.merge(qn),zn=at.extend({method:c.literal("notifications/tasks/status"),params:Hk}),vs=je.extend({method:c.literal("tasks/get"),params:tt.extend({taskId:c.string()})}),_s=De.merge(qn),Ss=je.extend({method:c.literal("tasks/result"),params:tt.extend({taskId:c.string()})}),BN=De.loose(),ks=Un.extend({method:c.literal("tasks/list")}),Ts=Mn.extend({tasks:c.array(qn)}),xs=je.extend({method:c.literal("tasks/cancel"),params:tt.extend({taskId:c.string()})}),Rm=De.merge(qn),$m=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Em=$m.extend({text:c.string()}),tl=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pm=$m.extend({blob:tl}),Bn=c.enum(["user","assistant"]),Vr=c.object({audience:c.array(Bn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Am=c.object({...Hr.shape,...Dn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Kk=c.object({...Hr.shape,...Dn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Vr.optional(),_meta:c.optional(c.looseObject({}))}),Rs=Un.extend({method:c.literal("resources/list")}),Vk=Mn.extend({resources:c.array(Am)}),$s=Un.extend({method:c.literal("resources/templates/list")}),Gk=Mn.extend({resourceTemplates:c.array(Kk)}),rl=tt.extend({uri:c.string()}),Wk=rl,Es=je.extend({method:c.literal("resources/read"),params:Wk}),Jk=De.extend({contents:c.array(c.union([Em,Pm]))}),Yk=at.extend({method:c.literal("notifications/resources/list_changed"),params:it.optional()}),Xk=rl,Zk=je.extend({method:c.literal("resources/subscribe"),params:Xk}),Qk=rl,eT=je.extend({method:c.literal("resources/unsubscribe"),params:Qk}),tT=it.extend({uri:c.string()}),rT=at.extend({method:c.literal("notifications/resources/updated"),params:tT}),nT=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),oT=c.object({...Hr.shape,...Dn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(nT)),_meta:c.optional(c.looseObject({}))}),Ps=Un.extend({method:c.literal("prompts/list")}),sT=Mn.extend({prompts:c.array(oT)}),iT=tt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),As=je.extend({method:c.literal("prompts/get"),params:iT}),nl=c.object({type:c.literal("text"),text:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ol=c.object({type:c.literal("image"),data:tl,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),sl=c.object({type:c.literal("audio"),data:tl,mimeType:c.string(),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),aT=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()}),lT=c.object({type:c.literal("resource"),resource:c.union([Em,Pm]),annotations:Vr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),cT=Am.extend({type:c.literal("resource_link")}),il=c.union([nl,ol,sl,cT,lT]),dT=c.object({role:Bn,content:il}),uT=De.extend({description:c.string().optional(),messages:c.array(dT)}),pT=at.extend({method:c.literal("notifications/prompts/list_changed"),params:it.optional()}),hT=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),mT=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Cm=c.object({...Hr.shape,...Dn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:hT.optional(),execution:mT.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Cs=Un.extend({method:c.literal("tools/list")}),fT=Mn.extend({tools:c.array(Cm)}),Is=De.extend({content:c.array(il).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),FN=Is.or(De.extend({toolResult:c.unknown()})),gT=Ln.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Gr=je.extend({method:c.literal("tools/call"),params:gT}),yT=at.extend({method:c.literal("notifications/tools/list_changed"),params:it.optional()}),HN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Fn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),bT=tt.extend({level:Fn}),al=je.extend({method:c.literal("logging/setLevel"),params:bT}),wT=it.extend({level:Fn,logger:c.string().optional(),data:c.unknown()}),vT=at.extend({method:c.literal("notifications/message"),params:wT}),_T=c.object({name:c.string().optional()}),ST=c.object({hints:c.array(_T).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()}),kT=c.object({mode:c.enum(["auto","required","none"]).optional()}),TT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(il).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),xT=c.discriminatedUnion("type",[nl,ol,sl]),hs=c.discriminatedUnion("type",[nl,ol,sl,aT,TT]),RT=c.object({role:Bn,content:c.union([hs,c.array(hs)]),_meta:c.record(c.string(),c.unknown()).optional()}),$T=Ln.extend({messages:c.array(RT),modelPreferences:ST.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:Ae.optional(),tools:c.array(Cm).optional(),toolChoice:kT.optional()}),ET=je.extend({method:c.literal("sampling/createMessage"),params:$T}),Hn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Bn,content:xT}),ll=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Bn,content:c.union([hs,c.array(hs)])}),PT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),AT=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()}),CT=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()}),IT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),OT=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()}),NT=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()}),LT=c.union([IT,OT]),jT=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()}),DT=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()}),UT=c.union([jT,DT]),MT=c.union([NT,LT,UT]),qT=c.union([MT,PT,AT,CT]),zT=Ln.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),qT),required:c.array(c.string()).optional()})}),BT=Ln.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),FT=c.union([zT,BT]),HT=je.extend({method:c.literal("elicitation/create"),params:FT}),KT=it.extend({elicitationId:c.string()}),VT=at.extend({method:c.literal("notifications/elicitation/complete"),params:KT}),Wr=De.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())}),GT=c.object({type:c.literal("ref/resource"),uri:c.string()}),WT=c.object({type:c.literal("ref/prompt"),name:c.string()}),JT=tt.extend({ref:c.union([WT,GT]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Os=je.extend({method:c.literal("completion/complete"),params:JT});YT=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),XT=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ZT=je.extend({method:c.literal("roots/list"),params:tt.optional()}),cl=De.extend({roots:c.array(XT)}),QT=at.extend({method:c.literal("notifications/roots/list_changed"),params:it.optional()}),KN=c.union([bs,Qa,Os,al,As,Ps,Rs,$s,Es,Zk,eT,Gr,Cs,vs,Ss,ks,xs]),VN=c.union([ys,ws,el,QT,zn]),GN=c.union([gs,Hn,ll,Wr,cl,_s,Ts,Kr]),WN=c.union([bs,ET,HT,ZT,vs,Ss,ks,xs]),JN=c.union([ys,ws,vT,rT,Yk,yT,pT,zn,VT]),YN=c.union([gs,Mk,YT,uT,sT,Vk,Gk,Jk,Is,fT,_s,Ts,Kr]),z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===K.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ga(o.elicitations,r)}return new t(e,r,n)}},Ga=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Nm=j(()=>{});var jm,Lm,Dm,Ns=j(()=>{jm=Symbol("Let zodToJsonSchema decide on which parser to use"),Lm={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"},Dm=t=>typeof t=="string"?{...Lm,name:t}:{...Lm,...t}});var Um,dl=j(()=>{Ns();Um=t=>{let e=Dm(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function ul(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,ul(t,e,n,o)}var er=j(()=>{});var Ls,js=j(()=>{Ls=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Te(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ls(e,t.currentPath):e.join("/")}}var lt=j(()=>{js()});import{ZodFirstPartyTypeKind as ex}from"zod/v3";function Mm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ex.ZodAny&&(r.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var pl=j(()=>{er();Pe()});function qm(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var hl=j(()=>{er()});function zm(){return{type:"boolean"}}var ml=j(()=>{});function Ds(t,e){return X(t.type._def,e)}var Us=j(()=>{Pe()});var Bm,fl=j(()=>{Pe();Bm=(t,e)=>X(t.innerType._def,e)});function gl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>gl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tx(t,e)}}var tx,yl=j(()=>{er();tx=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Fm(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var bl=j(()=>{Pe()});function Hm(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):Te(e)}var wl=j(()=>{Pe();lt()});function Km(t){return{type:"string",enum:Array.from(t.values)}}var vl=j(()=>{});function Vm(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(rx(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var rx,_l=j(()=>{Pe();rx=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Gm(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Sl=j(()=>{});function Ms(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":bt(r,"email",n.message,e);break;case"format:idn-email":bt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,yt.email,n.message,e);break}break;case"url":bt(r,"uri",n.message,e);break;case"uuid":bt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,yt.cuid,n.message,e);break;case"cuid2":He(r,yt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${Tl(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${Tl(n.value,e)}$`),n.message,e);break;case"datetime":bt(r,"date-time",n.message,e);break;case"date":bt(r,"date",n.message,e);break;case"time":bt(r,"time",n.message,e);break;case"duration":bt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(Tl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&bt(r,"ipv4",n.message,e),n.version!=="v4"&&bt(r,"ipv6",n.message,e);break}case"base64url":He(r,yt.base64url,n.message,e);break;case"jwt":He(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,yt.ipv6Cidr,n.message,e);break}case"emoji":He(r,yt.emoji(),n.message,e);break;case"ulid":{He(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,yt.base64,n.message,e);break}}break}case"nanoid":He(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Tl(t,e){return e.patternStrategy==="escape"?ox(t):t}function ox(t){let e="";for(let r=0;r<t.length;r++)nx.has(t[r])||(e+="\\"),e+=t[r];return e}function bt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Wm(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",Wm(e,n),r,n)}function Wm(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
2003
2300
|
]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
|
|
2004
2301
|
]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
|
|
2005
2302
|
`:`[${n[l]}\r
|
|
2006
|
-
]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var vl,yt,qT,Us=j(()=>{er();yt={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:()=>(vl===void 0&&(vl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vl),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-_]*$/};qT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Kn}from"zod/v3";function Ms(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===Kn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Kn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ds(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Kn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Kn.ZodBranded&&t.keyType._def.type._def.typeName===Kn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ls(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var qs=j(()=>{Pe();Us();js();lt()});function Mm(t,e){if(e.mapStrategy==="record")return Ms(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),n=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Sl=j(()=>{Pe();qs();lt()});function qm(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var kl=j(()=>{});function zm(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}var Tl=j(()=>{lt()});function Bm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xl=j(()=>{});function Hm(t,e){if(e.target==="openApi3")return Fm(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Fm(t,e)}var Vn,Fm,zs=j(()=>{Pe();Vn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fm=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Km(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:Vn[t.innerType._def.typeName],nullable:!0}:{type:[Vn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Rl=j(()=>{Pe();zs()});function Vm(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ll(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var $l=j(()=>{er()});function Gm(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let d=FT(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,d||o.push(a))}o.length&&(n.required=o);let i=BT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function BT(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 FT(t){try{return t.isOptional()}catch{return!0}}var El=j(()=>{Pe()});var Wm,Pl=j(()=>{Pe();lt();Wm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ke(e)},r]}:ke(e)}});var Jm,Al=j(()=>{Pe();Jm=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Ym(t,e){return X(t.type._def,e)}var Cl=j(()=>{Pe()});function Xm(t,e){let n={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Il=j(()=>{er();Pe()});function Zm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ol=j(()=>{Pe()});function Qm(t){return{not:ke(t)}}var Nl=j(()=>{lt()});function ef(t){return ke(t)}var Ll=j(()=>{lt()});var tf,jl=j(()=>{Pe();tf=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var rf,Dl=j(()=>{lt();cl();dl();ul();js();pl();ml();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();qs();Il();Us();Ol();Nl();zs();Ll();jl();rf=(t,e,r)=>{switch(e){case le.ZodString:return Ds(t,r);case le.ZodNumber:return Vm(t,r);case le.ZodObject:return Gm(t,r);case le.ZodBigInt:return Am(t,r);case le.ZodBoolean:return Cm();case le.ZodDate:return hl(t,r);case le.ZodUndefined:return Qm(r);case le.ZodNull:return Bm(r);case le.ZodArray:return Pm(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Hm(t,r);case le.ZodIntersection:return jm(t,r);case le.ZodTuple:return Zm(t,r);case le.ZodRecord:return Ms(t,r);case le.ZodLiteral:return Dm(t,r);case le.ZodEnum:return Lm(t);case le.ZodNativeEnum:return qm(t);case le.ZodNullable:return Km(t,r);case le.ZodOptional:return Wm(t,r);case le.ZodMap:return Mm(t,r);case le.ZodSet:return Xm(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return Ym(t,r);case le.ZodNaN:case le.ZodNever:return zm(r);case le.ZodEffects:return Nm(t,r);case le.ZodAny:return ke(r);case le.ZodUnknown:return ef(r);case le.ZodDefault:return Om(t,r);case le.ZodBranded:return Ls(t,r);case le.ZodReadonly:return tf(t,r);case le.ZodCatch:return Im(t,r);case le.ZodPipeline:return Jm(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Rm)return a}if(n&&!r){let a=HT(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=rf(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&KT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var HT,KT,Pe=j(()=>{Is();Dl();Ns();lt();HT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Os(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},KT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var nf=j(()=>{});var Ul,Ml=j(()=>{Pe();al();lt();Ul=(t,e)=>{let r=Em(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,p])=>({...l,[d]:X(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??ke(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??ke(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var of=j(()=>{Is();al();er();Ns();Pe();nf();lt();cl();dl();ul();js();pl();ml();fl();gl();yl();bl();wl();Sl();kl();Tl();xl();Rl();$l();El();Pl();Al();Cl();jl();qs();Il();Us();Ol();Nl();zs();Ll();Dl();Ml();Ml()});import*as sf from"zod/v4-mini";function VT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ql(t,e){return $t(t)?sf.toJSONSchema(t,{target:VT(e?.target),io:e?.pipeStrategy??"input"}):Ul(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function zl(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bl(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var Fl=j(()=>{Nn();of()});function af(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function lf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];af(i)&&af(s)?r[o]={...i,...s}:r[o]=s}return r}var GT,Bs,cf=j(()=>{Nn();Jr();Tm();Fl();GT=6e4,Bs=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(fs,r=>{this._oncancel(r)}),this.setNotificationHandler(ys,r=>{this._onprogress(r)}),this.setRequestHandler(gs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(bs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vs,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,d=l.id,p=this._requestResolvers.get(d);if(p)if(this._requestResolvers.delete(d),a.type==="response")p(l);else{let f=l,_=new z(f.error.code,f.error.message,f.error.data);p(_)}else{let f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(K.InvalidParams,`Task not found: ${s}`);if(!Qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(_s,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ks,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(K.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(K.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),jn(s)||hm(s)?this._onresponse(s):Ga(s)?this._onrequest(s,i):pm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Zt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=cm(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};s&&(f.relatedTask={taskId:s}),await this.notification(p,f)},sendRequest:async(p,f,_)=>{if(i.signal.aborted)throw new z(K.ConnectionClosed,"Request was cancelled");let y={..._,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let k=y.relatedTask?.taskId??s;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,y)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async p=>{if(i.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async p=>{if(i.signal.aborted)return;let f={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}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).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:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),jn(e))n(e);else{let i=new z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(jn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),jn(e))o(e);else{let i=z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Kr,n);if(i.task)s=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:s},n);if(yield{type:"taskStatus",task:a},Qt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((d,p)=>{let f=I=>{p(I)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(I){f(I);return}n?.signal?.throwIfAborted();let _=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:_};n?.onprogress&&(this._progressHandlers.set(_,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Zt]:l}});let k=I=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=I instanceof z?I:new z(K.RequestTimeout,String(I));p(D)};this._responseHandlers.set(_,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Yt(r,I.result);D.success?d(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let R=n?.timeout??GT,$=()=>k(z.fromError(K.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(_,R,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let Y=this._responseHandlers.get(_);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(_),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ws,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ss,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},gm,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Zt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Zt]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=zl(e);this._notificationHandlers.set(n,o=>{let s=Bl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ga(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(K.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let l=zn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Qt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let l=await n.getTask(o,r);if(l){let d=zn.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Qt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Jn=U(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 Gn=class{};he._CodeOrName=Gn;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var br=class extends Gn{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=br;var ct=class extends Gn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ct;he.nil=new ct("");function df(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Kl(r,e[n]),r.push(t[++n]);return new ct(r)}he._=df;var Hl=new ct("+");function uf(t,...e){let r=[Wn(t[0])],n=0;for(;n<e.length;)r.push(Hl),Kl(r,e[n]),r.push(Hl,Wn(t[++n]));return WT(r),new ct(r)}he.str=uf;function Kl(t,e){e instanceof ct?t.push(...e._items):e instanceof br?t.push(e):t.push(XT(e))}he.addCodeArg=Kl;function WT(t){let e=1;for(;e<t.length-1;){if(t[e]===Hl){let r=JT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof br||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 br))return`"${t}${e.slice(1)}`}function YT(t,e){return e.emptyStr()?t:t.emptyStr()?e:uf`${t}${e}`}he.strConcat=YT;function XT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Wn(Array.isArray(t)?t.join(","):t)}function ZT(t){return new ct(Wn(t))}he.stringify=ZT;function Wn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Wn;function QT(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ct(`.${t}`):df`[${t}]`}he.getProperty=QT;function ex(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=ex;function tx(t){return new ct(t.toString())}he.regexpCode=tx});var Wl=U(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Jn(),Vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Fs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Fs||(Xe.UsedValueState=Fs={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Hs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=Hs;var Ks=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Ks;var rx=(0,Ye._)`\n`,Gl=class extends Hs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?rx:Ye.nil}}get(){return this._scope}name(e){return new Ks(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),d=l.length;return l[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,Fs.Started);let p=r(d);if(p){let f=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${f} ${d} = ${p};${this.opts._n}`}else if(p=o?.(d))s=(0,Ye._)`${s}${p}${this.opts._n}`;else throw new Vl(d);l.set(d,Fs.Completed)})}return s}};Xe.ValueScope=Gl});var re=U(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 de=Jn(),wt=Wl(),tr=Jn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return tr.Name}});var Js=Wl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Js.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Js.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Js.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Js.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Dt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Jl=class extends Dt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?wt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Xr(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Vs=class extends Dt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Xr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return Ws(e,this.rhs)}},Yl=class extends Vs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Xl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Zl=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ql=class extends Dt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ec=class extends Dt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Xr(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Yn=class extends Dt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(nx(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_r(e,r.names),{})}},Ut=class extends Yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},tc=class extends Yn{},Yr=class extends Ut{};Yr.kind="else";var wr=class t extends Ut{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Yr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(pf(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Xr(this.condition,e,r),this}get names(){let e=super.names;return Ws(e,this.condition),this.else&&_r(e,this.else.names),e}};wr.kind="if";var vr=class extends Ut{};vr.kind="for";var rc=class extends vr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Xr(this.iteration,e,r),this}get names(){return _r(super.names,this.iteration.names)}},nc=class extends vr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?wt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ws(super.names,this.from);return Ws(e,this.to)}},Gs=class extends vr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Xr(this.iterable,e,r),this}get names(){return _r(super.names,this.iterable.names)}},Xn=class extends Ut{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Xn.kind="func";var Zn=class extends Yn{render(e){return"return "+super.render(e)}};Zn.kind="return";var oc=class extends Ut{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&_r(e,this.catch.names),this.finally&&_r(e,this.finally.names),e}},Qn=class extends Ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qn.kind="catch";var eo=class extends Ut{render(e){return"finally"+super.render(e)}};eo.kind="finally";var sc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2007
|
-
`:""},this._extScope=e,this._scope=new wt.Scope({parent:e}),this._nodes=[new tc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Jl(e,s,n)),s}const(e,r,n){return this._def(wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Vs(e,r,n))}add(e,r){return this._leafNode(new Yl(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new ec(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new wr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new wr(e))}else(){return this._elseNode(new Yr)}endIf(){return this._endBlockNode(wr,Yr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new rc(e),r)}forRange(e,r,n,o,s=this.opts.es5?wt.varKinds.var:wt.varKinds.let){let i=this._scope.toName(e);return this._for(new nc(s,i,r,n),()=>o(i))}forOf(e,r,n,o=wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Gs("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?wt.varKinds.var:wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Gs("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vr)}label(e){return this._leafNode(new Xl(e))}break(e){return this._leafNode(new Zl(e))}return(e){let r=new Zn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Zn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new oc;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qn(s),r(s)}return n&&(this._currNode=o.finally=new eo,this.code(n)),this._endBlockNode(Qn,eo)}throw(e){return this._leafNode(new Ql(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=de.nil,n,o){return this._blockNode(new Xn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof wr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=sc;function _r(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ws(t,e){return e instanceof de._CodeOrName?_r(t,e.names):t}function Xr(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function nx(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function pf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${ic(t)}`}ne.not=pf;var ox=hf(ne.operators.AND);function sx(...t){return t.reduce(ox)}ne.and=sx;var ix=hf(ne.operators.OR);function ax(...t){return t.reduce(ix)}ne.or=ax;function hf(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${ic(e)} ${t} ${ic(r)}`}function ic(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var ue=U(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var we=re(),lx=Jn();function cx(t){let e={};for(let r of t)e[r]=!0;return e}oe.toHash=cx;function dx(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(gf(t,e),!yf(e,t.self.RULES.all))}oe.alwaysValidSchema=dx;function gf(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||vf(t,`unknown keyword: "${s}"`)}oe.checkUnknownRules=gf;function yf(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}oe.schemaHasRules=yf;function ux(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}oe.schemaHasRulesButRef=ux;function px({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}oe.schemaRefOrVal=px;function hx(t){return bf(decodeURIComponent(t))}oe.unescapeFragment=hx;function mx(t){return encodeURIComponent(lc(t))}oe.escapeFragment=mx;function lc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=lc;function bf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=bf;function fx(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}oe.eachItem=fx;function mf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}oe.mergeEvaluated={props:mf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),cc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:wf}),items:mf({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function wf(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&cc(t,r,e),r}oe.evaluatedPropsToName=wf;function cc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}oe.setEvaluated=cc;var ff={};function gx(t,e){return t.scopeValue("func",{ref:e,code:ff[e.code]||(ff[e.code]=new lx._Code(e.code))})}oe.useFunc=gx;var ac;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ac||(oe.Type=ac={}));function yx(t,e,r){if(t instanceof we.Name){let n=e===ac.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+lc(t)}oe.getErrorPath=yx;function vf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}oe.checkStrictMode=vf});var Mt=U(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var qe=re(),bx={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};dc.default=bx});var to=U(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var pe=re(),Ys=ue(),Ke=Mt();ze.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ze.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 wx(t,e=ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=kf(t,e,r);n??(i||a)?_f(s,l):Sf(o,(0,pe._)`[${l}]`)}ze.reportError=wx;function vx(t,e=ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=kf(t,e,r);_f(o,a),s||i||Sf(n,Ke.default.vErrors)}ze.reportExtraError=vx;function _x(t,e){t.assign(Ke.default.errors,e),t.if((0,pe._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=_x;function Sx({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ke.default.errors,a=>{t.const(i,(0,pe._)`${Ke.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(Ke.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ze.extendErrors=Sx;function _f(t,e){let r=t.const("err",e);t.if((0,pe._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${Ke.default.vErrors}.push(${r})`),t.code((0,pe._)`${Ke.default.errors}++`)}function Sf(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var Sr={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 kf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:kx(t,e,r)}function kx(t,e,r={}){let{gen:n,it:o}=t,s=[Tx(o,r),xx(t,r)];return Rx(t,e,s),n.object(...s)}function Tx({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Ys.getErrorPath)(e,Ys.Type.Str)}`:t;return[Ke.default.instancePath,(0,pe.strConcat)(Ke.default.instancePath,r)]}function xx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Ys.getErrorPath)(r,Ys.Type.Str)}`),[Sr.schemaPath,o]}function Rx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:p,schemaPath:f}=a;n.push([Sr.keyword,o],[Sr.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([Sr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Sr.schema,i],[Sr.parentSchema,(0,pe._)`${p}${f}`],[Ke.default.data,s]),d&&n.push([Sr.propertyName,d])}});var xf=U(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.boolOrEmptySchema=Zr.topBoolOrEmptySchema=void 0;var $x=to(),Ex=re(),Px=Mt(),Ax={message:"boolean schema is false"};function Cx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Tf(t,!1):typeof r=="object"&&r.$async===!0?e.return(Px.default.data):(e.assign((0,Ex._)`${n}.errors`,null),e.return(!0))}Zr.topBoolOrEmptySchema=Cx;function Ix(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Tf(t)):r.var(e,!0)}Zr.boolOrEmptySchema=Ix;function Tf(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,$x.reportError)(o,Ax,void 0,e)}});var uc=U(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getRules=Qr.isJSONType=void 0;var Ox=["string","number","integer","boolean","null","object","array"],Nx=new Set(Ox);function Lx(t){return typeof t=="string"&&Nx.has(t)}Qr.isJSONType=Lx;function jx(){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:{}}}Qr.getRules=jx});var pc=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function Dx({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rf(t,n)}rr.schemaHasRulesForType=Dx;function Rf(t,e){return e.rules.some(r=>$f(t,r))}rr.shouldUseGroup=Rf;function $f(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}rr.shouldUseRule=$f});var ro=U(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var Ux=uc(),Mx=pc(),qx=to(),te=re(),Ef=ue(),en;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(en||(Be.DataType=en={}));function zx(t){let e=Pf(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}Be.getSchemaTypes=zx;function Pf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ux.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Pf;function Bx(t,e){let{gen:r,data:n,opts:o}=t,s=Fx(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Mx.schemaHasRulesForType)(t,e[0]));if(i){let a=mc(e,n,o.strictNumbers,en.Wrong);r.if(a,()=>{s.length?Hx(t,e,s):fc(t)})}return i}Be.coerceAndCheckDataType=Bx;var Af=new Set(["string","number","integer","boolean","null"]);function Fx(t,e){return e?t.filter(r=>Af.has(r)||e==="array"&&r==="array"):[]}function Hx(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(mc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let d of r)(Af.has(d)||d==="array"&&s.coerceTypes==="array")&&l(d);n.else(),fc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),Kx(t,a)});function l(d){switch(d){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
|
|
2303
|
+
]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var kl,yt,nx,qs=j(()=>{er();yt={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:()=>(kl===void 0&&(kl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),kl),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-_]*$/};nx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Kn}from"zod/v3";function zs(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===Kn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Te(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Kn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ms(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Kn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Kn.ZodBranded&&t.keyType._def.type._def.typeName===Kn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ds(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Bs=j(()=>{Pe();qs();Us();lt()});function Jm(t,e){if(e.mapStrategy==="record")return zs(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Te(e),n=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Te(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var xl=j(()=>{Pe();Bs();lt()});function Ym(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Rl=j(()=>{});function Xm(t){return t.target==="openAi"?void 0:{not:Te({...t,currentPath:[...t.currentPath,"not"]})}}var $l=j(()=>{lt()});function Zm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var El=j(()=>{});function ef(t,e){if(e.target==="openApi3")return Qm(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Vn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Vn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Qm(t,e)}var Vn,Qm,Fs=j(()=>{Pe();Vn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Qm=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function 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:Vn[t.innerType._def.typeName],nullable:!0}:{type:[Vn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Pl=j(()=>{Pe();Fs()});function rf(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ul(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var Al=j(()=>{er()});function nf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let d=ix(l);d&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,d||o.push(a))}o.length&&(n.required=o);let i=sx(t,e);return i!==void 0&&(n.additionalProperties=i),n}function sx(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 ix(t){try{return t.isOptional()}catch{return!0}}var Cl=j(()=>{Pe()});var of,Il=j(()=>{Pe();lt();of=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Te(e)},r]}:Te(e)}});var sf,Ol=j(()=>{Pe();sf=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function af(t,e){return X(t.type._def,e)}var Nl=j(()=>{Pe()});function lf(t,e){let n={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Ll=j(()=>{er();Pe()});function cf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var jl=j(()=>{Pe()});function df(t){return{not:Te(t)}}var Dl=j(()=>{lt()});function uf(t){return Te(t)}var Ul=j(()=>{lt()});var pf,Ml=j(()=>{Pe();pf=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var hf,ql=j(()=>{lt();pl();hl();ml();Us();fl();yl();bl();wl();vl();_l();Sl();xl();Rl();$l();El();Pl();Al();Cl();Il();Ol();Nl();Bs();Ll();qs();jl();Dl();Fs();Ul();Ml();hf=(t,e,r)=>{switch(e){case le.ZodString:return Ms(t,r);case le.ZodNumber:return rf(t,r);case le.ZodObject:return nf(t,r);case le.ZodBigInt:return qm(t,r);case le.ZodBoolean:return zm();case le.ZodDate:return gl(t,r);case le.ZodUndefined:return df(r);case le.ZodNull:return Zm(r);case le.ZodArray:return Mm(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return ef(t,r);case le.ZodIntersection:return Vm(t,r);case le.ZodTuple:return cf(t,r);case le.ZodRecord:return zs(t,r);case le.ZodLiteral:return Gm(t,r);case le.ZodEnum:return Km(t);case le.ZodNativeEnum:return Ym(t);case le.ZodNullable:return tf(t,r);case le.ZodOptional:return of(t,r);case le.ZodMap:return Jm(t,r);case le.ZodSet:return lf(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return af(t,r);case le.ZodNaN:case le.ZodNever:return Xm(r);case le.ZodEffects:return Hm(t,r);case le.ZodAny:return Te(r);case le.ZodUnknown:return uf(r);case le.ZodDefault:return Fm(t,r);case le.ZodBranded:return Ds(t,r);case le.ZodReadonly:return pf(t,r);case le.ZodCatch:return Bm(t,r);case le.ZodPipeline:return sf(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==jm)return a}if(n&&!r){let a=ax(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=hf(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&lx(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var ax,lx,Pe=j(()=>{Ns();ql();js();lt();ax=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ls(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Te(e)):e.$refStrategy==="seen"?Te(e):void 0}},lx=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var mf=j(()=>{});var zl,Bl=j(()=>{Pe();dl();lt();zl=(t,e)=>{let r=Um(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,p])=>({...l,[d]:X(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Te(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Te(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var ff=j(()=>{Ns();dl();er();js();Pe();mf();lt();pl();hl();ml();Us();fl();yl();bl();wl();vl();_l();Sl();xl();Rl();$l();El();Pl();Al();Cl();Il();Ol();Nl();Ml();Bs();Ll();qs();jl();Dl();Fs();Ul();ql();Bl();Bl()});import*as gf from"zod/v4-mini";function cx(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Fl(t,e){return $t(t)?gf.toJSONSchema(t,{target:cx(e?.target),io:e?.pipeStrategy??"input"}):zl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Hl(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Kl(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var Vl=j(()=>{Nn();ff()});function yf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];yf(i)&&yf(s)?r[o]={...i,...s}:r[o]=s}return r}var dx,Hs,wf=j(()=>{Nn();Jr();Nm();Vl();dx=6e4,Hs=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(ys,r=>{this._oncancel(r)}),this.setNotificationHandler(ws,r=>{this._onprogress(r)}),this.setRequestHandler(bs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(vs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ss,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,d=l.id,p=this._requestResolvers.get(d);if(p)if(this._requestResolvers.delete(d),a.type==="response")p(l);else{let g=l,S=new z(g.error.code,g.error.message,g.error.data);p(S)}else{let g=a.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(K.InvalidParams,`Task not found: ${s}`);if(!Qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ks,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(K.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new z(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(K.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(K.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),jn(s)||km(s)?this._onresponse(s):Ya(s)?this._onrequest(s,i):Sm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=z.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Zt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.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=wm(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,d={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(p,g)},sendRequest:async(p,g,S)=>{if(i.signal.aborted)throw new z(K.ConnectionClosed,"Request was cancelled");let y={...S,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let k=y.relatedTask?.taskId??s;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,g,y)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,d)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.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}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.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:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),jn(e))n(e);else{let i=new z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(jn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),jn(e))o(e);else{let i=z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Kr,n);if(i.task)s=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:s},n);if(yield{type:"taskStatus",task:a},Qt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new z(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((d,p)=>{let g=I=>{p(I)};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(I){g(I);return}n?.signal?.throwIfAborted();let S=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:S};n?.onprogress&&(this._progressHandlers.set(S,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:S}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Zt]:l}});let k=I=>{this._responseHandlers.delete(S),this._progressHandlers.delete(S),this._cleanupTimeout(S),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=I instanceof z?I:new z(K.RequestTimeout,String(I));p(D)};this._responseHandlers.set(S,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Yt(r,I.result);D.success?d(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let R=n?.timeout??dx,$=()=>k(z.fromError(K.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(S,R,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let Y=this._responseHandlers.get(S);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${S}`))};this._requestResolvers.set(S,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(S),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(S),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},_s,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ts,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Rm,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Zt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Zt]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Hl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Kl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Hl(e);this._notificationHandlers.set(n,o=>{let s=Kl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Ya(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(K.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new z(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let l=zn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Qt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new z(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new z(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let l=await n.getTask(o,r);if(l){let d=zn.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Qt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Jn=U(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 Gn=class{};he._CodeOrName=Gn;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var br=class extends Gn{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=br;var ct=class extends Gn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof br&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ct;he.nil=new ct("");function vf(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Wl(r,e[n]),r.push(t[++n]);return new ct(r)}he._=vf;var Gl=new ct("+");function _f(t,...e){let r=[Wn(t[0])],n=0;for(;n<e.length;)r.push(Gl),Wl(r,e[n]),r.push(Gl,Wn(t[++n]));return ux(r),new ct(r)}he.str=_f;function Wl(t,e){e instanceof ct?t.push(...e._items):e instanceof br?t.push(e):t.push(mx(e))}he.addCodeArg=Wl;function ux(t){let e=1;for(;e<t.length-1;){if(t[e]===Gl){let r=px(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function px(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof br||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 br))return`"${t}${e.slice(1)}`}function hx(t,e){return e.emptyStr()?t:t.emptyStr()?e:_f`${t}${e}`}he.strConcat=hx;function mx(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Wn(Array.isArray(t)?t.join(","):t)}function fx(t){return new ct(Wn(t))}he.stringify=fx;function Wn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Wn;function gx(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ct(`.${t}`):vf`[${t}]`}he.getProperty=gx;function yx(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=yx;function bx(t){return new ct(t.toString())}he.regexpCode=bx});var Xl=U(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Jn(),Jl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ks;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ks||(Xe.UsedValueState=Ks={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Vs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=Vs;var Gs=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Gs;var wx=(0,Ye._)`\n`,Yl=class extends Vs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?wx:Ye.nil}}get(){return this._scope}name(e){return new Gs(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),d=l.length;return l[d]=r.ref,o.setValue(r,{property:s,itemIndex:d}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,Ks.Started);let p=r(d);if(p){let g=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${g} ${d} = ${p};${this.opts._n}`}else if(p=o?.(d))s=(0,Ye._)`${s}${p}${this.opts._n}`;else throw new Jl(d);l.set(d,Ks.Completed)})}return s}};Xe.ValueScope=Yl});var re=U(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 de=Jn(),wt=Xl(),tr=Jn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return tr.Name}});var Xs=Xl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Xs.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Xs.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Xs.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Xs.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Dt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Zl=class extends Dt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?wt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Xr(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Ws=class extends Dt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Xr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return Ys(e,this.rhs)}},Ql=class extends Ws{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ec=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},tc=class extends Dt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},rc=class extends Dt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},nc=class extends Dt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Xr(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Yn=class extends Dt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(vx(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_r(e,r.names),{})}},Ut=class extends Yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},oc=class extends Yn{},Yr=class extends Ut{};Yr.kind="else";var wr=class t extends Ut{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Yr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Sf(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Xr(this.condition,e,r),this}get names(){let e=super.names;return Ys(e,this.condition),this.else&&_r(e,this.else.names),e}};wr.kind="if";var vr=class extends Ut{};vr.kind="for";var sc=class extends vr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Xr(this.iteration,e,r),this}get names(){return _r(super.names,this.iteration.names)}},ic=class extends vr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?wt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ys(super.names,this.from);return Ys(e,this.to)}},Js=class extends vr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Xr(this.iterable,e,r),this}get names(){return _r(super.names,this.iterable.names)}},Xn=class extends Ut{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Xn.kind="func";var Zn=class extends Yn{render(e){return"return "+super.render(e)}};Zn.kind="return";var ac=class extends Ut{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&_r(e,this.catch.names),this.finally&&_r(e,this.finally.names),e}},Qn=class extends Ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Qn.kind="catch";var eo=class extends Ut{render(e){return"finally"+super.render(e)}};eo.kind="finally";var lc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2304
|
+
`:""},this._extScope=e,this._scope=new wt.Scope({parent:e}),this._nodes=[new oc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Zl(e,s,n)),s}const(e,r,n){return this._def(wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ws(e,r,n))}add(e,r){return this._leafNode(new Ql(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new nc(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new wr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new wr(e))}else(){return this._elseNode(new Yr)}endIf(){return this._endBlockNode(wr,Yr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new sc(e),r)}forRange(e,r,n,o,s=this.opts.es5?wt.varKinds.var:wt.varKinds.let){let i=this._scope.toName(e);return this._for(new ic(s,i,r,n),()=>o(i))}forOf(e,r,n,o=wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Js("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?wt.varKinds.var:wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Js("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vr)}label(e){return this._leafNode(new ec(e))}break(e){return this._leafNode(new tc(e))}return(e){let r=new Zn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Zn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ac;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Qn(s),r(s)}return n&&(this._currNode=o.finally=new eo,this.code(n)),this._endBlockNode(Qn,eo)}throw(e){return this._leafNode(new rc(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=de.nil,n,o){return this._blockNode(new Xn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof wr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=lc;function _r(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ys(t,e){return e instanceof de._CodeOrName?_r(t,e.names):t}function Xr(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function vx(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Sf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${cc(t)}`}ne.not=Sf;var _x=kf(ne.operators.AND);function Sx(...t){return t.reduce(_x)}ne.and=Sx;var kx=kf(ne.operators.OR);function Tx(...t){return t.reduce(kx)}ne.or=Tx;function kf(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${cc(e)} ${t} ${cc(r)}`}function cc(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var ue=U(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var ve=re(),xx=Jn();function Rx(t){let e={};for(let r of t)e[r]=!0;return e}oe.toHash=Rx;function $x(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Rf(t,e),!$f(e,t.self.RULES.all))}oe.alwaysValidSchema=$x;function Rf(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Af(t,`unknown keyword: "${s}"`)}oe.checkUnknownRules=Rf;function $f(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}oe.schemaHasRules=$f;function Ex(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}oe.schemaHasRulesButRef=Ex;function Px({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ve._)`${r}`}return(0,ve._)`${t}${e}${(0,ve.getProperty)(n)}`}oe.schemaRefOrVal=Px;function Ax(t){return Ef(decodeURIComponent(t))}oe.unescapeFragment=Ax;function Cx(t){return encodeURIComponent(uc(t))}oe.escapeFragment=Cx;function uc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=uc;function Ef(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=Ef;function Ix(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}oe.eachItem=Ix;function Tf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof ve.Name?(s instanceof ve.Name?t(o,s,i):e(o,s,i),i):s instanceof ve.Name?(e(o,i,s),s):r(s,i);return a===ve.Name&&!(l instanceof ve.Name)?n(o,l):l}}oe.mergeEvaluated={props:Tf({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ve._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ve._)`${r} || {}`).code((0,ve._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ve._)`${r} || {}`),pc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pf}),items:Tf({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ve._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ve._)`${r} > ${e} ? ${r} : ${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 r=t.var("props",(0,ve._)`{}`);return e!==void 0&&pc(t,r,e),r}oe.evaluatedPropsToName=Pf;function pc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ve._)`${e}${(0,ve.getProperty)(n)}`,!0))}oe.setEvaluated=pc;var xf={};function Ox(t,e){return t.scopeValue("func",{ref:e,code:xf[e.code]||(xf[e.code]=new xx._Code(e.code))})}oe.useFunc=Ox;var dc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(dc||(oe.Type=dc={}));function Nx(t,e,r){if(t instanceof ve.Name){let n=e===dc.Num;return r?n?(0,ve._)`"[" + ${t} + "]"`:(0,ve._)`"['" + ${t} + "']"`:n?(0,ve._)`"/" + ${t}`:(0,ve._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ve.getProperty)(t).toString():"/"+uc(t)}oe.getErrorPath=Nx;function Af(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}oe.checkStrictMode=Af});var Mt=U(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var qe=re(),Lx={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};hc.default=Lx});var to=U(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var pe=re(),Zs=ue(),Ke=Mt();ze.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ze.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 jx(t,e=ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=Of(t,e,r);n??(i||a)?Cf(s,l):If(o,(0,pe._)`[${l}]`)}ze.reportError=jx;function Dx(t,e=ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Of(t,e,r);Cf(o,a),s||i||If(n,Ke.default.vErrors)}ze.reportExtraError=Dx;function Ux(t,e){t.assign(Ke.default.errors,e),t.if((0,pe._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=Ux;function Mx({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ke.default.errors,a=>{t.const(i,(0,pe._)`${Ke.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(Ke.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ze.extendErrors=Mx;function Cf(t,e){let r=t.const("err",e);t.if((0,pe._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${Ke.default.vErrors}.push(${r})`),t.code((0,pe._)`${Ke.default.errors}++`)}function If(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var Sr={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,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:qx(t,e,r)}function qx(t,e,r={}){let{gen:n,it:o}=t,s=[zx(o,r),Bx(t,r)];return Fx(t,e,s),n.object(...s)}function zx({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Zs.getErrorPath)(e,Zs.Type.Str)}`:t;return[Ke.default.instancePath,(0,pe.strConcat)(Ke.default.instancePath,r)]}function Bx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Zs.getErrorPath)(r,Zs.Type.Str)}`),[Sr.schemaPath,o]}function Fx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:p,schemaPath:g}=a;n.push([Sr.keyword,o],[Sr.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([Sr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Sr.schema,i],[Sr.parentSchema,(0,pe._)`${p}${g}`],[Ke.default.data,s]),d&&n.push([Sr.propertyName,d])}});var Lf=U(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.boolOrEmptySchema=Zr.topBoolOrEmptySchema=void 0;var Hx=to(),Kx=re(),Vx=Mt(),Gx={message:"boolean schema is false"};function Wx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Nf(t,!1):typeof r=="object"&&r.$async===!0?e.return(Vx.default.data):(e.assign((0,Kx._)`${n}.errors`,null),e.return(!0))}Zr.topBoolOrEmptySchema=Wx;function Jx(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Nf(t)):r.var(e,!0)}Zr.boolOrEmptySchema=Jx;function Nf(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Hx.reportError)(o,Gx,void 0,e)}});var mc=U(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getRules=Qr.isJSONType=void 0;var Yx=["string","number","integer","boolean","null","object","array"],Xx=new Set(Yx);function Zx(t){return typeof t=="string"&&Xx.has(t)}Qr.isJSONType=Zx;function Qx(){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:{}}}Qr.getRules=Qx});var fc=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function eR({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&jf(t,n)}rr.schemaHasRulesForType=eR;function jf(t,e){return e.rules.some(r=>Df(t,r))}rr.shouldUseGroup=jf;function Df(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}rr.shouldUseRule=Df});var ro=U(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var tR=mc(),rR=fc(),nR=to(),te=re(),Uf=ue(),en;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(en||(Be.DataType=en={}));function oR(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}Be.getSchemaTypes=oR;function Mf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(tR.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Mf;function sR(t,e){let{gen:r,data:n,opts:o}=t,s=iR(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,rR.schemaHasRulesForType)(t,e[0]));if(i){let a=yc(e,n,o.strictNumbers,en.Wrong);r.if(a,()=>{s.length?aR(t,e,s):bc(t)})}return i}Be.coerceAndCheckDataType=sR;var qf=new Set(["string","number","integer","boolean","null"]);function iR(t,e){return e?t.filter(r=>qf.has(r)||e==="array"&&r==="array"):[]}function aR(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(yc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let d of r)(qf.has(d)||d==="array"&&s.coerceTypes==="array")&&l(d);n.else(),bc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),lR(t,a)});function l(d){switch(d){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
|
|
2008
2305
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":n.elseIf((0,te._)`${i} === "boolean" || ${o} === null
|
|
2009
2306
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,te._)`+${o}`);return;case"boolean":n.elseIf((0,te._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,te._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,te._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,te._)`${i} === "string" || ${i} === "number"
|
|
2010
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Kx({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function hc(t,e,r,n=en.Correct){let o=n===en.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===en.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Be.checkDataType=hc;function mc(t,e,r,n){if(t.length===1)return hc(t[0],e,r,n);let o,s=(0,Ef.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,hc(i,e,r,n));return o}Be.checkDataTypes=mc;var Vx={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function fc(t){let e=Gx(t);(0,qx.reportError)(e,Vx)}Be.reportTypeError=fc;function Gx(t){let{gen:e,data:r,schema:n}=t,o=(0,Ef.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var If=U(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.assignDefaults=void 0;var tn=re(),Wx=ue();function Jx(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Cf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Cf(t,s,o.default))}Xs.assignDefaults=Jx;function Cf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,tn._)`${s}${(0,tn.getProperty)(e)}`;if(o){(0,Wx.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,tn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,tn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,tn._)`${a} = ${(0,tn.stringify)(r)}`)}});var dt=U(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var _e=re(),gc=ue(),nr=Mt(),Yx=ue();function Xx(t,e){let{gen:r,data:n,it:o}=t;r.if(bc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}be.checkReportMissingProp=Xx;function Zx({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(bc(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}be.checkMissingProp=Zx;function Qx(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=Qx;function Of(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Of;function yc(t,e,r){return(0,_e._)`${Of(t)}.call(${e}, ${r})`}be.isOwnProperty=yc;function eR(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${yc(t,e,r)}`:o}be.propertyInData=eR;function bc(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(yc(t,e,r))):o}be.noPropertyInData=bc;function Nf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Nf;function tR(t,e){return Nf(e).filter(r=>!(0,gc.alwaysValidSchema)(t,e[r]))}be.schemaProperties=tR;function rR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,d){let p=d?(0,_e._)`${t}, ${e}, ${n}${o}`:e,f=[[nr.default.instancePath,(0,_e.strConcat)(nr.default.instancePath,s)],[nr.default.parentData,i.parentData],[nr.default.parentDataProperty,i.parentDataProperty],[nr.default.rootData,nr.default.rootData]];i.opts.dynamicRef&&f.push([nr.default.dynamicAnchors,nr.default.dynamicAnchors]);let _=(0,_e._)`${p}, ${r.object(...f)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${_})`:(0,_e._)`${a}(${_})`}be.callValidateCode=rR;var nR=(0,_e._)`new RegExp`;function oR({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${o.code==="new RegExp"?nR:(0,Yx.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=oR;function sR(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let l=e.const("len",(0,_e._)`${r}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:gc.Type.Num},s),e.if((0,_e.not)(s),a)})}}be.validateArray=sR;function iR(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,gc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,d)=>{let p=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,_e._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=iR});var Df=U(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateKeywordUsage=Et.validSchemaType=Et.funcKeywordCode=Et.macroKeywordCode=void 0;var Ve=re(),kr=Mt(),aR=dt(),lR=to();function cR(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=jf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}Et.macroKeywordCode=cR;function dR(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;pR(l,e);let d=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=jf(n,o,d),f=n.let("valid");t.block$data(f,_),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function _(){if(e.errors===!1)R(),e.modifying&&Lf(t),$(()=>t.error());else{let P=e.async?y():k();e.modifying&&Lf(t),$(()=>uR(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ve._)`await `),I=>n.assign(f,!1).if((0,Ve._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ve._)`${I}.errors`),()=>n.throw(I))),P}function k(){let P=(0,Ve._)`${p}.errors`;return n.assign(P,null),R(Ve.nil),P}function R(P=e.async?(0,Ve._)`await `:Ve.nil){let I=l.opts.passContext?kr.default.this:kr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(f,(0,Ve._)`${P}${(0,aR.callValidateCode)(t,p,I,D)}`,e.modifying)}function $(P){var I;n.if((0,Ve.not)((I=e.valid)!==null&&I!==void 0?I:f),P)}}Et.funcKeywordCode=dR;function Lf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function uR(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(kr.default.vErrors,(0,Ve._)`${kr.default.vErrors} === null ? ${e} : ${kr.default.vErrors}.concat(${e})`).assign(kr.default.errors,(0,Ve._)`${kr.default.vErrors}.length`),(0,lR.extendErrors)(t)},()=>t.error())}function pR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function jf(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function hR(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Et.validSchemaType=hR;function mR({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Et.validateKeywordUsage=mR});var Mf=U(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var Pt=re(),Uf=ue();function fR(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}${(0,Pt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Uf.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}or.getSubschema=fR;function gR(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:d,dataPathArr:p,opts:f}=e,_=a.let("data",(0,Pt._)`${e.data}${(0,Pt.getProperty)(r)}`,!0);l(_),t.errorPath=(0,Pt.str)`${d}${(0,Uf.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Pt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let d=o instanceof Pt.Name?o:a.let("data",o,!0);l(d),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}or.extendSubschemaData=gR;function yR(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}or.extendSubschemaMode=yR});var wc=U((WD,qf)=>{"use strict";qf.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Bf=U((JD,zf)=>{"use strict";var sr=zf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Zs(e,n,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 Zs(t,e,r,n,o,s,i,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,d);for(var p in n){var f=n[p];if(Array.isArray(f)){if(p in sr.arrayKeywords)for(var _=0;_<f.length;_++)Zs(t,e,r,f[_],o+"/"+p+"/"+_,s,o,p,n,_)}else if(p in sr.propsKeywords){if(f&&typeof f=="object")for(var y in f)Zs(t,e,r,f[y],o+"/"+p+"/"+bR(y),s,o,p,n,y)}else(p in sr.keywords||t.allKeys&&!(p in sr.skipKeywords))&&Zs(t,e,r,f,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,d)}}function bR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var no=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var wR=ue(),vR=wc(),_R=Bf(),SR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!vc(t):e?Ff(t)<=e:!1}Ze.inlineRef=kR;var TR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vc(t){for(let e in t){if(TR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(vc)||typeof r=="object"&&vc(r))return!0}return!1}function Ff(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!SR.has(r)&&(typeof t[r]=="object"&&(0,wR.eachItem)(t[r],n=>e+=Ff(n)),e===1/0))return 1/0}return e}function Hf(t,e="",r){r!==!1&&(e=rn(e));let n=t.parse(e);return Kf(t,n)}Ze.getFullPath=Hf;function Kf(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=Kf;var xR=/#\/?$/;function rn(t){return t?t.replace(xR,""):""}Ze.normalizeId=rn;function RR(t,e,r){return r=rn(r),t.resolve(e,r)}Ze.resolveUrl=RR;var $R=/^[a-z_][-a-z0-9._]*$/i;function ER(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=rn(t[r]||e),s={"":o},i=Hf(n,o,!1),a={},l=new Set;return _R(t,{allKeys:!0},(f,_,y,k)=>{if(k===void 0)return;let R=i+_,$=s[k];typeof f[r]=="string"&&($=P.call(this,f[r])),I.call(this,f.$anchor),I.call(this,f.$dynamicAnchor),s[_]=$;function P(D){let Y=this.opts.uriResolver.resolve;if(D=rn($?Y($,D):D),l.has(D))throw p(D);l.add(D);let F=this.refs[D];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?d(f,F.schema,D):D!==rn(R)&&(D[0]==="#"?(d(f,a[D],D),a[D]=f):this.refs[D]=R),D}function I(D){if(typeof D=="string"){if(!$R.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function d(f,_,y){if(_!==void 0&&!vR(f,_))throw p(y)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Ze.getSchemaRefs=ER});var io=U(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var Yf=xf(),Vf=ro(),Sc=pc(),Qs=ro(),PR=If(),so=Df(),_c=Mf(),B=re(),ee=Mt(),AR=no(),qt=ue(),oo=to();function CR(t){if(Qf(t)&&(eg(t),Zf(t))){NR(t);return}Xf(t,()=>(0,Yf.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=CR;function Xf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,B._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${Gf(r,o)}`),OR(t,o),t.code(s)}):t.func(e,(0,B._)`${ee.default.data}, ${IR(o)}`,n.$async,()=>t.code(Gf(r,o)).code(s))}function IR(t){return(0,B._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,B._)`, ${ee.default.dynamicAnchors}={}`:B.nil}}={}`}function OR(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,B._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,B._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,B._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,B._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,B._)`""`),t.var(ee.default.parentData,(0,B._)`undefined`),t.var(ee.default.parentDataProperty,(0,B._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,B._)`{}`)})}function NR(t){let{schema:e,opts:r,gen:n}=t;Xf(t,()=>{r.$comment&&e.$comment&&rg(t),MR(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&LR(t),tg(t),BR(t)})}function LR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.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 Gf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function jR(t,e){if(Qf(t)&&(eg(t),Zf(t))){DR(t,e);return}(0,Yf.boolOrEmptySchema)(t,e)}function Zf({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Qf(t){return typeof t.schema!="boolean"}function DR(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&rg(t),qR(t),zR(t);let s=n.const("_errs",ee.default.errors);tg(t,s),n.var(e,(0,B._)`${s} === ${ee.default.errors}`)}function eg(t){(0,qt.checkUnknownRules)(t),UR(t)}function tg(t,e){if(t.opts.jtd)return Wf(t,[],!1,e);let r=(0,Vf.getSchemaTypes)(t.schema),n=(0,Vf.coerceAndCheckDataType)(t,r);Wf(t,r,!n,e)}function UR(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function MR(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,qt.checkStrictMode)(t,"default is ignored in the schema root")}function qR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,AR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function rg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,B._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function BR(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,B._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,B._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&FR(t),e.return((0,B._)`${ee.default.errors} === 0`))}function FR({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function Wf(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:d}=t,{RULES:p}=d;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,qt.schemaHasRulesButRef)(s,p))){o.block(()=>og(t,"$ref",p.all.$ref.definition));return}l.jtd||HR(t,e),o.block(()=>{for(let _ of p.rules)f(_);f(p.post)});function f(_){(0,Sc.shouldUseGroup)(s,_)&&(_.type?(o.if((0,Qs.checkDataType)(_.type,i,l.strictNumbers)),Jf(t,_),e.length===1&&e[0]===_.type&&r&&(o.else(),(0,Qs.reportTypeError)(t)),o.endIf()):Jf(t,_),a||o.if((0,B._)`${ee.default.errors} === ${n||0}`))}}function Jf(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,PR.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sc.shouldUseRule)(n,s)&&og(t,s.keyword,s.definition,e.type)})}function HR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(KR(t,e),t.opts.allowUnionTypes||VR(t,e),GR(t,t.dataTypes))}function KR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{ng(t.dataTypes,r)||kc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),JR(t,e)}}function VR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&kc(t,"use allowUnionTypes to allow union type keyword")}function GR(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>WR(e,i))&&kc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ng(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JR(t,e){let r=[];for(let n of t.dataTypes)ng(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function kc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,qt.checkStrictMode)(t,e,t.opts.strictTypes)}var ei=class{constructor(e,r,n){if((0,so.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,qt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",sg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,so.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,r,n){this.failResult((0,B.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,B.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,B._)`${r} !== undefined && (${(0,B.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?oo.reportExtraError:oo.reportError)(this,this.def.error,r)}$dataError(){(0,oo.reportError)(this,this.def.$dataError||oo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,B.or)((0,B._)`${o} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,B._)`${(0,Qs.checkDataTypes)(l,r,s.opts.strictNumbers,Qs.DataType.Wrong)}`}return B.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,B._)`!${l}(${r})`}return B.nil}}subschema(e,r){let n=(0,_c.getSubschema)(this.it,e);(0,_c.extendSubschemaData)(n,this.it,e),(0,_c.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return jR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=qt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=qt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,B.Name)),!0}};ir.KeywordCxt=ei;function og(t,e,r,n){let o=new ei(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,so.funcKeywordCode)(o,r):"macro"in r?(0,so.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,so.funcKeywordCode)(o,r)}var YR=/^\/(?:[^~]|~0|~1)*$/,XR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!YR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let d=XR.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+d[1];if(o=d[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let d of a)d&&(s=(0,B._)`${s}${(0,B.getProperty)((0,qt.unescapeJsonPointer)(d))}`,i=(0,B._)`${i} && ${s}`);return i;function l(d,p){return`Cannot access ${d} ${p} levels up, current level is ${e}`}}ir.getData=sg});var ti=U(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Tc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xc.default=Tc});var ao=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Rc=no(),$c=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Rc.resolveUrl)(e,r,n),this.missingSchema=(0,Rc.normalizeId)((0,Rc.getFullPath)(e,this.missingRef))}};Ec.default=$c});var ni=U(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.resolveSchema=ut.getCompilingSchema=ut.resolveRef=ut.compileSchema=ut.SchemaEnv=void 0;var vt=re(),ZR=ti(),Tr=Mt(),_t=no(),ig=ue(),QR=io(),nn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,_t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ut.SchemaEnv=nn;function Ac(t){let e=ag.call(this,t);if(e)return e;let r=(0,_t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:ZR.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:Tr.default.data,parentData:Tr.default.parentData,parentDataProperty:Tr.default.parentDataProperty,dataNames:[Tr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,QR.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(Tr.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${Tr.default.self}`,`${Tr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=d;y.evaluated={props:k instanceof vt.Name?void 0:k,items:R instanceof vt.Name?void 0:R,dynamicProps:k instanceof vt.Name,dynamicItems:R instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return t.validate=y,t}catch(f){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),f}finally{this._compilations.delete(t)}}ut.compileSchema=Ac;function e$(t,e,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=n$.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new nn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=t$.call(this,s)}ut.resolveRef=e$;function t$(t){return(0,_t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ac.call(this,t)}function ag(t){for(let e of this._compilations)if(r$(e,t))return e}ut.getCompilingSchema=ag;function r$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function n$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ri.call(this,t,e)}function ri(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Pc.call(this,r,t);let s=(0,_t.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ri.call(this,t,i);return typeof a?.schema!="object"?void 0:Pc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ac.call(this,i),s===(0,_t.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,d)),new nn({schema:a,schemaId:l,root:t,baseId:o})}return Pc.call(this,r,i)}}ut.resolveSchema=ri;var o$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Pc(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,ig.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r=="object"&&r[this.opts.schemaId];!o$.has(a)&&d&&(e=(0,_t.resolveUrl)(this.opts.uriResolver,e,d))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ig.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ri.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new nn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lg=U((t1,s$)=>{s$.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 Oc=U((r1,mg)=>{"use strict";var i$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dg=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),Cc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ug=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ic(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var l$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function cg(t){return t.length=0,!0}function c$(t,e,r){if(t.length){let n=Ic(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function d$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=c$;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(d==="%"){if(!a(o,n,r))break;a=cg}else{o.push(d);continue}}return o.length&&(a===cg?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ic(o))),r.address=n.join(""),r}function pg(t){if(u$(t,":")<2)return{host:t,isIPV6:!1};let e=d$(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function u$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function p$(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var h$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},m$=/[@/?#:]/g,f$=/[@/?#]/g;function hg(t,e){let r=e?f$:m$;return r.lastIndex=0,t.replace(r,n=>h$[n])}function g$(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Cc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&ug(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function y$(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Cc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ug(s)?e+=s:e+="%"+o,r+=2;continue}}a$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function b$(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Cc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function w$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!dg(r)){let n=pg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=hg(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}mg.exports={nonSimpleDomain:l$,recomposeAuthority:w$,reescapeHostDelimiters:hg,normalizePercentEncoding:g$,normalizePathEncoding:y$,escapePreservingEscapes:b$,removeDotSegments:p$,isIPv4:dg,isUUID:i$,normalizeIPv6:pg,stringArrayToHexStripped:Ic}});var wg=U((n1,bg)=>{"use strict";var{isUUID:v$}=Oc(),_$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,S$=["http","https","ws","wss","urn","urn:uuid"];function k$(t){return S$.indexOf(t)!==-1}function Nc(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 fg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function gg(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 T$(t){return t.secure=Nc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function x$(t){if((t.port===(Nc(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function R$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(_$);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Lc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function $$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Lc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function E$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!v$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function P$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var yg={scheme:"http",domainHost:!0,parse:fg,serialize:gg},A$={scheme:"https",domainHost:yg.domainHost,parse:fg,serialize:gg},oi={scheme:"ws",domainHost:!0,parse:T$,serialize:x$},C$={scheme:"wss",domainHost:oi.domainHost,parse:oi.parse,serialize:oi.serialize},I$={scheme:"urn",parse:R$,serialize:$$,skipNormalize:!0},O$={scheme:"urn:uuid",parse:E$,serialize:P$,skipNormalize:!0},si={http:yg,https:A$,ws:oi,wss:C$,urn:I$,"urn:uuid":O$};Object.setPrototypeOf(si,null);function Lc(t){return t&&(si[t]||si[t.toLowerCase()])||void 0}bg.exports={wsIsSecure:Nc,SCHEMES:si,isValidSchemeName:k$,getSchemeHandler:Lc}});var Tg=U((o1,li)=>{"use strict";var{normalizeIPv6:N$,removeDotSegments:lo,recomposeAuthority:L$,normalizePercentEncoding:j$,normalizePathEncoding:D$,escapePreservingEscapes:U$,reescapeHostDelimiters:M$,isIPv4:q$,nonSimpleDomain:z$}=Oc(),{SCHEMES:B$,getSchemeHandler:_g}=wg();function F$(t,e){return typeof t=="string"?t=Y$(t,e):typeof t=="object"&&(t=ai(xr(t,e),e)),t}function H$(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=ii(t,n),{parsed:i,malformedAuthorityOrPort:a}=ii(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=Sg(o,i,n,!0);return n.skipEscape=!0,xr(l,n)}function Sg(t,e,r,n){let o={};return n||(t=ai(xr(t,r),r),e=ai(xr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=lo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=lo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=lo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=lo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function K$(t,e,r){let n=vg(t,r),o=vg(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function xr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=_g(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=j$(r.path):(r.path=U$(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=L$(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=lo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var V$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,G$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,W$=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function J$(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 ii(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(G$);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(W$);if(a!==null){let d=a[1],p=d.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):d.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(V$);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let d=J$(n,l);if(d!==void 0&&(n.error=n.error||d,o=!0),n.host)if(q$(n.host)===!1){let _=N$(n.host);n.host=_.host.toLowerCase(),s=_.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=_g(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&z$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(f){n.error=n.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=M$(unescape(n.host),s))),n.path&&(n.path=D$(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function ai(t,e){return ii(t,e).parsed}function Y$(t,e){return kg(t,e).normalized}function kg(t,e){let{parsed:r,malformedAuthorityOrPort:n}=ii(t,e);return{normalized:n?t:xr(r,e),malformedAuthorityOrPort:n}}function vg(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=kg(t,e);return n?void 0:r}if(typeof t=="object")return xr(t,e)}var jc={SCHEMES:B$,normalize:F$,resolve:H$,resolveComponent:Sg,equal:K$,serialize:xr,parse:ai};li.exports=jc;li.exports.default=jc;li.exports.fastUri=jc});var Rg=U(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var xg=Tg();xg.code='require("ajv/dist/runtime/uri").default';Dc.default=xg});var Ng=U(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var X$=io();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return X$.KeywordCxt}});var on=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return on.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return on.CodeGen}});var Z$=ti(),Cg=ao(),Q$=uc(),co=ni(),eE=re(),uo=no(),ci=ro(),Mc=ue(),$g=lg(),tE=Rg(),Ig=(t,e)=>new RegExp(t,e);Ig.code="new RegExp";var rE=["removeAdditional","useDefaults","coerceTypes"],nE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oE={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."},sE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Eg=200;function iE(t){var e,r,n,o,s,i,a,l,d,p,f,_,y,k,R,$,P,I,D,Y,F,Oe,Ce,Bt,Ft;let Ht=t.strict,mn=(e=t.code)===null||e===void 0?void 0:e.optimize,dr=mn===!0||mn===void 0?1:mn||0,Tt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ig,Li=(o=t.uriResolver)!==null&&o!==void 0?o:tE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ht)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ht)!==null&&l!==void 0?l:!0,strictTypes:(p=(d=t.strictTypes)!==null&&d!==void 0?d:Ht)!==null&&p!==void 0?p:"log",strictTuples:(_=(f=t.strictTuples)!==null&&f!==void 0?f:Ht)!==null&&_!==void 0?_:"log",strictRequired:(k=(y=t.strictRequired)!==null&&y!==void 0?y:Ht)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:dr,regExp:Tt}:{optimize:dr,regExp:Tt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Eg,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Eg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(F=t.addUsedSchema)!==null&&F!==void 0?F:!0,validateSchema:(Oe=t.validateSchema)!==null&&Oe!==void 0?Oe:!0,validateFormats:(Ce=t.validateFormats)!==null&&Ce!==void 0?Ce:!0,unicodeRegExp:(Bt=t.unicodeRegExp)!==null&&Bt!==void 0?Bt:!0,int32range:(Ft=t.int32range)!==null&&Ft!==void 0?Ft:!0,uriResolver:Li}}var po=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,...iE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new eE.ValueScope({scope:{},prefixes:nE,es5:r,lines:n}),this.logger=pE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Q$.getRules)(),Pg.call(this,oE,e,"NOT SUPPORTED"),Pg.call(this,sE,e,"DEPRECATED","warn"),this._metaOpts=dE.call(this),e.formats&&lE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&cE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),aE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=$g;n==="id"&&(o={...$g},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(p,f){await s.call(this,p.$schema);let _=this._addSchema(p,f);return _.validate||i.call(this,_)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(f){if(!(f instanceof Cg.default))throw f;return a.call(this,f),await l.call(this,f.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:f}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${f} cannot be resolved`)}async function l(p){let f=await d.call(this,p);this.refs[p]||await s.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,r)}async function d(p){let f=this._loading[p];if(f)return f;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,uo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Ag.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new co.SchemaEnv({schema:{},schemaId:n});if(r=co.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Ag.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,uo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(mE.call(this,n,r),!r)return(0,Mc.eachItem)(n,s=>Uc.call(this,s)),this;gE.call(this,r);let o={...r,type:(0,ci.getJSONTypes)(r.type),schemaType:(0,ci.getJSONTypes)(r.schemaType)};return(0,Mc.eachItem)(n,o.type.length===0?s=>Uc.call(this,s,o):s=>o.type.forEach(i=>Uc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:d}=l.definition,p=i[a];d&&p&&(i[a]=Og(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,uo.normalizeId)(i||n);let d=uo.getSchemaRefs.call(this,e,n);return l=new co.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&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):co.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{co.compileSchema.call(this,e)}finally{this.opts=r}}};po.ValidationError=Z$.default;po.MissingRefError=Cg.default;Ue.default=po;function Pg(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Ag(t){return t=(0,uo.normalizeId)(t),this.schemas[t]||this.refs[t]}function aE(){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 lE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function cE(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function dE(){let t={...this.opts};for(let e of rE)delete t[e];return t}var uE={log(){},warn(){},error(){}};function pE(t){if(t===!1)return uE;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 hE=/^[a-z_$][a-z0-9_$:-]*$/i;function mE(t,e){let{RULES:r}=this;if((0,Mc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hE.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Uc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ci.getJSONTypes)(e.type),schemaType:(0,ci.getJSONTypes)(e.schemaType)}};e.before?fE.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function fE(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function gE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Og(e)),t.validateSchema=this.compile(e,!0))}var yE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Og(t){return{anyOf:[t,yE]}}});var Lg=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var bE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qc.default=bE});var Mg=U(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.callRef=Rr.getValidate=void 0;var wE=ao(),jg=dt(),Qe=re(),sn=Mt(),Dg=ni(),di=ue(),vE={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:d}=s;if((r==="#"||r==="#/")&&o===d.baseId)return f();let p=Dg.resolveRef.call(l,d,o,r);if(p===void 0)throw new wE.default(n.opts.uriResolver,o,r);if(p instanceof Dg.SchemaEnv)return _(p);return y(p);function f(){if(s===d)return ui(t,i,s,s.$async);let k=e.scopeValue("root",{ref:d});return ui(t,(0,Qe._)`${k}.validate`,d,d.$async)}function _(k){let R=Ug(t,k);ui(t,R,k,k.$async)}function y(k){let R=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Qe.stringify)(k)}:{ref:k}),$=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:R,errSchemaPath:r},$);t.mergeEvaluated(P),t.ok($)}}};function Ug(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Rr.getValidate=Ug;function ui(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,d=l.passContext?sn.default.this:Qe.nil;n?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,jg.callValidateCode)(t,e,d)}`),y(e),i||o.assign(k,!0)},R=>{o.if((0,Qe._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),_(R),i||o.assign(k,!1)}),t.ok(k)}function f(){t.result((0,jg.callValidateCode)(t,e,d),()=>y(e),()=>_(e))}function _(k){let R=(0,Qe._)`${k}.errors`;o.assign(sn.default.vErrors,(0,Qe._)`${sn.default.vErrors} === null ? ${R} : ${sn.default.vErrors}.concat(${R})`),o.assign(sn.default.errors,(0,Qe._)`${sn.default.vErrors}.length`)}function y(k){var R;if(!s.opts.unevaluated)return;let $=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=di.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,Qe._)`${k}.evaluated.props`);s.props=di.mergeEvaluated.props(o,P,s.props,Qe.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=di.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,Qe._)`${k}.evaluated.items`);s.items=di.mergeEvaluated.items(o,P,s.items,Qe.Name)}}}Rr.callRef=ui;Rr.default=vE});var qg=U(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var _E=Lg(),SE=Mg(),kE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_E.default,SE.default];zc.default=kE});var zg=U(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var pi=re(),ar=pi.operators,hi={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},TE={message:({keyword:t,schemaCode:e})=>(0,pi.str)`must be ${hi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pi._)`{comparison: ${hi[t].okStr}, limit: ${e}}`},xE={keyword:Object.keys(hi),type:"number",schemaType:"number",$data:!0,error:TE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,pi._)`${r} ${hi[e].fail} ${n} || isNaN(${r})`)}};Bc.default=xE});var Bg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var ho=re(),RE={message:({schemaCode:t})=>(0,ho.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ho._)`{multipleOf: ${t}}`},$E={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:RE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ho._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ho._)`${i} !== parseInt(${i})`;t.fail$data((0,ho._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fc.default=$E});var Hg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});function Fg(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Hc.default=Fg;Fg.code='require("ajv/dist/runtime/ucs2length").default'});var Kg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var $r=re(),EE=ue(),PE=Hg(),AE={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},CE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:AE,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$r.operators.GT:$r.operators.LT,i=o.opts.unicode===!1?(0,$r._)`${r}.length`:(0,$r._)`${(0,EE.useFunc)(t.gen,PE.default)}(${r})`;t.fail$data((0,$r._)`${i} ${s} ${n}`)}};Kc.default=CE});var Vg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var IE=dt(),OE=ue(),an=re(),NE={message:({schemaCode:t})=>(0,an.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,an._)`{pattern: ${t}}`},LE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NE,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,d=l.code==="new RegExp"?(0,an._)`new RegExp`:(0,OE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,an._)`${d}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,an._)`!${p}`)}else{let l=(0,IE.usePattern)(t,o);t.fail$data((0,an._)`!${l}.test(${r})`)}}};Vc.default=LE});var Gg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var mo=re(),jE={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,mo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,mo._)`{limit: ${t}}`},DE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?mo.operators.GT:mo.operators.LT;t.fail$data((0,mo._)`Object.keys(${r}).length ${o} ${n}`)}};Gc.default=DE});var Wg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var fo=dt(),go=re(),UE=ue(),ME={message:({params:{missingProperty:t}})=>(0,go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,go._)`{missingProperty: ${t}}`},qE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ME,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?d():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:k}=t.it;for(let R of r)if(y?.[R]===void 0&&!k.has(R)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,UE.checkStrictMode)(i,P,i.opts.strictRequired)}}function d(){if(l||s)t.block$data(go.nil,f);else for(let y of r)(0,fo.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let k=e.let("valid",!0);t.block$data(k,()=>_(y,k)),t.ok(k)}else e.if((0,fo.checkMissingProp)(t,r,y)),(0,fo.reportMissingProp)(t,y),e.else()}function f(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,fo.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function _(y,k){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(k,(0,fo.propertyInData)(e,o,y,a.ownProperties)),e.if((0,go.not)(k),()=>{t.error(),e.break()})},go.nil)}}};Wc.default=qE});var Jg=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var yo=re(),zE={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,yo._)`{limit: ${t}}`},BE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?yo.operators.GT:yo.operators.LT;t.fail$data((0,yo._)`${r}.length ${o} ${n}`)}};Jc.default=BE});var mi=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Yg=wc();Yg.code='require("ajv/dist/runtime/equal").default';Yc.default=Yg});var Xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Xc=ro(),Me=re(),FE=ue(),HE=mi(),KE={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},VE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:KE,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),d=s.items?(0,Xc.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Me._)`${r}.length`),R=e.let("j");t.setParams({i:k,j:R}),e.assign(l,!0),e.if((0,Me._)`${k} > 1`,()=>(f()?_:y)(k,R))}function f(){return d.length>0&&!d.some(k=>k==="object"||k==="array")}function _(k,R){let $=e.name("item"),P=(0,Xc.checkDataTypes)(d,$,a.opts.strictNumbers,Xc.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${k}--;`,()=>{e.let($,(0,Me._)`${r}[${k}]`),e.if(P,(0,Me._)`continue`),d.length>1&&e.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),e.if((0,Me._)`typeof ${I}[${$}] == "number"`,()=>{e.assign(R,(0,Me._)`${I}[${$}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${$}] = ${k}`)})}function y(k,R){let $=(0,FE.useFunc)(e,HE.default),P=e.name("outer");e.label(P).for((0,Me._)`;${k}--;`,()=>e.for((0,Me._)`${R} = ${k}; ${R}--;`,()=>e.if((0,Me._)`${$}(${r}[${k}], ${r}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Zc.default=VE});var Zg=U(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Qc=re(),GE=ue(),WE=mi(),JE={message:"must be equal to constant",params:({schemaCode:t})=>(0,Qc._)`{allowedValue: ${t}}`},YE={keyword:"const",$data:!0,error:JE,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Qc._)`!${(0,GE.useFunc)(e,WE.default)}(${r}, ${o})`):t.fail((0,Qc._)`${s} !== ${r}`)}};ed.default=YE});var Qg=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var bo=re(),XE=ue(),ZE=mi(),QE={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,bo._)`{allowedValues: ${t}}`},e0={keyword:"enum",schemaType:"array",$data:!0,error:QE,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,l,d=()=>l??(l=(0,XE.useFunc)(e,ZE.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,bo.or)(...o.map((k,R)=>_(y,R)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,bo._)`${d()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function _(y,k){let R=o[k];return typeof R=="object"&&R!==null?(0,bo._)`${d()}(${r}, ${y}[${k}])`:(0,bo._)`${r} === ${R}`}}};td.default=e0});var ey=U(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var t0=zg(),r0=Bg(),n0=Kg(),o0=Vg(),s0=Gg(),i0=Wg(),a0=Jg(),l0=Xg(),c0=Zg(),d0=Qg(),u0=[t0.default,r0.default,n0.default,o0.default,s0.default,i0.default,a0.default,l0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c0.default,d0.default];rd.default=u0});var od=U(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Er=re(),nd=ue(),p0={message:({params:{len:t}})=>(0,Er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Er._)`{limit: ${t}}`},h0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:p0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,nd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ty(t,n)}};function ty(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,nd.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,Er._)`${a} <= ${e.length}`);r.if((0,Er.not)(d),()=>l(d)),t.ok(d)}function l(d){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:nd.Type.Num},d),i.allErrors||r.if((0,Er.not)(d),()=>r.break())})}}wo.validateAdditionalItems=ty;wo.default=h0});var sd=U(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.validateTuple=void 0;var ry=re(),fi=ue(),m0=dt(),f0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ny(t,"additionalItems",e);r.items=!0,!(0,fi.alwaysValidSchema)(r,e)&&t.ok((0,m0.validateArray)(t))}};function ny(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=fi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),d=n.const("len",(0,ry._)`${s}.length`);r.forEach((f,_)=>{(0,fi.alwaysValidSchema)(a,f)||(n.if((0,ry._)`${d} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(f){let{opts:_,errSchemaPath:y}=a,k=r.length,R=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(_.strictTuples&&!R){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,fi.checkStrictMode)(a,$,_.strictTuples)}}}vo.validateTuple=ny;vo.default=f0});var oy=U(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var g0=sd(),y0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,g0.validateTuple)(t,"items")};id.default=y0});var iy=U(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sy=re(),b0=ue(),w0=dt(),v0=od(),_0={message:({params:{len:t}})=>(0,sy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sy._)`{limit: ${t}}`},S0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,b0.alwaysValidSchema)(n,e)&&(o?(0,v0.validateAdditionalItems)(t,o):t.ok((0,w0.validateArray)(t)))}};ad.default=S0});var ay=U(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var pt=re(),gi=ue(),k0={message:({params:{min:t,max:e}})=>e===void 0?(0,pt.str)`must contain at least ${t} valid item(s)`:(0,pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,pt._)`{minContains: ${t}}`:(0,pt._)`{minContains: ${t}, maxContains: ${e}}`},T0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:k0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:d}=n;s.opts.next?(i=l===void 0?1:l,a=d):i=1;let p=e.const("len",(0,pt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gi.alwaysValidSchema)(s,r)){let R=(0,pt._)`${p} >= ${i}`;a!==void 0&&(R=(0,pt._)`${R} && ${p} <= ${a}`),t.pass(R);return}s.items=!0;let f=e.name("valid");a===void 0&&i===1?y(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,pt._)`${o}.length > 0`,_)):(e.let(f,!1),_()),t.result(f,()=>t.reset());function _(){let R=e.name("_valid"),$=e.let("count",0);y(R,()=>e.if(R,()=>k($)))}function y(R,$){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:gi.Type.Num,compositeRule:!0},R),$()})}function k(R){e.code((0,pt._)`${R}++`),a===void 0?e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,pt._)`${R} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(f,!0)))}}};ld.default=T0});var dy=U(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.validateSchemaDeps=At.validatePropertyDeps=At.error=void 0;var cd=re(),x0=ue(),_o=dt();At.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,cd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,cd._)`{property: ${t},
|
|
2307
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function lR({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function gc(t,e,r,n=en.Correct){let o=n===en.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===en.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Be.checkDataType=gc;function yc(t,e,r,n){if(t.length===1)return gc(t[0],e,r,n);let o,s=(0,Uf.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,gc(i,e,r,n));return o}Be.checkDataTypes=yc;var cR={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function bc(t){let e=dR(t);(0,nR.reportError)(e,cR)}Be.reportTypeError=bc;function dR(t){let{gen:e,data:r,schema:n}=t,o=(0,Uf.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Bf=U(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.assignDefaults=void 0;var tn=re(),uR=ue();function pR(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)zf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>zf(t,s,o.default))}Qs.assignDefaults=pR;function zf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,tn._)`${s}${(0,tn.getProperty)(e)}`;if(o){(0,uR.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,tn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,tn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,tn._)`${a} = ${(0,tn.stringify)(r)}`)}});var dt=U(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.validateUnion=we.validateArray=we.usePattern=we.callValidateCode=we.schemaProperties=we.allSchemaProperties=we.noPropertyInData=we.propertyInData=we.isOwnProperty=we.hasPropFunc=we.reportMissingProp=we.checkMissingProp=we.checkReportMissingProp=void 0;var Se=re(),wc=ue(),nr=Mt(),hR=ue();function mR(t,e){let{gen:r,data:n,it:o}=t;r.if(_c(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Se._)`${e}`},!0),t.error()})}we.checkReportMissingProp=mR;function fR({gen:t,data:e,it:{opts:r}},n,o){return(0,Se.or)(...n.map(s=>(0,Se.and)(_c(t,e,s,r.ownProperties),(0,Se._)`${o} = ${s}`)))}we.checkMissingProp=fR;function gR(t,e){t.setParams({missingProperty:e},!0),t.error()}we.reportMissingProp=gR;function Ff(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Se._)`Object.prototype.hasOwnProperty`})}we.hasPropFunc=Ff;function vc(t,e,r){return(0,Se._)`${Ff(t)}.call(${e}, ${r})`}we.isOwnProperty=vc;function yR(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} !== undefined`;return n?(0,Se._)`${o} && ${vc(t,e,r)}`:o}we.propertyInData=yR;function _c(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} === undefined`;return n?(0,Se.or)(o,(0,Se.not)(vc(t,e,r))):o}we.noPropertyInData=_c;function Hf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}we.allSchemaProperties=Hf;function bR(t,e){return Hf(e).filter(r=>!(0,wc.alwaysValidSchema)(t,e[r]))}we.schemaProperties=bR;function wR({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,d){let p=d?(0,Se._)`${t}, ${e}, ${n}${o}`:e,g=[[nr.default.instancePath,(0,Se.strConcat)(nr.default.instancePath,s)],[nr.default.parentData,i.parentData],[nr.default.parentDataProperty,i.parentDataProperty],[nr.default.rootData,nr.default.rootData]];i.opts.dynamicRef&&g.push([nr.default.dynamicAnchors,nr.default.dynamicAnchors]);let S=(0,Se._)`${p}, ${r.object(...g)}`;return l!==Se.nil?(0,Se._)`${a}.call(${l}, ${S})`:(0,Se._)`${a}(${S})`}we.callValidateCode=wR;var vR=(0,Se._)`new RegExp`;function _R({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Se._)`${o.code==="new RegExp"?vR:(0,hR.useFunc)(t,o)}(${r}, ${n})`})}we.usePattern=_R;function SR(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let l=e.const("len",(0,Se._)`${r}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:n,dataProp:d,dataPropType:wc.Type.Num},s),e.if((0,Se.not)(s),a)})}}we.validateArray=SR;function kR(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,wc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,d)=>{let p=t.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,Se._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,Se.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}we.validateUnion=kR});var Gf=U(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateKeywordUsage=Et.validSchemaType=Et.funcKeywordCode=Et.macroKeywordCode=void 0;var Ve=re(),kr=Mt(),TR=dt(),xR=to();function RR(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=Vf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}Et.macroKeywordCode=RR;function $R(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;PR(l,e);let d=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=Vf(n,o,d),g=n.let("valid");t.block$data(g,S),t.ok((r=e.valid)!==null&&r!==void 0?r:g);function S(){if(e.errors===!1)R(),e.modifying&&Kf(t),$(()=>t.error());else{let P=e.async?y():k();e.modifying&&Kf(t),$(()=>ER(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ve._)`await `),I=>n.assign(g,!1).if((0,Ve._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ve._)`${I}.errors`),()=>n.throw(I))),P}function k(){let P=(0,Ve._)`${p}.errors`;return n.assign(P,null),R(Ve.nil),P}function R(P=e.async?(0,Ve._)`await `:Ve.nil){let I=l.opts.passContext?kr.default.this:kr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(g,(0,Ve._)`${P}${(0,TR.callValidateCode)(t,p,I,D)}`,e.modifying)}function $(P){var I;n.if((0,Ve.not)((I=e.valid)!==null&&I!==void 0?I:g),P)}}Et.funcKeywordCode=$R;function Kf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function ER(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(kr.default.vErrors,(0,Ve._)`${kr.default.vErrors} === null ? ${e} : ${kr.default.vErrors}.concat(${e})`).assign(kr.default.errors,(0,Ve._)`${kr.default.vErrors}.length`),(0,xR.extendErrors)(t)},()=>t.error())}function PR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Vf(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ve.stringify)(r)})}function AR(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Et.validSchemaType=AR;function CR({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Et.validateKeywordUsage=CR});var Jf=U(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var Pt=re(),Wf=ue();function IR(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Pt._)`${t.schemaPath}${(0,Pt.getProperty)(e)}${(0,Pt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Wf.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}or.getSubschema=IR;function OR(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:d,dataPathArr:p,opts:g}=e,S=a.let("data",(0,Pt._)`${e.data}${(0,Pt.getProperty)(r)}`,!0);l(S),t.errorPath=(0,Pt.str)`${d}${(0,Wf.getErrorPath)(r,n,g.jsPropertySyntax)}`,t.parentDataProperty=(0,Pt._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let d=o instanceof Pt.Name?o:a.let("data",o,!0);l(d),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}or.extendSubschemaData=OR;function NR(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}or.extendSubschemaMode=NR});var Sc=U((p1,Yf)=>{"use strict";Yf.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Zf=U((h1,Xf)=>{"use strict";var sr=Xf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ei(e,n,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 ei(t,e,r,n,o,s,i,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,d);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in sr.arrayKeywords)for(var S=0;S<g.length;S++)ei(t,e,r,g[S],o+"/"+p+"/"+S,s,o,p,n,S)}else if(p in sr.propsKeywords){if(g&&typeof g=="object")for(var y in g)ei(t,e,r,g[y],o+"/"+p+"/"+LR(y),s,o,p,n,y)}else(p in sr.keywords||t.allKeys&&!(p in sr.skipKeywords))&&ei(t,e,r,g,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,d)}}function LR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var no=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var jR=ue(),DR=Sc(),UR=Zf(),MR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!kc(t):e?Qf(t)<=e:!1}Ze.inlineRef=qR;var zR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function kc(t){for(let e in t){if(zR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(kc)||typeof r=="object"&&kc(r))return!0}return!1}function Qf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!MR.has(r)&&(typeof t[r]=="object"&&(0,jR.eachItem)(t[r],n=>e+=Qf(n)),e===1/0))return 1/0}return e}function eg(t,e="",r){r!==!1&&(e=rn(e));let n=t.parse(e);return tg(t,n)}Ze.getFullPath=eg;function tg(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=tg;var BR=/#\/?$/;function rn(t){return t?t.replace(BR,""):""}Ze.normalizeId=rn;function FR(t,e,r){return r=rn(r),t.resolve(e,r)}Ze.resolveUrl=FR;var HR=/^[a-z_][-a-z0-9._]*$/i;function KR(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=rn(t[r]||e),s={"":o},i=eg(n,o,!1),a={},l=new Set;return UR(t,{allKeys:!0},(g,S,y,k)=>{if(k===void 0)return;let R=i+S,$=s[k];typeof g[r]=="string"&&($=P.call(this,g[r])),I.call(this,g.$anchor),I.call(this,g.$dynamicAnchor),s[S]=$;function P(D){let Y=this.opts.uriResolver.resolve;if(D=rn($?Y($,D):D),l.has(D))throw p(D);l.add(D);let H=this.refs[D];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?d(g,H.schema,D):D!==rn(R)&&(D[0]==="#"?(d(g,a[D],D),a[D]=g):this.refs[D]=R),D}function I(D){if(typeof D=="string"){if(!HR.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function d(g,S,y){if(S!==void 0&&!DR(g,S))throw p(y)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}Ze.getSchemaRefs=KR});var io=U(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var ig=Lf(),rg=ro(),xc=fc(),ti=ro(),VR=Bf(),so=Gf(),Tc=Jf(),F=re(),ee=Mt(),GR=no(),qt=ue(),oo=to();function WR(t){if(cg(t)&&(dg(t),lg(t))){XR(t);return}ag(t,()=>(0,ig.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=WR;function ag({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,F._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,F._)`"use strict"; ${ng(r,o)}`),YR(t,o),t.code(s)}):t.func(e,(0,F._)`${ee.default.data}, ${JR(o)}`,n.$async,()=>t.code(ng(r,o)).code(s))}function JR(t){return(0,F._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,F._)`, ${ee.default.dynamicAnchors}={}`:F.nil}}={}`}function YR(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,F._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,F._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,F._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,F._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,F._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,F._)`""`),t.var(ee.default.parentData,(0,F._)`undefined`),t.var(ee.default.parentDataProperty,(0,F._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,F._)`{}`)})}function XR(t){let{schema:e,opts:r,gen:n}=t;ag(t,()=>{r.$comment&&e.$comment&&pg(t),r$(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&ZR(t),ug(t),s$(t)})}function ZR(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,F._)`${r}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function ng(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${r} */`:F.nil}function QR(t,e){if(cg(t)&&(dg(t),lg(t))){e$(t,e);return}(0,ig.boolOrEmptySchema)(t,e)}function lg({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function cg(t){return typeof t.schema!="boolean"}function e$(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&pg(t),n$(t),o$(t);let s=n.const("_errs",ee.default.errors);ug(t,s),n.var(e,(0,F._)`${s} === ${ee.default.errors}`)}function dg(t){(0,qt.checkUnknownRules)(t),t$(t)}function ug(t,e){if(t.opts.jtd)return og(t,[],!1,e);let r=(0,rg.getSchemaTypes)(t.schema),n=(0,rg.coerceAndCheckDataType)(t,r);og(t,r,!n,e)}function t$(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function r$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,qt.checkStrictMode)(t,"default is ignored in the schema root")}function n$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,GR.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function o$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function pg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,F._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function s$(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,F._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,F._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&i$(t),e.return((0,F._)`${ee.default.errors} === 0`))}function i$({gen:t,evaluated:e,props:r,items:n}){r instanceof F.Name&&t.assign((0,F._)`${e}.props`,r),n instanceof F.Name&&t.assign((0,F._)`${e}.items`,n)}function og(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:d}=t,{RULES:p}=d;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,qt.schemaHasRulesButRef)(s,p))){o.block(()=>mg(t,"$ref",p.all.$ref.definition));return}l.jtd||a$(t,e),o.block(()=>{for(let S of p.rules)g(S);g(p.post)});function g(S){(0,xc.shouldUseGroup)(s,S)&&(S.type?(o.if((0,ti.checkDataType)(S.type,i,l.strictNumbers)),sg(t,S),e.length===1&&e[0]===S.type&&r&&(o.else(),(0,ti.reportTypeError)(t)),o.endIf()):sg(t,S),a||o.if((0,F._)`${ee.default.errors} === ${n||0}`))}}function sg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,VR.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,xc.shouldUseRule)(n,s)&&mg(t,s.keyword,s.definition,e.type)})}function a$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(l$(t,e),t.opts.allowUnionTypes||c$(t,e),d$(t,t.dataTypes))}function l$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{hg(t.dataTypes,r)||Rc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),p$(t,e)}}function c$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Rc(t,"use allowUnionTypes to allow union type keyword")}function d$(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,xc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>u$(e,i))&&Rc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function u$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function hg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function p$(t,e){let r=[];for(let n of t.dataTypes)hg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Rc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,qt.checkStrictMode)(t,e,t.opts.strictTypes)}var ri=class{constructor(e,r,n){if((0,so.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,qt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",fg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,so.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,r,n){this.failResult((0,F.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,F.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,F._)`${r} !== undefined && (${(0,F.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?oo.reportExtraError:oo.reportError)(this,this.def.error,r)}$dataError(){(0,oo.reportError)(this,this.def.$dataError||oo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,oo.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=F.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=F.nil,r=F.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,F.or)((0,F._)`${o} === undefined`,r)),e!==F.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(n.length){if(!(r instanceof F.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,F._)`${(0,ti.checkDataTypes)(l,r,s.opts.strictNumbers,ti.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${l}(${r})`}return F.nil}}subschema(e,r){let n=(0,Tc.getSubschema)(this.it,e);(0,Tc.extendSubschemaData)(n,this.it,e),(0,Tc.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return QR(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=qt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=qt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,F.Name)),!0}};ir.KeywordCxt=ri;function mg(t,e,r,n){let o=new ri(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,so.funcKeywordCode)(o,r):"macro"in r?(0,so.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,so.funcKeywordCode)(o,r)}var h$=/^\/(?:[^~]|~0|~1)*$/,m$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!h$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let d=m$.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+d[1];if(o=d[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let d of a)d&&(s=(0,F._)`${s}${(0,F.getProperty)((0,qt.unescapeJsonPointer)(d))}`,i=(0,F._)`${i} && ${s}`);return i;function l(d,p){return`Cannot access ${d} ${p} levels up, current level is ${e}`}}ir.getData=fg});var ni=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var $c=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ec.default=$c});var ao=U(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var Pc=no(),Ac=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Pc.resolveUrl)(e,r,n),this.missingSchema=(0,Pc.normalizeId)((0,Pc.getFullPath)(e,this.missingRef))}};Cc.default=Ac});var si=U(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.resolveSchema=ut.getCompilingSchema=ut.resolveRef=ut.compileSchema=ut.SchemaEnv=void 0;var vt=re(),f$=ni(),Tr=Mt(),_t=no(),gg=ue(),g$=io(),nn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,_t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ut.SchemaEnv=nn;function Oc(t){let e=yg.call(this,t);if(e)return e;let r=(0,_t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:f$.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:Tr.default.data,parentData:Tr.default.parentData,parentDataProperty:Tr.default.parentDataProperty,dataNames:[Tr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,g$.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(Tr.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${Tr.default.self}`,`${Tr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=d;y.evaluated={props:k instanceof vt.Name?void 0:k,items:R instanceof vt.Name?void 0:R,dynamicProps:k instanceof vt.Name,dynamicItems:R instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return t.validate=y,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)}}ut.compileSchema=Oc;function y$(t,e,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=v$.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new nn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=b$.call(this,s)}ut.resolveRef=y$;function b$(t){return(0,_t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Oc.call(this,t)}function yg(t){for(let e of this._compilations)if(w$(e,t))return e}ut.getCompilingSchema=yg;function w$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function v$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||oi.call(this,t,e)}function oi(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ic.call(this,r,t);let s=(0,_t.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=oi.call(this,t,i);return typeof a?.schema!="object"?void 0:Ic.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Oc.call(this,i),s===(0,_t.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,d)),new nn({schema:a,schemaId:l,root:t,baseId:o})}return Ic.call(this,r,i)}}ut.resolveSchema=oi;var _$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ic(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,gg.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r=="object"&&r[this.opts.schemaId];!_$.has(a)&&d&&(e=(0,_t.resolveUrl)(this.opts.uriResolver,e,d))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,gg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=oi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new nn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var bg=U((w1,S$)=>{S$.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 jc=U((v1,Tg)=>{"use strict";var k$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),vg=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),Nc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),_g=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),T$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Lc(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var x$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wg(t){return t.length=0,!0}function R$(t,e,r){if(t.length){let n=Lc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function $$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=R$;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(d==="%"){if(!a(o,n,r))break;a=wg}else{o.push(d);continue}}return o.length&&(a===wg?r.zone=o.join(""):i?n.push(o.join("")):n.push(Lc(o))),r.address=n.join(""),r}function Sg(t){if(E$(t,":")<2)return{host:t,isIPV6:!1};let e=$$(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function E$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function P$(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var A$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},C$=/[@/?#:]/g,I$=/[@/?#]/g;function kg(t,e){let r=e?I$:C$;return r.lastIndex=0,t.replace(r,n=>A$[n])}function O$(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Nc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&_g(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function N$(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Nc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&_g(s)?e+=s:e+="%"+o,r+=2;continue}}T$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function L$(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Nc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function j$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!vg(r)){let n=Sg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=kg(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Tg.exports={nonSimpleDomain:x$,recomposeAuthority:j$,reescapeHostDelimiters:kg,normalizePercentEncoding:O$,normalizePathEncoding:N$,escapePreservingEscapes:L$,removeDotSegments:P$,isIPv4:vg,isUUID:k$,normalizeIPv6:Sg,stringArrayToHexStripped:Lc}});var Pg=U((_1,Eg)=>{"use strict";var{isUUID:D$}=jc(),U$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,M$=["http","https","ws","wss","urn","urn:uuid"];function q$(t){return M$.indexOf(t)!==-1}function Dc(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 xg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Rg(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 z$(t){return t.secure=Dc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function B$(t){if((t.port===(Dc(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function F$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(U$);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Uc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function H$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Uc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function K$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!D$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function V$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var $g={scheme:"http",domainHost:!0,parse:xg,serialize:Rg},G$={scheme:"https",domainHost:$g.domainHost,parse:xg,serialize:Rg},ii={scheme:"ws",domainHost:!0,parse:z$,serialize:B$},W$={scheme:"wss",domainHost:ii.domainHost,parse:ii.parse,serialize:ii.serialize},J$={scheme:"urn",parse:F$,serialize:H$,skipNormalize:!0},Y$={scheme:"urn:uuid",parse:K$,serialize:V$,skipNormalize:!0},ai={http:$g,https:G$,ws:ii,wss:W$,urn:J$,"urn:uuid":Y$};Object.setPrototypeOf(ai,null);function Uc(t){return t&&(ai[t]||ai[t.toLowerCase()])||void 0}Eg.exports={wsIsSecure:Dc,SCHEMES:ai,isValidSchemeName:q$,getSchemeHandler:Uc}});var Ng=U((S1,di)=>{"use strict";var{normalizeIPv6:X$,removeDotSegments:lo,recomposeAuthority:Z$,normalizePercentEncoding:Q$,normalizePathEncoding:eE,escapePreservingEscapes:tE,reescapeHostDelimiters:rE,isIPv4:nE,nonSimpleDomain:oE}=jc(),{SCHEMES:sE,getSchemeHandler:Cg}=Pg();function iE(t,e){return typeof t=="string"?t=hE(t,e):typeof t=="object"&&(t=ci(xr(t,e),e)),t}function aE(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=li(t,n),{parsed:i,malformedAuthorityOrPort:a}=li(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=Ig(o,i,n,!0);return n.skipEscape=!0,xr(l,n)}function Ig(t,e,r,n){let o={};return n||(t=ci(xr(t,r),r),e=ci(xr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=lo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=lo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=lo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=lo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function lE(t,e,r){let n=Ag(t,r),o=Ag(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function xr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Cg(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Q$(r.path):(r.path=tE(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Z$(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=lo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var cE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,dE=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,uE=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function pE(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 li(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(dE);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(uE);if(a!==null){let d=a[1],p=d.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):d.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(cE);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let d=pE(n,l);if(d!==void 0&&(n.error=n.error||d,o=!0),n.host)if(nE(n.host)===!1){let S=X$(n.host);n.host=S.host.toLowerCase(),s=S.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=Cg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&oE(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(g){n.error=n.error||"Host's domain name can not be converted to ASCII: "+g}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=rE(unescape(n.host),s))),n.path&&(n.path=eE(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function ci(t,e){return li(t,e).parsed}function hE(t,e){return Og(t,e).normalized}function Og(t,e){let{parsed:r,malformedAuthorityOrPort:n}=li(t,e);return{normalized:n?t:xr(r,e),malformedAuthorityOrPort:n}}function Ag(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Og(t,e);return n?void 0:r}if(typeof t=="object")return xr(t,e)}var Mc={SCHEMES:sE,normalize:iE,resolve:aE,resolveComponent:Ig,equal:lE,serialize:xr,parse:ci};di.exports=Mc;di.exports.default=Mc;di.exports.fastUri=Mc});var jg=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var Lg=Ng();Lg.code='require("ajv/dist/runtime/uri").default';qc.default=Lg});var Hg=U(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var mE=io();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return mE.KeywordCxt}});var on=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return on.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return on.CodeGen}});var fE=ni(),zg=ao(),gE=mc(),co=si(),yE=re(),uo=no(),ui=ro(),Bc=ue(),Dg=bg(),bE=jg(),Bg=(t,e)=>new RegExp(t,e);Bg.code="new RegExp";var wE=["removeAdditional","useDefaults","coerceTypes"],vE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_E={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."},SE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ug=200;function kE(t){var e,r,n,o,s,i,a,l,d,p,g,S,y,k,R,$,P,I,D,Y,H,Oe,Ce,Bt,Ft;let Ht=t.strict,mn=(e=t.code)===null||e===void 0?void 0:e.optimize,dr=mn===!0||mn===void 0?1:mn||0,Tt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Bg,Di=(o=t.uriResolver)!==null&&o!==void 0?o:bE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ht)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ht)!==null&&l!==void 0?l:!0,strictTypes:(p=(d=t.strictTypes)!==null&&d!==void 0?d:Ht)!==null&&p!==void 0?p:"log",strictTuples:(S=(g=t.strictTuples)!==null&&g!==void 0?g:Ht)!==null&&S!==void 0?S:"log",strictRequired:(k=(y=t.strictRequired)!==null&&y!==void 0?y:Ht)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:dr,regExp:Tt}:{optimize:dr,regExp:Tt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Ug,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:Ug,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(H=t.addUsedSchema)!==null&&H!==void 0?H:!0,validateSchema:(Oe=t.validateSchema)!==null&&Oe!==void 0?Oe:!0,validateFormats:(Ce=t.validateFormats)!==null&&Ce!==void 0?Ce:!0,unicodeRegExp:(Bt=t.unicodeRegExp)!==null&&Bt!==void 0?Bt:!0,int32range:(Ft=t.int32range)!==null&&Ft!==void 0?Ft:!0,uriResolver:Di}}var po=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,...kE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new yE.ValueScope({scope:{},prefixes:vE,es5:r,lines:n}),this.logger=PE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,gE.getRules)(),Mg.call(this,_E,e,"NOT SUPPORTED"),Mg.call(this,SE,e,"DEPRECATED","warn"),this._metaOpts=$E.call(this),e.formats&&xE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&RE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),TE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Dg;n==="id"&&(o={...Dg},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(p,g){await s.call(this,p.$schema);let S=this._addSchema(p,g);return S.validate||i.call(this,S)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(g){if(!(g instanceof zg.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 d.call(this,p);this.refs[p]||await s.call(this,g.$schema),this.refs[p]||this.addSchema(g,p,r)}async function d(p){let g=this._loading[p];if(g)return g;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,uo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=qg.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new co.SchemaEnv({schema:{},schemaId:n});if(r=co.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=qg.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,uo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(CE.call(this,n,r),!r)return(0,Bc.eachItem)(n,s=>zc.call(this,s)),this;OE.call(this,r);let o={...r,type:(0,ui.getJSONTypes)(r.type),schemaType:(0,ui.getJSONTypes)(r.schemaType)};return(0,Bc.eachItem)(n,o.type.length===0?s=>zc.call(this,s,o):s=>o.type.forEach(i=>zc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:d}=l.definition,p=i[a];d&&p&&(i[a]=Fg(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,uo.normalizeId)(i||n);let d=uo.getSchemaRefs.call(this,e,n);return l=new co.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:d}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&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):co.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{co.compileSchema.call(this,e)}finally{this.opts=r}}};po.ValidationError=fE.default;po.MissingRefError=zg.default;Ue.default=po;function Mg(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function qg(t){return t=(0,uo.normalizeId)(t),this.schemas[t]||this.refs[t]}function TE(){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 xE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function RE(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function $E(){let t={...this.opts};for(let e of wE)delete t[e];return t}var EE={log(){},warn(){},error(){}};function PE(t){if(t===!1)return EE;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 AE=/^[a-z_$][a-z0-9_$:-]*$/i;function CE(t,e){let{RULES:r}=this;if((0,Bc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!AE.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function zc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ui.getJSONTypes)(e.type),schemaType:(0,ui.getJSONTypes)(e.schemaType)}};e.before?IE.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function IE(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function OE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Fg(e)),t.validateSchema=this.compile(e,!0))}var NE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Fg(t){return{anyOf:[t,NE]}}});var Kg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var LE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Fc.default=LE});var Jg=U(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.callRef=Rr.getValidate=void 0;var jE=ao(),Vg=dt(),Qe=re(),sn=Mt(),Gg=si(),pi=ue(),DE={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:d}=s;if((r==="#"||r==="#/")&&o===d.baseId)return g();let p=Gg.resolveRef.call(l,d,o,r);if(p===void 0)throw new jE.default(n.opts.uriResolver,o,r);if(p instanceof Gg.SchemaEnv)return S(p);return y(p);function g(){if(s===d)return hi(t,i,s,s.$async);let k=e.scopeValue("root",{ref:d});return hi(t,(0,Qe._)`${k}.validate`,d,d.$async)}function S(k){let R=Wg(t,k);hi(t,R,k,k.$async)}function y(k){let R=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Qe.stringify)(k)}:{ref:k}),$=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:R,errSchemaPath:r},$);t.mergeEvaluated(P),t.ok($)}}};function Wg(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Rr.getValidate=Wg;function hi(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,d=l.passContext?sn.default.this:Qe.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,Vg.callValidateCode)(t,e,d)}`),y(e),i||o.assign(k,!0)},R=>{o.if((0,Qe._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),S(R),i||o.assign(k,!1)}),t.ok(k)}function g(){t.result((0,Vg.callValidateCode)(t,e,d),()=>y(e),()=>S(e))}function S(k){let R=(0,Qe._)`${k}.errors`;o.assign(sn.default.vErrors,(0,Qe._)`${sn.default.vErrors} === null ? ${R} : ${sn.default.vErrors}.concat(${R})`),o.assign(sn.default.errors,(0,Qe._)`${sn.default.vErrors}.length`)}function y(k){var R;if(!s.opts.unevaluated)return;let $=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=pi.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,Qe._)`${k}.evaluated.props`);s.props=pi.mergeEvaluated.props(o,P,s.props,Qe.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=pi.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,Qe._)`${k}.evaluated.items`);s.items=pi.mergeEvaluated.items(o,P,s.items,Qe.Name)}}}Rr.callRef=hi;Rr.default=DE});var Yg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var UE=Kg(),ME=Jg(),qE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",UE.default,ME.default];Hc.default=qE});var Xg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var mi=re(),ar=mi.operators,fi={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},zE={message:({keyword:t,schemaCode:e})=>(0,mi.str)`must be ${fi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mi._)`{comparison: ${fi[t].okStr}, limit: ${e}}`},BE={keyword:Object.keys(fi),type:"number",schemaType:"number",$data:!0,error:zE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,mi._)`${r} ${fi[e].fail} ${n} || isNaN(${r})`)}};Kc.default=BE});var Zg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var ho=re(),FE={message:({schemaCode:t})=>(0,ho.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ho._)`{multipleOf: ${t}}`},HE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ho._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ho._)`${i} !== parseInt(${i})`;t.fail$data((0,ho._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Vc.default=HE});var ey=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});function Qg(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Gc.default=Qg;Qg.code='require("ajv/dist/runtime/ucs2length").default'});var ty=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var $r=re(),KE=ue(),VE=ey(),GE={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},WE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:GE,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$r.operators.GT:$r.operators.LT,i=o.opts.unicode===!1?(0,$r._)`${r}.length`:(0,$r._)`${(0,KE.useFunc)(t.gen,VE.default)}(${r})`;t.fail$data((0,$r._)`${i} ${s} ${n}`)}};Wc.default=WE});var ry=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var JE=dt(),YE=ue(),an=re(),XE={message:({schemaCode:t})=>(0,an.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,an._)`{pattern: ${t}}`},ZE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XE,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,d=l.code==="new RegExp"?(0,an._)`new RegExp`:(0,YE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,an._)`${d}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,an._)`!${p}`)}else{let l=(0,JE.usePattern)(t,o);t.fail$data((0,an._)`!${l}.test(${r})`)}}};Jc.default=ZE});var ny=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var mo=re(),QE={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,mo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,mo._)`{limit: ${t}}`},eP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:QE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?mo.operators.GT:mo.operators.LT;t.fail$data((0,mo._)`Object.keys(${r}).length ${o} ${n}`)}};Yc.default=eP});var oy=U(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var fo=dt(),go=re(),tP=ue(),rP={message:({params:{missingProperty:t}})=>(0,go.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,go._)`{missingProperty: ${t}}`},nP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:rP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?d():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:k}=t.it;for(let R of r)if(y?.[R]===void 0&&!k.has(R)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,tP.checkStrictMode)(i,P,i.opts.strictRequired)}}function d(){if(l||s)t.block$data(go.nil,g);else for(let y of r)(0,fo.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let k=e.let("valid",!0);t.block$data(k,()=>S(y,k)),t.ok(k)}else e.if((0,fo.checkMissingProp)(t,r,y)),(0,fo.reportMissingProp)(t,y),e.else()}function g(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,fo.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function S(y,k){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(k,(0,fo.propertyInData)(e,o,y,a.ownProperties)),e.if((0,go.not)(k),()=>{t.error(),e.break()})},go.nil)}}};Xc.default=nP});var sy=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var yo=re(),oP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,yo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,yo._)`{limit: ${t}}`},sP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:oP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?yo.operators.GT:yo.operators.LT;t.fail$data((0,yo._)`${r}.length ${o} ${n}`)}};Zc.default=sP});var gi=U(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var iy=Sc();iy.code='require("ajv/dist/runtime/equal").default';Qc.default=iy});var ay=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ed=ro(),Me=re(),iP=ue(),aP=gi(),lP={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},cP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:lP,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),d=s.items?(0,ed.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Me._)`${r}.length`),R=e.let("j");t.setParams({i:k,j:R}),e.assign(l,!0),e.if((0,Me._)`${k} > 1`,()=>(g()?S:y)(k,R))}function g(){return d.length>0&&!d.some(k=>k==="object"||k==="array")}function S(k,R){let $=e.name("item"),P=(0,ed.checkDataTypes)(d,$,a.opts.strictNumbers,ed.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${k}--;`,()=>{e.let($,(0,Me._)`${r}[${k}]`),e.if(P,(0,Me._)`continue`),d.length>1&&e.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),e.if((0,Me._)`typeof ${I}[${$}] == "number"`,()=>{e.assign(R,(0,Me._)`${I}[${$}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${$}] = ${k}`)})}function y(k,R){let $=(0,iP.useFunc)(e,aP.default),P=e.name("outer");e.label(P).for((0,Me._)`;${k}--;`,()=>e.for((0,Me._)`${R} = ${k}; ${R}--;`,()=>e.if((0,Me._)`${$}(${r}[${k}], ${r}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};td.default=cP});var ly=U(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=re(),dP=ue(),uP=gi(),pP={message:"must be equal to constant",params:({schemaCode:t})=>(0,rd._)`{allowedValue: ${t}}`},hP={keyword:"const",$data:!0,error:pP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,rd._)`!${(0,dP.useFunc)(e,uP.default)}(${r}, ${o})`):t.fail((0,rd._)`${s} !== ${r}`)}};nd.default=hP});var cy=U(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var bo=re(),mP=ue(),fP=gi(),gP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,bo._)`{allowedValues: ${t}}`},yP={keyword:"enum",schemaType:"array",$data:!0,error:gP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,l,d=()=>l??(l=(0,mP.useFunc)(e,fP.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,bo.or)(...o.map((k,R)=>S(y,R)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,bo._)`${d()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function S(y,k){let R=o[k];return typeof R=="object"&&R!==null?(0,bo._)`${d()}(${r}, ${y}[${k}])`:(0,bo._)`${r} === ${R}`}}};od.default=yP});var dy=U(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var bP=Xg(),wP=Zg(),vP=ty(),_P=ry(),SP=ny(),kP=oy(),TP=sy(),xP=ay(),RP=ly(),$P=cy(),EP=[bP.default,wP.default,vP.default,_P.default,SP.default,kP.default,TP.default,xP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},RP.default,$P.default];sd.default=EP});var ad=U(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.validateAdditionalItems=void 0;var Er=re(),id=ue(),PP={message:({params:{len:t}})=>(0,Er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Er._)`{limit: ${t}}`},AP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,id.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}uy(t,n)}};function uy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,id.alwaysValidSchema)(i,n)){let d=r.var("valid",(0,Er._)`${a} <= ${e.length}`);r.if((0,Er.not)(d),()=>l(d)),t.ok(d)}function l(d){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:id.Type.Num},d),i.allErrors||r.if((0,Er.not)(d),()=>r.break())})}}wo.validateAdditionalItems=uy;wo.default=AP});var ld=U(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.validateTuple=void 0;var py=re(),yi=ue(),CP=dt(),IP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return hy(t,"additionalItems",e);r.items=!0,!(0,yi.alwaysValidSchema)(r,e)&&t.ok((0,CP.validateArray)(t))}};function hy(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=yi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),d=n.const("len",(0,py._)`${s}.length`);r.forEach((g,S)=>{(0,yi.alwaysValidSchema)(a,g)||(n.if((0,py._)`${d} > ${S}`,()=>t.subschema({keyword:i,schemaProp:S,dataProp:S},l)),t.ok(l))});function p(g){let{opts:S,errSchemaPath:y}=a,k=r.length,R=k===g.minItems&&(k===g.maxItems||g[e]===!1);if(S.strictTuples&&!R){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,yi.checkStrictMode)(a,$,S.strictTuples)}}}vo.validateTuple=hy;vo.default=IP});var my=U(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var OP=ld(),NP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,OP.validateTuple)(t,"items")};cd.default=NP});var gy=U(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var fy=re(),LP=ue(),jP=dt(),DP=ad(),UP={message:({params:{len:t}})=>(0,fy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fy._)`{limit: ${t}}`},MP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:UP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,LP.alwaysValidSchema)(n,e)&&(o?(0,DP.validateAdditionalItems)(t,o):t.ok((0,jP.validateArray)(t)))}};dd.default=MP});var yy=U(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var pt=re(),bi=ue(),qP={message:({params:{min:t,max:e}})=>e===void 0?(0,pt.str)`must contain at least ${t} valid item(s)`:(0,pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,pt._)`{minContains: ${t}}`:(0,pt._)`{minContains: ${t}, maxContains: ${e}}`},zP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:qP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:d}=n;s.opts.next?(i=l===void 0?1:l,a=d):i=1;let p=e.const("len",(0,pt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,bi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,bi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,bi.alwaysValidSchema)(s,r)){let R=(0,pt._)`${p} >= ${i}`;a!==void 0&&(R=(0,pt._)`${R} && ${p} <= ${a}`),t.pass(R);return}s.items=!0;let g=e.name("valid");a===void 0&&i===1?y(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,pt._)`${o}.length > 0`,S)):(e.let(g,!1),S()),t.result(g,()=>t.reset());function S(){let R=e.name("_valid"),$=e.let("count",0);y(R,()=>e.if(R,()=>k($)))}function y(R,$){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:bi.Type.Num,compositeRule:!0},R),$()})}function k(R){e.code((0,pt._)`${R}++`),a===void 0?e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,pt._)`${R} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(g,!0)))}}};ud.default=zP});var vy=U(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.validateSchemaDeps=At.validatePropertyDeps=At.error=void 0;var pd=re(),BP=ue(),_o=dt();At.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,pd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,pd._)`{property: ${t},
|
|
2011
2308
|
missingProperty: ${n},
|
|
2012
2309
|
depsCount: ${e},
|
|
2013
|
-
deps: ${r}}`};var R0={keyword:"dependencies",type:"object",schemaType:"object",error:At.error,code(t){let[e,r]=$0(t);ly(t,e),cy(t,r)}};function $0({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function ly(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,_o.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let d of a)(0,_o.checkReportMissingProp)(t,d)}):(r.if((0,cd._)`${l} && (${(0,_o.checkMissingProp)(t,a,s)})`),(0,_o.reportMissingProp)(t,s),r.else())}}At.validatePropertyDeps=ly;function cy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,x0.alwaysValidSchema)(s,e[a])||(r.if((0,_o.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}At.validateSchemaDeps=cy;At.default=R0});var py=U(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var uy=re(),E0=ue(),P0={message:"property name must be valid",params:({params:t})=>(0,uy._)`{propertyName: ${t.propertyName}}`},A0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:P0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,E0.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,uy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};dd.default=A0});var pd=U(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var yi=dt(),St=re(),C0=Mt(),bi=ue(),I0={message:"must NOT have additional properties",params:({params:t})=>(0,St._)`{additionalProperty: ${t.additionalProperty}}`},O0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:I0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,bi.alwaysValidSchema)(i,r))return;let d=(0,yi.allSchemaProperties)(n.properties),p=(0,yi.allSchemaProperties)(n.patternProperties);f(),t.ok((0,St._)`${s} === ${C0.default.errors}`);function f(){e.forIn("key",o,$=>{!d.length&&!p.length?k($):e.if(_($),()=>k($))})}function _($){let P;if(d.length>8){let I=(0,bi.schemaRefOrVal)(i,n.properties,"properties");P=(0,yi.isOwnProperty)(e,I,$)}else d.length?P=(0,St.or)(...d.map(I=>(0,St._)`${$} === ${I}`)):P=St.nil;return p.length&&(P=(0,St.or)(P,...p.map(I=>(0,St._)`${(0,yi.usePattern)(t,I)}.test(${$})`))),(0,St.not)(P)}function y($){e.code((0,St._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,bi.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(R($,P,!1),e.if((0,St.not)(P),()=>{t.reset(),y($)})):(R($,P),a||e.if((0,St.not)(P),()=>e.break()))}}function R($,P,I){let D={keyword:"additionalProperties",dataProp:$,dataPropType:bi.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};ud.default=O0});var fy=U(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var N0=io(),hy=dt(),hd=ue(),my=pd(),L0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&my.default.code(new N0.KeywordCxt(s,my.default,"additionalProperties"));let i=(0,hy.allSchemaProperties)(r);for(let f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=hd.mergeEvaluated.props(e,(0,hd.toHash)(i),s.props));let a=i.filter(f=>!(0,hd.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)d(f)?p(f):(e.if((0,hy.propertyInData)(e,o,f,s.opts.ownProperties)),p(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function d(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};md.default=L0});var wy=U(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var gy=dt(),wi=re(),yy=ue(),by=ue(),j0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,gy.allSchemaProperties)(r),l=a.filter(R=>(0,yy.alwaysValidSchema)(s,r[R]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof wi.Name)&&(s.props=(0,by.evaluatedPropsToName)(e,s.props));let{props:f}=s;_();function _(){for(let R of a)d&&y(R),s.allErrors?k(R):(e.var(p,!0),k(R),e.if(p))}function y(R){for(let $ in d)new RegExp(R).test($)&&(0,yy.checkStrictMode)(s,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){e.forIn("key",n,$=>{e.if((0,wi._)`${(0,gy.usePattern)(t,R)}.test(${$})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:by.Type.Str},p),s.opts.unevaluated&&f!==!0?e.assign((0,wi._)`${f}[${$}]`,!0):!P&&!s.allErrors&&e.if((0,wi.not)(p),()=>e.break())})})}}};fd.default=j0});var vy=U(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var D0=ue(),U0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,D0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};gd.default=U0});var _y=U(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var M0=dt(),q0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:M0.validateUnion,error:{message:"must match a schema in anyOf"}};yd.default=q0});var Sy=U(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var vi=re(),z0=ue(),B0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,vi._)`{passingSchemas: ${t.passing}}`},F0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:B0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){s.forEach((p,f)=>{let _;(0,z0.alwaysValidSchema)(o,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,vi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,vi._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),_&&t.mergeEvaluated(_,vi.Name)})})}}};bd.default=F0});var ky=U(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var H0=ue(),K0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,H0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};wd.default=K0});var Ry=U(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var _i=re(),xy=ue(),V0={message:({params:t})=>(0,_i.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_i._)`{failingKeyword: ${t.ifClause}}`},G0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:V0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,xy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ty(n,"then"),s=Ty(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,d("then",p),d("else",p))}else o?e.if(a,d("then")):e.if((0,_i.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function d(p,f){return()=>{let _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),f?e.assign(f,(0,_i._)`${p}`):t.setParams({ifClause:p})}}}};function Ty(t,e){let r=t.schema[e];return r!==void 0&&!(0,xy.alwaysValidSchema)(t,r)}vd.default=G0});var $y=U(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var W0=ue(),J0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,W0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};_d.default=J0});var Ey=U(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Y0=od(),X0=oy(),Z0=sd(),Q0=iy(),eP=ay(),tP=dy(),rP=py(),nP=pd(),oP=fy(),sP=wy(),iP=vy(),aP=_y(),lP=Sy(),cP=ky(),dP=Ry(),uP=$y();function pP(t=!1){let e=[iP.default,aP.default,lP.default,cP.default,dP.default,uP.default,rP.default,nP.default,tP.default,oP.default,sP.default];return t?e.push(X0.default,Q0.default):e.push(Y0.default,Z0.default),e.push(eP.default),e}Sd.default=pP});var Py=U(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var xe=re(),hP={message:({schemaCode:t})=>(0,xe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,xe._)`{format: ${t}}`},mP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hP,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;o?_():y();function _(){let k=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),R=r.const("fDef",(0,xe._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,xe._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign($,(0,xe._)`${R}.type || "string"`).assign(P,(0,xe._)`${R}.validate`),()=>r.assign($,(0,xe._)`"string"`).assign(P,R)),t.fail$data((0,xe.or)(I(),D()));function I(){return l.strictSchema===!1?xe.nil:(0,xe._)`${i} && !${P}`}function D(){let Y=p.$async?(0,xe._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,xe._)`${P}(${n})`,F=(0,xe._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${n}))`;return(0,xe._)`${P} && ${P} !== true && ${$} === ${e} && !${F}`}}function y(){let k=f.formats[s];if(!k){I();return}if(k===!0)return;let[R,$,P]=D(k);R===e&&t.pass(Y());function I(){if(l.strictSchema===!1){f.logger.warn(F());return}throw new Error(F());function F(){return`unknown format "${s}" ignored in schema at path "${d}"`}}function D(F){let Oe=F instanceof RegExp?(0,xe.regexpCode)(F):l.code.formats?(0,xe._)`${l.code.formats}${(0,xe.getProperty)(s)}`:void 0,Ce=r.scopeValue("formats",{key:s,ref:F,code:Oe});return typeof F=="object"&&!(F instanceof RegExp)?[F.type||"string",F.validate,(0,xe._)`${Ce}.validate`]:["string",F,Ce]}function Y(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${P}(${n})`}return typeof $=="function"?(0,xe._)`${P}(${n})`:(0,xe._)`${P}.test(${n})`}}}};kd.default=mP});var Ay=U(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var fP=Py(),gP=[fP.default];Td.default=gP});var Cy=U(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.contentVocabulary=ln.metadataVocabulary=void 0;ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Oy=U(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var yP=qg(),bP=ey(),wP=Ey(),vP=Ay(),Iy=Cy(),_P=[yP.default,bP.default,(0,wP.default)(),vP.default,Iy.metadataVocabulary,Iy.contentVocabulary];xd.default=_P});var Ly=U(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.DiscrError=void 0;var Ny;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ny||(Si.DiscrError=Ny={}))});var Dy=U($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var cn=re(),Rd=Ly(),jy=ni(),SP=ao(),kP=ue(),TP={message:({params:{discrError:t,tagName:e}})=>t===Rd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,cn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xP={keyword:"discriminator",type:"object",schemaType:"object",error:TP,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),d=e.const("tag",(0,cn._)`${r}${(0,cn.getProperty)(a)}`);e.if((0,cn._)`typeof ${d} == "string"`,()=>p(),()=>t.error(!1,{discrError:Rd.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function p(){let y=_();e.if(!1);for(let k in y)e.elseIf((0,cn._)`${d} === ${k}`),e.assign(l,f(y[k]));e.else(),t.error(!1,{discrError:Rd.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function f(y){let k=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:y},k);return t.mergeEvaluated(R,cn.Name),k}function _(){var y;let k={},R=P(o),$=!0;for(let Y=0;Y<i.length;Y++){let F=i[Y];if(F?.$ref&&!(0,kP.schemaHasRulesButRef)(F,s.self.RULES)){let Ce=F.$ref;if(F=jy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ce),F instanceof jy.SchemaEnv&&(F=F.schema),F===void 0)throw new SP.default(s.opts.uriResolver,s.baseId,Ce)}let Oe=(y=F?.properties)===null||y===void 0?void 0:y[a];if(typeof Oe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(R||P(F)),I(Oe,Y)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function I(Y,F){if(Y.const)D(Y.const,F);else if(Y.enum)for(let Oe of Y.enum)D(Oe,F);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,F){if(typeof Y!="string"||Y in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[Y]=F}}}};$d.default=xP});var Uy=U((V1,RP)=>{RP.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 Pd=U((Se,Ed)=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.MissingRefError=Se.ValidationError=Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=Se.Ajv=void 0;var $P=Ng(),EP=Oy(),PP=Dy(),My=Uy(),AP=["/properties"],ki="http://json-schema.org/draft-07/schema",dn=class extends $P.default{_addVocabularies(){super._addVocabularies(),EP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(PP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(My,AP):My;this.addMetaSchema(e,ki,!1),this.refs["http://json-schema.org/schema"]=ki}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ki)?ki:void 0)}};Se.Ajv=dn;Ed.exports=Se=dn;Ed.exports.Ajv=dn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=dn;var CP=io();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return CP.KeywordCxt}});var un=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return un.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return un.CodeGen}});var IP=ti();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return IP.default}});var OP=ao();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return OP.default}})});var Gy=U(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.formatNames=It.fastFormats=It.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}It.fullFormats={date:Ct(Fy,Od),time:Ct(Cd(!0),Nd),"date-time":Ct(qy(!0),Ky),"iso-time":Ct(Cd(),Hy),"iso-date-time":Ct(qy(),Vy),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:MP,"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:VP,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:qP,int32:{type:"number",validate:FP},int64:{type:"number",validate:HP},float:{type:"number",validate:By},double:{type:"number",validate:By},password:!0,binary:!0};It.fastFormats={...It.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Od),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Nd),"date-time":Ct(/^\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,Ky),"iso-time":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hy),"iso-date-time":Ct(/^\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,Vy),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};It.formatNames=Object.keys(It.fullFormats);function NP(t){return t%4===0&&(t%100!==0||t%400===0)}var LP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Fy(t){let e=LP.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&NP(r)?29:jP[n])}function Od(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ad=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cd(t){return function(r){let n=Ad.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),p=+(n[7]||0);if(d>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let f=s-p*l,_=o-d*l-(f<0?1:0);return(_===23||_===-1)&&(f===59||f===-1)&&i<61}}function Nd(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Hy(t,e){if(!(t&&e))return;let r=Ad.exec(t),n=Ad.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Id=/t|\s/i;function qy(t){let e=Cd(t);return function(n){let o=n.split(Id);return o.length===2&&Fy(o[0])&&e(o[1])}}function Ky(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Vy(t,e){if(!(t&&e))return;let[r,n]=t.split(Id),[o,s]=e.split(Id),i=Od(r,o);if(i!==void 0)return i||Nd(n,s)}var DP=/\/|:/,UP=/^(?:[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 MP(t){return DP.test(t)&&UP.test(t)}var zy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function qP(t){return zy.lastIndex=0,zy.test(t)}var zP=-(2**31),BP=2**31-1;function FP(t){return Number.isInteger(t)&&t<=BP&&t>=zP}function HP(t){return Number.isInteger(t)}function By(){return!0}var KP=/[^\\]\\Z/;function VP(t){if(KP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Wy=U(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.formatLimitDefinition=void 0;var GP=Pd(),kt=re(),lr=kt.operators,Ti={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},WP={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${Ti[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${Ti[t].okStr}, limit: ${e}}`};pn.formatLimitDefinition={keyword:Object.keys(Ti),type:"string",schemaType:"string",$data:!0,error:WP,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new GP.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?d():p();function d(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,kt._)`${_}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${y} != "object"`,(0,kt._)`${y} instanceof RegExp`,(0,kt._)`typeof ${y}.compare != "function"`,f(y)))}function p(){let _=l.schema,y=a.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${_}" does not define "compare" function`);let k=e.scopeValue("formats",{key:_,ref:y,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(_)}`:void 0});t.fail$data(f(k))}function f(_){return(0,kt._)`${_}.compare(${r}, ${n}) ${Ti[o].fail} 0`}},dependencies:["format"]};var JP=t=>(t.addKeyword(pn.formatLimitDefinition),t);pn.default=JP});var Zy=U((So,Xy)=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});var hn=Gy(),YP=Wy(),Ld=re(),Jy=new Ld.Name("fullFormats"),XP=new Ld.Name("fastFormats"),jd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Yy(t,e,hn.fullFormats,Jy),t;let[r,n]=e.mode==="fast"?[hn.fastFormats,XP]:[hn.fullFormats,Jy],o=e.formats||hn.formatNames;return Yy(t,o,r,n),e.keywords&&(0,YP.default)(t),t};jd.get=(t,e="full")=>{let n=(e==="fast"?hn.fastFormats:hn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Yy(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ld._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Xy.exports=So=jd;Object.defineProperty(So,"__esModule",{value:!0});So.default=jd});function ZP(){let t=new Qy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eb.default)(t),t}var Qy,eb,xi,tb=j(()=>{Qy=Xd(Pd(),1),eb=Xd(Zy(),1);xi=class{constructor(e){this._ajv=e??ZP()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Ri,rb=j(()=>{Jr();Ri=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(l.filter(_=>_.type==="tool_use").map(_=>_.id)),f=new Set(s.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==f.size||![...p].every(_=>f.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},Hn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Wr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function nb(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function ob(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var sb=j(()=>{});var $i,ib=j(()=>{cf();Jr();tb();Nn();rb();sb();$i=class extends Bs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new xi,this.setRequestHandler(Ya,n=>this._oninitialize(n)),this.setNotificationHandler(Xa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ol,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ri(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=lf(this._capabilities,e)}setRequestHandler(e,r){let o=Xt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Fr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,d)=>{let p=Yt(Gr,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new z(K.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,_=await Promise.resolve(r(l,d));if(f.task){let k=Yt(Kr,_);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new z(K.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let y=Yt(As,_);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new z(K.InvalidParams,`Invalid tools/call result: ${k}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){ob(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:im.includes(r)?r:Ka,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"},ms)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(d=>d.type==="tool_use");if(s){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(a.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(d.size!==p.size||![...d].every(f=>p.has(f)))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},sl,r):this.request({method:"sampling/createMessage",params:e},Hn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Wr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Wr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.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 s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},il,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Dd(t){return!!t&&typeof t=="object"&&lb in t}function cb(t){return t[lb]?.complete}var lb,ab,db=j(()=>{lb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ab||(ab={}))});var ub=j(()=>{});function eA(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"),!QP.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function tA(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Ud(t){let e=eA(t);return tA(t,e.warnings),e.isValid}var QP,pb=j(()=>{QP=/^[A-Za-z0-9._-]{1,128}$/});var Ei,hb=j(()=>{Ei=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as rA}from"zod";function gb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function yb(t){return"_def"in t||"_zod"in t||gb(t)}function Md(t){return typeof t!="object"||t===null||yb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(gb)}function mb(t){if(t){if(Md(t))return yr(t);if(!yb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function oA(t){let e=Xt(t);return e?Object.entries(e).map(([r,n])=>{let o=om(n),s=sm(n);return{name:r,description:o,required:!s}}):[]}function cr(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function fb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pi,nA,ko,bb=j(()=>{ib();Nn();Fl();Jr();db();ub();pb();hb();Pi=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new $i(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ei(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ps)),this.server.assertCanSetRequestHandler(cr(Gr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ps,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Br(r.inputSchema);return o?ql(o,{strictUnions:!0,pipeStrategy:"input"}):nA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Br(r.outputSchema);o&&(n.outputSchema=ql(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof z&&n.code===K.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Br(e.inputSchema)??e.inputSchema,i=await cs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ds(a);throw new z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new z(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Br(e.outputSchema),s=await cs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ds(i);throw new z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),l=a.task.taskId,d=a.task,p=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(_=>setTimeout(_,p));let f=await n.taskStore.getTask(l);if(!f)throw new z(K.InternalError,`Task ${l} not found during polling`);d=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cr(Cs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Sm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return km(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,r){let n=this._registeredPrompts[r.name];if(!n)throw new z(K.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ko;let s=Xt(n.argsSchema)?.[e.params.argument.name];if(!Dd(s))return ko;let i=cb(s);if(!i)return ko;let a=await i(e.params.argument.value,e.params.context);return fb(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ko;throw new z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ko;let s=await o(e.params.argument.value,e.params.context);return fb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ts)),this.server.assertCanSetRequestHandler(cr(xs)),this.server.assertCanSetRequestHandler(cr(Rs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ts,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(xs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rs,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(K.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new z(K.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cr($s)),this.server.assertCanSetRequestHandler(cr(Es)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($s,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?oA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Es,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Br(n.argsSchema),s=await cs(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",d=ds(l);throw new z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:yr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=yr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(l=>{let d=l instanceof rA?l._def?.innerType:l;return Dd(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,d){Ud(e);let p={title:r,description:n,inputSchema:mb(o),outputSchema:mb(s),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&Ud(f.name),delete this._registeredTools[e],f.name&&(this._registeredTools[f.name]=p)),typeof f.title<"u"&&(p.title=f.title),typeof f.description<"u"&&(p.description=f.description),typeof f.paramsSchema<"u"&&(p.inputSchema=yr(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=yr(f.outputSchema)),typeof f.callback<"u"&&(p.handler=f.callback),typeof f.annotations<"u"&&(p.annotations=f.annotations),typeof f._meta<"u"&&(p._meta=f._meta),typeof f.enabled<"u"&&(p.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Md(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Md(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:d}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},d,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},nA={type:"object",properties:{}};ko={completion:{values:[],hasMore:!1}}});function iA(t){return mm.parse(JSON.parse(t))}function wb(t){return JSON.stringify(t)+`
|
|
2014
|
-
`}var
|
|
2015
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
2310
|
+
deps: ${r}}`};var FP={keyword:"dependencies",type:"object",schemaType:"object",error:At.error,code(t){let[e,r]=HP(t);by(t,e),wy(t,r)}};function HP({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function by(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,_o.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let d of a)(0,_o.checkReportMissingProp)(t,d)}):(r.if((0,pd._)`${l} && (${(0,_o.checkMissingProp)(t,a,s)})`),(0,_o.reportMissingProp)(t,s),r.else())}}At.validatePropertyDeps=by;function wy(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,BP.alwaysValidSchema)(s,e[a])||(r.if((0,_o.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}At.validateSchemaDeps=wy;At.default=FP});var Sy=U(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var _y=re(),KP=ue(),VP={message:"property name must be valid",params:({params:t})=>(0,_y._)`{propertyName: ${t.propertyName}}`},GP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:VP,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,KP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,_y.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};hd.default=GP});var fd=U(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var wi=dt(),St=re(),WP=Mt(),vi=ue(),JP={message:"must NOT have additional properties",params:({params:t})=>(0,St._)`{additionalProperty: ${t.additionalProperty}}`},YP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:JP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,vi.alwaysValidSchema)(i,r))return;let d=(0,wi.allSchemaProperties)(n.properties),p=(0,wi.allSchemaProperties)(n.patternProperties);g(),t.ok((0,St._)`${s} === ${WP.default.errors}`);function g(){e.forIn("key",o,$=>{!d.length&&!p.length?k($):e.if(S($),()=>k($))})}function S($){let P;if(d.length>8){let I=(0,vi.schemaRefOrVal)(i,n.properties,"properties");P=(0,wi.isOwnProperty)(e,I,$)}else d.length?P=(0,St.or)(...d.map(I=>(0,St._)`${$} === ${I}`)):P=St.nil;return p.length&&(P=(0,St.or)(P,...p.map(I=>(0,St._)`${(0,wi.usePattern)(t,I)}.test(${$})`))),(0,St.not)(P)}function y($){e.code((0,St._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,vi.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(R($,P,!1),e.if((0,St.not)(P),()=>{t.reset(),y($)})):(R($,P),a||e.if((0,St.not)(P),()=>e.break()))}}function R($,P,I){let D={keyword:"additionalProperties",dataProp:$,dataPropType:vi.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};md.default=YP});var xy=U(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var XP=io(),ky=dt(),gd=ue(),Ty=fd(),ZP={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ty.default.code(new XP.KeywordCxt(s,Ty.default,"additionalProperties"));let i=(0,ky.allSchemaProperties)(r);for(let g of i)s.definedProperties.add(g);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=gd.mergeEvaluated.props(e,(0,gd.toHash)(i),s.props));let a=i.filter(g=>!(0,gd.alwaysValidSchema)(s,r[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)d(g)?p(g):(e.if((0,ky.propertyInData)(e,o,g,s.opts.ownProperties)),p(g),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function d(g){return s.opts.useDefaults&&!s.compositeRule&&r[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};yd.default=ZP});var Py=U(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var Ry=dt(),_i=re(),$y=ue(),Ey=ue(),QP={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Ry.allSchemaProperties)(r),l=a.filter(R=>(0,$y.alwaysValidSchema)(s,r[R]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof _i.Name)&&(s.props=(0,Ey.evaluatedPropsToName)(e,s.props));let{props:g}=s;S();function S(){for(let R of a)d&&y(R),s.allErrors?k(R):(e.var(p,!0),k(R),e.if(p))}function y(R){for(let $ in d)new RegExp(R).test($)&&(0,$y.checkStrictMode)(s,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){e.forIn("key",n,$=>{e.if((0,_i._)`${(0,Ry.usePattern)(t,R)}.test(${$})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:Ey.Type.Str},p),s.opts.unevaluated&&g!==!0?e.assign((0,_i._)`${g}[${$}]`,!0):!P&&!s.allErrors&&e.if((0,_i.not)(p),()=>e.break())})})}}};bd.default=QP});var Ay=U(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var e0=ue(),t0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,e0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};wd.default=t0});var Cy=U(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var r0=dt(),n0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r0.validateUnion,error:{message:"must match a schema in anyOf"}};vd.default=n0});var Iy=U(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var Si=re(),o0=ue(),s0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Si._)`{passingSchemas: ${t.passing}}`},i0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:s0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){s.forEach((p,g)=>{let S;(0,o0.alwaysValidSchema)(o,p)?e.var(l,!0):S=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,Si._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Si._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),S&&t.mergeEvaluated(S,Si.Name)})})}}};_d.default=i0});var Oy=U(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var a0=ue(),l0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,a0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Sd.default=l0});var jy=U(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var ki=re(),Ly=ue(),c0={message:({params:t})=>(0,ki.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ki._)`{failingKeyword: ${t.ifClause}}`},d0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:c0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Ly.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ny(n,"then"),s=Ny(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,d("then",p),d("else",p))}else o?e.if(a,d("then")):e.if((0,ki.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function d(p,g){return()=>{let S=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(S,i),g?e.assign(g,(0,ki._)`${p}`):t.setParams({ifClause:p})}}}};function Ny(t,e){let r=t.schema[e];return r!==void 0&&!(0,Ly.alwaysValidSchema)(t,r)}kd.default=d0});var Dy=U(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var u0=ue(),p0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,u0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Td.default=p0});var Uy=U(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var h0=ad(),m0=my(),f0=ld(),g0=gy(),y0=yy(),b0=vy(),w0=Sy(),v0=fd(),_0=xy(),S0=Py(),k0=Ay(),T0=Cy(),x0=Iy(),R0=Oy(),$0=jy(),E0=Dy();function P0(t=!1){let e=[k0.default,T0.default,x0.default,R0.default,$0.default,E0.default,w0.default,v0.default,b0.default,_0.default,S0.default];return t?e.push(m0.default,g0.default):e.push(h0.default,f0.default),e.push(y0.default),e}xd.default=P0});var My=U(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var Re=re(),A0={message:({schemaCode:t})=>(0,Re.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Re._)`{format: ${t}}`},C0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:A0,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;o?S():y();function S(){let k=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),R=r.const("fDef",(0,Re._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,Re._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign($,(0,Re._)`${R}.type || "string"`).assign(P,(0,Re._)`${R}.validate`),()=>r.assign($,(0,Re._)`"string"`).assign(P,R)),t.fail$data((0,Re.or)(I(),D()));function I(){return l.strictSchema===!1?Re.nil:(0,Re._)`${i} && !${P}`}function D(){let Y=p.$async?(0,Re._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,Re._)`${P}(${n})`,H=(0,Re._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${n}))`;return(0,Re._)`${P} && ${P} !== true && ${$} === ${e} && !${H}`}}function y(){let k=g.formats[s];if(!k){I();return}if(k===!0)return;let[R,$,P]=D(k);R===e&&t.pass(Y());function I(){if(l.strictSchema===!1){g.logger.warn(H());return}throw new Error(H());function H(){return`unknown format "${s}" ignored in schema at path "${d}"`}}function D(H){let Oe=H instanceof RegExp?(0,Re.regexpCode)(H):l.code.formats?(0,Re._)`${l.code.formats}${(0,Re.getProperty)(s)}`:void 0,Ce=r.scopeValue("formats",{key:s,ref:H,code:Oe});return typeof H=="object"&&!(H instanceof RegExp)?[H.type||"string",H.validate,(0,Re._)`${Ce}.validate`]:["string",H,Ce]}function Y(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${P}(${n})`}return typeof $=="function"?(0,Re._)`${P}(${n})`:(0,Re._)`${P}.test(${n})`}}}};Rd.default=C0});var qy=U($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var I0=My(),O0=[I0.default];$d.default=O0});var zy=U(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.contentVocabulary=ln.metadataVocabulary=void 0;ln.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ln.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Fy=U(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var N0=Yg(),L0=dy(),j0=Uy(),D0=qy(),By=zy(),U0=[N0.default,L0.default,(0,j0.default)(),D0.default,By.metadataVocabulary,By.contentVocabulary];Ed.default=U0});var Ky=U(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.DiscrError=void 0;var Hy;(function(t){t.Tag="tag",t.Mapping="mapping"})(Hy||(Ti.DiscrError=Hy={}))});var Gy=U(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var cn=re(),Pd=Ky(),Vy=si(),M0=ao(),q0=ue(),z0={message:({params:{discrError:t,tagName:e}})=>t===Pd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,cn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},B0={keyword:"discriminator",type:"object",schemaType:"object",error:z0,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),d=e.const("tag",(0,cn._)`${r}${(0,cn.getProperty)(a)}`);e.if((0,cn._)`typeof ${d} == "string"`,()=>p(),()=>t.error(!1,{discrError:Pd.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function p(){let y=S();e.if(!1);for(let k in y)e.elseIf((0,cn._)`${d} === ${k}`),e.assign(l,g(y[k]));e.else(),t.error(!1,{discrError:Pd.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function g(y){let k=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:y},k);return t.mergeEvaluated(R,cn.Name),k}function S(){var y;let k={},R=P(o),$=!0;for(let Y=0;Y<i.length;Y++){let H=i[Y];if(H?.$ref&&!(0,q0.schemaHasRulesButRef)(H,s.self.RULES)){let Ce=H.$ref;if(H=Vy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ce),H instanceof Vy.SchemaEnv&&(H=H.schema),H===void 0)throw new M0.default(s.opts.uriResolver,s.baseId,Ce)}let Oe=(y=H?.properties)===null||y===void 0?void 0:y[a];if(typeof Oe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(R||P(H)),I(Oe,Y)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function I(Y,H){if(Y.const)D(Y.const,H);else if(Y.enum)for(let Oe of Y.enum)D(Oe,H);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,H){if(typeof Y!="string"||Y in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[Y]=H}}}};Ad.default=B0});var Wy=U((dU,F0)=>{F0.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 Id=U((ke,Cd)=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.MissingRefError=ke.ValidationError=ke.CodeGen=ke.Name=ke.nil=ke.stringify=ke.str=ke._=ke.KeywordCxt=ke.Ajv=void 0;var H0=Hg(),K0=Fy(),V0=Gy(),Jy=Wy(),G0=["/properties"],xi="http://json-schema.org/draft-07/schema",dn=class extends H0.default{_addVocabularies(){super._addVocabularies(),K0.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(V0.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Jy,G0):Jy;this.addMetaSchema(e,xi,!1),this.refs["http://json-schema.org/schema"]=xi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xi)?xi:void 0)}};ke.Ajv=dn;Cd.exports=ke=dn;Cd.exports.Ajv=dn;Object.defineProperty(ke,"__esModule",{value:!0});ke.default=dn;var W0=io();Object.defineProperty(ke,"KeywordCxt",{enumerable:!0,get:function(){return W0.KeywordCxt}});var un=re();Object.defineProperty(ke,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(ke,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(ke,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(ke,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(ke,"Name",{enumerable:!0,get:function(){return un.Name}});Object.defineProperty(ke,"CodeGen",{enumerable:!0,get:function(){return un.CodeGen}});var J0=ni();Object.defineProperty(ke,"ValidationError",{enumerable:!0,get:function(){return J0.default}});var Y0=ao();Object.defineProperty(ke,"MissingRefError",{enumerable:!0,get:function(){return Y0.default}})});var nb=U(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.formatNames=It.fastFormats=It.fullFormats=void 0;function Ct(t,e){return{validate:t,compare:e}}It.fullFormats={date:Ct(Qy,jd),time:Ct(Nd(!0),Dd),"date-time":Ct(Yy(!0),tb),"iso-time":Ct(Nd(),eb),"iso-date-time":Ct(Yy(),rb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:rA,"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:cA,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:nA,int32:{type:"number",validate:iA},int64:{type:"number",validate:aA},float:{type:"number",validate:Zy},double:{type:"number",validate:Zy},password:!0,binary:!0};It.fastFormats={...It.fullFormats,date:Ct(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jd),time:Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Dd),"date-time":Ct(/^\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":Ct(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,eb),"iso-date-time":Ct(/^\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,rb),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};It.formatNames=Object.keys(It.fullFormats);function X0(t){return t%4===0&&(t%100!==0||t%400===0)}var Z0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Q0=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Qy(t){let e=Z0.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&X0(r)?29:Q0[n])}function jd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Od=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Nd(t){return function(r){let n=Od.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),p=+(n[7]||0);if(d>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let g=s-p*l,S=o-d*l-(g<0?1:0);return(S===23||S===-1)&&(g===59||g===-1)&&i<61}}function Dd(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function eb(t,e){if(!(t&&e))return;let r=Od.exec(t),n=Od.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Ld=/t|\s/i;function Yy(t){let e=Nd(t);return function(n){let o=n.split(Ld);return o.length===2&&Qy(o[0])&&e(o[1])}}function tb(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function rb(t,e){if(!(t&&e))return;let[r,n]=t.split(Ld),[o,s]=e.split(Ld),i=jd(r,o);if(i!==void 0)return i||Dd(n,s)}var eA=/\/|:/,tA=/^(?:[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 rA(t){return eA.test(t)&&tA.test(t)}var Xy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function nA(t){return Xy.lastIndex=0,Xy.test(t)}var oA=-(2**31),sA=2**31-1;function iA(t){return Number.isInteger(t)&&t<=sA&&t>=oA}function aA(t){return Number.isInteger(t)}function Zy(){return!0}var lA=/[^\\]\\Z/;function cA(t){if(lA.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ob=U(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.formatLimitDefinition=void 0;var dA=Id(),kt=re(),lr=kt.operators,Ri={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},uA={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${Ri[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${Ri[t].okStr}, limit: ${e}}`};pn.formatLimitDefinition={keyword:Object.keys(Ri),type:"string",schemaType:"string",$data:!0,error:uA,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new dA.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?d():p();function d(){let S=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,kt._)`${S}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${y} != "object"`,(0,kt._)`${y} instanceof RegExp`,(0,kt._)`typeof ${y}.compare != "function"`,g(y)))}function p(){let S=l.schema,y=a.formats[S];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${S}" does not define "compare" function`);let k=e.scopeValue("formats",{key:S,ref:y,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(S)}`:void 0});t.fail$data(g(k))}function g(S){return(0,kt._)`${S}.compare(${r}, ${n}) ${Ri[o].fail} 0`}},dependencies:["format"]};var pA=t=>(t.addKeyword(pn.formatLimitDefinition),t);pn.default=pA});var lb=U((So,ab)=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});var hn=nb(),hA=ob(),Ud=re(),sb=new Ud.Name("fullFormats"),mA=new Ud.Name("fastFormats"),Md=(t,e={keywords:!0})=>{if(Array.isArray(e))return ib(t,e,hn.fullFormats,sb),t;let[r,n]=e.mode==="fast"?[hn.fastFormats,mA]:[hn.fullFormats,sb],o=e.formats||hn.formatNames;return ib(t,o,r,n),e.keywords&&(0,hA.default)(t),t};Md.get=(t,e="full")=>{let n=(e==="fast"?hn.fastFormats:hn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function ib(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ud._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}ab.exports=So=Md;Object.defineProperty(So,"__esModule",{value:!0});So.default=Md});function fA(){let t=new cb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,db.default)(t),t}var cb,db,$i,ub=j(()=>{cb=eu(Id(),1),db=eu(lb(),1);$i=class{constructor(e){this._ajv=e??fA()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Ei,pb=j(()=>{Jr();Ei=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(l.filter(S=>S.type==="tool_use").map(S=>S.id)),g=new Set(s.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(p.size!==g.size||![...p].every(S=>g.has(S)))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},Hn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Wr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function hb(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function mb(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var fb=j(()=>{});var Pi,gb=j(()=>{wf();Jr();ub();Nn();pb();fb();Pi=class extends Hs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new $i,this.setRequestHandler(Qa,n=>this._oninitialize(n)),this.setNotificationHandler(el,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(al,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Fn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ei(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=bf(this._capabilities,e)}setRequestHandler(e,r){let o=Xt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Fr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,d)=>{let p=Yt(Gr,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new z(K.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:g}=p.data,S=await Promise.resolve(r(l,d));if(g.task){let k=Yt(Kr,S);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new z(K.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let y=Yt(Is,S);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new z(K.InvalidParams,`Invalid tools/call result: ${k}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){mb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&hb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:gm.includes(r)?r:Wa,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"},gs)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(d=>d.type==="tool_use");if(s){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(a.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(o.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(d.size!==p.size||![...d].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},ll,r):this.request({method:"sampling/createMessage",params:e},Hn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Wr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Wr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.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 s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},cl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function qd(t){return!!t&&typeof t=="object"&&bb in t}function wb(t){return t[bb]?.complete}var bb,yb,vb=j(()=>{bb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(yb||(yb={}))});var _b=j(()=>{});function yA(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"),!gA.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function bA(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function zd(t){let e=yA(t);return bA(t,e.warnings),e.isValid}var gA,Sb=j(()=>{gA=/^[A-Za-z0-9._-]{1,128}$/});var Ai,kb=j(()=>{Ai=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as wA}from"zod";function Rb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function $b(t){return"_def"in t||"_zod"in t||Rb(t)}function Bd(t){return typeof t!="object"||t===null||$b(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Rb)}function Tb(t){if(t){if(Bd(t))return yr(t);if(!$b(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function _A(t){let e=Xt(t);return e?Object.entries(e).map(([r,n])=>{let o=mm(n),s=fm(n);return{name:r,description:o,required:!s}}):[]}function cr(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fr(r);if(typeof n=="string")return n;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 Ci,vA,ko,Eb=j(()=>{gb();Nn();Vl();Jr();vb();_b();Sb();kb();Ci=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Pi(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ai(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Cs)),this.server.assertCanSetRequestHandler(cr(Gr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Cs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Br(r.inputSchema);return o?Fl(o,{strictUnions:!0,pipeStrategy:"input"}):vA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Br(r.outputSchema);o&&(n.outputSchema=Fl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Gr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new z(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof z&&n.code===K.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Br(e.inputSchema)??e.inputSchema,i=await us(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ps(a);throw new z(K.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new z(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Br(e.outputSchema),s=await us(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ps(i);throw new z(K.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),l=a.task.taskId,d=a.task,p=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(S=>setTimeout(S,p));let g=await n.taskStore.getTask(l);if(!g)throw new z(K.InternalError,`Task ${l} not found during polling`);d=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cr(Os)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Os,async e=>{switch(e.params.ref.type){case"ref/prompt":return Im(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Om(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,r){let n=this._registeredPrompts[r.name];if(!n)throw new z(K.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ko;let s=Xt(n.argsSchema)?.[e.params.argument.name];if(!qd(s))return ko;let i=wb(s);if(!i)return ko;let a=await i(e.params.argument.value,e.params.context);return xb(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ko;throw new z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ko;let s=await o(e.params.argument.value,e.params.context);return xb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Rs)),this.server.assertCanSetRequestHandler(cr($s)),this.server.assertCanSetRequestHandler(cr(Es)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Rs,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler($s,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Es,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(K.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new z(K.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Ps)),this.server.assertCanSetRequestHandler(cr(As)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ps,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?_A(r.argsSchema):void 0}))})),this.server.setRequestHandler(As,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Br(n.argsSchema),s=await us(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",d=ps(l);throw new z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:yr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=yr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(l=>{let d=l instanceof wA?l._def?.innerType:l;return qd(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,d){zd(e);let p={title:r,description:n,inputSchema:Tb(o),outputSchema:Tb(s),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&zd(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=yr(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=yr(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,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Bd(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Bd(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:d}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},d,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},vA={type:"object",properties:{}};ko={completion:{values:[],hasMore:!1}}});function kA(t){return Tm.parse(JSON.parse(t))}function Pb(t){return JSON.stringify(t)+`
|
|
2311
|
+
`}var SA,Ii,Ab=j(()=>{Jr();SA=10*1024*1024,Ii=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??SA}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(`
|
|
2312
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),kA(r)}clear(){this._buffer=void 0}}});import Cb from"node:process";var Oi,Ib=j(()=>{Ab();Oi=class{constructor(e=Cb.stdin,r=Cb.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Ii({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Pb(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Ob,Nb=j(()=>{Ob=[]});var Fb={};Qd(Fb,{AUTHORING_MCP_SERVER_NAME:()=>Ub,AUTHORING_MCP_SERVER_VERSION:()=>Mb,AUTHORING_RESOURCES:()=>AA,AUTHORING_TOOLS:()=>PA,AUTHORING_TOOLS_PUBLIC:()=>Bb,buildAuthoringMcpServer:()=>zb,resolveSamplesDir:()=>qb,runAuthoringMcpServer:()=>CA});import{promises as TA}from"node:fs";import{isAbsolute as xA,resolve as Ni,sep as RA}from"node:path";import{z as M}from"zod";function Db(){return jb??=import("../mcp/grounding.js").then(e=>e,()=>null),jb}function qb(t,e){if(e===void 0)return Ni(process.cwd(),t??"samples");let r=Ni(e);if(t===void 0)return r;if(xA(t))return null;let n=Ni(r,t);return n===r||n.startsWith(r+RA)?n:null}function xe(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function EA(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function zb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let y=await ht(t.baseUrl);if(!y)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:y.baseUrl,token:y.token}}let r=t.grounding??{},n=await Db(),o=null;if(n)try{let y=await e();o={surface:"mcp-authoring",baseUrl:y.baseUrl,token:y.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],l=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(o,i)).map(y=>({id:y.id,record_type:y.record_type,intent:y.intent}))}catch{l=[]}}let d=o?await EA(o,r):null,p=new Ci({name:Ub,version:Mb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:d,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let R=await n.getMcpPromptSkill(y,k.id,r);if(!R)throw new Error(`unknown prompt: ${k.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
|
|
2016
2313
|
|
|
2017
|
-
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Te(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return Te(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Te(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(xb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:k,limit:R})=>{let{baseUrl:$,token:P}=await e(),I=new URLSearchParams({q:y});k&&I.set("kind",k),R!==void 0&&I.set("limit",String(R));let D=await fetch(`${$}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Te(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(xb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:R,token:$}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Te(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return Te(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:R}=await e(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Te(await $.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:k,token:R}=await e();return{content:[{type:"text",text:await hr({baseUrl:k,token:R,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let k=Rt("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return Te({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let k=Rt("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return Te({path:k.relativePath,content:k.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:M.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:M.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:M.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:M.string().optional()}},async y=>{let k=Rt("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return Te({path:k.relativePath,content:k.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:M.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:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:M.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:M.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:M.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:M.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:M.array(M.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.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:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let R=Ab(k,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:dA})}],isError:!0};let $;try{$=await _n(R)}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 Ho(y,$.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return Te({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:k,token:R}=await e(),P=await new q({baseUrl:k,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return Te(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:k,description:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsCreate({slug:y,name:k,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return Te(await $.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:k,note:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return Te(await I.appsPush(y,k,{note:R}))});let f=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(f).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return Te(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return Te(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:R}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:R}=await e(),$=await hr({baseUrl:k,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ii(process.cwd(),"samples"),R=[];try{R=(await aA.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let $=await _n(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await $b(),R=[];if(k){let{baseUrl:$,token:P}=await e();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function mA(t={}){let e=await Cb(t),r=new Ci;await e.connect(r)}var xb,Rb,Eb,Pb,dA,Ib,pA,hA,Nb=j(()=>{bb();Sb();Zi();bn();mt();ca();Jo();Tb();xb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Eb="turbobase-authoring",Pb="0.1.0";dA="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.";Ib=["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"],pA=[...Ib,...kb],hA=["catalog:///","types://all","samples:///","recipes:///"]});Zi();bn();mt();ca();import{spawn as Kd}from"node:child_process";import{promises as ae}from"node:fs";import{homedir as fA}from"node:os";import{basename as Db,dirname as zt,join as et,relative as Ni,resolve as se,sep as Hd}from"node:path";import{Command as gA}from"commander";Fo();import{promises as Du}from"node:fs";var qw=/^[a-z][a-z0-9_]+$/;function Iu(t,e){if(typeof t!="string"||!qw.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var zw="customrecord",Bw="customlist";function Fw(t){return t.startsWith("customrecord_")?t.slice(13):t}function Hw(t){return t.startsWith("customlist_")?t.slice(11):t}function Kw(t){return Iu(t,"custom_record scriptId"),`cr_${Fw(t)}`}function Vw(t){return Iu(t,"custom_list scriptId"),`cl_${Hw(t)}`}function Ou(t){return t.startsWith(zw)?Kw(t):t.startsWith(Bw)?Vw(t):null}var Gw={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Nu(t,e){let r=e?Jw[`${e}:${t}`]:void 0;if(r)return r;let n=Gw[t];if(n)return n;let o=Ou(t);return o?{table:o}:void 0}var Ww={accountingPeriod:"accounting_period",printer:"printer"};var Jw={...Object.fromEntries(Object.entries(Ww).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function Lu(t,e){let r=Nu(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function ju(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Lu(t,n),i=Lu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Uu=4;function da(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Ir(t,"id"),r=Ir(t,"on"),n=Ir(t,"source"),o=Ir(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let d=Ir(l[1]??"","source"),p=Ir(l[1]??"","recordType");d&&p&&s.push({source:d,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Uu}}function Ir(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Yw(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 Mu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=da(t)}catch(d){return{fixtureName:o,conduit:Zw(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}let a=Yw(e),l=Object.entries(e.atlasLinks??{}).map(([d,p])=>({key:d,resolved:p}));try{let d=await Bo(t,{resolveDir:n.resolveDir}),f=!!(await vn(d,a,{member:"when",timeoutMs:zo})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let _=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${_} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let y=[],k=[],R=[];for(let P=0;P<i.targets.length;P+=1){let I=i.targets[P],D=await vn(d,{...a,materialized:R.map(Ft=>({...Ft}))},{member:"transform",stepIndex:P,timeoutMs:zo});y.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let F=Y,Oe=ju(i.fromRecordType,I.recordType,{fromSource:i.fromSource,toSource:I.source}),{wouldWriteBindings:Ce,masterAction:Bt}=Xw(i,I,Oe,e);k.push({to:I,transformResult:F,applyBranch:Oe,wouldWriteBindings:Ce,masterAction:Bt}),R.push({source:I.source,recordType:I.recordType,masterTable:`<${I.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let $=k[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:k,logs:y}}catch(d){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}}function Xw(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function Zw(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Uu}}async function qu(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 zu(t){let e=await Du.readFile(t,"utf8");return JSON.parse(e)}function Bu(t){return Du.readFile(t,"utf8")}function Fu(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((l,d)=>l+d.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
|
|
2018
|
-
`);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let d=n?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${d} \u2192 patch:`),o.push(
|
|
2019
|
-
`)}function
|
|
2314
|
+
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return xe(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return xe(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return xe(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return xe(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Lb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:k,limit:R})=>{let{baseUrl:$,token:P}=await e(),I=new URLSearchParams({q:y});k&&I.set("kind",k),R!==void 0&&I.set("limit",String(R));let D=await fetch(`${$}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return xe(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(Lb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:R,token:$}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return xe(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return xe(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:R}=await e(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return xe(await $.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:k,token:R}=await e();return{content:[{type:"text",text:await hr({baseUrl:k,token:R,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let k=Rt("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return xe({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let k=Rt("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return xe({path:k.relativePath,content:k.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:M.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:M.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:M.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:M.string().optional()}},async y=>{let k=Rt("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return xe({path:k.relativePath,content:k.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:M.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:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:M.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:M.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:M.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:M.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:M.array(M.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return xe(await $.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.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:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let R=qb(k,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:$A})}],isError:!0};let $;try{$=await _n(R)}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 Ko(y,$.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return xe({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:k,token:R}=await e(),P=await new q({baseUrl:k,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return xe(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return xe({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return xe(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:k,description:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return xe(await I.appsCreate({slug:y,name:k,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:R}=await e(),$=new q({baseUrl:k,token:R});return xe(await $.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:k,note:R})=>{let{baseUrl:$,token:P}=await e(),I=new q({baseUrl:$,token:P});return xe(await I.appsPush(y,k,{note:R}))});let g=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),S=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(g).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),R=new q({baseUrl:y,token:k});return xe(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(S),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return xe(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(S),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await e(),P=new q({baseUrl:R,token:$});return xe(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:R}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:R}=await e(),$=await hr({baseUrl:k,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ni(process.cwd(),"samples"),R=[];try{R=(await TA.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let $=await _n(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await Db(),R=[];if(k){let{baseUrl:$,token:P}=await e();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function CA(t={}){let e=await zb(t),r=new Oi;await e.connect(r)}var Lb,jb,Ub,Mb,$A,Bb,PA,AA,Hb=j(()=>{Eb();Ib();ea();bn();mt();ua();Xo();Nb();Lb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Ub="turbobase-authoring",Mb="0.1.0";$A="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","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],PA=[...Bb,...Ob],AA=["catalog:///","types://all","samples:///","recipes:///"]});ea();bn();mt();ua();import{spawn as Wd}from"node:child_process";import{promises as ae}from"node:fs";import{homedir as IA}from"node:os";import{basename as Gb,dirname as zt,join as et,relative as ji,resolve as se,sep as Gd}from"node:path";import{Command as OA}from"commander";Ho();import{promises as Bu}from"node:fs";var ev=/^[a-z][a-z0-9_]+$/;function Du(t,e){if(typeof t!="string"||!ev.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var tv="customrecord",rv="customlist";function nv(t){return t.startsWith("customrecord_")?t.slice(13):t}function ov(t){return t.startsWith("customlist_")?t.slice(11):t}function sv(t){return Du(t,"custom_record scriptId"),`cr_${nv(t)}`}function iv(t){return Du(t,"custom_list scriptId"),`cl_${ov(t)}`}function Uu(t){return t.startsWith(tv)?sv(t):t.startsWith(rv)?iv(t):null}var av={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Mu(t,e){let r=e?cv[`${e}:${t}`]:void 0;if(r)return r;let n=av[t];if(n)return n;let o=Uu(t);return o?{table:o}:void 0}var lv={accountingPeriod:"accounting_period",printer:"printer"};var cv={...Object.fromEntries(Object.entries(lv).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function qu(t,e){let r=Mu(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function zu(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=qu(t,n),i=qu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Fu=4;function pa(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Ir(t,"id"),r=Ir(t,"on"),n=Ir(t,"source"),o=Ir(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let d=Ir(l[1]??"","source"),p=Ir(l[1]??"","recordType");d&&p&&s.push({source:d,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Fu}}function Ir(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function dv(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 Hu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=pa(t)}catch(d){return{fixtureName:o,conduit:pv(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}let a=dv(e),l=Object.entries(e.atlasLinks??{}).map(([d,p])=>({key:d,resolved:p}));try{let d=await Fo(t,{resolveDir:n.resolveDir}),g=!!(await vn(d,a,{member:"when",timeoutMs:Bo})).whenResult;s.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 S=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${S} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!g)return{fixtureName:o,conduit:i,guards:s,whenPassed:g,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let y=[],k=[],R=[];for(let P=0;P<i.targets.length;P+=1){let I=i.targets[P],D=await vn(d,{...a,materialized:R.map(Ft=>({...Ft}))},{member:"transform",stepIndex:P,timeoutMs:Bo});y.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let H=Y,Oe=zu(i.fromRecordType,I.recordType,{fromSource:i.fromSource,toSource:I.source}),{wouldWriteBindings:Ce,masterAction:Bt}=uv(i,I,Oe,e);k.push({to:I,transformResult:H,applyBranch:Oe,wouldWriteBindings:Ce,masterAction:Bt}),R.push({source:I.source,recordType:I.recordType,masterTable:`<${I.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let $=k[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:g,atlasResolutions:l,transformResult:$.transformResult,applyBranch:$.applyBranch,wouldWriteBindings:$.wouldWriteBindings,masterAction:$.masterAction,targets:k,logs:y}}catch(d){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:d instanceof Error?d.message:String(d)}}}function uv(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function pv(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Fu}}async function Ku(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 Vu(t){let e=await Bu.readFile(t,"utf8");return JSON.parse(e)}function Gu(t){return Bu.readFile(t,"utf8")}function Wu(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((l,d)=>l+d.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
|
|
2315
|
+
`);let i=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let d=n?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${d} \u2192 patch:`),o.push(hv(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${d}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${d}:`);for(let p of a.wouldWriteBindings)o.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
|
|
2316
|
+
`)}function hv(t,e){return t.split(`
|
|
2020
2317
|
`).map(r=>e+r).join(`
|
|
2021
|
-
`)}var
|
|
2318
|
+
`)}var mv="2026-01-01",Ju="2026-01-01T00:00:00.000Z";function fv(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?mv:r.startsWith("timestamp")?Ju:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:Ju}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function gv(t){let e={};for(let r of t.columns)e[r.name]=fv(r.pgType,r.name);return e}function yv(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:gv(t)},expect:e.expect??"pass"}}function Yu(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:yv(r,e)}))}import{promises as Xu}from"node:fs";import{join as Zu,relative as bv,sep as wv}from"node:path";var vv=67324752,_v=33639248,Sv=101010256,kv=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Tv(t){let e=4294967295;for(let r=0;r<t.length;r++)e=kv[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function xv(t){let e=[];async function r(n){let o=await Xu.readdir(n,{withFileTypes:!0});for(let s of o){let i=Zu(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(bv(t,i).split(wv).join("/"))}}return await r(t),e.sort(),e}async function Qu(t){let e=await xv(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),d=await Xu.readFile(Zu(t,a)),p=Tv(d),g=Buffer.alloc(30+l.length);g.writeUInt32LE(vv,0),g.writeUInt16LE(20,4),g.writeUInt16LE(0,6),g.writeUInt16LE(0,8),g.writeUInt32LE(p,14),g.writeUInt32LE(d.length,18),g.writeUInt32LE(d.length,22),g.writeUInt16LE(l.length,26),l.copy(g,30),r.push(g,d);let S=Buffer.alloc(46+l.length);S.writeUInt32LE(_v,0),S.writeUInt16LE(20,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,10),S.writeUInt32LE(p,16),S.writeUInt32LE(d.length,20),S.writeUInt32LE(d.length,24),S.writeUInt16LE(l.length,28),S.writeUInt32LE(o,42),l.copy(S,46),n.push(S),o+=g.length+d.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(Sv,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}ia();function Rv(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Vo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function $v(t){let e=Ev(t,"from"),n=ep(t,"to").map(o=>({source:Vo(o,"source"),recordType:Vo(o,"recordType")}));return{fromSource:e?Vo(e,"source"):void 0,fromRecordType:e?Vo(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function Ev(t,e){return ep(t,e)[0]??null}function ep(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function Pv(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let l=t[s];if(o){l==="\\"?s+=1:l===o&&(o=null);continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Av(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function Cv(t){return/\bcreatedFrom\b/.test(t)}function tp(t){let e=Rv(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=$v(t);for(let p of i)if(n&&p.source&&n===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=Pv(t);if(a!==null){let p=/\bexternalId\b/.test(a),g=/\bfromSource\b/.test(a);!p&&!g&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let l=i.find(p=>p.recordType&&o&&p.recordType!==o)?.recordType??(o!==s?s:void 0);o&&l&&!Cv(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \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 d=Av(t,"cycleBudget");return d!==void 0&&(d<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${d} 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)."}):d>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${d} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function rp(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
|
|
2022
2319
|
`);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
2023
2320
|
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
2024
|
-
`)}function
|
|
2321
|
+
`)}function np(t){return t.cases.filter(e=>e.status==="failed").length}function kn(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Iv(t){let e=np(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${kn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${kn(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${kn(n.type)}"`:"";r.push(` <failure${i} message="${kn(s)}">${kn(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
2025
2322
|
`)}
|
|
2026
|
-
`}function
|
|
2027
|
-
`}function
|
|
2028
|
-
`)}function ft(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(d=>d.length)),i=[];for(let d=0;d<s;d+=1)i[d]=Math.max(0,...o.map(p=>Nt(p[d]??"")));let a=d=>{let p=d.map((
|
|
2029
|
-
`)}function
|
|
2323
|
+
`}function Ov(t){let e={suite:t.name,tests:t.cases.length,failures:np(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
2324
|
+
`}function Go(t,e){return e==="junit"?Iv(t):Ov(t)}var Ge={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"},Ee={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Or=["\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"},op=/\x1b\[[0-9;]*m/g;function Nt(t){return t.replace(op,"").length}function ha(t,e){return e<=0?1:Math.max(1,Math.ceil(Nt(t)/e))}function Nv(){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 ma=Nv();function Ie(){return ma}function fa(t){ma=t}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ot(t,e){return ma?`${t}${e}${Ge.reset}`:e}var m={bold:t=>ot(Ge.bold,t),dim:t=>ot(Ge.dim,t),red:t=>ot(Ge.red,t),green:t=>ot(Ge.green,t),yellow:t=>ot(Ge.yellow,t),blue:t=>ot(Ge.blue,t),magenta:t=>ot(Ge.magenta,t),cyan:t=>ot(Ge.cyan,t),grey:t=>ot(Ge.grey,t)};var _e={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},Vt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},Lv=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),jv=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Dv=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Nr(t){let e=t.toLowerCase();return Lv.has(e)?m.green(t):jv.has(e)?m.red(t):Dv.has(e)?m.yellow(t):t}function Gt(t,e=[]){let r=Math.max(Nt(t),...e.map(Nt),0),n=r+2,o=m.cyan(nt.v),s=a=>` ${a}${" ".repeat(r-Nt(a))} `,i=[m.cyan(`${nt.tl}${nt.h.repeat(n)}${nt.tr}`),`${o}${m.bold(s(t))}${o}`];if(e.length){i.push(`${m.cyan(nt.ml)}${m.dim(nt.h.repeat(n))}${m.cyan(nt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(m.cyan(`${nt.bl}${nt.h.repeat(n)}${nt.br}`)),i.join(`
|
|
2325
|
+
`)}function ft(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(d=>d.length)),i=[];for(let d=0;d<s;d+=1)i[d]=Math.max(0,...o.map(p=>Nt(p[d]??"")));let a=d=>{let p=d.map((g,S)=>{let y=g??"";return S===d.length-1?y:y+" ".repeat(Math.max(0,i[S]-Nt(y)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(d=>m.bold(d)))),l.push(a(e.head.map((d,p)=>m.dim("\u2500".repeat(i[p]??Nt(d)))))));for(let d of t)l.push(a(d));return l.join(`
|
|
2326
|
+
`)}function ga(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`${Ie()?e.map(n=>ot(Ge.cyan,n)).join(`
|
|
2030
2327
|
`):e.join(`
|
|
2031
2328
|
`)}
|
|
2032
|
-
${
|
|
2033
|
-
`),i}catch(i){throw s(),r&&st(`${
|
|
2034
|
-
`),i}}function
|
|
2035
|
-
`),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),st(Ee.showCursor);let d=l.stage!=="failed",p=`${t} ${
|
|
2036
|
-
`)},stop(){clearInterval(a),i(),st(Ee.showCursor)}}}function
|
|
2037
|
-
`),a(`${
|
|
2038
|
-
`),a(Ee.hideCursor);let p=0,
|
|
2039
|
-
`),$+=
|
|
2329
|
+
${m.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function Wo(){return Ie()&&process.stderr.isTTY===!0}function sp(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${m.dim("\u2591".repeat(e-n))}`}async function J(t,e){let r=Wo(),n=0,o;r&&(st(Ee.hideCursor),o=setInterval(()=>{st(`${Ee.col0}${Ee.clearLine}${m.magenta(Or[n++%Or.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&st(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await e();return s(),r&&st(`${_e.success(t)}
|
|
2330
|
+
`),i}catch(i){throw s(),r&&st(`${_e.error(t)}
|
|
2331
|
+
`),i}}function ya(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=m.magenta(Or[e%Or.length]),d=m.cyan(r.stage),p=r.runStatus?` ${m.dim(`(${r.runStatus})`)}`:"",g=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${m.dim("\u25B8")} ${d}${p} ${sp(r.percent)} ${g}`},s=()=>{st(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&st(`${Ee.col0}${Ee.clearLine}`),n=!1};st(Ee.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),st(`${l}
|
|
2332
|
+
`),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),st(Ee.showCursor);let d=l.stage!=="failed",p=`${t} ${m.dim("\u25B8")} ${Uv(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${d?_e.success(p):_e.error(p)}
|
|
2333
|
+
`)},stop(){clearInterval(a),i(),st(Ee.showCursor)}}}function Uv(t){return t==="completed"?m.green(t):t==="failed"?m.red(t):m.cyan(t)}function Le(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(R=>!R.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=R=>{process.stderr.write(R)},l=process.stdin,d=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(t)}
|
|
2334
|
+
`),a(`${m.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
2335
|
+
`),a(Ee.hideCursor);let p=0,g=()=>{let R=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let $=0;for(let P=0;P<e.length;P+=1){let I=e[P],D=P===i,Y=D?m.cyan("\u25B6"):" ",H=I.disabled?m.grey(I.label):D?m.bold(m.cyan(I.label)):I.label,Oe=I.description?` ${m.dim(I.description)}`:"",Ce=` ${Y} ${H}${Oe}`;a(`\r${Ce}
|
|
2336
|
+
`),$+=ha(Ce,R)}p=$},S=()=>{l.removeListener("data",k),l.setRawMode?.(d??!1),l.pause(),a(Ee.showCursor)},y=R=>{let $=i;for(let P=0;P<e.length;P+=1)if($=($+R+e.length)%e.length,!e[$].disabled){i=$;return}},k=R=>{let $=R.toString("utf8");if($===""||$==="q"){S(),a(`
|
|
2040
2337
|
`),o(new Error("aborted"));return}if($==="\r"||$===`
|
|
2041
|
-
`){let I=e[i];if(I.disabled)return;
|
|
2042
|
-
`)}),o=r.sleep??
|
|
2043
|
-
`)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(
|
|
2044
|
-
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function
|
|
2045
|
-
`)}),n=e.sleep??
|
|
2338
|
+
`){let I=e[i];if(I.disabled)return;S(),n(I.value);return}if($==="\x1B[A"||$==="k"){y(-1),g();return}if($==="\x1B[B"||$==="j"){y(1),g();return}let P=Number($);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,g())};l.on("data",k),g()})}function Jo(t,e){return`${Nr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var ap=t=>new Promise(e=>setTimeout(e,t));function ip(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Jo(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function lp(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
|
|
2339
|
+
`)}),o=r.sleep??ap,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())n(ip(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let d=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<d;p+=1){await o(s);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let S of[...g].reverse())n(ip(S)),a+=1,S.updatedAt>l&&(l=S.updatedAt)}return a}function Mv(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Jo(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function cp(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
|
|
2340
|
+
`)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(Mv(o));return r(`
|
|
2341
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function qv(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Jo(t.severity,5)} ${Jo(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function dp(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
|
|
2342
|
+
`)}),n=e.sleep??ap,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:d,intervalMs:p,...g}=e,S=P=>{r(a?JSON.stringify(P):qv(P))},y=await t.platformEvents({...g,limit:g.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let k=0,R="";for(let P of[...y].reverse())S(P),k+=1,P.ts>R&&(R=P.ts);if(!s)return k;let $=i??Number.POSITIVE_INFINITY;for(let P=0;P<$;P+=1){await n(o);let I=await t.platformEvents({...g,...R?{after:R,since:void 0}:{},limit:200});for(let D of[...I].reverse())S(D),k+=1,D.ts>R&&(R=D.ts)}return k}var up=new Set(["committed","failed","rolled_back","cancelled"]),Yo=t=>{process.stdout.write(`${t}
|
|
2343
|
+
`)},zv=t=>new Promise(e=>setTimeout(e,t));function Bv(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function pp(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${Bv(t.durationMs)}${n}${r}`}function Fv(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function hp(t,e=Yo){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${Fv(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(pp(n));e("")}e(`${t.length} process(es).`)}function mp(t,e,r=Yo){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(pp(n));r(`
|
|
2344
|
+
${e.length} run(s).`)}function ba(t,e=Yo){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let l of a){let d=l.externalId??l.pgRowId??"\u2014",p=l.refusal?.message?` ${l.refusal.message}`:"";e(` ${String(l.sequence).padStart(3)} ${l.stepId.padEnd(16)} ${l.disposition.padEnd(12)} ${l.recordType}/${d}${p}`)}}async function fp(t,e,r={}){let n=r.sink??Yo,o=r.sleep??zv,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,l=p=>{let g=[];ba(p,S=>g.push(S));for(let S of g)a.has(S)||(a.add(S),n(S));return p.run?.state??p.state??""},d=l(await t.processRun(e));if(!r.follow)return d;for(let p=0;p<i;p+=1){if(up.has(d))return d;await o(s),d=l(await t.processRun(e))}return up.has(d)?d:null}Xo();Ho();function yp(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 vp=9,Tn=" ".repeat(2+vp);function Lr(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,vp-t.length))}function Wv(t,e,r){return t===1?e:r}function _p(t){return t?m.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function Sp(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function Jv(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${Sp(o[s]??[])}`);return e}function bp(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:m.dim(`${Tn}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:m.dim(`${Tn}adopted ${s} ${Sp(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:m.dim(`${Tn}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:m.dim(`${Tn}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:m.yellow(`${Tn}! ${s}`)});return e}function kp(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function wp(t){return kp(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function Yv(t,e,r){let n=r==="applied",o=Jv(t.scopeChanges),s=n?_p(t.holdersRestamped):"",i=l=>{let d=[...l,...o];return d.length>0?` ${m.dim(d.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${Lr("ERROR",m.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...bp(t)];let a;if(t.action==="create"){let l=t.addCapabilities?.length??0;a=` ${Lr(n?"created":"create")}${e}${i([`${l} ${Wv(l,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let l=(t.addCapabilities??[]).map(d=>`+${d}`).join(", ");a=` ${Lr(n?"updated":"add")}${e}${i([l])}${s}`}else t.action==="update_scopes"?a=` ${Lr(n?"updated":"update")}${e}${o.length>0?i([]):` ${m.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${Lr("ok",m.dim)}${e} ${m.dim("already up to date")}`:a=` ${Lr(n?"changed":"change")}${e}${i([])} ${m.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...bp(t)]}function Xv(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${m.dim(o)}${e==="applied"?_p(n.holdersRestamped):""}`})}return r}function Tp(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(d=>d.action!=="noop"||wp(d)),o=Xv(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:m.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(d=>d.name.length)):0;for(let d of n)s.push(...Yv(d,d.name.padEnd(i),e));s.push(...o);let a=n.some(d=>Zv.has(d.action)),l=n.every(d=>d.action==="noop");if(a){let d=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:m.dim(d)})}else if(o.length===0&&l&&n.some(d=>wp(d))){let d=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",p=n.some(g=>kp(g))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:m.dim(` ${d} \u2014 ${p}`)})}return s}var Zv=new Set(["create","add_capabilities","update_scopes"]);function wa(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:m.yellow(`! ${o}`)},{stream:"out",text:m.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:m.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function xp(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var va=".github/workflows/turbobase-release-deploy.yml",Qv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2046
2345
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
2047
2346
|
#
|
|
2048
2347
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -2144,7 +2443,7 @@ jobs:
|
|
|
2144
2443
|
--ref "\${{ github.sha }}" \\
|
|
2145
2444
|
--project . \\
|
|
2146
2445
|
--follow
|
|
2147
|
-
`,
|
|
2446
|
+
`,e_=".github/workflows/turbobase-app-deploy.yml",t_=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2148
2447
|
# Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
2149
2448
|
#
|
|
2150
2449
|
# What ships from this repo, and when:
|
|
@@ -2364,14 +2663,14 @@ jobs:
|
|
|
2364
2663
|
else
|
|
2365
2664
|
echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
|
|
2366
2665
|
fi
|
|
2367
|
-
`;function
|
|
2666
|
+
`;function Rp(){return[{path:va,content:Qv}]}function $p(){return[{path:e_,content:t_}]}Xo();var r_=[".mcp.json"];function Ap(t,e=r_){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
2368
2667
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
|
|
2369
2668
|
`)?t:`${t}
|
|
2370
2669
|
`}
|
|
2371
2670
|
# Added by the Turbobase scaffold.
|
|
2372
2671
|
${o.join(`
|
|
2373
2672
|
`)}
|
|
2374
|
-
`}var
|
|
2673
|
+
`}var n_=`# Turbobase Extensions \u2014 extension project
|
|
2375
2674
|
|
|
2376
2675
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
2377
2676
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -2440,8 +2739,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
2440
2739
|
|
|
2441
2740
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
2442
2741
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
2443
|
-
`,
|
|
2444
|
-
`;function
|
|
2742
|
+
`,o_=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)+`
|
|
2743
|
+
`;function s_(t){return`---
|
|
2445
2744
|
name: generate-types
|
|
2446
2745
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
2447
2746
|
---
|
|
@@ -2452,7 +2751,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
2452
2751
|
|
|
2453
2752
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
2454
2753
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
2455
|
-
`}var
|
|
2754
|
+
`}var i_=`---
|
|
2456
2755
|
name: mock-test
|
|
2457
2756
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
2458
2757
|
---
|
|
@@ -2461,7 +2760,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
2461
2760
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
2462
2761
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
2463
2762
|
fixture for each branch (a passing record and a rejecting record).
|
|
2464
|
-
`,
|
|
2763
|
+
`,a_=`---
|
|
2465
2764
|
name: deploy
|
|
2466
2765
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
2467
2766
|
---
|
|
@@ -2469,7 +2768,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
2469
2768
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
2470
2769
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
2471
2770
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
2472
|
-
`;function
|
|
2771
|
+
`;function l_(t){return`# ${t} \u2014 Turbobase app
|
|
2473
2772
|
|
|
2474
2773
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
2475
2774
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -2832,7 +3131,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
2832
3131
|
review, so what you write reaches the knowledge base and the product team instead
|
|
2833
3132
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
2834
3133
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
2835
|
-
`}var jr="customer",mr="email",
|
|
3134
|
+
`}var jr="customer",mr="email",c_="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",d_=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
2836
3135
|
//
|
|
2837
3136
|
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
2838
3137
|
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
@@ -2851,8 +3150,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
|
|
|
2851
3150
|
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
2852
3151
|
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
2853
3152
|
// every import except the SDK).
|
|
2854
|
-
`;function
|
|
2855
|
-
`;return[{path:t.relativePath,content:`${
|
|
3153
|
+
`;function u_(){let t=Rt("hook",{recordType:jr,event:"before_save",template:"enforce-format",field:mr,regex:c_,id:`app:${jr}:${mr}-format`,description:`Reject a ${jr} write whose ${mr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:jr,event:"before_save",payload:r},expect:n},null,2)+`
|
|
3154
|
+
`;return[{path:t.relativePath,content:`${d_}${t.content}`},{path:`samples/${jr}.${mr}-ok.json`,content:e({company_name:"Acme Supply",[mr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${jr}.${mr}-malformed.json`,content:e({company_name:"Acme Supply",[mr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var p_="---\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",h_=`---
|
|
2856
3155
|
name: ship-app
|
|
2857
3156
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
2858
3157
|
---
|
|
@@ -2895,7 +3194,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
2895
3194
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
2896
3195
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
2897
3196
|
project root and DO travel \u2014 deploy reads them.
|
|
2898
|
-
`,
|
|
3197
|
+
`,m_=`---
|
|
2899
3198
|
name: business-rule-to-hook
|
|
2900
3199
|
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.
|
|
2901
3200
|
---
|
|
@@ -2963,7 +3262,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
|
|
|
2963
3262
|
standing rules for every agent on the instance \u2014 see the record-learning skill.
|
|
2964
3263
|
A rule enforced in code and nowhere written down gets re-litigated by the next
|
|
2965
3264
|
person.
|
|
2966
|
-
`;function
|
|
3265
|
+
`;function f_(t){return`---
|
|
2967
3266
|
name: record-learning
|
|
2968
3267
|
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.
|
|
2969
3268
|
---
|
|
@@ -3018,7 +3317,7 @@ earlier claim" and still publish.
|
|
|
3018
3317
|
|
|
3019
3318
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
3020
3319
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
3021
|
-
`}function
|
|
3320
|
+
`}function g_(t){return`# What this instance's source system actually does
|
|
3022
3321
|
|
|
3023
3322
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
3024
3323
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -3149,7 +3448,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
3149
3448
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
3150
3449
|
already live, which is worth reading before adding another rule. -->
|
|
3151
3450
|
|
|
3152
|
-
`}function
|
|
3451
|
+
`}function y_(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
3153
3452
|
|
|
3154
3453
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
3155
3454
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -3229,7 +3528,7 @@ Expected / happened / cost / fix.
|
|
|
3229
3528
|
and what it would replace. These are the highest-signal entries in the file:
|
|
3230
3529
|
each one is a page downloading rows to fold that it could have asked for
|
|
3231
3530
|
folded. -->
|
|
3232
|
-
`}function
|
|
3531
|
+
`}function b_(t,e){let r=e?`
|
|
3233
3532
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
3234
3533
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
3235
3534
|
# narrows what an agent deliberately widened.
|
|
@@ -3260,8 +3559,8 @@ ${r}
|
|
|
3260
3559
|
# surface unticked items at the start of a session.
|
|
3261
3560
|
turbobase project adopt -o ADOPT.md >/dev/null \\
|
|
3262
3561
|
|| echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
|
|
3263
|
-
`}var
|
|
3264
|
-
name: ${
|
|
3562
|
+
`}var Cp="Turbobase consultant",w_="turbobase-consultant",v_=`---
|
|
3563
|
+
name: ${Cp}
|
|
3265
3564
|
description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
|
|
3266
3565
|
keep-coding-instructions: true
|
|
3267
3566
|
---
|
|
@@ -3334,8 +3633,8 @@ exists on purpose.
|
|
|
3334
3633
|
- Do not show a stack trace. Say what broke and what you are doing about it.
|
|
3335
3634
|
- Do not apologise repeatedly or pad with "great question".
|
|
3336
3635
|
- Do not use a table when a sentence works.
|
|
3337
|
-
`,
|
|
3338
|
-
`,
|
|
3636
|
+
`,__=JSON.stringify({outputStyle:Cp,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)+`
|
|
3637
|
+
`,S_=`#!/usr/bin/env bash
|
|
3339
3638
|
# PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
|
|
3340
3639
|
#
|
|
3341
3640
|
# Advisory only: exits 0 always, and adds a note for the agent when the edited
|
|
@@ -3352,7 +3651,7 @@ set -uo pipefail
|
|
|
3352
3651
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3353
3652
|
|
|
3354
3653
|
exec node "$(dirname "$0")/check-rule-placement.mjs"
|
|
3355
|
-
`,
|
|
3654
|
+
`,k_=String.raw`/**
|
|
3356
3655
|
* Is the file that was just edited enforcing a business rule inside the SPA?
|
|
3357
3656
|
*
|
|
3358
3657
|
* Reads the PostToolUse payload on stdin, and when BOTH signals are present —
|
|
@@ -3421,7 +3720,7 @@ process.stdout.write(
|
|
|
3421
3720
|
},
|
|
3422
3721
|
}),
|
|
3423
3722
|
);
|
|
3424
|
-
`,
|
|
3723
|
+
`,T_=`---
|
|
3425
3724
|
name: roles-and-permissions
|
|
3426
3725
|
description: Decide who can open a screen and who can change a record \u2014 declare roles (and their scopes \u2014 row restrictions and Slack channel content grants) in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, a scope, a screen that reads Slack history, or answering "who can see/do X".
|
|
3427
3726
|
---
|
|
@@ -3654,7 +3953,7 @@ a denial look like emptiness.
|
|
|
3654
3953
|
- Does every write catch \`TurbobasePermissionError\`?
|
|
3655
3954
|
- Did you run \`turbobase apps plan . --app <slug>\`?
|
|
3656
3955
|
- Did you tell the user their administrator still has to ASSIGN the role?
|
|
3657
|
-
`,
|
|
3956
|
+
`,x_=`---
|
|
3658
3957
|
name: app-design
|
|
3659
3958
|
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.
|
|
3660
3959
|
---
|
|
@@ -3749,7 +4048,7 @@ The design system covers the look. Two rules it does not:
|
|
|
3749
4048
|
Load it in the browser and check: does it render with ZERO rows, with ONE row,
|
|
3750
4049
|
and with several hundred? Does it survive the query failing? Does tab reach every
|
|
3751
4050
|
control, with a visible focus ring? A green \`npm run build\` proves none of these.
|
|
3752
|
-
`,
|
|
4051
|
+
`,Zo="",Ep=String.raw`{
|
|
3753
4052
|
"_comment": [
|
|
3754
4053
|
"Declarative sync config — part of this repo's desired state.",
|
|
3755
4054
|
" turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
|
|
@@ -3771,7 +4070,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3771
4070
|
"fields": [],
|
|
3772
4071
|
"tables": []
|
|
3773
4072
|
}
|
|
3774
|
-
`,
|
|
4073
|
+
`,Pp=String.raw`{
|
|
3775
4074
|
"_comment": [
|
|
3776
4075
|
"Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
|
|
3777
4076
|
"Removing an entry does NOT remove the schedule unless you pass --prune.",
|
|
@@ -3787,93 +4086,93 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3787
4086
|
],
|
|
3788
4087
|
"schedules": []
|
|
3789
4088
|
}
|
|
3790
|
-
`,
|
|
4089
|
+
`,R_=t=>`node_modules/
|
|
3791
4090
|
|
|
3792
4091
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
3793
4092
|
.mcp.json
|
|
3794
4093
|
|
|
3795
4094
|
.DS_Store
|
|
3796
|
-
`;function
|
|
3797
|
-
`))r(i)}return n}async function
|
|
3798
|
-
`)}),n=e.sleep??
|
|
4095
|
+
`;function _a(t={}){let e=o_.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:R_(r)},{path:"INSTANCE-LEARNINGS.md",content:g_(o)},{path:"TURBOBASE-FEEDBACK.md",content:y_(o)},{path:".claude/settings.json",content:__},{path:`.claude/output-styles/${w_}.md`,content:v_},{path:".claude/skills/generate-types/SKILL.md",content:s_(n)},{path:".claude/skills/record-learning/SKILL.md",content:f_(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:m_},{path:".claude/hooks/session-start-refresh-types.sh",content:b_(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:S_,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:k_}];return r?[{path:"CLAUDE.md",content:l_(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:p_},{path:".claude/skills/ship-app/SKILL.md",content:h_},{path:".claude/skills/app-design/SKILL.md",content:x_},{path:".claude/skills/roles-and-permissions/SKILL.md",content:T_},...u_(),{path:"conduits/.gitkeep",content:Zo},{path:"turbobase/sync.json",content:Ep},{path:"turbobase/schedules.json",content:Pp},...$p()]:[{path:"CLAUDE.md",content:n_},...s,{path:".claude/skills/mock-test/SKILL.md",content:i_},{path:".claude/skills/deploy/SKILL.md",content:a_},{path:"hooks/.gitkeep",content:Zo},{path:"conduits/.gitkeep",content:Zo},{path:"samples/.gitkeep",content:Zo},{path:"turbobase/sync.json",content:Ep},{path:"turbobase/schedules.json",content:Pp}]}import{promises as ka}from"node:fs";import{dirname as $_,join as gt,resolve as jp}from"node:path";function Op(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var xn="bundle.json",Qo="turbobase";function Np(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 r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=l=>Array.isArray(l)?l:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return Sa(a)}function Sa(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Ip)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Ip)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Ip(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Lp(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}var ts="hooks",rs="conduits",Dp="processes",Wt="turbobase/sync.json",Jt="turbobase/schedules.json";function Ta(t){let e=d=>{let p=new RegExp(`${d}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let d=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:d,extensionKind:"process"}:null}if(r){let d=e("on"),p=e("source");return!s||!i||!d||!p?null:{id:s,recordType:i,event:d,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function xa(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Rn(t){let e;try{e=await ka.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await Rn(gt(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function es(t,e){let r;try{r=await ka.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function E_(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function P_(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function A_(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 Up(t=process.cwd()){let e=jp(t),[r,n,o]=await Promise.all([Rn(gt(e,ts)),Rn(gt(e,rs)),Rn(gt(e,Dp))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([es(gt(e,Wt),Wt).catch(()=>{}),es(gt(e,Jt),Jt).catch(()=>{})]);return s!==void 0||i!==void 0}async function Mp(t=process.cwd(),e={}){let r=jp(t),n=Op(e.tenant),o=[],s=[];for(let l of[ts,rs,Dp])for(let d of await Rn(gt(r,l))){let p=`${l}/${d}`,g=await ka.readFile(gt(r,l,d),"utf8"),S=e.inline?await e.inline(g,$_(gt(r,l,d))):g,y=Ta(S);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(S)&&s.push({file:p,reason:xa(S)});continue}let k={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:S};y.extensionKind==="conduit"?n.conduits.push(k):n.hooks.push(k),o.push(p)}let i=await es(gt(r,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let d of Array.isArray(l.fields)?l.fields:[])n.sync.fields.push(E_(d));for(let d of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(P_(d));o.push(Wt)}let a=await es(gt(r,Jt),Jt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Jt} must be a JSON array, or an object with a "schedules" array.`);for(let d of l)n.schedules.push(A_(d));o.push(Jt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:Sa(n),contributed:o,unparsed:s}}import{promises as Ea}from"node:fs";import{resolve as j_}from"node:path";var C_="For app developers \u2014 adopt these";function qp(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 zp(t,e){let r=qp(t),n=qp(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function I_(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var rO=I_(C_);bn();mt();var O_=t=>new Promise(e=>setTimeout(e,t));function Bp(t){return t.stage==="completed"||t.stage==="failed"}function N_(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function L_(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
|
|
4096
|
+
`))r(i)}return n}async function Ra(t,e={}){let r=e.sink??(S=>{process.stdout.write(`${S}
|
|
4097
|
+
`)}),n=e.sleep??O_,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(S=>r(N_(S))),a=e.onPoll,l="",d="",p=S=>{a?.(S),S.stage!==d&&i(S),l=L_(S,l,r),d=S.stage},g=await t();if(p(g),Bp(g))return g;for(let S=0;S<s;S+=1)if(await n(o),g=await t(),p(g),Bp(g))return g;return g}var b=t=>{process.stdout.write(`${t}
|
|
3799
4098
|
`)},L=t=>{process.stderr.write(`${t}
|
|
3800
|
-
`)};function
|
|
3801
|
-
`)){let o=
|
|
4099
|
+
`)};function v(t){L(m.red(`turbobase: ${t}`)),process.exit(1)}var $n=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Fp(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&fa(!1)}async function B(t){let e=await ht(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Ot();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${rt(t)}.${n} Run \`turbobase auth login --base-url ${rt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne())try{let n=await Le("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Do(n);let o=await ht();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}v(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function V(t,e,r){if(!(t instanceof Q)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function $a(t,e,r){let n=r?Number(r):void 0;if(Wo()){let s=ya(e),i;try{i=await Ra(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),v(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Ra(t,{sink:b,intervalMs:n})}catch(s){v(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),b(`${e} ${o.stage}.`)}var D_=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function U_(t){try{let e=await Ea.readFile(t,"utf8");return D_.exec(e)?.[1]??null}catch{return null}}var M_=/GENERATED by `turbobase project adopt`/,Kp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,q_=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Hp(t){let e=[],r=null;for(let n of t.split(`
|
|
4100
|
+
`)){let o=Kp.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=q_.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function z_(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
|
|
3802
4101
|
`)).join(`
|
|
3803
4102
|
`);return`## v${t.version}
|
|
3804
4103
|
|
|
3805
|
-
${e}`}function
|
|
3806
|
-
`),a=i.findIndex(p=>
|
|
4104
|
+
${e}`}function B_(t,e){let r=Hp(t);if(r.length===0&&!M_.test(t))return null;let n=new Map(r.map(p=>[p.version,p])),o=[],s=0;for(let p of Hp(e)){let g=n.get(p.version);n.delete(p.version);let S=new Set(p.items.map(k=>k.key)),y=p.items.map(k=>{let R=g?.items.find($=>$.key===k.key);return R?{...k,done:R.done,extra:R.extra}:k});for(let k of g?.items??[])S.has(k.key)||k.done||(y.push(k),s+=1);o.push({version:p.version,items:y})}for(let p of n.values()){let g=p.items.filter(S=>!S.done);g.length!==0&&(s+=g.length,o.push({version:p.version,items:g}))}o.sort((p,g)=>zp(g.version,p.version));let i=e.split(`
|
|
4105
|
+
`),a=i.findIndex(p=>Kp.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
|
|
3807
4106
|
`).replace(/\s+$/,"");return{markdown:o.length===0?`${l}
|
|
3808
4107
|
`:`${l}
|
|
3809
4108
|
|
|
3810
|
-
${o.map(
|
|
4109
|
+
${o.map(z_).join(`
|
|
3811
4110
|
|
|
3812
4111
|
`)}
|
|
3813
|
-
`,carried:s}}function
|
|
3814
|
-
|
|
3815
|
-
`,y=await
|
|
3816
|
-
`);for(let n of r.slice(0,
|
|
3817
|
-
`)),b(
|
|
3818
|
-
`))}catch(d){if(d instanceof Q&&d.status===409){L(
|
|
3819
|
-
`))}async function
|
|
3820
|
-
`))r.push(` ${
|
|
3821
|
-
`)),b(
|
|
3822
|
-
`)).trim();continue}e[i]=
|
|
4112
|
+
`,carried:s}}function Vp(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await B(e.baseUrl),o=j_(process.cwd(),e.out),s=e.since?.trim()||await U_(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let d=await l.json();if(!d.available){b(`${r} ships no release notes to adopt from (nothing written).`);return}let p=d.releases.reduce(($,P)=>$+P.items.length,0);if(p===0){b(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${d.currentVersion?` (instance is on v${d.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let g=d.currentVersion??d.releases[0]?.version??"",S=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
|
|
4113
|
+
|
|
4114
|
+
`,y=await Ea.readFile(o,"utf8").catch(()=>null),k=d.markdown,R=0;if(y!==null&&y.trim()!==""){let $=B_(y,d.markdown);$||v(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),k=$.markdown,R=$.carried}await Ea.writeFile(o,S+k,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${d.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}mt();var En=["suggested_kb_edit","kb_correction"];var F_=[{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 H_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var fO=new Map(F_.map(t=>[H_(t.heading),t]));var gO=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 K_(t){return t.diff??!!t.dryRun}var V_={update_page:"append to the existing page",new_page:"create a NEW page"},Lt=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,Jp=t=>t.ownerEmail??t.ownerId;function Dr(t){return!t.needsPageRef&&!t.blockedBy}var ns=t=>m.green(t?` + ${t}`:" +"),G_=t=>m.red(t?` - ${t}`:" -"),fr=t=>m.dim(` ${t}`),W_=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Pa=80;function J_(t){let e=[W_];t.target?(e.push(fr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(G_(`visibility: ${t.target.visibility}`)),e.push(ns("visibility: admin"))):e.push(fr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(fr("title, slug, evidence: untouched")),e.push(fr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(fr("turbobase.document \xB7 new")),e.push(ns(`title: ${t.pageTitle}`)),e.push(ns("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(fr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(fr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
4115
|
+
`);for(let n of r.slice(0,Pa))e.push(ns(n?` ${n}`:""));return r.length>Pa&&e.push(m.yellow(` \u2026 ${r.length-Pa} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function Y_(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${m.bold(n.pageTitle)}`),r.push(Lt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:m.dim("new \u2014 no existing page matches"))),r.push(Lt("action",Dr(n)?V_[n.action]:m.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(Lt("unresolved",m.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(r.push(Lt("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?` ${m.dim(`\xB7 ${a.verdict}`)}`:"",d=a.kb_page_ref?` ${m.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${m.dim("\xB7")} ${a.title.trim()}${d}${l}`)}),r.push(Lt("confidence",n.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),n.supersedes&&r.push(Lt("supersedes",m.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Lt("blocked",m.red(`unpublished work on this page belongs to ${Jp(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Lt("ambiguous",m.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(l=>{let d=t.findIndex(g=>g.key===l),p=d>=0?t[d]:void 0;return p?`#${d+1} "${p.pageTitle}"`:l});r.push(Lt("similar",m.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&&Dr(n)&&r.push(...J_(n)),r.push("")}),r}function X_(t){let e=d=>t.filter(d).length,r=t.reduce((d,p)=>d+p.entries.length,0),n=e(d=>d.withdraws),o=e(d=>d.blockedBy!=null),s=e(d=>d.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(Dr)} page(s)`,`${e(d=>d.action==="update_page"&&Dr(d))} appended`,`${e(d=>d.action==="new_page"&&Dr(d))} created (unpublished)`,...s>0?[m.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?m.red(`${n} page(s) WITHDRAWN from readers`):m.dim("no page withdrawn"),l=o>0?` \xB7 ${m.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Z_(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${m.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Jp(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(d=>d.kb_page_ref?.trim()).filter(d=>!!d))];n.push(`${m.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(d=>`"${d}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${m.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?m.green("created "):m.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${m.bold(o.documentId??"?")}`+(o.created?m.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${m.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${m.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${m.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Gp(t){if(t instanceof Q){let e=t.body;t.status===403&&e?.reason==="admin_required"&&v("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&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function Pn(t,e){let r;try{r=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Q&&o.status===404?L(m.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`.")):Au(o)?L(m.yellow(Wp(o))):L(m.yellow(`could not re-read the pushed markdown: ${Wp(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(m.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(m.yellow(`${r.parseSkipped} unparseable`)),L(m.dim(n.join(" \xB7 "))),r}function Wp(t){return t instanceof Error?t.message:String(t)}async function Yp(t,e=r=>new q(r)){t.section&&!En.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${En.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await B(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending queue",()=>n.learningsPending(o))}catch(d){Gp(d),v(`could not read the pending queue: ${d instanceof Error?d.message:String(d)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}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(b(Y_(i.items,{diff:K_(t)}).join(`
|
|
4116
|
+
`)),b(X_(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Dr);if(a.length===0){L(m.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((d,p)=>d+p.entries.length,0);if(!t.yes){if(!Ne()){L(m.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 Le(`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 d=await J("writing pages",()=>n.learningsPushKb(i.planToken,o));b(Z_(d.applied,i.items).join(`
|
|
4117
|
+
`))}catch(d){if(d instanceof Q&&d.status===409){L(m.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${$n} kb push\` to review the current plan.`),process.exitCode=2;return}Gp(d),L(m.red(`turbobase: ${d instanceof Error?d.message:String(d)}`)),process.exitCode=2}}mt();var Ur=t=>new q(t);async function Mr(t,e){let r=await B(t.baseUrl);return e(r)}async function os(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Q_(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function Xp(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function eS(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Xp(m.bold(s.slug),e)} ${Xp(Q_(s),10)} ${m.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Zp(t,e=Ur){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Mr(t,e),o;try{o=await J("reading the knowledge base",()=>n.docsList(r))}catch(s){V(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(eS(o).join(`
|
|
4118
|
+
`))}async function Qp(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await os(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>o.docsPublish(n))}catch(l){V(l,"docs:publish","publish a page"),v(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);b(m.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(m.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function eh(t,e,r=Ur){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Mr(e,r);if(!await os(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.docsUnpublish(n))}catch(l){V(l,"docs:publish","unpublish a page"),v(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);b(m.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(m.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function th(t,e=Ur){let r=await Mr(t,e),n;try{n=await J("reading the releases",()=>r.docsVersions())}catch(o){V(o,"docs:publish","read the knowledge-base releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){b("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?m.green("current"):m.dim(" ");b(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${m.dim(o.published_by)}`:""}`),o.release_note&&b(` ${m.dim(o.release_note)}`)}}async function rh(t,e,r=Ur){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Mr(e,r);if(await os(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>o.docsRollback(n));b(m.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){V(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function nh(t,e,r=Ur){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await Mr(e,r);if(await os(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>o.docsDelete(n));b(m.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){V(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}mt();function tS(t){return t.diff??!!t.dryRun}function rS(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?m.green("new rule"):m.yellow("amend rule"),i=n.targetPublished?` ${m.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${m.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${m.dim(n.description)}`);for(let a of n.entries)r.push(` ${m.dim("\xB7")} ${m.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
|
|
4119
|
+
`))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function nS(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(m.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function oh(t,e=r=>new q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await B(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await Pn(n,t.app),i;try{i=await J("reading the pending rules",()=>n.rulesPending(o))}catch(l){V(l,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}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(b(rS(i.items,{diff:tS(t)}).join(`
|
|
4120
|
+
`)),b(nS(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,d)=>l+d.entries.length,0);if(!t.yes){if(!Ne()){L(m.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 Le(`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 J("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Q&&l.status===409&&v("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),v(`push failed: ${l instanceof Error?l.message:String(l)}`)}b(m.green(`wrote ${i.items.length} draft rule(s).`)),L(m.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as cS,readFile as dS,stat as uS}from"node:fs/promises";import{join as ah,resolve as pS}from"node:path";var jt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},oS=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function sh(t){let e=t.replace(/^/,""),r=oS.exec(e);if(!r)throw new jt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=sS(n??""),i=s.name,a=s.description;if(!i)throw new jt("SKILL.md frontmatter is missing required `name`");if(!a)throw new jt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),d=Object.entries(s).filter(([g])=>!l.has(g));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...d.length?{extra:Object.fromEntries(d)}:{}},body:(o??"").trim()}}function sS(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new jt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new jt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=aS(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let d=r[n]??"";if(d.length===0||/^\s/.test(d))l.push(d.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
|
|
4121
|
+
`)).trim();continue}e[i]=iS(a),n+=1}return e}function iS(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function aS(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var lS=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function ih(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";lS.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}mt();async function hS(t){let e=pS(t),r;try{r=(await cS(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=ah(e,o,"SKILL.md");if(await uS(s).then(a=>a.isFile()).catch(()=>!1))try{let a=sh(await dS(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof jt&&v(`${ah(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var ss={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},mS={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function fS(t){let e=[];for(let r of t.items){let n=r.action==="refused"?m.red(ss.refused):r.action==="unchanged"?m.dim(ss.unchanged):r.action==="new"?m.green(ss.new):m.yellow(ss.update),o=r.targetPublished?` ${m.yellow("[currently live]")}`:"";e.push(`${n} ${m.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${m.red(mS[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${m.yellow("orphan")} ${m.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function lh(t,e=r=>new q(r)){t.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await hS(t.from),n=ih(r);n.length>0&&v(`nothing was sent:
|
|
3823
4122
|
${n.join(`
|
|
3824
|
-
`)}`);let o=await
|
|
3825
|
-
`));let l=a.items.filter(
|
|
3826
|
-
`+
|
|
3827
|
-
`))}async function
|
|
4123
|
+
`)}`);let o=await B(t.baseUrl),s=e(o),i=async S=>{try{return await J(S?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,S))}catch(y){if(V(y,"extensions:deploy","push skill files"),y instanceof Q&&y.status===404){let k=y.body;v(k?.error==="app_not_found"?String(k.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${y instanceof Error?y.message:String(y)}`)}},a=await i(!0);b(fS(a).join(`
|
|
4124
|
+
`));let l=a.items.filter(S=>S.action==="new"||S.action==="update").length,d=a.items.filter(S=>S.action==="refused").length;if(t.dryRun){L(m.dim("dry run \u2014 nothing was written.")),d>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ne()){L(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Le(`Write ${l} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let g=p.items.filter(S=>S.action==="new"||S.action==="update").map(S=>S.slug);if(b(`${g.length} written, ${p.items.filter(S=>S.action==="unchanged").length} unchanged, ${p.items.filter(S=>S.action==="refused").length} refused.`),t.publish&&g.length>0){let S;try{S=await J("publishing",()=>s.skillsPublish(g))}catch(y){V(y,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${y instanceof Error?y.message:String(y)}`)}b(m.green(`published ${S.published.join(", ")} \u2014 live as of release ${S.version.version_no}.`))}else t.publish?b(m.dim("nothing changed \u2014 nothing to publish.")):g.length>0&&L(m.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(S=>S.action==="refused")&&(L(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}mt();var gS=["proposed","active","rejected"],yS=["mechanic","operator","learning","code-baseline"],is=t=>new q(t);async function as(t,e){let r=await B(t.baseUrl);return e(r)}function ch(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||v(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function bS(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&v("--limit must be a positive number."),Math.floor(e)}function ph(t){let e=ch(t.status,gS,"--status"),r=ch(t.provenance,yS,"--provenance"),n=bS(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function dh(t){return!!(t.provenance?.length||t.recordType||t.source)}var hh=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function wS(t){return t.status==="active"?m.green("active"):t.status==="rejected"?m.dim("rejected"):m.yellow("proposed")}function vS(t){return t.message?t.message:t.kind&&t.field?m.dim(`${t.kind} ${t.field}`):t.kind?m.dim(t.kind):m.dim("(no description)")}function mh(t){return[t.hookId,wS(t),t.provenance==="learning"?m.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),vS(t)]}async function fh(t={},e=is){let r=await as(t,e),n=ph(t),o;try{o=await r.proposals(n)}catch(i){V(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return b(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return b(`no ${i} hook proposals.
|
|
4125
|
+
`+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(ft(o.map(mh),{head:hh})),b(m.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&b(m.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function _S(t,e,r){return r.yes?!0:Ne()?await Le(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(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function SS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Aa(t,e){SS(t)&&V(t,"extensions:deploy",e)}function Ca(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(_e.error(`${m.bold(t)} \u2014 ${s}`))}async function uh(t,e){try{let r=await t.proposalPromote(e);return b(_e.success(`${m.bold(e)} ${m.dim(`${r.previousStatus} \u2192`)} ${m.green(r.status)}`)),!0}catch(r){return Aa(r,"promote a hook proposal"),Ca(e,r),!1}}async function gh(t,e={},r=is){!e.auto&&t.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await as(e,r);if(!e.auto){let p=0;for(let g of t)await uh(n,g)&&(p+=1);p>0&&b(m.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=ph({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&v("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(p=>p!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){V(p,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(b(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(b(`nothing to promote${dh(o)?" for that filter":""}.`),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(b(e.apply?`promoting ${m.bold(String(a.length))} hook proposal(s):`:`${m.bold("dry run")} \u2014 would promote ${m.bold(String(a.length))} hook proposal(s):`),b(ft(a.map(mh),{head:hh})),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){b(""),b(_e.info("nothing was changed. Re-run with --apply to arm these."));return}if(!dh(o)&&!e.all&&v(`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 _S(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let d=0;for(let p of a)await uh(n,p.hookId)&&(d+=1);b(m.dim(` ${d}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),d<a.length&&(process.exitCode=1)}async function yh(t,e={},r=is){t.length===0&&v("retract: name at least one proposal id.");let n=await as(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);b(_e.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.yellow(i.status)}`)),o+=1}catch(i){Aa(i,"retract a hook proposal"),Ca(s,i)}o>0&&b(m.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function bh(t,e={},r=is){t.length===0&&v("reject: name at least one proposal id.");let n=await as(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);b(_e.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.dim(i.status)}`)),o+=1}catch(i){Aa(i,"reject a hook proposal"),Ca(s,i)}o<t.length&&(process.exitCode=1)}mt();var Ia=t=>new q(t);async function kS(t,e){let r=await B(t.baseUrl);return e(r)}function TS(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function xS(t,e){let r=e instanceof Q?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(_e.error(`${m.bold(t)} \u2014 ${s}`))}async function Oa(t,e,r,n,o,s,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await kS(r,n),l=[];for(let d of e)try{let p=await o(a,d);l.push(p),r.json||b(s(p))}catch(p){TS(p)&&V(p,"extensions:deploy",`${t} an extension`),xS(d,p)}if(r.json)b(JSON.stringify(l,null,2));else{let d=i(l.length);d&&b(m.dim(d))}l.length<e.length&&(process.exitCode=1)}async function wh(t,e={},r=Ia){await Oa("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function vh(t,e={},r=Ia){await Oa("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function _h(t,e={},r=Ia){await Oa("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}mt();var qr=t=>new q(t);async function zr(t,e){let r=await B(t.baseUrl);return e(r)}async function ls(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function RS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function Sh(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function $S(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Sh(m.bold(s.slug),e)} ${Sh(RS(s),10)} ${s.surfaces.join(",")||m.dim("none")}`),s.description&&r.push(` ${m.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function kh(t,e=qr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await zr(t,e),o;try{o=await J("reading the skills",()=>n.skillsList(r))}catch(s){V(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b($S(o).join(`
|
|
4126
|
+
`))}async function Th(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await ls(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function xh(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await ls(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Rh(t,e,r=qr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await zr(e,r);if(await ls(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function $h(t,e=qr){let r=await zr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function Eh(t,e,r=qr){let n=[...new Set((t??[]).map(d=>d.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await zr(e,r);if(!await ls(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
3828
4127
|
${n.join(`
|
|
3829
|
-
`)}`,"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 d of n)try{i.push(await J(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(
|
|
3830
|
-
`,{mode:384})}async function zS(t){let e=await za();e.push(t),await Ph(e)}async function Ah(t){let e=await za(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Ph(e),n??null}async function ls(){return za()}function Ba(t,e=Date.now()){let r=[],n=[];for(let o of t)PS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Ch(t,e){qa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=AS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>DS(d)))(e.fromTenant),i=MS(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=CS(d.rows,n),f=NS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ES(e.ttl,o),sampleFraction:n,url:qS(s,e.baseUrl)};return await zS(l),l}async function Ih(t,e){qa(t.target());let n=(await ls()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Ah(e),n):null}async function Fa(t,e=Date.now()){qa(t.target());let r=await ls(),{expired:n}=Ba(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Ah(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write"],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"}},lN=Object.keys(In).filter(t=>In[t].mintable);var uN=In.pat.prefix,BS=Object.entries(In).map(([t,e])=>[e.prefix,t]),FS=/^[A-Za-z0-9_-]{20,}$/;function HS(t){if(typeof t!="string")return null;for(let[e,r]of BS)if(t.startsWith(e)&&FS.test(t.slice(e.length)))return r;return null}function Oh(t){return HS(t)==="pat"}bn();var KS=8e3,VS={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 GS(t){return VS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WS(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(KS)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Nh(t){return t.state==="accepted"?Ie()?h.green("accepted"):"accepted":t.state==="rejected"?Ie()?h.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?h.yellow("unreachable"):"unreachable"}async function Lh(t={},e=fetch){let r=await Ot(),{file:n}=Lo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(h.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?h.green("*"):" ",h.bold(i.baseUrl),Nh(i.check),h.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Nh(i.check)} (updated ${i.updatedAt})`);L(h.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(h.red(`${i.baseUrl}: ${GS(i.check.reason)}.`)),L(h.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(h.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function yA(t){let e=await Ot();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function bA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function wA(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 vA(t,e,r){let n=await vu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),wA(n.baseUrl),!r)return;let s=await bA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.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.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function _A(t){let e=await aa(await Sn(t),zt(t)),r=_a(e);return r||w(`${t}: ${Sa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Lb(t,e){if(Db(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=vp(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function qd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oi(t){process.exit(t)}function SA(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function kA(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function TA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function jb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Vd({includeInternal:t=!0}={}){let e=new gA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.37.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ma()}
|
|
3831
|
-
`),e.hook("preAction",(u,
|
|
3832
|
-
${$n} auth login --base-url ${
|
|
3833
|
-
`).length} lines).`)}),
|
|
4128
|
+
`)}`,"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 d of n)try{i.push(await J(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),v(`delete failed on '${d}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(d=>d.wasPublished).map(d=>d.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Ph}from"node:fs";import{join as ES,relative as PS,resolve as AS,sep as CS}from"node:path";var IS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),OS=new Set([".mcp.json",".env"]);function NS(t){return OS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function LS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function jS(t){return t.includes(0)}async function Ah(t){let e=AS(t),r={},n=[],o=[],s=[];async function i(a){let l=await Ph.readdir(a,{withFileTypes:!0});for(let d of l){let p=ES(a,d.name);if(IS.has(d.name))continue;if(d.isDirectory()){await i(p);continue}if(!d.isFile())continue;let g=PS(e,p).split(CS).join("/");if(NS(d.name)){o.push(g);continue}let S=await Ph.readFile(p);if(!LS(S)){n.push(g);continue}jS(S)&&s.push(g),r[g]=S.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as DS}from"node:crypto";var US="/_tb/app-assets",MS=16,qS=/^[0-9a-f]{32}$/;function Ch(){return DS(MS).toString("hex")}function zS(t){return qS.test(t)}function Ih(t){if(!zS(t))throw new Error(`not a build id: ${t}`);return`${US}/${t}/`}var Oh=7;La();var ja=50*1024*1024;import cs from"node:fs/promises";import An from"node:path";var Da={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ua="@turbobase/isolated-vm-prebuilds";function Ma(t,e){return`${t}-${e}`}function qa(t=process.versions){return`abi${t.modules}`}var Nh=["darwin-x64","win32-arm64"];async function Lh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Ma(e,r),o=An.join(t.home,"node_modules"),s=An.join(o,...Ua.split("/"),"prebuilds",n),i=An.join(o,"isolated-vm","prebuilds",n),a;try{a=await cs.readdir(s)}catch{return[]}let l=[];await cs.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let p=An.join(i,d);try{await cs.copyFile(An.join(s,d),p,cs.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as BS}from"node:os";import{join as jh}from"node:path";import{promises as za}from"node:fs";function Uh(){let t=process.env.TURBOBASE_HOME??jh(BS(),".turbobase");return{dir:t,file:jh(t,"sandboxes.json")}}var FS={s:1e3,m:6e4,h:36e5,d:864e5};function HS(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*FS[e[2]]}function KS(t,e=Date.now()){return new Date(e+HS(t)).toISOString()}function VS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function GS(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function WS(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var JS="[REDACTED]",Cn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ba=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function YS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ba(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:JS:n[o]=s}return n}function XS(t,e,r){return e.map(n=>YS(t,n,r))}var Dh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ZS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function QS(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Fa(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of ZS)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=QS(t);if(!Dh.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Dh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function ek(t,e=tk){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function tk(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function rk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function nk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ha(){let{file:t}=Uh();try{let e=await za.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Mh(t){let{dir:e,file:r}=Uh();await za.mkdir(e,{recursive:!0}),await za.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
4129
|
+
`,{mode:384})}async function ok(t){let e=await Ha();e.push(t),await Mh(e)}async function qh(t){let e=await Ha(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mh(e),n??null}async function ds(){return Ha()}function Ka(t,e=Date.now()){let r=[],n=[];for(let o of t)VS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function zh(t,e){Fa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=GS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>ek(d)))(e.fromTenant),i=rk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=WS(d.rows,n),g=XS(d.table,p,d.classification);g.length>0&&await t.copyRows(i,d.table,g)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:KS(e.ttl,o),sampleFraction:n,url:nk(s,e.baseUrl)};return await ok(l),l}async function Bh(t,e){Fa(t.target());let n=(await ds()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await qh(e),n):null}async function Va(t,e=Date.now()){Fa(t.target());let r=await ds(),{expired:n}=Ka(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await qh(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},RN=Object.keys(In).filter(t=>In[t].mintable);var PN=In.pat.prefix,sk=Object.entries(In).map(([t,e])=>[e.prefix,t]),ik=/^[A-Za-z0-9_-]{20,}$/;function ak(t){if(typeof t!="string")return null;for(let[e,r]of sk)if(t.startsWith(e)&&ik.test(t.slice(e.length)))return r;return null}function Fh(t){return ak(t)==="pat"}bn();var lk=8e3,ck={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 dk(t){return ck[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function uk(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(lk)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Hh(t){return t.state==="accepted"?Ie()?m.green("accepted"):"accepted":t.state==="rejected"?Ie()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?m.yellow("unreachable"):"unreachable"}async function Kh(t={},e=fetch){let r=await Ot(),{file:n}=jo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await uk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Hh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Hh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${dk(i.check.reason)}.`)),L(m.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(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function NA(t){let e=await Ot();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function LA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function jA(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 DA(t,e,r){let n=await xu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),jA(n.baseUrl),!r)return;let s=await LA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.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.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function UA(t){let e=await ca(await Sn(t),zt(t)),r=Ta(e);return r||v(`${t}: ${xa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Kb(t,e){if(Gb(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=Ap(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function Fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Li(t){process.exit(t)}function MA(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function qA(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function zA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function Vb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Jd({includeInternal:t=!0}={}){let e=new OA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.38.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ga()}
|
|
4130
|
+
`),e.hook("preAction",(u,h)=>{Fp(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async u=>{let h=rt(u.baseUrl);u.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4131
|
+
${$n} auth login --base-url ${h} --token tb_pat_\u2026`),Fh(u.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await DA(h,u.token,u.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async u=>Kh({probe:u.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async u=>{let h=u??await NA("Pick the active instance:"),w=await Do(h);if(!w){let T=await Ot();v(`no stored sign-in for ${rt(h)}.`+(T.length?` Stored: ${T.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async u=>{if(u.all){let T=await Ot();for(let _ of T)await na(_.baseUrl);b(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await na(u.baseUrl);h||v(u.baseUrl?`no stored sign-in for ${rt(u.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ht();b(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T;try{T=await hr({baseUrl:h,token:w,recordsOnly:u.recordsOnly})}catch(f){let x=f instanceof Error?f.message:String(f);if(!u.recordsOnly&&/openapi\.json failed \(401/.test(x)){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{T=await hr({baseUrl:h,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${x}`)}let _=se(process.cwd(),u.out);await ae.writeFile(_,T,"utf8"),b(`wrote ${_} (${T.split(`
|
|
4132
|
+
`).length} lines).`)}),Vp(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new URLSearchParams;u.records&&T.set("records",u.records),u.query&&T.set("query",u.query);let _=T.toString(),f=await fetch(`${h}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let E=((await f.json()).markdown??"").trim(),A=se(process.cwd(),u.out),C=u.records?` records=${u.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
|
|
3834
4133
|
|
|
3835
4134
|
`;await ae.writeFile(A,O+(E?`${E}
|
|
3836
4135
|
`:`(no grounding available yet)
|
|
3837
|
-
`),"utf8"),b(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${En.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",u=>Number.parseInt(u,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(u=>qp(u)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(u=>Bp(u)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Fp(u,m)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Hp(u,m)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>Kp(u)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Vp(u,m)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>Gp(u,m)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>(u.publish&&!u.from&&w("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),u.from?Zp({baseUrl:u.baseUrl,from:u.from,app:u.app,dryRun:u.dryRun,publish:u.publish,yes:u.yes}):Wp(u))),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(u=>hh(u)),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((u,m)=>mh(u,m)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>fh(u,m)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>yh(u)),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((u,m)=>gh(u,m)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,m)=>bh(u,m));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async u=>{let m;try{m=Rt("hook",{recordType:u.record,event:u.event,template:u.template,field:u.field,regex:u.regex,source:u.source,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async u=>{let m;try{m=Rt("conduit",{recordType:u.record,source:u.source,to:u.to,toRecordType:u.toRecord,event:u.event,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async u=>{let m;try{m=Rt("process",{recordType:u.record,then:u.then,onFailure:u.onFailure,id:u.id})}catch(S){w(S instanceof Error?S.message:String(S))}let v=se(process.cwd(),m.relativePath);await Pr(v,m.content)==="skipped"&&w(`refusing to overwrite existing file: ${v}`),b(`wrote ${v}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(u,m)=>{let v=qd(m.reporter),x=await Sn(se(process.cwd(),u)),S=se(process.cwd(),m.samples),g=await _n(S);g.length===0&&!v&&b(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Ho(x,g.map(C=>C.fixture),{resolveDir:zt(se(process.cwd(),u))})}catch(C){w(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(v){let C=SA(T);b(Vo(C,v)),Oi(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of T){let O=C.pass?h.green("PASS"):h.red("FAIL");C.pass||(E+=1);let G=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";b(` ${O} ${C.name}${G}`)}let A=`${T.length-E}/${T.length} sample(s) passed.`;b(`
|
|
3838
|
-
${E===0?h.green(A):h.yellow(A)}`),Oi(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(u,m)=>{if(m.to){let T=await zd(),{baseUrl:E,token:A}=await H(m.baseUrl),C=new q({baseUrl:E,token:A});try{let O=await J(`applying bundle to ${m.to}`,()=>C.configApply(T,{prune:m.prune}));b(`applied bundle to ${m.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let G=O.skippedDestroys??[];if(G.length>0){L(`${G.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let N of G)L(` ${N.kind} ${N.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&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}u||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:x}=await H(m.baseUrl),S=await _A(se(process.cwd(),u)),g=new q({baseUrl:v,token:x});try{let T=await J(`deploying ${Db(u)}`,()=>g.deploy(S));Ie()?b(Gt("Deployed",[`${h.bold(T.id)} ${Nr(T.status)} ${h.dim(T.outcome)}`])):b(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof Q&&T.status===403&&w("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),w(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});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(u,m,v)=>{let x=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&w("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=se(process.cwd(),m??".");await ae.mkdir(S,{recursive:!0});let g=v.proposal??await $(S),{baseUrl:T,token:E}=await H(v.baseUrl),A=new q({baseUrl:T,token:E}),C=!1;try{C=(await A.appsList()).some(ie=>ie.slug===u||ie.id===u)}catch(ie){V(ie,"extensions:deploy","deploy"),w(`could not reach ${T}: ${ie instanceof Error?ie.message:String(ie)}`)}if(!C){v.create||w(`no app "${u}" on ${T} \u2014 create it with \`turbobase apps create ${u}\`, or pass --create.`);let ie=await J(`creating app ${u}`,()=>f(T,E,{slug:u},{tolerateExisting:!0}));ie.existed||b(`created ${ie.slug??u}.`)}let O;if(v.replace)if(typeof v.replace=="string")O=v.replace;else{let{previews:ie}=await F(T,E,u);if(ie.length===0&&w(`no open preview on ${u} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ie.length>1){for(let Re of ie)b(` ${Re.previewId} v${Re.version}${Re.label?` ${Re.label}`:""} ${Re.url}`);w(`${u} has ${ie.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ie[0].previewId}\`.`)}O=ie[0].previewId}let G;if(v.replaceLabel){let ie=v.replaceLabel,{previews:Re}=await F(T,E,u),xt=Re.filter(Di=>Di.label===ie);xt.length>0?(O=xt[0].previewId,xt.length>1&&L(`${xt.length} open previews carry the label "${ie}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ie}" \u2014 opening one.`),G=ie}let N=ie=>ae.stat(et(S,ie)).then(()=>!0).catch(()=>!1),W=u,me=S,Z=v.build!==!1;if(Z&&!await N("package.json"))if(await N("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Z=!1;else if(v.pull===!1)w(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ie=await J(`pulling ${u}`,()=>_(T,E,u));W=ie.slug??u,await y(S,ie.files,!0),b(`pulled generated source (rev ${ie.rev}).`)}let ye;if(Z){let ie=_h();if(ye={buildId:ie,assetBase:Sh(ie)},v.install!==!1&&!await N("node_modules")){b("installing dependencies\u2026");try{await I(["install"],S)}catch(Re){w(`npm install failed: ${Re instanceof Error?Re.message:String(Re)}`)}}b("building\u2026");try{await I(["run","build"],S,{TURBOBASE_ASSET_BASE:ye.assetBase})}catch(Re){w(`build failed: ${Re instanceof Error?Re.message:String(Re)}`)}await N("dist")||w(`no dist/ after build in ${S} \u2014 check the app's build script.`),me=et(S,"dist")}x&&!ye&&w(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${W}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let fe=await Oe(T,E,W,me,v.entry,g,ye,x?{label:v.label??G,replacePreviewId:O}:void 0);if(x){let ie=fe.previewUrl??"(no url returned)",Re=fe.expiresAt?new Date(fe.expiresAt).toLocaleDateString():`${kh} days`,xt=fe.replacedVersion==null?null:`replaced v${fe.replacedVersion} \u2014 same URL`;if(Ie())b(Gt(xt?"Preview replaced":"Preview deployed",[`${h.bold(W)} ${h.green(`v${fe.version??"?"}`)} ${h.dim("not live")}`,`${h.bold(ie)}`,...xt?[h.dim(xt)]:[],h.dim(`expires ${Re}`)]));else{let Di=xt?`; ${xt}`:"";b(`preview ${W} v${fe.version??"?"} \u2192 ${ie} (expires ${Re}; /a/${W} unchanged${Di}).`)}Bt(fe),b(`next: turbobase apps promote ${W} ${fe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${fe.previewId??"<preview-id>"}`);return}Ie()?b(Gt("Deployed",[`${h.bold(W)} ${h.green(`v${fe.version??"?"}`)} ${h.dim(fe.url??`/a/${W}`)}`])):b(`deployed ${W} \u2192 v${fe.version??"?"} (${fe.url??`/a/${W}`}).`),Bt(fe),Ft(fe),await Ht(fe,S)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(u,m)=>{let v=m.as?.startsWith("app:")?m.as.slice(4).trim():"";m.app!==void 0&&m.app.trim()===""&&w("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let x=m.app?.trim()??"";x&&v&&x!==v&&w(`--app ${x} and --as app:${v} name two different apps \u2014 pass one slug.`);let S=x||v||null,g=await RA(u??".");g||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`);let T=Array.isArray(g.manifest.tables)?g.manifest.tables:[],E=Array.isArray(g.manifest.writes)?g.manifest.writes:[],A=Array.isArray(g.manifest.roles)?g.manifest.roles:null,C=A??[],O=Array.isArray(g.manifest.labels)?g.manifest.labels:[],G=A!==null&&A.length===0;if(T.length===0&&E.length===0&&C.length===0&&O.length===0){if(!G)return b(`${g.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(S===null){for(let Z of ga({app:null,roles:A}))b(Z.text);return}}let{baseUrl:N,token:W}=await H(m.baseUrl),me=new q({baseUrl:N,token:W});if(T.length>0){let Z;try{Z=await J("planning tables",()=>me.tablesPlan({claimedBy:m.as,tables:T}))}catch(ye){V(ye,"extensions:deploy","plan tables"),Ro(ye)}b(`claiming as ${h.bold(Z.claimedBy)}`);for(let ye of Z.tables)xo(ye,{showClaimants:!0})}if(E.length>0||C.length>0||O.length>0||G&&S!==null){let Z;try{Z=await J("checking declared writes, roles and labels",()=>me.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:O,...S!==null?{app:S}:{}}))}catch(ye){V(ye,"extensions:deploy","plan writes"),w(`plan writes failed: ${ye instanceof Error?ye.message:String(ye)}`)}Z.roles&&Ce("plan",Z.roles.verdicts,Z.roles.retired);for(let ye of ga({app:S,roles:A,retired:Z.roles?.retired??null}))b(ye.text);if(Z.labels&&Z.labels.verdicts.length>0){b(""),b(h.bold("labels"));let ye=Math.max(...Z.labels.verdicts.map(fe=>fe.name.length));for(let fe of Z.labels.verdicts){let ie=fe.name.padEnd(ye);if(fe.action==="create")b(` create ${ie} ${h.dim(fe.color)}`);else{let Re=fe.declaredColor?`${fe.color} \u2014 declared ${fe.declaredColor}, the instance's colour is kept`:fe.color;b(` ${h.dim("ok")} ${ie} ${h.dim(Re)}`)}}b(h.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let ye of Z.verdicts){let fe=`${ye.source} ${ye.recordType}.${ye.op}`;ye.allowed?ye.heldForApproval?b(`${h.dim("HELD")} ${fe} \u2014 allowed, but each write waits for operator approval.`):b(`${h.dim("ok")} ${fe}`):L(`${h.bold("DENIED")} ${fe}${ye.rule?` \u2014 guardrail "${ye.rule}"`:""} (${ye.reason})`)}Z.ok||(b(""),w(Z.message??(Z.roles&&!Z.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(h.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(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl),g=await J(`promoting ${m}`,()=>Y(x,S,u,"promote",{previewId:m}));Ie()?b(Gt("Promoted",[`${h.bold(u)} ${h.green(`v${g.version??"?"}`)} ${h.dim(g.url??`/a/${u}`)}`])):b(`promoted ${u} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${u}`}.`);let T=fp(g);Ce("applied",T.verdicts,T.retired),Ft({labels:g.labels?{applied:!0,verdicts:g.labels}:null}),await Ht(g)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=await F(v,x,u);if(m.json)return b(JSON.stringify(S.previews,null,2));if(S.previews.length===0){b(`no open previews for ${u}.`);return}for(let g of S.previews){let T=g.label?` ${g.label}`:"",E=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";b(`v${g.version} ${g.previewId}${T} ${g.url} (expires ${E})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);await J(`discarding ${m}`,()=>Y(x,S,u,"discard",{previewId:m})),b(`discarded ${m}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=await J(`creating ${u}`,()=>f(v,x,{slug:u,name:m.name,description:m.description})),g=S.slug??u;Ie()?b(Gt("Created",[`${h.bold(g)} ${h.dim(S.url??`/a/${g}`)}`])):b(`created ${g} (${S.url??`/a/${g}`}).`),b(`next: turbobase apps push ${g} . # store the source`),b(` turbobase apps deploy ${g} # build + go live`)});let p=Do(fetch);async function f(u,m,v,x={}){let S=`${u.replace(/\/+$/,"")}/v1/apps`,g;try{g=await p(S,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(T){w(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:v.slug,existed:!0};w(`an app with slug "${v.slug}" already exists.`)}return g.ok||w(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function _(u,m,v){let x=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,S;try{S=await p(x,{headers:{Authorization:`Bearer ${m}`}})}catch(g){w(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&w(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||w(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function y(u,m,v){let x=se(u),S=0;for(let[g,T]of Object.entries(m)){let E=se(x,g);E!==x&&!E.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${g}`),v||await ae.stat(E).then(()=>!0).catch(()=>!1)&&w(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(E),{recursive:!0}),await ae.writeFile(E,T,"utf8"),S+=1}return S}function k(u){let m=u.indexOf(","),v=u.startsWith("data:")?m>=0?u.slice(m+1):"":u;if(!v)return null;try{let x=Buffer.from(v,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function R(u,m,v){let x=se(u),S=async(T,E)=>{let A=se(x,T);A!==x&&!A.startsWith(x+Hd)&&w(`refusing to write outside ${x}: ${T}`),v||await ae.stat(A).then(()=>!0).catch(()=>!1)&&w(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(A),{recursive:!0}),await ae.writeFile(A,E)},g=`# ${m.title||"App change request"}
|
|
4136
|
+
`),"utf8"),b(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${En.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",u=>Number.parseInt(u,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(u=>Yp(u)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(u=>Zp(u)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>Qp(u,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>eh(u,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(u=>th(u)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>rh(u,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((u,h)=>nh(u,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.",u=>Number.parseInt(u,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(u=>(u.publish&&!u.from&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),u.from?lh({baseUrl:u.baseUrl,from:u.from,app:u.app,dryRun:u.dryRun,publish:u.publish,yes:u.yes}):oh(u))),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(u=>kh(u)),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((u,h)=>Th(u,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((u,h)=>xh(u,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(u=>$h(u)),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((u,h)=>Rh(u,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((u,h)=>Eh(u,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async u=>{let h;try{h=Rt("hook",{recordType:u.record,event:u.event,template:u.template,field:u.field,regex:u.regex,source:u.source,id:u.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=se(process.cwd(),h.relativePath);await Pr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`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 u=>{let h;try{h=Rt("conduit",{recordType:u.record,source:u.source,to:u.to,toRecordType:u.toRecord,event:u.event,id:u.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=se(process.cwd(),h.relativePath);await Pr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`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 u=>{let h;try{h=Rt("process",{recordType:u.record,then:u.then,onFailure:u.onFailure,id:u.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=se(process.cwd(),h.relativePath);await Pr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(u,h)=>{let w=Fd(h.reporter),T=await Sn(se(process.cwd(),u)),_=se(process.cwd(),h.samples),f=await _n(_);f.length===0&&!w&&b(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await Ko(T,f.map(C=>C.fixture),{resolveDir:zt(se(process.cwd(),u))})}catch(C){v(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(w){let C=MA(x);b(Go(C,w)),Li(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of x){let O=C.pass?m.green("PASS"):m.red("FAIL");C.pass||(E+=1);let G=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";b(` ${O} ${C.name}${G}`)}let A=`${x.length-E}/${x.length} sample(s) passed.`;b(`
|
|
4137
|
+
${E===0?m.green(A):m.yellow(A)}`),Li(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(u,h)=>{if(h.to){let x=await Hd(),{baseUrl:E,token:A}=await B(h.baseUrl),C=new q({baseUrl:E,token:A});try{let O=await J(`applying bundle to ${h.to}`,()=>C.configApply(x,{prune:h.prune}));b(`applied bundle to ${h.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let G=O.skippedDestroys??[];if(G.length>0){L(`${G.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of G)L(` ${N.kind} ${N.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&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}u||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:T}=await B(h.baseUrl),_=await UA(se(process.cwd(),u)),f=new q({baseUrl:w,token:T});try{let x=await J(`deploying ${Gb(u)}`,()=>f.deploy(_));Ie()?b(Gt("Deployed",[`${m.bold(x.id)} ${Nr(x.status)} ${m.dim(x.outcome)}`])):b(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof Q&&x.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").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(u,h,w)=>{let T=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let _=se(process.cwd(),h??".");await ae.mkdir(_,{recursive:!0});let f=w.proposal??await $(_),{baseUrl:x,token:E}=await B(w.baseUrl),A=new q({baseUrl:x,token:E}),C=!1;try{C=(await A.appsList()).some(ie=>ie.slug===u||ie.id===u)}catch(ie){V(ie,"extensions:deploy","deploy"),v(`could not reach ${x}: ${ie instanceof Error?ie.message:String(ie)}`)}if(!C){w.create||v(`no app "${u}" on ${x} \u2014 create it with \`turbobase apps create ${u}\`, or pass --create.`);let ie=await J(`creating app ${u}`,()=>g(x,E,{slug:u},{tolerateExisting:!0}));ie.existed||b(`created ${ie.slug??u}.`)}let O;if(w.replace)if(typeof w.replace=="string")O=w.replace;else{let{previews:ie}=await H(x,E,u);if(ie.length===0&&v(`no open preview on ${u} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ie.length>1){for(let $e of ie)b(` ${$e.previewId} v${$e.version}${$e.label?` ${$e.label}`:""} ${$e.url}`);v(`${u} has ${ie.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ie[0].previewId}\`.`)}O=ie[0].previewId}let G;if(w.replaceLabel){let ie=w.replaceLabel,{previews:$e}=await H(x,E,u),xt=$e.filter(Mi=>Mi.label===ie);xt.length>0?(O=xt[0].previewId,xt.length>1&&L(`${xt.length} open previews carry the label "${ie}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ie}" \u2014 opening one.`),G=ie}let N=ie=>ae.stat(et(_,ie)).then(()=>!0).catch(()=>!1),W=u,me=_,Z=w.build!==!1;if(Z&&!await N("package.json"))if(await N("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Z=!1;else if(w.pull===!1)v(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ie=await J(`pulling ${u}`,()=>S(x,E,u));W=ie.slug??u,await y(_,ie.files,!0),b(`pulled generated source (rev ${ie.rev}).`)}let be;if(Z){let ie=Ch();if(be={buildId:ie,assetBase:Ih(ie)},w.install!==!1&&!await N("node_modules")){b("installing dependencies\u2026");try{await I(["install"],_)}catch($e){v(`npm install failed: ${$e instanceof Error?$e.message:String($e)}`)}}b("building\u2026");try{await I(["run","build"],_,{TURBOBASE_ASSET_BASE:be.assetBase})}catch($e){v(`build failed: ${$e instanceof Error?$e.message:String($e)}`)}await N("dist")||v(`no dist/ after build in ${_} \u2014 check the app's build script.`),me=et(_,"dist")}T&&!be&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${W}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let fe=await Oe(x,E,W,me,w.entry,f,be,T?{label:w.label??G,replacePreviewId:O}:void 0);if(T){let ie=fe.previewUrl??"(no url returned)",$e=fe.expiresAt?new Date(fe.expiresAt).toLocaleDateString():`${Oh} days`,xt=fe.replacedVersion==null?null:`replaced v${fe.replacedVersion} \u2014 same URL`;if(Ie())b(Gt(xt?"Preview replaced":"Preview deployed",[`${m.bold(W)} ${m.green(`v${fe.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ie)}`,...xt?[m.dim(xt)]:[],m.dim(`expires ${$e}`)]));else{let Mi=xt?`; ${xt}`:"";b(`preview ${W} v${fe.version??"?"} \u2192 ${ie} (expires ${$e}; /a/${W} unchanged${Mi}).`)}Bt(fe),b(`next: turbobase apps promote ${W} ${fe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${fe.previewId??"<preview-id>"}`);return}Ie()?b(Gt("Deployed",[`${m.bold(W)} ${m.green(`v${fe.version??"?"}`)} ${m.dim(fe.url??`/a/${W}`)}`])):b(`deployed ${W} \u2192 v${fe.version??"?"} (${fe.url??`/a/${W}`}).`),Bt(fe),Ft(fe),await Ht(fe,_)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(u,h)=>{let w=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&v("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&w&&T!==w&&v(`--app ${T} and --as app:${w} name two different apps \u2014 pass one slug.`);let _=T||w||null,f=await FA(u??".");f||v(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`);let x=Array.isArray(f.manifest.tables)?f.manifest.tables:[],E=Array.isArray(f.manifest.writes)?f.manifest.writes:[],A=Array.isArray(f.manifest.roles)?f.manifest.roles:null,C=A??[],O=Array.isArray(f.manifest.labels)?f.manifest.labels:[],G=A!==null&&A.length===0;if(x.length===0&&E.length===0&&C.length===0&&O.length===0){if(!G)return b(`${f.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(_===null){for(let Z of wa({app:null,roles:A}))b(Z.text);return}}let{baseUrl:N,token:W}=await B(h.baseUrl),me=new q({baseUrl:N,token:W});if(x.length>0){let Z;try{Z=await J("planning tables",()=>me.tablesPlan({claimedBy:h.as,tables:x}))}catch(be){V(be,"extensions:deploy","plan tables"),Ro(be)}b(`claiming as ${m.bold(Z.claimedBy)}`);for(let be of Z.tables)xo(be,{showClaimants:!0})}if(E.length>0||C.length>0||O.length>0||G&&_!==null){let Z;try{Z=await J("checking declared writes, roles and labels",()=>me.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:O,..._!==null?{app:_}:{}}))}catch(be){V(be,"extensions:deploy","plan writes"),v(`plan writes failed: ${be instanceof Error?be.message:String(be)}`)}Z.roles&&Ce("plan",Z.roles.verdicts,Z.roles.retired);for(let be of wa({app:_,roles:A,retired:Z.roles?.retired??null}))b(be.text);if(Z.labels&&Z.labels.verdicts.length>0){b(""),b(m.bold("labels"));let be=Math.max(...Z.labels.verdicts.map(fe=>fe.name.length));for(let fe of Z.labels.verdicts){let ie=fe.name.padEnd(be);if(fe.action==="create")b(` create ${ie} ${m.dim(fe.color)}`);else{let $e=fe.declaredColor?`${fe.color} \u2014 declared ${fe.declaredColor}, the instance's colour is kept`:fe.color;b(` ${m.dim("ok")} ${ie} ${m.dim($e)}`)}}b(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let be of Z.verdicts){let fe=`${be.source} ${be.recordType}.${be.op}`;be.allowed?be.heldForApproval?b(`${m.dim("HELD")} ${fe} \u2014 allowed, but each write waits for operator approval.`):b(`${m.dim("ok")} ${fe}`):L(`${m.bold("DENIED")} ${fe}${be.rule?` \u2014 guardrail "${be.rule}"`:""} (${be.reason})`)}Z.ok||(b(""),v(Z.message??(Z.roles&&!Z.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(m.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(u,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl),f=await J(`promoting ${h}`,()=>Y(T,_,u,"promote",{previewId:h}));Ie()?b(Gt("Promoted",[`${m.bold(u)} ${m.green(`v${f.version??"?"}`)} ${m.dim(f.url??`/a/${u}`)}`])):b(`promoted ${u} \u2192 v${f.version??"?"} is now live at ${f.url??`/a/${u}`}.`);let x=xp(f);Ce("applied",x.verdicts,x.retired),Ft({labels:f.labels?{applied:!0,verdicts:f.labels}:null}),await Ht(f)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=await H(w,T,u);if(h.json)return b(JSON.stringify(_.previews,null,2));if(_.previews.length===0){b(`no open previews for ${u}.`);return}for(let f of _.previews){let x=f.label?` ${f.label}`:"",E=f.expiresAt?new Date(f.expiresAt).toLocaleDateString():"?";b(`v${f.version} ${f.previewId}${x} ${f.url} (expires ${E})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl);await J(`discarding ${h}`,()=>Y(T,_,u,"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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=await J(`creating ${u}`,()=>g(w,T,{slug:u,name:h.name,description:h.description})),f=_.slug??u;Ie()?b(Gt("Created",[`${m.bold(f)} ${m.dim(_.url??`/a/${f}`)}`])):b(`created ${f} (${_.url??`/a/${f}`}).`),b(`next: turbobase apps push ${f} . # store the source`),b(` turbobase apps deploy ${f} # build + go live`)});let p=Uo(fetch);async function g(u,h,w,T={}){let _=`${u.replace(/\/+$/,"")}/v1/apps`,f;try{f=await p(_,{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(x){v(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(f.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),f.status===409){if(T.tolerateExisting)return{slug:w.slug,existed:!0};v(`an app with slug "${w.slug}" already exists.`)}return f.ok||v(`create failed: HTTP ${f.status} ${(await f.text().catch(()=>"")).slice(0,200)}`),await f.json().catch(()=>({}))}async function S(u,h,w){let T=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,_;try{_=await p(T,{headers:{Authorization:`Bearer ${h}`}})}catch(f){v(`pull request failed: ${f instanceof Error?f.message:String(f)}`)}return _.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&v(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||v(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function y(u,h,w){let T=se(u),_=0;for(let[f,x]of Object.entries(h)){let E=se(T,f);E!==T&&!E.startsWith(T+Gd)&&v(`refusing to write outside ${T}: ${f}`),w||await ae.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(E),{recursive:!0}),await ae.writeFile(E,x,"utf8"),_+=1}return _}function k(u){let h=u.indexOf(","),w=u.startsWith("data:")?h>=0?u.slice(h+1):"":u;if(!w)return null;try{let T=Buffer.from(w,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function R(u,h,w){let T=se(u),_=async(x,E)=>{let A=se(T,x);A!==T&&!A.startsWith(T+Gd)&&v(`refusing to write outside ${T}: ${x}`),w||await ae.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ae.mkdir(zt(A),{recursive:!0}),await ae.writeFile(A,E)},f=`# ${h.title||"App change request"}
|
|
3839
4138
|
|
|
3840
|
-
> Widget proposal \`${
|
|
3841
|
-
> \`turbobase apps deploy ${
|
|
4139
|
+
> Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
|
|
4140
|
+
> \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
|
|
3842
4141
|
|
|
3843
|
-
${
|
|
4142
|
+
${h.bodyMarkdown||"_No description provided._"}
|
|
3844
4143
|
|
|
3845
4144
|
## Screen context
|
|
3846
4145
|
|
|
3847
|
-
`+(
|
|
3848
|
-
`);if(await
|
|
3849
|
-
`)}async function $(u){try{let m=await ae.readFile(et(u,".turbobase","proposal.json"),"utf8"),v=JSON.parse(m);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function P(u,m,v,x,S,g){let T=new q({baseUrl:u,token:m});try{return await T.appsPush(v,x,{note:S,proposalId:g})}catch(E){if(E instanceof Q){let A=E.body;if(E.status===401&&w("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&w("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&V(E,"extensions:deploy","push app source"),E.status===404&&w(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&w("push rejected: the request body exceeded the instance limit."),w(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}w(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function I(u,m,v){return new Promise((x,S)=>{let g=Kd("npm",u,{cwd:m,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});g.on("error",S),g.on("exit",T=>T===0?x():S(new Error(`npm ${u.join(" ")} exited ${T??"?"}`)))})}async function D(u,m,v,x){let S=`${u.replace(/\/+$/,"")}${v}`,g;try{g=await p(S,{method:x.method,headers:{Authorization:`Bearer ${m}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(T){w(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let T=await g.text().catch(()=>""),E=T.slice(0,300);try{let A=JSON.parse(T);E=A.message??A.error??E}catch{}w(`failed: HTTP ${g.status} ${E}`)}return await g.json().catch(()=>({}))}async function Y(u,m,v,x,S){return await D(u,m,`/v1/apps/${encodeURIComponent(v)}/preview/${x}`,{method:"POST",body:S})}async function F(u,m,v){return{previews:(await D(u,m,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Oe(u,m,v,x,S,g,T,E){let A;try{A=await J(`zipping ${x}`,()=>Wu(x))}catch(N){w(`could not zip ${x}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&w(`${x} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Oa&&w(`${x} zips to ${jb(A.buffer.byteLength)} \u2014 over the ${jb(Oa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};S&&(C["x-app-entry"]=S),g&&(C["x-proposal-id"]=g),T&&(C["x-app-build-id"]=T.buildId,C["x-app-asset-base"]=T.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=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,G;try{G=await J(`deploying ${v} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(G.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404){let N=await G.text().catch(()=>""),W={};try{W=JSON.parse(N)}catch{}W.error==="no_preview"&&w(`${W.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),w(`no app "${v}" on ${u} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!G.ok){let N=await G.text().catch(()=>""),W=N.slice(0,300);try{let me=JSON.parse(N);W=me.message??me.error??W}catch{}w(`deploy failed: HTTP ${G.status} ${W}`)}return await G.json().catch(()=>({}))}function Ce(u,m,v){for(let x of mp({mode:u,verdicts:m,retired:v}))(x.stream==="err"?L:b)(x.text)}function Bt(u){let m=u.roles;m&&Ce(m.applied?"applied":"preview",m.verdicts??[],m.retired)}function Ft(u){let m=u.labels;if(!m||m.verdicts.length===0)return;let v=m.verdicts.filter(S=>S.action!=="noop");if(v.length===0)return;b(""),b(h.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let x=Math.max(...v.map(S=>S.name.length));for(let S of v){let g=S.name.padEnd(x);if(S.action==="detach")b(` removed ${g} ${h.dim("no longer declared in the manifest")}`);else if(S.action==="create")b(` created ${g} ${h.dim(S.color)}`);else{let T=S.declaredColor?`${S.color} \u2014 declared ${S.declaredColor}, the instance's colour is kept`:S.color;b(` added ${g} ${h.dim(T)}`)}}b(h.dim(m.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Ht(u,m){let v=ap(u,{localDocsModifiedAt:await mn(m)});v&&b(v.level==="warn"?h.yellow(v.message):h.dim(v.message))}async function mn(u){if(!u)return null;let m=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await ae.stat(et(u,v));(m===null||x.mtimeMs>m)&&(m=x.mtimeMs)}catch{}return m===null?null:new Date(m)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(u,m,v)=>{let{baseUrl:x,token:S}=await H(v.baseUrl);if(v.proposal){let A=new q({baseUrl:x,token:S}),C;try{C=await J(`fetching proposal ${v.proposal}`,()=>A.appPullContext(v.proposal))}catch(me){V(me,"extensions:deploy","pull proposal"),me instanceof Q&&me.status===404&&w(`no widget proposal "${v.proposal}" on ${x}.`),w(`could not fetch proposal ${v.proposal}: ${me instanceof Error?me.message:String(me)}`)}let O=await J(`pulling ${C.appSlug}`,()=>_(x,S,C.appSlug)),G=m??u,N=se(process.cwd(),G??C.appSlug);await ae.mkdir(N,{recursive:!0});let W=await y(N,O.files,!!v.force);await R(N,C,!!v.force),b(`pulled ${W} file${W===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),b(`next: cd ${Ni(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}u||w("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${u}`,()=>_(x,S,u)),T=se(process.cwd(),m??g.slug??u);await ae.mkdir(T,{recursive:!0});let E=await y(T,g.files,!!v.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${T} (rev ${g.rev}).`),b(`next: cd ${Ni(process.cwd(),T)||"."} && turbobase apps deploy ${g.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(u,m,v)=>{let x=se(process.cwd(),m??u),S=await ht(v.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:T}=await Promise.resolve().then(()=>(rm(),tm)),E=v.title??u,A=g({slug:u,title:E,appTsx:T(E),instanceOrigin:S?.baseUrl});await ae.mkdir(x,{recursive:!0});let C=await y(x,A,!!v.force);if(b(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${x}`),v.claude!==!1){let G=ba({baseUrl:S?.baseUrl,token:S?.token,appSlug:u}),N=0;for(let W of G){let me=await Lb(et(x,W.path),W);(me==="wrote"||me==="merged")&&(N+=1)}b(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||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=Ni(process.cwd(),x)||".";b(`next: cd ${O} && npm install && npm run dev`),b(` turbobase apps create ${u}`),b(` turbobase apps push ${u} .`),b(` turbobase apps deploy ${u} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.appsList()}catch(g){V(g,"extensions:deploy","list apps"),w(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ft(S.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(u,m,v)=>{let x=se(process.cwd(),m??".");await ae.stat(x).then(Z=>Z.isDirectory()).catch(()=>!1)||w(`${x} is not a directory.`);let{baseUrl:g,token:T}=await H(v.baseUrl),E=v.proposal??await $(x),{files:A,skipped:C,secrets:O,unstorable:G}=await vh(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),G.length>0){for(let Z of G)L(`${Z} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Z of C)L(h.dim(`skipped binary file ${Z}`));for(let Z of O)L(h.dim(`skipped ${Z} (holds credentials \u2014 never pushed)`));let W=await J(`pushing ${N} file${N===1?"":"s"}`,()=>P(g,T,u,A,v.note,E));b(`pushed ${W.files} file${W.files===1?"":"s"} \u2192 ${W.slug} rev ${W.rev} (source only, nothing deployed).`);let me=await Pn(new q({baseUrl:g,token:T}),W.slug);me&&me.entriesAdded>0&&b(`${me.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${W.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let m=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`planning against ${u.to??v}`,()=>S.configPlan(m))}catch(T){w(`plan failed: ${T instanceof Error?T.message:String(T)}`)}EA(g,u.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async u=>{let m=await zd(),{baseUrl:v,token:x}=await H(u.baseUrl),S=m.tenant??PA(v),g=xp(u.confirm,S);g.ok||w(`promote refused (fail-closed): ${g.reason}`);let T=new q({baseUrl:v,token:x});try{let E=await J(`promoting ${u.from} \u2192 ${u.to} (${S})`,()=>T.configApply(m,{prune:u.prune}));if(Ie()){let C=[`${h.bold(`${u.from} \u2192 ${u.to}`)} ${h.dim(S??"")}`,`${Vt.add(String(E.applied.add))} ${Vt.change(String(E.applied.change))} ${Vt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(h.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Gt("Promoted",C))}else b(`promoted ${u.from} \u2192 ${u.to} (${S}): +${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 ${u.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&&w("promote forbidden (403) \u2014 the stored PAT is not for an admin."),w(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(u,m)=>{let v=qd(m.reporter),x=se(process.cwd(),u),S=await Sn(x),g=Yu(S);v?b(Vo(kA(u,g),v)):b(Xu(u,g,{warn:h.yellow,ok:h.green,dim:h.dim})),m.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(u,m)=>{let v=qd(m.reporter),x=await Bu(se(process.cwd(),u));if(m.against){m.against!=="sandbox"&&w(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await qu(da(x))}catch(T){w(T instanceof Error?T.message:String(T))}return}m.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await zu(se(process.cwd(),m.fixture))}catch(T){w(`could not read fixture ${m.fixture}: ${T instanceof Error?T.message:String(T)}`)}let g=await Mu(x,S,m.fixture,{resolveDir:zt(se(process.cwd(),u))});if(v){let T=TA(g);b(Vo(T,v)),Oi(T.cases.some(E=>E.status==="failed")?1:0)}b(Fu(g,!!m.trace)),Oi(g.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v});try{await op(x,{status:u.status,retry:u.retry,limit:u.limit?Number(u.limit):void 0,sink:b})}catch(S){S instanceof Q&&S.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof Q&&S.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let dr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");dr.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 u=>{await sh(u)}),dr.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(u,m)=>{await ih(u??[],m)}),dr.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(u,m)=>{await ah(u,m)}),dr.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(u,m)=>{await lh(u,m)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await ch(u,m)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await dh(u,m)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,m)=>{await uh(u,m)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(u,m)=>{let v=u.lastIndexOf("@"),x=v>0?u.slice(0,v):u,S=v>0?u.slice(v+1):void 0,g=sa();g||w(`marketplace not configured \u2014 set ${Cr} and ${Uo}.
|
|
3850
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
3851
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
3852
|
-
project init: ${
|
|
3853
|
-
project ci: ${
|
|
3854
|
-
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async u=>{let{baseUrl:
|
|
4146
|
+
`+(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.
|
|
4147
|
+
`);if(await _("PROPOSAL.md",f),h.screenshot){let x=k(h.screenshot);x&&await _("proposal-screenshot.png",x)}await _(et(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
|
|
4148
|
+
`)}async function $(u){try{let h=await ae.readFile(et(u,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(u,h,w,T,_,f){let x=new q({baseUrl:u,token:h});try{return await x.appsPush(w,T,{note:_,proposalId:f})}catch(E){if(E instanceof Q){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&V(E,"extensions:deploy","push app source"),E.status===404&&v(`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"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function I(u,h,w){return new Promise((T,_)=>{let f=Wd("npm",u,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});f.on("error",_),f.on("exit",x=>x===0?T():_(new Error(`npm ${u.join(" ")} exited ${x??"?"}`)))})}async function D(u,h,w,T){let _=`${u.replace(/\/+$/,"")}${w}`,f;try{f=await p(_,{method:T.method,headers:{Authorization:`Bearer ${h}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(x){v(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(f.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!f.ok){let x=await f.text().catch(()=>""),E=x.slice(0,300);try{let A=JSON.parse(x);E=A.message??A.error??E}catch{}v(`failed: HTTP ${f.status} ${E}`)}return await f.json().catch(()=>({}))}async function Y(u,h,w,T,_){return await D(u,h,`/v1/apps/${encodeURIComponent(w)}/preview/${T}`,{method:"POST",body:_})}async function H(u,h,w){return{previews:(await D(u,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function Oe(u,h,w,T,_,f,x,E){let A;try{A=await J(`zipping ${T}`,()=>Qu(T))}catch(N){v(`could not zip ${T}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&v(`${T} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>ja&&v(`${T} zips to ${Vb(A.buffer.byteLength)} \u2014 over the ${Vb(ja)} 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"};_&&(C["x-app-entry"]=_),f&&(C["x-proposal-id"]=f),x&&(C["x-app-build-id"]=x.buildId,C["x-app-asset-base"]=x.assetBase),E&&(C["x-app-channel"]="preview",E.label&&(C["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(C["x-app-preview-replace"]=E.replacePreviewId));let O=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,G;try{G=await J(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){v(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(G.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404){let N=await G.text().catch(()=>""),W={};try{W=JSON.parse(N)}catch{}W.error==="no_preview"&&v(`${W.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),v(`no app "${w}" on ${u} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!G.ok){let N=await G.text().catch(()=>""),W=N.slice(0,300);try{let me=JSON.parse(N);W=me.message??me.error??W}catch{}v(`deploy failed: HTTP ${G.status} ${W}`)}return await G.json().catch(()=>({}))}function Ce(u,h,w){for(let T of Tp({mode:u,verdicts:h,retired:w}))(T.stream==="err"?L:b)(T.text)}function Bt(u){let h=u.roles;h&&Ce(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function Ft(u){let h=u.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(_=>_.action!=="noop");if(w.length===0)return;b(""),b(m.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...w.map(_=>_.name.length));for(let _ of w){let f=_.name.padEnd(T);if(_.action==="detach")b(` removed ${f} ${m.dim("no longer declared in the manifest")}`);else if(_.action==="create")b(` created ${f} ${m.dim(_.color)}`);else{let x=_.declaredColor?`${_.color} \u2014 declared ${_.declaredColor}, the instance's colour is kept`:_.color;b(` added ${f} ${m.dim(x)}`)}}b(m.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 Ht(u,h){let w=yp(u,{localDocsModifiedAt:await mn(h)});w&&b(w.level==="warn"?m.yellow(w.message):m.dim(w.message))}async function mn(u){if(!u)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ae.stat(et(u,w));(h===null||T.mtimeMs>h)&&(h=T.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(u,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl);if(w.proposal){let A=new q({baseUrl:T,token:_}),C;try{C=await J(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(me){V(me,"extensions:deploy","pull proposal"),me instanceof Q&&me.status===404&&v(`no widget proposal "${w.proposal}" on ${T}.`),v(`could not fetch proposal ${w.proposal}: ${me instanceof Error?me.message:String(me)}`)}let O=await J(`pulling ${C.appSlug}`,()=>S(T,_,C.appSlug)),G=h??u,N=se(process.cwd(),G??C.appSlug);await ae.mkdir(N,{recursive:!0});let W=await y(N,O.files,!!w.force);await R(N,C,!!w.force),b(`pulled ${W} file${W===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),b(`next: cd ${ji(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}u||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let f=await J(`pulling ${u}`,()=>S(T,_,u)),x=se(process.cwd(),h??f.slug??u);await ae.mkdir(x,{recursive:!0});let E=await y(x,f.files,!!w.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${x} (rev ${f.rev}).`),b(`next: cd ${ji(process.cwd(),x)||"."} && turbobase apps deploy ${f.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(u,h,w)=>{let T=se(process.cwd(),h??u),_=await ht(w.baseUrl).catch(()=>null),{scaffoldAppFiles:f,starterApp:x}=await Promise.resolve().then(()=>(pm(),um)),E=w.title??u,A=f({slug:u,title:E,appTsx:x(E),instanceOrigin:_?.baseUrl});await ae.mkdir(T,{recursive:!0});let C=await y(T,A,!!w.force);if(b(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${T}`),w.claude!==!1){let G=_a({baseUrl:_?.baseUrl,token:_?.token,appSlug:u}),N=0;for(let W of G){let me=await Kb(et(T,W.path),W);(me==="wrote"||me==="merged")&&(N+=1)}b(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||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=ji(process.cwd(),T)||".";b(`next: cd ${O} && npm install && npm run dev`),b(` turbobase apps create ${u}`),b(` turbobase apps push ${u} .`),b(` turbobase apps deploy ${u} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.appsList()}catch(f){V(f,"extensions:deploy","list apps"),v(`list apps failed: ${f instanceof Error?f.message:String(f)}`)}if(u.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ft(_.map(f=>[f.slug,f.name,f.deployed?"yes":"no",f.sourceRev===null?"\u2014":`rev ${f.sourceRev}`,f.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(u,h,w)=>{let T=se(process.cwd(),h??".");await ae.stat(T).then(Z=>Z.isDirectory()).catch(()=>!1)||v(`${T} is not a directory.`);let{baseUrl:f,token:x}=await B(w.baseUrl),E=w.proposal??await $(T),{files:A,skipped:C,secrets:O,unstorable:G}=await Ah(T),N=Object.keys(A).length;if(N===0&&v(`no source files found under ${T} (build output and node_modules are skipped).`),G.length>0){for(let Z of G)L(`${Z} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Z of C)L(m.dim(`skipped binary file ${Z}`));for(let Z of O)L(m.dim(`skipped ${Z} (holds credentials \u2014 never pushed)`));let W=await J(`pushing ${N} file${N===1?"":"s"}`,()=>P(f,x,u,A,w.note,E));b(`pushed ${W.files} file${W.files===1?"":"s"} \u2192 ${W.slug} rev ${W.rev} (source only, nothing deployed).`);let me=await Pn(new q({baseUrl:f,token:x}),W.slug);me&&me.entriesAdded>0&&b(`${me.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${W.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let h=await Hd(),{baseUrl:w,token:T}=await B(u.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await J(`planning against ${u.to??w}`,()=>_.configPlan(h))}catch(x){v(`plan failed: ${x instanceof Error?x.message:String(x)}`)}KA(f,u.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async u=>{let h=await Hd(),{baseUrl:w,token:T}=await B(u.baseUrl),_=h.tenant??VA(w),f=Lp(u.confirm,_);f.ok||v(`promote refused (fail-closed): ${f.reason}`);let x=new q({baseUrl:w,token:T});try{let E=await J(`promoting ${u.from} \u2192 ${u.to} (${_})`,()=>x.configApply(h,{prune:u.prune}));if(Ie()){let C=[`${m.bold(`${u.from} \u2192 ${u.to}`)} ${m.dim(_??"")}`,`${Vt.add(String(E.applied.add))} ${Vt.change(String(E.applied.change))} ${Vt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(m.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Gt("Promoted",C))}else b(`promoted ${u.from} \u2192 ${u.to} (${_}): +${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 ${u.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&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(u,h)=>{let w=Fd(h.reporter),T=se(process.cwd(),u),_=await Sn(T),f=tp(_);w?b(Go(qA(u,f),w)):b(rp(u,f,{warn:m.yellow,ok:m.green,dim:m.dim})),h.ci&&f.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(u,h)=>{let w=Fd(h.reporter),T=await Gu(se(process.cwd(),u));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Ku(pa(T))}catch(x){v(x instanceof Error?x.message:String(x))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await Vu(se(process.cwd(),h.fixture))}catch(x){v(`could not read fixture ${h.fixture}: ${x instanceof Error?x.message:String(x)}`)}let f=await Hu(T,_,h.fixture,{resolveDir:zt(se(process.cwd(),u))});if(w){let x=zA(f);b(Go(x,w)),Li(x.cases.some(E=>E.status==="failed")?1:0)}b(Wu(f,!!h.trace)),Li(f.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w});try{await cp(T,{status:u.status,retry:u.retry,limit:u.limit?Number(u.limit):void 0,sink:b})}catch(_){_ instanceof Q&&_.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof Q&&_.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}});let dr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");dr.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 u=>{await fh(u)}),dr.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(u,h)=>{await gh(u??[],h)}),dr.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(u,h)=>{await yh(u,h)}),dr.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(u,h)=>{await bh(u,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await wh(u,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await vh(u,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(u,h)=>{await _h(u,h)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(u,h)=>{let w=u.lastIndexOf("@"),T=w>0?u.slice(0,w):u,_=w>0?u.slice(w+1):void 0,f=aa();f||v(`marketplace not configured \u2014 set ${Cr} and ${Mo}.
|
|
4149
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=la(f.registryUrl);x&&v(x);let{baseUrl:E,token:A}=await B(h.baseUrl),C=new wn(f),O;try{O=await J(`fetching ${u}`,()=>C.fetchBundle(T,_))}catch(Z){v(`marketplace fetch failed for ${u}: ${Z instanceof Error?Z.message:String(Z)}`)}let G=Po(O.manifest),N=null;if(G.length>0){if(!h.connection){let Z=G.map(be=>be.source_system).join(", ");v(`${O.name}@${O.version} declares a connection input (source: ${Z}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let W=BA(O.bundle,O.name,O.kind),me=new q({baseUrl:E,token:A});try{let Z=await J(`installing ${O.name}@${O.version}`,()=>me.deploy({...W,provenance:"marketplace",...N?{connectionId:N}:{}}));b(`installed ${O.name}@${O.version} \u2192 ${Z.id} (status=${Z.status}, ${Z.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(Z){Z instanceof Q&&Z.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${Z instanceof Error?Z.message:String(Z)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(u,h)=>{let w=aa();w||v(`marketplace not configured \u2014 set ${Cr} and ${Mo}.
|
|
4150
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=la(w.registryUrl);T&&v(T);let _=se(process.cwd(),u),f=await Sn(_),x=/\bdefineConduit\s*[<(]/.test(f)?"conduit":"hook",E={};if(h.manifest){let O=se(process.cwd(),h.manifest),G;try{G=await ae.readFile(O,"utf8")}catch{v(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(G)}catch{v(`manifest is not valid JSON: ${h.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&v("manifest must be a JSON object."),E=N}try{Bi(E,f)}catch(O){O instanceof Kt&&v(O.message),v(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new wn(w);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:x,bundle:f,manifest:E}))}catch(O){O instanceof Q&&O.status===403&&v("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&&v(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),v(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=Po(E);b(`published ${h.name}@${h.pkgVersion} (kind=${x}) to the marketplace.`),C.length>0&&b(` declares ${C.length} connection input(s): ${C.map(O=>O.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async u=>{let h=await ht(u.baseUrl).catch(()=>null),w=_a({baseUrl:h?.baseUrl,token:h?.token}),T=0,_=0,f=0;for(let x of w){let E=se(process.cwd(),x.path),A=await Kb(E,x);A==="wrote"?(T+=1,b(` wrote ${x.path}`)):A==="merged"?(f+=1,b(` merged ${x.path} (added the .mcp.json rule)`)):(_+=1,b(` skipped ${x.path} (exists)`))}b(`
|
|
4151
|
+
project init: ${T} written, ${f} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${va} (non-destructive).`).action(async()=>{let u=Rp(),h=0,w=0;for(let T of u){let _=se(process.cwd(),T.path);await Pr(_,T.content,T.executable)==="wrote"?(h+=1,b(` wrote ${T.path}`)):(w+=1,b(` skipped ${T.path} (exists)`))}b(`
|
|
4152
|
+
project ci: ${h} written, ${w} skipped.`),h>0&&(b(`
|
|
4153
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.catalogRecords()}catch(C){C instanceof Q&&(C.status===401||C.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(_.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let f=se(process.cwd(),u.out),x=Yu(_,{event:u.event}),E=0,A=0;for(let{recordType:C,fixture:O}of x){let G=et(f,`${C}.json`),N=`${JSON.stringify(O,null,2)}
|
|
3855
4154
|
`;u.force?(await ae.mkdir(zt(G),{recursive:!0}),await ae.writeFile(G,N,{mode:420}),E+=1,b(` wrote ${u.out}/${C}.json`)):await Pr(G,N)==="wrote"?(E+=1,b(` wrote ${u.out}/${C}.json`)):(A+=1,b(` skipped ${u.out}/${C}.json (exists \u2014 use --force to overwrite)`))}b(`
|
|
3856
|
-
samples init: ${E} written, ${A} skipped.`)});let Tt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),
|
|
3857
|
-
`+h.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(S.map(Li),{head:Ub})),b(h.dim(" first match wins; lower PRIO is evaluated first."))}),Tt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailCreate({name:u,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){V(T,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} created${g.status==="active"?"":h.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(h.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),Tt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailUpdate(u,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(T){V(T,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} updated`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[u,m,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Tt.command(`${u} <name>`).description(m==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,S)=>{let{baseUrl:g,token:T}=await H(S.baseUrl),E=new q({baseUrl:g,token:T});try{await E.guardrailUpdate(x,{status:m})}catch(A){V(A,"extensions:deploy",`${u} a guardrail`),w(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(x)} ${v}`),m==="inactive"&&b(h.dim(" writes it was gating now fall through to the other rules."))});Tt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x});try{await S.guardrailDelete(u)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(u)} deleted`)}),Tt.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(u,m)=>{let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${h.bold(g(A.mode))}`),b(h.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=u.trim().toLowerCase();T!=="allow"&&T!=="deny"&&w("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(T)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail posture set to ${h.bold(g(E.mode))}`),E.mode==="deny"&&b(h.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Tt.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 u=>{let m;if(u.fields)try{m=JSON.parse(u.fields)}catch(E){w(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...m?{fields:m}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch(E){V(E,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return b(JSON.stringify(g,null,2));let T=`${u.source}/${g.op??u.record}`;g.degraded?(b(`${h.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(h.dim(` ${g.reason}`))):g.allowed?b(`${h.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?h.dim(` (rule ${g.blockedBy})`):h.dim(" (no rule matched)"))):(b(`${h.red("\u2717")} ${T} \u2014 ${g.decision} by ${h.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(h.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(h.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,m={})=>{let v=`${h.bold(u.table)} ${h.dim(u.displayName)}`;b(u.exists===!1?`${v} ${h.dim("(new)")}`:v);for(let x of u.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=m.showClaimants&&x.claimedBy?.length?` ${h.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}m.showClaimants&&u.claimants.length>1&&b(h.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let m=u.body;m?.error==="table_conflict"&&m.message&&(L(m.message),process.exit(1))}w(`tables: ${u instanceof Error?u.message:String(u)}`)}let Gd=async u=>{let m=et(se(process.cwd(),u),"public","turbobase.json"),v=await ae.readFile(m,"utf8").catch(()=>null);if(v===null)return null;let x;try{x=JSON.parse(v)}catch(g){w(`${m} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:m}:(Array.isArray(S)||w(`${m}: "tables" must be an array.`),{tables:S,manifestPath:m})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:m,token:v}=await H(u.baseUrl),x=new q({baseUrl:m,token:v}),S;try{S=await x.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,m)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("planning tables",()=>g.tablesPlan({claimedBy:m.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","plan tables"),Ro(E)}b(`claiming as ${h.bold(T.claimedBy)}`);for(let E of T.tables)xo(E,{showClaimants:!0});b(""),b(h.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,m)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("applying tables",()=>g.tablesApply({claimedBy:m.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","apply tables"),Ro(E)}for(let E of T.tables)xo(E,{showClaimants:!0});b(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,m)=>[...m??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{let v=m.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&w(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(m.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J(`creating cr_${u}`,()=>g.tablesApply({tables:[{slug:u,displayName:m.name??u,fields:v,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){V(E,"extensions:deploy","create a table"),Ro(E)}for(let E of T.tables)xo(E);b(""),b(h.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,m)=>{m.confirm!==u&&w(`drop refused: --confirm "${m.confirm}" does not match "${u}".`);let{baseUrl:v,token:x}=await H(m.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`dropping cr_${u}`,()=>S.tablesDrop(u,m.confirm))}catch(T){V(T,"extensions:deploy","drop a table"),w(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let ji=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ji.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async u=>{process.env.TURBOBASE_SANDBOX="1";let m=Bd(),v;try{v=await Ch(m,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(x){x instanceof Cn&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${v.name} ready.`),b(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),b(` url: ${v.url}`),b(` expires: ${v.expiresAt}`)}),ji.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let m=Bd();await Fa(m).catch(()=>[]);let v;try{v=await Ih(m,u)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}v||w(`no sandbox named '${u}'.`),b(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ji.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Bd(),m=await Fa(u).catch(()=>[]),v=await ls(),{active:x}=Ba(v);if(x.length===0)b("no active sandboxes.");else{for(let S of x)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
|
|
3858
|
-
${
|
|
3859
|
-
`,
|
|
3860
|
-
`).length} lines).`)});let
|
|
3861
|
-
run \`${$n} ext extras install\` to fetch them into ${
|
|
4155
|
+
samples init: ${E} written, ${A} skipped.`)});let Tt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Di=u=>[u.name??m.dim(u.id.slice(0,8)),u.status==="active"?m.green("active"):u.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),u.decision==="deny"?m.red(u.decision):u.decision==="require_confirm"?m.yellow(u.decision):m.green(u.decision),String(u.priority),u.source,u.record??u.op,u.actor??m.dim("any"),u.when||m.dim("(always)"),u.reason??""],Wb=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Tt.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 u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.guardrailsList()}catch(f){V(f,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${f instanceof Error?f.message:String(f)}`)}if(u.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
4156
|
+
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(_.map(Di),{head:Wb})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Tt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.guardrailCreate({name:u,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(x){V(x,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} created${f.status==="active"?"":m.dim(` (${f.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.actor?` actor=${f.actor}`:""}${f.when?` where ${f.when}`:""} @prio ${f.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${f.source==="*"?"<source>":f.source} --record <record>`))}),Tt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.guardrailUpdate(u,{...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(x){V(x,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} updated`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.when?` where ${f.when}`:""} @prio ${f.priority}`))});for(let[u,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Tt.command(`${u} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,_)=>{let{baseUrl:f,token:x}=await B(_.baseUrl),E=new q({baseUrl:f,token:x});try{await E.guardrailUpdate(T,{status:h})}catch(A){V(A,"extensions:deploy",`${u} a guardrail`),v(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(T)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});Tt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T});try{await _.guardrailDelete(u)}catch(f){V(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(u)} deleted`)}),Tt.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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await _.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(f(A.mode))}`),b(m.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 x=u.trim().toLowerCase();x!=="allow"&&x!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await _.guardrailPostureSet(x)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(f(E.mode))}`),E.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Tt.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 u=>{let h;if(u.fields)try{h=JSON.parse(u.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:T}=await B(u.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...h?{fields:h}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch(E){V(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return b(JSON.stringify(f,null,2));let x=`${u.source}/${f.op??u.record}`;f.degraded?(b(`${m.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${x} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${x} \u2014 ${f.decision} by ${m.bold(f.blockedBy??"?")} at the ${f.phase} gate`),f.message&&b(m.dim(` ${f.message}`))),f.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),f.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,h={})=>{let w=`${m.bold(u.table)} ${m.dim(u.displayName)}`;b(u.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let T of u.fields){let _=[T.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&T.claimedBy?.length?` ${m.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";b(` ${T.column.padEnd(28)} ${T.type}${_?` (${_})`:""}${f}`)}h.showClaimants&&u.claimants.length>1&&b(m.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let h=u.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}v(`tables: ${u instanceof Error?u.message:String(u)}`)}let Yd=async u=>{let h=et(se(process.cwd(),u),"public","turbobase.json"),w=await ae.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let T;try{T=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let _=T.tables;return _===void 0?{tables:[],manifestPath:h}:(Array.isArray(_)||v(`${h}: "tables" must be an array.`),{tables:_,manifestPath:h})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.tablesList()}catch(f){V(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(u.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,h)=>{let w=await Yd(u??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new q({baseUrl:T,token:_}),x;try{x=await J("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){V(E,"extensions:deploy","plan tables"),Ro(E)}b(`claiming as ${m.bold(x.claimedBy)}`);for(let E of x.tables)xo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,h)=>{let w=await Yd(u??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new q({baseUrl:T,token:_}),x;try{x=await J("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){V(E,"extensions:deploy","apply tables"),Ro(E)}for(let E of x.tables)xo(E,{showClaimants:!0});b(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,h)=>[...h??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let w=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:T,token:_}=await B(h.baseUrl),f=new q({baseUrl:T,token:_}),x;try{x=await J(`creating cr_${u}`,()=>f.tablesApply({tables:[{slug:u,displayName:h.name??u,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){V(E,"extensions:deploy","create a table"),Ro(E)}for(let E of x.tables)xo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.confirm!==u&&v(`drop refused: --confirm "${h.confirm}" does not match "${u}".`);let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await J(`dropping cr_${u}`,()=>_.tablesDrop(u,h.confirm))}catch(x){V(x,"extensions:deploy","drop a table"),v(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!f.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${f.table} and every row in it.`)});let Ui=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ui.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async u=>{process.env.TURBOBASE_SANDBOX="1";let h=Kd(),w;try{w=await zh(h,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(T){T instanceof Cn&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Ui.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let h=Kd();await Va(h).catch(()=>[]);let w;try{w=await Bh(h,u)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}w||v(`no sandbox named '${u}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ui.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Kd(),h=await Va(u).catch(()=>[]),w=await ds(),{active:T}=Ka(w);if(T.length===0)b("no active sandboxes.");else{for(let _ of T)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
|
|
4157
|
+
${T.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Qo).action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await J("exporting instance config",()=>T.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let f=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
4158
|
+
`,x=se(process.cwd(),u.out,xn);await ae.mkdir(zt(x),{recursive:!0}),await ae.writeFile(x,f,"utf8"),b(`wrote ${u.out}/${xn} (${f.split(`
|
|
4159
|
+
`).length} lines).`)});let Xd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Jb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Zd=()=>process.env.TURBOBASE_HOME?.trim()||et(IA(),".turbobase"),Yb=()=>"1.38.0",$o=async()=>Promise.all(Jb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Xd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?_e.success("installed"):_e.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
|
|
4160
|
+
run \`${$n} ext extras install\` to fetch them into ${Zd()}.`)}),Xd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let u=await $o();if(u.every(A=>A.present)){b(_e.success("extras already installed \u2014 nothing to do."));return}let h=Zd();await ae.mkdir(h,{recursive:!0});let w=u.filter(A=>!A.present).map(A=>A.name),T=Ma(process.platform,process.arch),_=async(A,C)=>{let{code:O,stderr:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&v(`extras install failed while installing ${C} (npm exited ${O}).
|
|
3862
4161
|
${G.trim()}
|
|
3863
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},
|
|
3864
|
-
${Object.keys(
|
|
3865
|
-
`+(
|
|
4162
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},f=w.filter(A=>A!=="isolated-vm");if(f.length>0){let A=f.map(C=>`${C}@${Da[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await _(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Da["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),Nh.includes(T)){let O=`${Ua}@${Yb()}`;b(`fetching ${O} (no upstream binary for ${T}) \u2026`);let{code:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);G!==0&&b(_e.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Lh({home:h});C.length>0&&b(` ${_e.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let x=await $o(),E=x.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(_e.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${qa()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await To("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(x=await $o(),E=x.filter(C=>!C.present).map(C=>C.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${qa()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(_e.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Ar=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");Ar.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 u=>{let h=u.target==="approved"?"approved":u.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${u.target}').`);let w=await GA(se(process.cwd(),u.project??".")),T=Object.keys(w).length;!u.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(u.ref?await Vd(["rev-parse",u.ref])??u.ref:null)??process.env.GITHUB_SHA??await Vd(["rev-parse","HEAD"]),x=u.gitRepo??process.env.GITHUB_REPOSITORY??await Vd(["remote","get-url","origin"]),E=u.gitRef??process.env.GITHUB_REF??null,A=u.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await B(u.baseUrl),G=new q({baseUrl:C,token:O}),N;try{N=await G.releaseDeploy({solutionId:u.solution??null,target:h,approvedBy:u.approvedBy??null,files:T>0?w:null,gitRepo:x,gitRef:E,gitSha:f,prUrl:A})}catch(W){V(W,"releases:write","release deploy"),W instanceof Q&&W.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${W instanceof Error?W.message:String(W)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),u.follow&&await $a(()=>G.releaseStatus(N.releaseId),`release ${N.releaseId}`,u.intervalMs)}),Ar.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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.releaseFiles(u)}catch(A){A instanceof Q&&A.status===404&&v(`release ${u} not found.`),A instanceof Q&&A.status===409&&v(`no built project was retained for release ${u}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let x=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",f.owned],["context",f.context]])for(let[O,G]of Object.entries(C)){let N=et(x,A,O);await ae.mkdir(zt(N),{recursive:!0}),await ae.writeFile(N,G,"utf8"),E++}await ae.writeFile(et(x,".turbobase-release.json"),JSON.stringify({releaseId:f.releaseId,version:f.version,contentDigest:f.contentDigest},null,2),"utf8"),b(`pulled release ${f.releaseId} (${f.status}) \u2192 ${x}
|
|
4163
|
+
${Object.keys(f.owned).length} owned file(s), ${Object.keys(f.context).length} context file(s), ${E} total
|
|
4164
|
+
`+(f.logTail?`
|
|
3866
4165
|
the failure these bytes produced:
|
|
3867
|
-
${
|
|
4166
|
+
${f.logTail.trim()}
|
|
3868
4167
|
`:"")+`
|
|
3869
4168
|
edit the files under owned/, then:
|
|
3870
|
-
turbobase release push ${
|
|
4169
|
+
turbobase release push ${f.releaseId} --dir ${h.dir}`)}),Ar.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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f=se(process.cwd(),h.dir),x;try{x=await _.releaseFiles(u)}catch(N){N instanceof Q&&N.status===404&&v(`release ${u} not found.`),V(N,"releases:write","push a release"),v(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let E=async(N,W)=>{try{return await ae.readFile(et(f,N,W),"utf8")}catch{return null}},A=[];for(let[N,W]of Object.entries(x.context)){let me=await E("context",N);me!==null&&me!==W&&A.push(N)}A.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
3871
4170
|
`+A.map(N=>` context/${N}`).join(`
|
|
3872
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...
|
|
4171
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...x.context},O=0;for(let[N,W]of Object.entries(x.owned)){let me=await E("owned",N);C[N]=me??W,me!==null&&me!==W&&O++}O===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let G=h.target==="approved"?"approved":"auto";try{let N=await _.releasePush(u,{files:C,target:G,...h.approvedBy?{approvedBy:h.approvedBy}:{}});b(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
|
|
3873
4172
|
follow it with:
|
|
3874
|
-
turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Q&&N.status===403&&
|
|
3875
|
-
${
|
|
3876
|
-
`)),t&&void 0,e}function
|
|
3877
|
-
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return
|
|
3878
|
-
${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
|
|
4173
|
+
turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Q&&N.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof Q&&N.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),v(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Ar.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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T});if(h.follow){await $a(()=>_.releaseStatus(u),`release ${u}`,h.intervalMs);return}let f;try{f=await _.releaseStatus(u)}catch(x){V(x,"releases:write","release status"),x instanceof Q&&x.status===404&&v(`release ${u} not found.`),v(`release status failed: ${x instanceof Error?x.message:String(x)}`)}b(`release ${u}: status=${f.releaseStatus??"?"} stage=${f.stage} ${f.percent}%`+(f.runStatus?` (${f.runStatus})`:"")),f.outputTail&&b(f.outputTail.replace(/\n+$/,""))}),Ar.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(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.releaseRollback(u)}catch(x){V(x,"releases:write","release rollback"),x instanceof Q&&x.status===404&&v(`release ${u} not found.`),x instanceof Q&&x.status===409&&v(`release ${u} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}b(`release ${f.releaseId} rolled back \u2192 status=${f.release?.status??"rolled_back"}.`)}),Ar.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 u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.releaseList()}catch(f){V(f,"releases:write","release list"),v(`release list failed: ${f instanceof Error?f.message:String(f)}`)}if(_.length===0){b("no releases.");return}if(Ie())b(ft(_.map(f=>[f.id,Nr(f.status),f.target,f.backend,f.solutionTitles?.length?f.solutionTitles.map(x=>`"${x}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let f of _){let x=f.solutionTitles?.length?` "${f.solutionTitles.join('", "')}"`:"";b(` ${f.id} ${f.status.padEnd(11)} target=${f.target} backend=${f.backend}${x}`)}b(`
|
|
4174
|
+
${_.length} release(s).`)});let Eo=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");return Eo.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w});try{let _=await T.processes();u.json?b(JSON.stringify(_,null,2)):hp(_,b)}catch(_){v(`processes list failed: ${_ instanceof Error?_.message:String(_)}`)}}),Eo.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.processRuns(u);h.json?b(JSON.stringify(f,null,2)):mp(u,f,b)}catch(f){v(`processes runs failed: ${f instanceof Error?f.message:String(f)}`)}}),Eo.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.processRun(u);h.json?b(JSON.stringify(f,null,2)):ba(f,b)}catch(f){v(`processes run failed: ${f instanceof Error?f.message:String(f)}`)}}),Eo.command("cancel").description("Stop one run \u2014 a queued run never executes, a running one stops at its next step.").argument("<run-id>","The run to stop.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.cancelProcessRun(u);b(`cancelled ${f.runId??u} (${f.state??"cancelled"}).`),b("A run already going stops at its next step boundary; writes it has already made stay.")}catch(f){v(`processes cancel failed: ${f instanceof Error?f.message:String(f)}`)}}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),_=u.limit?Number(u.limit):void 0,f=u.intervalMs?Number(u.intervalMs):void 0;if(u.processRun){try{await fp(T,u.processRun,{...u.follow?{follow:!0}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(x){v(`logs --process-run failed: ${x instanceof Error?x.message:String(x)}`)}return}if(u.conduit){try{await lp(T,u.conduit,{...u.follow?{follow:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(x){v(`logs --conduit failed: ${x instanceof Error?x.message:String(x)}`)}return}if(u.extension){try{let x=await T.logs(u.extension,_);x.length===0&&b(`no logs for ${u.extension}.`);for(let E of x)b(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(x){v(`logs --extension failed: ${x instanceof Error?x.message:String(x)}`)}return}try{await dp(T,{...u.subsystem?{subsystem:u.subsystem}:{},...u.severity?{severity:u.severity}:{},...u.code?{code:u.code}:{},...u.since?{since:u.since}:{},...u.correlationId?{correlationId:u.correlationId}:{},...u.follow?{follow:!0}:{},...u.json?{json:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(x){v(`logs failed: ${x instanceof Error?x.message:String(x)}`)}}),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 u=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(Hb(),Fb));await h({baseUrl:u.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(`
|
|
4175
|
+
`)),t&&void 0,e}function BA(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function FA(t){let e=et(se(process.cwd(),t),"public","turbobase.json"),r=await ae.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){v(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&v(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function HA(){let t=se(process.cwd(),Qo,xn),e;try{e=await ae.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${ts}/, ${rs}/, ${Wt} or ${Jt}) and there is no ${Qo}/${xn}.
|
|
4176
|
+
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Np(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Hd(){let t=process.cwd();if(!await Up(t))return HA();let e;try{e=await Mp(t,{inline:ca})}catch(r){v(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)L(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&v(`${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 KA(t,e){b(`plan against ${e}:`);for(let r of t.add)b(` ${Vt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)b(` ${Vt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)b(` ${Vt.destroy(`${r.kind} ${r.id}`)}`);b(`
|
|
4177
|
+
${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 VA(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function To(t,e,r){return new Promise(n=>{let o=Wd(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function Kd(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await To("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await To("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function GA(t){let e=se(t,"src"),r={},n=async o=>{let s;try{s=await ae.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=et(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=ji(e,a).split(Gd).join("/");r[l]=await ae.readFile(a,"utf8")}}};return await n(e),r}function Vd(t){return new Promise(e=>{let r=Wd("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var WA=!1;WA&&Jd().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Jd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
3879
4178
|
`),process.exit(1)});
|