@turbobase/cli 1.4.2 → 1.5.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.
@@ -3289,7 +3289,7 @@ ${o.map(QE).join(`
3289
3289
  `))}async function sb(t,e,r=go){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await yo(e,r);if(!await aa(`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 ae("publishing",()=>o.skillsPublish(n))}catch(a){oe(a,"skills:publish","publish a skill"),x(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function ib(t,e,r=go){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await yo(e,r);if(!await aa(`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 ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){oe(a,"skills:publish","unpublish a skill"),x(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function ab(t,e,r=go){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await yo(e,r);if(await aa(`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 ae("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){oe(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function cb(t,e=go){let r=await yo(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){oe(o,"skills:publish","read the skills releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function lb(t,e,r=go){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&x("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await yo(e,r);if(!await aa(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3290
3290
  ${n.join(`
3291
3291
  `)}`,"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 l of n)try{i.push(await ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof pe&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),oe(u,"skills:publish","delete a skill"),x(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as ub}from"node:fs";import{join as SR,relative as TR,resolve as ER,sep as RR}from"node:path";var PR=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),AR=new Set([".mcp.json",".env"]);function IR(t){return AR.has(t)||t.startsWith(".env.")&&t!==".env.example"}function OR(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function CR(t){return t.includes(0)}async function db(t){let e=ER(t),r={},n=[],o=[],s=[];async function i(a){let c=await ub.readdir(a,{withFileTypes:!0});for(let l of c){let u=SR(a,l.name);if(l.isDirectory()){if(PR.has(l.name))continue;await i(u);continue}if(!l.isFile())continue;let p=TR(e,u).split(RR).join("/");if(IR(l.name)){o.push(p);continue}let w=await ub.readFile(u);if(!OR(w)){n.push(p);continue}CR(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as NR}from"node:crypto";var zR="/_tb/app-assets",jR=16,LR=/^[0-9a-f]{32}$/;function pb(){return NR(jR).toString("hex")}function DR(t){return LR.test(t)}function hb(t){if(!DR(t))throw new Error(`not a build id: ${t}`);return`${zR}/${t}/`}var fb=7;import ca from"node:fs/promises";import ms from"node:path";var pu={esbuild:"0.28.1","isolated-vm":"6.1.2"},hu="@turbobase/isolated-vm-prebuilds";function fu(t,e){return`${t}-${e}`}function mu(t=process.versions){return`abi${t.modules}`}var mb=["darwin-x64","win32-arm64"];async function gb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=fu(e,r),o=ms.join(t.home,"node_modules"),s=ms.join(o,...hu.split("/"),"prebuilds",n),i=ms.join(o,"isolated-vm","prebuilds",n),a;try{a=await ca.readdir(s)}catch{return[]}let c=[];await ca.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ms.join(i,l);try{await ca.copyFile(ms.join(s,l),u,ca.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as UR}from"node:os";import{join as yb}from"node:path";import{promises as gu}from"node:fs";function wb(){let t=process.env.TURBOBASE_HOME??yb(UR(),".turbobase");return{dir:t,file:yb(t,"sandboxes.json")}}var MR={s:1e3,m:6e4,h:36e5,d:864e5};function qR(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*MR[e[2]]}function ZR(t,e=Date.now()){return new Date(e+qR(t)).toISOString()}function BR(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function FR(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 HR(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 VR="[REDACTED]",gs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},yu=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 KR(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new yu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:VR:n[o]=s}return n}function GR(t,e,r){return e.map(n=>KR(t,n,r))}var bb=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),WR=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function JR(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 bu(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 WR)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=JR(t);if(!bb.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...bb].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function YR(t,e=QR){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function QR(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function XR(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function eP(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function wu(){let{file:t}=wb();try{let e=await gu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function vb(t){let{dir:e,file:r}=wb();await gu.mkdir(e,{recursive:!0}),await gu.writeFile(r,`${JSON.stringify(t,null,2)}
3292
- `,{mode:384})}async function tP(t){let e=await wu();e.push(t),await vb(e)}async function _b(t){let e=await wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await vb(e),n??null}async function la(){return wu()}function vu(t,e=Date.now()){let r=[],n=[];for(let o of t)BR(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function xb(t,e){bu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new gs(r);let n=FR(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>YR(l)))(e.fromTenant),i=XR(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=HR(l.rows,n),p=GR(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ZR(e.ttl,o),sampleFraction:n,url:eP(s,e.baseUrl)};return await tP(c),c}async function kb(t,e){bu(t.target());let n=(await la()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await _b(e),n):null}async function _u(t,e=Date.now()){bu(t.target());let r=await la(),{expired:n}=vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await _b(s.name),o.push(s)}return o}var ys={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},mZ=Object.keys(ys).filter(t=>ys[t].mintable);var bZ=ys.pat.prefix,rP=Object.entries(ys).map(([t,e])=>[e.prefix,t]),nP=/^[A-Za-z0-9_-]{20,}$/;function oP(t){if(typeof t!="string")return null;for(let[e,r]of rP)if(t.startsWith(e)&&nP.test(t.slice(e.length)))return r;return null}function $b(t){return oP(t)==="pat"}ss();var sP=8e3,iP={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 aP(t){return iP[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function cP(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(sP)})}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 Sb(t){return t.state==="accepted"?et()?g.green("accepted"):"accepted":t.state==="rejected"?et()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:et()?g.yellow("unreachable"):"unreachable"}async function Tb(t={},e=fetch){let r=await Sr(),{file:n}=qi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),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 cP(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(et())_(Xt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Sb(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Sb(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${aP(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function OD(t){let e=await Sr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ht()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ft(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function CD(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 ND(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function zD(t,e,r){let n=await Ug({baseUrl:t,token:e}),o=(await Sr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),ND(n.baseUrl),!r)return;let s=await CD(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function jD(t){let e=await ls(t),r=su(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);x(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Go(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Ko(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function TS(t,e){if(ES(t)!==".gitignore")return Go(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Go(t,e.content,e.executable,e.mode);let n=vy(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function Lm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function rl(t){process.exit(t)}function LD(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 DD(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 UD(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 Bm({includeInternal:t=!0}={}){let e=new cg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.4.2").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Xl()}
3292
+ `,{mode:384})}async function tP(t){let e=await wu();e.push(t),await vb(e)}async function _b(t){let e=await wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await vb(e),n??null}async function la(){return wu()}function vu(t,e=Date.now()){let r=[],n=[];for(let o of t)BR(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function xb(t,e){bu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new gs(r);let n=FR(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>YR(l)))(e.fromTenant),i=XR(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=HR(l.rows,n),p=GR(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ZR(e.ttl,o),sampleFraction:n,url:eP(s,e.baseUrl)};return await tP(c),c}async function kb(t,e){bu(t.target());let n=(await la()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await _b(e),n):null}async function _u(t,e=Date.now()){bu(t.target());let r=await la(),{expired:n}=vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await _b(s.name),o.push(s)}return o}var ys={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},mZ=Object.keys(ys).filter(t=>ys[t].mintable);var bZ=ys.pat.prefix,rP=Object.entries(ys).map(([t,e])=>[e.prefix,t]),nP=/^[A-Za-z0-9_-]{20,}$/;function oP(t){if(typeof t!="string")return null;for(let[e,r]of rP)if(t.startsWith(e)&&nP.test(t.slice(e.length)))return r;return null}function $b(t){return oP(t)==="pat"}ss();var sP=8e3,iP={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 aP(t){return iP[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function cP(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(sP)})}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 Sb(t){return t.state==="accepted"?et()?g.green("accepted"):"accepted":t.state==="rejected"?et()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:et()?g.yellow("unreachable"):"unreachable"}async function Tb(t={},e=fetch){let r=await Sr(),{file:n}=qi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),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 cP(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(et())_(Xt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Sb(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Sb(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${aP(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function OD(t){let e=await Sr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ht()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ft(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function CD(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 ND(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function zD(t,e,r){let n=await Ug({baseUrl:t,token:e}),o=(await Sr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),ND(n.baseUrl),!r)return;let s=await CD(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function jD(t){let e=await ls(t),r=su(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);x(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Go(t,e,r,n){try{return await ye.access(t),"skipped"}catch{}return await ye.mkdir(Ko(t),{recursive:!0}),await ye.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ye.chmod(t,n),"wrote"}async function TS(t,e){if(ES(t)!==".gitignore")return Go(t,e.content,e.executable,e.mode);let r=await ye.readFile(t,"utf8").catch(()=>null);if(r===null)return Go(t,e.content,e.executable,e.mode);let n=vy(r);return n===null?"skipped":(await ye.writeFile(t,n,"utf8"),"merged")}function Lm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function rl(t){process.exit(t)}function LD(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 DD(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 UD(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 Bm({includeInternal:t=!0}={}){let e=new cg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.5.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Xl()}
3293
3293
  `),e.hook("preAction",(d,f)=>{Oy(e.opts(),f.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 d=>{let f=jt(d.baseUrl);d.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3294
3294
  ${ps} auth login --base-url ${f} --token tb_pat_\u2026`),$b(d.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await zD(f,d.token,d.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 d=>Tb({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let f=d??await OD("Pick the active instance:"),v=await Zi(f);if(!v){let T=await Sr();x(`no stored sign-in for ${jt(f)}.`+(T.length?` Stored: ${T.map($=>$.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${jt(f)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${v.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 d=>{if(d.all){let T=await Sr();for(let $ of T)await Zl($.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let f=await Zl(d.baseUrl);f||x(d.baseUrl?`no stored sign-in for ${jt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Qt();_(`signed out of ${f}.`+(v?` Active instance \u2192 ${v.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 d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T;try{T=await Rn({baseUrl:f,token:v,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("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 Rn({baseUrl:f,token:v,recordsOnly:!0})}catch(R){x(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else x(`types generation failed: ${S}`)}let $=xe(process.cwd(),d.out);await ye.writeFile($,T,"utf8"),_(`wrote ${$} (${T.split(`
3295
3295
  `).length} lines).`)}),zy(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 d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let $=T.toString(),y=await fetch(`${f}/v1/catalog/grounding${$?`?${$}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||x(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),O=xe(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",U=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${C} \u2014 do not edit; re-run to refresh. -->
@@ -3319,7 +3319,7 @@ samples init: ${R} written, ${O} skipped.`)});let Wt=e.command("guardrails").des
3319
3319
  `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Xt($.map(un),{head:Wo})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),Wt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){oe(S,"extensions:deploy","create a guardrail"),x(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),Wt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch(S){oe(S,"extensions:deploy","edit a guardrail"),x(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,f,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Wt.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,$)=>{let{baseUrl:y,token:S}=await te($.baseUrl),R=new Y({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:f})}catch(O){oe(O,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),f==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});Wt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T});try{await $.guardrailDelete(d)}catch(y){oe(y,"extensions:deploy","delete a guardrail"),x(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),Wt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y=O=>O==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let O;try{O=await $.guardrailPostureGet()}catch(C){oe(C,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}_(`guardrail posture: ${g.bold(y(O.mode))}`),_(g.dim(O.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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&x("posture must be 'allow' or 'deny'.");let R;try{R=await $.guardrailPostureSet(S)}catch(O){oe(O,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Wt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(R){x(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:v,token:T}=await te(d.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){oe(R,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return _(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let zr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),dn=(d,f={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let $=[T.required?"required":null].filter(Boolean).join(", "),y=f.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${$?` (${$})`:""}${y}`)}f.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Wn(d){if(d instanceof pe&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(q(f.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let Fm=async d=>{let f=At(xe(process.cwd(),d),"public","turbobase.json"),v=await ye.readFile(f,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){x(`${f} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let $=T.tables;return $===void 0?{tables:[],manifestPath:f}:(Array.isArray($)||x(`${f}: "tables" must be an array.`),{tables:$,manifestPath:f})};zr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new Y({baseUrl:f,token:v}),$;try{$=await T.tablesList()}catch(y){oe(y,"extensions:deploy","list tables"),x(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify($,null,2));if($.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(Xt($.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),zr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,f)=>{let v=await Fm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:f.as,tables:v.tables}))}catch(R){oe(R,"extensions:deploy","plan tables"),Wn(R)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)dn(R,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),zr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,f)=>{let v=await Fm(d??".");if(v||x(`no public/turbobase.json under ${xe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:f.as,tables:v.tables}))}catch(R){oe(R,"extensions:deploy","apply tables"),Wn(R)}for(let R of S.tables)dn(R,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),zr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,f)=>[...f??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let v=f.field.map(R=>{let[O,C,U]=R.split(":");return(!O||!C)&&x(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),U!==void 0&&U!=="required"&&x(`--field "${R}": the third part may only be "required".`),{name:O,type:C,...U==="required"?{required:!0}:{}}}),{baseUrl:T,token:$}=await te(f.baseUrl),y=new Y({baseUrl:T,token:$}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:v,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){oe(R,"extensions:deploy","create a table"),Wn(R)}for(let R of S.tables)dn(R);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),zr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.confirm!==d&&x(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>$.tablesDrop(d,f.confirm))}catch(S){oe(S,"extensions:deploy","drop a table"),x(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let ol=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ol.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let f=Um(),v;try{v=await xb(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof gs&&x(T.message),x(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),ol.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=Um();await _u(f).catch(()=>[]);let v;try{v=await kb(f,d)}catch(T){x(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||x(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ol.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Um(),f=await _u(d).catch(()=>[]),v=await la(),{active:T}=vu(v);if(T.length===0)_("no active sandboxes.");else{for(let $ of T)_(` ${$.name} from=${$.fromTenant} expires=${$.expiresAt} ${$.url}`);_(`
3320
3320
  ${T.length} active sandbox(es).`)}f.length>0&&_(`(reaped ${f.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.",Qi).action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new Y({baseUrl:f,token:v}),$;try{$=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof pe&&(R.status===401||R.status===403)&&x("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),x(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof $.serialized=="string"?$.serialized:`${JSON.stringify($.manifest??$,null,2)}
3321
3321
  `,S=xe(process.cwd(),d.out,ds);await ye.mkdir(Ko(S),{recursive:!0}),await ye.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${ds} (${y.split(`
3322
- `).length} lines).`)});let Hm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),RS=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Vm=()=>process.env.TURBOBASE_HOME?.trim()||At(ID(),".turbobase"),PS=()=>"1.4.2",ki=async()=>Promise.all(RS.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Hm.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ki();for(let f of d)_(`${f.present?He.success("installed"):He.warn("missing")} ${g.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&_(`
3322
+ `).length} lines).`)});let Hm=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),RS=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Vm=()=>process.env.TURBOBASE_HOME?.trim()||At(ID(),".turbobase"),PS=()=>"1.5.0",ki=async()=>Promise.all(RS.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Hm.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ki();for(let f of d)_(`${f.present?He.success("installed"):He.warn("missing")} ${g.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&_(`
3323
3323
  run \`${ps} ext extras install\` to fetch them into ${Vm()}.`)}),Hm.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ki();if(d.every(O=>O.present)){_(He.success("extras already installed \u2014 nothing to do."));return}let f=Vm();await ye.mkdir(f,{recursive:!0});let v=d.filter(O=>!O.present).map(O=>O.name),T=fu(process.platform,process.arch),$=async(O,C)=>{let{code:U,stderr:ie}=await xi("npm",["install","--prefix",f,"--no-audit","--no-fund",...O]);U!==0&&x(`extras install failed while installing ${C} (npm exited ${U}).
3324
3324
  ${ie.trim()}
3325
3325
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(O=>O!=="isolated-vm");if(y.length>0){let O=y.map(C=>`${C}@${pu[C]??"latest"}`);_(`installing ${O.join(", ")} \u2192 ${f}/node_modules \u2026`),await $(O,y.join(", "))}if(v.includes("isolated-vm")){let O=`isolated-vm@${pu["isolated-vm"]}`;if(_(`installing ${O} \u2192 ${f}/node_modules \u2026`),await $(["--ignore-scripts",O],"isolated-vm"),mb.includes(T)){let U=`${hu}@${PS()}`;_(`fetching ${U} (no upstream binary for ${T}) \u2026`);let{code:ie}=await xi("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",U]);ie!==0&&_(He.warn(`could not fetch ${U} \u2014 falling back to a source build.`))}let C=await gb({home:f});C.length>0&&_(` ${He.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await ki(),R=S.filter(O=>!O.present).map(O=>O.name);if(R.includes("isolated-vm")){_(He.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${mu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:O}=await xi("npm",["rebuild","--prefix",f,"isolated-vm"]);O===0&&(S=await ki(),R=S.filter(C=>!C.present).map(C=>C.name))}R.length>0&&x(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${mu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(He.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Jn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Jn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||x(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await HD(xe(process.cwd(),d.project??".")),T=Object.keys(v).length;!d.solution&&T===0&&x("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await Mm(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Mm(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await Mm(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,O=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:U}=await te(d.baseUrl),ie=new Y({baseUrl:C,token:U}),M;try{M=await ie.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:O})}catch(ne){oe(ne,"releases:write","release deploy"),ne instanceof pe&&ne.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${M.releaseId} enqueued \u2192 taskId=${M.taskId} (target=${f}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await au(()=>ie.releaseStatus(M.releaseId),`release ${M.releaseId}`,d.intervalMs)}),Jn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),$=new Y({baseUrl:v,token:T}),y;try{y=await $.releaseFiles(d)}catch(O){O instanceof pe&&O.status===404&&x(`release ${d} not found.`),O instanceof pe&&O.status===409&&x(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),oe(O,"releases:write","pull a release"),x(`release pull failed: ${O instanceof Error?O.message:String(O)}`)}let S=xe(process.cwd(),f.dir),R=0;for(let[O,C]of[["owned",y.owned],["context",y.context]])for(let[U,ie]of Object.entries(C)){let M=At(S,O,U);await ye.mkdir(Ko(M),{recursive:!0}),await ye.writeFile(M,ie,"utf8"),R++}await ye.writeFile(At(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
package/dist/turbobase.js CHANGED
@@ -3242,7 +3242,7 @@ ${s.map(Iw).join(`
3242
3242
  `))}async function lp(t,e,n=jn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Un(e,n);if(!await Ks(`Publish ${r.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>s.skillsPublish(r))}catch(a){V(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(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 cp(t,e,n=jn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Un(e,n);if(!await Ks(`Move ${r.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.skillsUnpublish(r))}catch(a){V(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(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 dp(t,e,n=jn){let r=Number(t);(!Number.isInteger(r)||r<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await Un(e,n);if(await Ks(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>s.skillsRollback(r));y(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function up(t,e=jn){let n=await Un(t,e),r;try{r=await J("reading the releases",()=>n.skillsReleases())}catch(s){V(s,"skills:publish","read the skills releases"),w(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){L("no releases yet.");return}for(let s of r.items){let o=s.is_current?m.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${m.dim(s.published_at)}${s.published_by?m.dim(` by ${s.published_by}`):""}${m.dim(i)}`)}}async function pp(t,e,n=jn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await Un(e,n);if(!await Ks(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
3243
3243
  ${r.join(`
3244
3244
  `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let u of r)try{i.push(await J(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof X&&p.status===404){a.push(u);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),w(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.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 hp}from"node:fs";import{join as sv,relative as ov,resolve as iv,sep as av}from"node:path";var lv=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),cv=new Set([".mcp.json",".env"]);function dv(t){return cv.has(t)||t.startsWith(".env.")&&t!==".env.example"}function uv(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function pv(t){return t.includes(0)}async function fp(t){let e=iv(t),n={},r=[],s=[],o=[];async function i(a){let l=await hp.readdir(a,{withFileTypes:!0});for(let u of l){let p=sv(a,u.name);if(u.isDirectory()){if(lv.has(u.name))continue;await i(p);continue}if(!u.isFile())continue;let f=ov(e,p).split(av).join("/");if(dv(u.name)){s.push(f);continue}let _=await hp.readFile(p);if(!uv(_)){r.push(f);continue}pv(_)&&o.push(f),n[f]=_.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as hv}from"node:crypto";var fv="/_tb/app-assets",mv=16,gv=/^[0-9a-f]{32}$/;function mp(){return hv(mv).toString("hex")}function bv(t){return gv.test(t)}function gp(t){if(!bv(t))throw new Error(`not a build id: ${t}`);return`${fv}/${t}/`}var bp=7;import Vs from"node:fs/promises";import $r from"node:path";var la={esbuild:"0.28.1","isolated-vm":"6.1.2"},ca="@turbobase/isolated-vm-prebuilds";function da(t,e){return`${t}-${e}`}function ua(t=process.versions){return`abi${t.modules}`}var yp=["darwin-x64","win32-arm64"];async function wp(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=da(e,n),s=$r.join(t.home,"node_modules"),o=$r.join(s,...ca.split("/"),"prebuilds",r),i=$r.join(s,"isolated-vm","prebuilds",r),a;try{a=await Vs.readdir(o)}catch{return[]}let l=[];await Vs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=$r.join(i,u);try{await Vs.copyFile($r.join(o,u),p,Vs.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as yv}from"node:os";import{join as vp}from"node:path";import{promises as pa}from"node:fs";function Sp(){let t=process.env.TURBOBASE_HOME??vp(yv(),".turbobase");return{dir:t,file:vp(t,"sandboxes.json")}}var wv={s:1e3,m:6e4,h:36e5,d:864e5};function vv(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*wv[e[2]]}function kv(t,e=Date.now()){return new Date(e+vv(t)).toISOString()}function Sv(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function _v(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function $v(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var xv="[REDACTED]",xr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ha=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=n}};function Tv(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new ha(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:xv:r[s]=o}return r}function Rv(t,e,n){return e.map(r=>Tv(t,r,n))}var kp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Ev=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Pv(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function 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 r of Ev)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=Pv(t);if(!kp.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...kp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Av(t,e=Iv){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Iv(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Cv(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Ov(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function ma(){let{file:t}=Sp();try{let e=await pa.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function _p(t){let{dir:e,file:n}=Sp();await pa.mkdir(e,{recursive:!0}),await pa.writeFile(n,`${JSON.stringify(t,null,2)}
3245
- `,{mode:384})}async function Nv(t){let e=await ma();e.push(t),await _p(e)}async function $p(t){let e=await ma(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await _p(e),r??null}async function Gs(){return ma()}function ga(t,e=Date.now()){let n=[],r=[];for(let s of t)Sv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function xp(t,e){fa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new xr(n);let r=_v(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Av(u)))(e.fromTenant),i=Cv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=$v(u.rows,r),f=Rv(u.table,p,u.classification);f.length>0&&await t.copyRows(i,u.table,f)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:kv(e.ttl,s),sampleFraction:r,url:Ov(o,e.baseUrl)};return await Nv(l),l}async function Tp(t,e){fa(t.target());let r=(await Gs()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await $p(e),r):null}async function ba(t,e=Date.now()){fa(t.target());let n=await Gs(),{expired:r}=ga(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await $p(o.name),s.push(o)}return s}var Tr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},XA=Object.keys(Tr).filter(t=>Tr[t].mintable);var nI=Tr.pat.prefix,Lv=Object.entries(Tr).map(([t,e])=>[e.prefix,t]),jv=/^[A-Za-z0-9_-]{20,}$/;function Uv(t){if(typeof t!="string")return null;for(let[e,n]of Lv)if(t.startsWith(e)&&jv.test(t.slice(e.length)))return n;return null}function Rp(t){return Uv(t)==="pat"}fr();var Dv=8e3,qv={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 zv(t){return qv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Mv(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Dv)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function Ep(t){return t.state==="accepted"?Ee()?m.green("accepted"):"accepted":t.state==="rejected"?Ee()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?m.yellow("unreachable"):"unreachable"}async function Pp(t={},e=fetch){let n=await Rt(),{file:r}=xs();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Mv(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())y(pt(o.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Ep(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Ep(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${zv(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}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function o0(t){let e=await Rt();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),De()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await qe(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{w("cancelled.")}}async function i0(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function a0(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 l0(t,e,n){let r=await Bd({baseUrl:t,token:e}),s=(await Rt()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),a0(r.baseUrl),!n)return;let o=await i0(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function c0(t){let e=await yr(t),n=ta(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);w(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function dr(t,e,n,r){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(cr(t),{recursive:!0}),await se.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await se.chmod(t,r),"wrote"}async function Ib(t,e){if(Cb(t)!==".gitignore")return dr(t,e.content,e.executable,e.mode);let n=await se.readFile(t,"utf8").catch(()=>null);if(n===null)return dr(t,e.content,e.executable,e.mode);let r=_u(n);return r===null?"skipped":(await se.writeFile(t,r,"utf8"),"merged")}function fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function yi(t){process.exit(t)}function d0(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function u0(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function p0(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function vd({includeInternal:t=!0}={}){let e=new s0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.4.2").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Ji()}
3245
+ `,{mode:384})}async function Nv(t){let e=await ma();e.push(t),await _p(e)}async function $p(t){let e=await ma(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await _p(e),r??null}async function Gs(){return ma()}function ga(t,e=Date.now()){let n=[],r=[];for(let s of t)Sv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function xp(t,e){fa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new xr(n);let r=_v(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Av(u)))(e.fromTenant),i=Cv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=$v(u.rows,r),f=Rv(u.table,p,u.classification);f.length>0&&await t.copyRows(i,u.table,f)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:kv(e.ttl,s),sampleFraction:r,url:Ov(o,e.baseUrl)};return await Nv(l),l}async function Tp(t,e){fa(t.target());let r=(await Gs()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await $p(e),r):null}async function ba(t,e=Date.now()){fa(t.target());let n=await Gs(),{expired:r}=ga(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await $p(o.name),s.push(o)}return s}var Tr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},XA=Object.keys(Tr).filter(t=>Tr[t].mintable);var nI=Tr.pat.prefix,Lv=Object.entries(Tr).map(([t,e])=>[e.prefix,t]),jv=/^[A-Za-z0-9_-]{20,}$/;function Uv(t){if(typeof t!="string")return null;for(let[e,n]of Lv)if(t.startsWith(e)&&jv.test(t.slice(e.length)))return n;return null}function Rp(t){return Uv(t)==="pat"}fr();var Dv=8e3,qv={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 zv(t){return qv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Mv(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Dv)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function Ep(t){return t.state==="accepted"?Ee()?m.green("accepted"):"accepted":t.state==="rejected"?Ee()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?m.yellow("unreachable"):"unreachable"}async function Pp(t={},e=fetch){let n=await Rt(),{file:r}=xs();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Mv(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())y(pt(o.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Ep(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Ep(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${zv(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}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function o0(t){let e=await Rt();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),De()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await qe(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{w("cancelled.")}}async function i0(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function a0(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 l0(t,e,n){let r=await Bd({baseUrl:t,token:e}),s=(await Rt()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),a0(r.baseUrl),!n)return;let o=await i0(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function c0(t){let e=await yr(t),n=ta(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);w(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function dr(t,e,n,r){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(cr(t),{recursive:!0}),await se.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await se.chmod(t,r),"wrote"}async function Ib(t,e){if(Cb(t)!==".gitignore")return dr(t,e.content,e.executable,e.mode);let n=await se.readFile(t,"utf8").catch(()=>null);if(n===null)return dr(t,e.content,e.executable,e.mode);let r=_u(n);return r===null?"skipped":(await se.writeFile(t,r,"utf8"),"merged")}function fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function yi(t){process.exit(t)}function d0(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function u0(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function p0(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function vd({includeInternal:t=!0}={}){let e=new s0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.5.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Ji()}
3246
3246
  `),e.hook("preAction",(d,h)=>{Lu(e.opts(),h.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=e.command("project").description("Set up the local project and the files an agent session reads."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");n.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=Qe(d.baseUrl);d.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3247
3247
  ${kr} auth login --base-url ${h} --token tb_pat_\u2026`),Rp(d.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await l0(h,d.token,d.verify)}),n.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>Pp({probe:d.probe})),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await o0("Pick the active instance:"),b=await Ts(h);if(!b){let x=await Rt();w(`no stored sign-in for ${Qe(h)}.`+(x.length?` Stored: ${x.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Qe(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${b.baseUrl}.`)}),n.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let x=await Rt();for(let S of x)await Di(S.baseUrl);y(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await Di(d.baseUrl);h||w(d.baseUrl?`no stored sign-in for ${Qe(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let b=await ut();y(`signed out of ${h}.`+(b?` Active instance \u2192 ${b.baseUrl}.`:""))}),r.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),x;try{x=await cn({baseUrl:h,token:b,recordsOnly:d.recordsOnly})}catch(g){let $=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{x=await cn({baseUrl:h,token:b,recordsOnly:!0})}catch(R){w(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else w(`types generation failed: ${$}`)}let S=le(process.cwd(),d.out);await se.writeFile(S,x,"utf8"),y(`wrote ${S} (${x.split(`
3248
3248
  `).length} lines).`)}),Du(r),r.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let S=x.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let R=((await g.json()).markdown??"").trim(),A=le(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
@@ -3272,7 +3272,7 @@ samples init: ${R} written, ${A} skipped.`)});let dt=e.command("guardrails").des
3272
3272
  `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(pt(S.map(on),{head:ur})),y(m.dim(" first match wins; lower PRIO is evaluated first."))}),dt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){V($,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),y(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),dt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch($){V($,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,h,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])dt.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,S)=>{let{baseUrl:g,token:$}=await H(S.baseUrl),R=new B({baseUrl:g,token:$});try{await R.guardrailUpdate(x,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),w(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(x)} ${b}`),h==="inactive"&&y(m.dim(" writes it was gating now fall through to the other rules."))});dt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x});try{await S.guardrailDelete(d)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),dt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await S.guardrailPostureGet()}catch(I){V(I,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}y(`guardrail posture: ${m.bold(g(A.mode))}`),y(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 $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&w("posture must be 'allow' or 'deny'.");let R;try{R=await S.guardrailPostureSet($)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail posture set to ${m.bold(g(R.mode))}`),R.mode==="deny"&&y(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),dt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(R){w(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:b,token:x}=await H(d.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){V(R,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return y(JSON.stringify(g,null,2));let $=`${d.source}/${g.op??d.record}`;g.degraded?(y(`${m.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(m.dim(` ${g.reason}`))):g.allowed?y(`${m.green("\u2713")} ${$} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(y(`${m.red("\u2717")} ${$} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&y(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&y(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let Ut=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),an=(d,h={})=>{let b=`${m.bold(d.table)} ${m.dim(d.displayName)}`;y(d.exists===!1?`${b} ${m.dim("(new)")}`:b);for(let x of d.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&x.claimedBy?.length?` ${m.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";y(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&d.claimants.length>1&&y(m.dim(` claimed by ${d.claimants.join(", ")}`))};function xn(d){if(d instanceof X&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}w(`tables: ${d instanceof Error?d.message:String(d)}`)}let kd=async d=>{let h=Ye(le(process.cwd(),d),"public","turbobase.json"),b=await se.readFile(h,"utf8").catch(()=>null);if(b===null)return null;let x;try{x=JSON.parse(b)}catch(g){w(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||w(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};Ut.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),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(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(pt(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Ut.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let b=await kd(d??".");if(b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","plan tables"),xn(R)}y(`claiming as ${m.bold($.claimedBy)}`);for(let R of $.tables)an(R,{showClaimants:!0});y(""),y(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Ut.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let b=await kd(d??".");if(b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","apply tables"),xn(R)}for(let R of $.tables)an(R,{showClaimants:!0});y(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),Ut.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let b=h.field.map(R=>{let[A,I,O]=R.split(":");return(!A||!I)&&w(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${R}": the third part may only be "required".`),{name:A,type:I,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:b,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){V(R,"extensions:deploy","create a table"),xn(R)}for(let R of $.tables)an(R);y(""),y(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Ut.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&w(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await J(`dropping cr_${d}`,()=>S.tablesDrop(d,h.confirm))}catch($){V($,"extensions:deploy","drop a table"),w(`drop failed: ${$ instanceof Error?$.message:String($)}`)}if(!g.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${g.table} and every row in it.`)});let vi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");vi.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=gd(),b;try{b=await xp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof xr&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}y(`sandbox ${b.name} ready.`),y(` source: ${b.fromTenant} (sampled ${Math.round(b.sampleFraction*100)}%, redacted)`),y(` url: ${b.url}`),y(` expires: ${b.expiresAt}`)}),vi.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=gd();await ba(h).catch(()=>[]);let b;try{b=await Tp(h,d)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}b||w(`no sandbox named '${d}'.`),y(`destroyed sandbox ${b.name} (dropped ${b.database}).`)}),vi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=gd(),h=await ba(d).catch(()=>[]),b=await Gs(),{active:x}=ga(b);if(x.length===0)y("no active sandboxes.");else{for(let S of x)y(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);y(`
3273
3273
  ${x.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),s.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",js).action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await J("exporting instance config",()=>x.configExport())}catch(R){R instanceof X&&(R.status===401||R.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3274
3274
  `,$=le(process.cwd(),d.out,vr);await se.mkdir(cr($),{recursive:!0}),await se.writeFile($,g,"utf8"),y(`wrote ${d.out}/${vr} (${g.split(`
3275
- `).length} lines).`)});let Sd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Ob=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_d=()=>process.env.TURBOBASE_HOME?.trim()||Ye(r0(),".turbobase"),Nb=()=>"1.4.2",ys=async()=>Promise.all(Ob.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Sd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ys();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3275
+ `).length} lines).`)});let Sd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Ob=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_d=()=>process.env.TURBOBASE_HOME?.trim()||Ye(r0(),".turbobase"),Nb=()=>"1.5.0",ys=async()=>Promise.all(Ob.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Sd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ys();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3276
3276
  run \`${kr} ext extras install\` to fetch them into ${_d()}.`)}),Sd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ys();if(d.every(A=>A.present)){y(ve.success("extras already installed \u2014 nothing to do."));return}let h=_d();await se.mkdir(h,{recursive:!0});let b=d.filter(A=>!A.present).map(A=>A.name),x=da(process.platform,process.arch),S=async(A,I)=>{let{code:O,stderr:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${I} (npm exited ${O}).
3277
3277
  ${W.trim()}
3278
3278
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=b.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(I=>`${I}@${la[I]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(b.includes("isolated-vm")){let A=`isolated-vm@${la["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),yp.includes(x)){let O=`${ca}@${Nb()}`;y(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&y(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let I=await wp({home:h});I.length>0&&y(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let $=await ys(),R=$.filter(A=>!A.present).map(A=>A.name);if(R.includes("isolated-vm")){y(ve.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${ua()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await bs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&($=await ys(),R=$.filter(I=>!I.present).map(I=>I.name))}R.length>0&&w(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${ua()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Tn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Tn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||w(`--target must be 'auto' or 'approved' (got '${d.target}').`);let b=await y0(le(process.cwd(),d.project??".")),x=Object.keys(b).length;!d.solution&&x===0&&w("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(d.ref?await bd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await bd(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await bd(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:O}=await H(d.baseUrl),W=new B({baseUrl:I,token:O}),N;try{N=await W.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:x>0?b:null,gitRepo:$,gitRef:R,gitSha:g,prUrl:A})}catch(K){V(K,"releases:write","release deploy"),K instanceof X&&K.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${K instanceof Error?K.message:String(K)}`)}y(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),d.follow&&await ra(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),Tn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.releaseFiles(d)}catch(A){A instanceof X&&A.status===404&&w(`release ${d} not found.`),A instanceof X&&A.status===409&&w(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let $=le(process.cwd(),h.dir),R=0;for(let[A,I]of[["owned",g.owned],["context",g.context]])for(let[O,W]of Object.entries(I)){let N=Ye($,A,O);await se.mkdir(cr(N),{recursive:!0}),await se.writeFile(N,W,"utf8"),R++}await se.writeFile(Ye($,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),y(`pulled release ${g.releaseId} (${g.status}) \u2192 ${$}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turbobase/cli",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "Author, test, and deploy Turbobase extensions (hooks + conduits) against a tenant over HTTP + a personal access token.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",