@turbobase/cli 1.39.0 → 1.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4174,7 +4174,7 @@ ${o.map(cA).join(`
4174
4174
  `))}async function _w(t,e,r=vo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await ko(e,r);if(!await ka(`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 se("publishing",()=>o.skillsPublish(n))}catch(a){te(a,"skills:publish","publish a skill"),k(`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 vw(t,e,r=vo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await ko(e,r);if(!await ka(`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 se("unpublishing",()=>o.skillsUnpublish(n))}catch(a){te(a,"skills:publish","unpublish a skill"),k(`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 kw(t,e,r=vo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await ko(e,r);if(await ka(`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 se("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){te(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function xw(t,e=vo){let r=await ko(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){te(o,"skills:publish","read the skills releases"),k(`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 Sw(t,e,r=vo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await ko(e,r);if(!await ka(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4175
4175
  ${n.join(`
4176
4176
  `)}`,"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 se(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),te(u,"skills:publish","delete a skill"),k(`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 $w}from"node:fs";import{join as GA,relative as JA,resolve as YA,sep as XA}from"node:path";var QA=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),eC=new Set([".mcp.json",".env"]);function tC(t){return eC.has(t)||t.startsWith(".env.")&&t!==".env.example"}function rC(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function nC(t){return t.includes(0)}async function Tw(t){let e=YA(t),r={},n=[],o=[],s=[];async function i(a){let c=await $w.readdir(a,{withFileTypes:!0});for(let l of c){let u=GA(a,l.name);if(QA.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=JA(e,u).split(XA).join("/");if(tC(l.name)){o.push(p);continue}let b=await $w.readFile(u);if(!rC(b)){n.push(p);continue}nC(b)&&s.push(p),r[p]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as oC}from"node:crypto";var sC="/_tb/app-assets",iC=16,aC=/^[0-9a-f]{32}$/;function Rw(){return oC(iC).toString("hex")}function cC(t){return aC.test(t)}function Ew(t){if(!cC(t))throw new Error(`not a build id: ${t}`);return`${sC}/${t}/`}var Pw=7;Du();var Mu=50*1024*1024;import xa from"node:fs/promises";import _s from"node:path";var Uu={esbuild:"0.28.1","isolated-vm":"6.1.2"},qu="@turbobase/isolated-vm-prebuilds";function Fu(t,e){return`${t}-${e}`}function Bu(t=process.versions){return`abi${t.modules}`}var Aw=["darwin-x64","win32-arm64"];async function Cw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Fu(e,r),o=_s.join(t.home,"node_modules"),s=_s.join(o,...qu.split("/"),"prebuilds",n),i=_s.join(o,"isolated-vm","prebuilds",n),a;try{a=await xa.readdir(s)}catch{return[]}let c=[];await xa.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=_s.join(i,l);try{await xa.copyFile(_s.join(s,l),u,xa.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as lC}from"node:os";import{join as Iw}from"node:path";import{promises as Zu}from"node:fs";function Nw(){let t=process.env.TURBOBASE_HOME??Iw(lC(),".turbobase");return{dir:t,file:Iw(t,"sandboxes.json")}}var uC={s:1e3,m:6e4,h:36e5,d:864e5};function dC(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*uC[e[2]]}function pC(t,e=Date.now()){return new Date(e+dC(t)).toISOString()}function hC(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function mC(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 fC(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 gC="[REDACTED]",vs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Vu=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 yC(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Vu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:gC:n[o]=s}return n}function bC(t,e,r){return e.map(n=>yC(t,n,r))}var Ow=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),wC=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function _C(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 Hu(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 wC)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=_C(t);if(!Ow.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Ow].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function vC(t,e=kC){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function kC(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function xC(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function SC(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ku(){let{file:t}=Nw();try{let e=await Zu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Lw(t){let{dir:e,file:r}=Nw();await Zu.mkdir(e,{recursive:!0}),await Zu.writeFile(r,`${JSON.stringify(t,null,2)}
4177
- `,{mode:384})}async function $C(t){let e=await Ku();e.push(t),await Lw(e)}async function zw(t){let e=await Ku(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Lw(e),n??null}async function Sa(){return Ku()}function Wu(t,e=Date.now()){let r=[],n=[];for(let o of t)hC(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function jw(t,e){Hu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=mC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>vC(l)))(e.fromTenant),i=xC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=fC(l.rows,n),p=bC(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:pC(e.ttl,o),sampleFraction:n,url:SC(s,e.baseUrl)};return await $C(c),c}async function Dw(t,e){Hu(t.target());let n=(await Sa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await zw(e),n):null}async function Gu(t,e=Date.now()){Hu(t.target());let r=await Sa(),{expired:n}=Wu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await zw(s.name),o.push(s)}return o}var ks={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},F2=Object.keys(ks).filter(t=>ks[t].mintable);var V2=ks.pat.prefix,TC=Object.entries(ks).map(([t,e])=>[e.prefix,t]),RC=/^[A-Za-z0-9_-]{20,}$/;function EC(t){if(typeof t!="string")return null;for(let[e,r]of TC)if(t.startsWith(e)&&RC.test(t.slice(e.length)))return r;return null}function Mw(t){return EC(t)==="pat"}cs();var PC=8e3,AC={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 CC(t){return AC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function IC(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(PC)})}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 Uw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function qw(t={},e=fetch){let r=await Cr(),{file:n}=Ji();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 IC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Uw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Uw(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}: ${CC(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 aq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function cq(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 lq(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 uq(t,e,r){let n=await vy({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),lq(n.baseUrl),!r)return;let s=await cq(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 dq(t){let e=await pu(await ps(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Eu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Ur(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function MT(t,e){if(qT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Tb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function dg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function bl(t){process.exit(t)}function pq(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 hq(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 mq(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 UT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function yg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.39.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${wu()}
4177
+ `,{mode:384})}async function $C(t){let e=await Ku();e.push(t),await Lw(e)}async function zw(t){let e=await Ku(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Lw(e),n??null}async function Sa(){return Ku()}function Wu(t,e=Date.now()){let r=[],n=[];for(let o of t)hC(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function jw(t,e){Hu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=mC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>vC(l)))(e.fromTenant),i=xC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=fC(l.rows,n),p=bC(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:pC(e.ttl,o),sampleFraction:n,url:SC(s,e.baseUrl)};return await $C(c),c}async function Dw(t,e){Hu(t.target());let n=(await Sa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await zw(e),n):null}async function Gu(t,e=Date.now()){Hu(t.target());let r=await Sa(),{expired:n}=Wu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await zw(s.name),o.push(s)}return o}var ks={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},F2=Object.keys(ks).filter(t=>ks[t].mintable);var V2=ks.pat.prefix,TC=Object.entries(ks).map(([t,e])=>[e.prefix,t]),RC=/^[A-Za-z0-9_-]{20,}$/;function EC(t){if(typeof t!="string")return null;for(let[e,r]of TC)if(t.startsWith(e)&&RC.test(t.slice(e.length)))return r;return null}function Mw(t){return EC(t)==="pat"}cs();var PC=8e3,AC={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 CC(t){return AC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function IC(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(PC)})}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 Uw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function qw(t={},e=fetch){let r=await Cr(),{file:n}=Ji();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 IC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Uw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Uw(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}: ${CC(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 aq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function cq(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 lq(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 uq(t,e,r){let n=await vy({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),lq(n.baseUrl),!r)return;let s=await cq(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 dq(t){let e=await pu(await ps(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Eu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Ur(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function MT(t,e){if(qT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Tb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function dg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function bl(t){process.exit(t)}function pq(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 hq(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 mq(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 UT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function yg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.39.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${wu()}
4178
4178
  `),e.hook("preAction",(d,m)=>{Mb(e.opts(),m.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 m=Ut(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4179
4179
  ${ys} auth login --base-url ${m} --token tb_pat_\u2026`),Mw(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await uq(m,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=>qw({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 m=d??await aq("Pick the active instance:"),v=await Yi(m);if(!v){let $=await Cr();k(`no stored sign-in for ${Ut(m)}.`+($.length?` Stored: ${$.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ut(m)} --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 $=await Cr();for(let x of $)await iu(x.baseUrl);_(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let m=await iu(d.baseUrl);m||k(d.baseUrl?`no stored sign-in for ${Ut(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Qt();_(`signed out of ${m}.`+(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:m,token:v}=await Y(d.baseUrl),$;try{$=await Nn({baseUrl:m,token:v,recordsOnly:d.recordsOnly})}catch(y){let T=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(T)){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{$=await Nn({baseUrl:m,token:v,recordsOnly:!0})}catch(P){k(`types generation failed: ${P instanceof Error?P.message:String(P)}`)}}else k(`types generation failed: ${T}`)}let x=ye(process.cwd(),d.out);await _e.writeFile(x,$,"utf8"),_(`wrote ${x} (${$.split(`
4180
4180
  `).length} lines).`)}),Fb(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:m,token:v}=await Y(d.baseUrl),$=new URLSearchParams;d.records&&$.set("records",d.records),d.query&&$.set("query",d.query);let x=$.toString(),y=await fetch(`${m}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let P=((await y.json()).markdown??"").trim(),N=ye(process.cwd(),d.out),z=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${z} \u2014 do not edit; re-run to refresh. -->
@@ -4204,7 +4204,7 @@ samples init: ${P} written, ${N} skipped.`)});let pr=e.command("guardrails").des
4204
4204
  `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(x.map(_l),{head:FT})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),pr.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,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){te(T,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}_(`${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>`))}),pr.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,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(T){te(T,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}_(`${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,m,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])pr.command(`${d} <name>`).description(m==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async($,x)=>{let{baseUrl:y,token:T}=await Y(x.baseUrl),P=new K({baseUrl:y,token:T});try{await P.guardrailUpdate($,{status:m})}catch(N){te(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail ${g.bold($)} ${v}`),m==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});pr.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,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$});try{await x.guardrailDelete(d)}catch(y){te(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),pr.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,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await x.guardrailPostureGet()}catch(z){te(z,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${z instanceof Error?z.message:String(z)}`)}_(`guardrail posture: ${g.bold(y(N.mode))}`),_(g.dim(N.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=d.trim().toLowerCase();T!=="allow"&&T!=="deny"&&k("posture must be 'allow' or 'deny'.");let P;try{P=await x.guardrailPostureSet(T)}catch(N){te(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(P.mode))}`),P.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>`."))}),pr.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 m;if(d.fields)try{m=JSON.parse(d.fields)}catch(P){k(`--fields must be valid JSON: ${P instanceof Error?P.message:String(P)}`)}let{baseUrl:v,token:$}=await Y(d.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(P){te(P,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${P instanceof Error?P.message:String(P)}`)}if(d.json)return _(JSON.stringify(y,null,2));let T=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${T} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${T} \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 Xo=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ei=(d,m={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let $ of d.fields){let x=[$.required?"required":null].filter(Boolean).join(", "),y=m.showClaimants&&$.claimedBy?.length?` ${g.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";_(` ${$.column.padEnd(28)} ${$.type}${x?` (${x})`:""}${y}`)}m.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Pi(d){if(d instanceof le&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(q(m.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let bg=async d=>{let m=Ot(ye(process.cwd(),d),"public","turbobase.json"),v=await _e.readFile(m,"utf8").catch(()=>null);if(v===null)return null;let $;try{$=JSON.parse(v)}catch(y){k(`${m} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=$.tables;return x===void 0?{tables:[],manifestPath:m}:(Array.isArray(x)||k(`${m}: "tables" must be an array.`),{tables:x,manifestPath:m})};Xo.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:m,token:v}=await Y(d.baseUrl),$=new K({baseUrl:m,token:v}),x;try{x=await $.tablesList()}catch(y){te(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(tr(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Xo.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,m)=>{let v=await bg(d??".");if(v||k(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se("planning tables",()=>y.tablesPlan({claimedBy:m.as,tables:v.tables}))}catch(P){te(P,"extensions:deploy","plan tables"),Pi(P)}_(`claiming as ${g.bold(T.claimedBy)}`);for(let P of T.tables)Ei(P,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Xo.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,m)=>{let v=await bg(d??".");if(v||k(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se("applying tables",()=>y.tablesApply({claimedBy:m.as,tables:v.tables}))}catch(P){te(P,"extensions:deploy","apply tables"),Pi(P)}for(let P of T.tables)Ei(P,{showClaimants:!0});_(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),Xo.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,m)=>[...m??[],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,m)=>{let v=m.field.map(P=>{let[N,z,M]=P.split(":");return(!N||!z)&&k(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${P}": the third part may only be "required".`),{name:N,type:z,...M==="required"?{required:!0}:{}}}),{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:v,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){te(P,"extensions:deploy","create a table"),Pi(P)}for(let P of T.tables)Ei(P);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Xo.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,m)=>{m.confirm!==d&&k(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await se(`dropping cr_${d}`,()=>x.tablesDrop(d,m.confirm))}catch(T){te(T,"extensions:deploy","drop a table"),k(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let vl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");vl.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 m=hg(),v;try{v=await jw(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof vs&&k($.message),k(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),vl.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 m=hg();await Gu(m).catch(()=>[]);let v;try{v=await Dw(m,d)}catch($){k(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}v||k(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),vl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=hg(),m=await Gu(d).catch(()=>[]),v=await Sa(),{active:$}=Wu(v);if($.length===0)_("no active sandboxes.");else{for(let x of $)_(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);_(`
4205
4205
  ${$.length} active sandbox(es).`)}m.length>0&&_(`(reaped ${m.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.",ha).action(async d=>{let{baseUrl:m,token:v}=await Y(d.baseUrl),$=new K({baseUrl:m,token:v}),x;try{x=await se("exporting instance config",()=>$.configExport())}catch(P){P instanceof le&&(P.status===401||P.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${P instanceof Error?P.message:String(P)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
4206
4206
  `,T=ye(process.cwd(),d.out,fs);await _e.mkdir(Ur(T),{recursive:!0}),await _e.writeFile(T,y,"utf8"),_(`wrote ${d.out}/${fs} (${y.split(`
4207
- `).length} lines).`)});let wg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),BT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_g=()=>process.env.TURBOBASE_HOME?.trim()||Ot(iq(),".turbobase"),ZT=()=>"1.39.0",Ai=async()=>Promise.all(BT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));wg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ai();for(let m of d)_(`${m.present?Le.success("installed"):Le.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&_(`
4207
+ `).length} lines).`)});let wg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),BT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_g=()=>process.env.TURBOBASE_HOME?.trim()||Ot(iq(),".turbobase"),ZT=()=>"1.39.1",Ai=async()=>Promise.all(BT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));wg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ai();for(let m of d)_(`${m.present?Le.success("installed"):Le.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&_(`
4208
4208
  run \`${ys} ext extras install\` to fetch them into ${_g()}.`)}),wg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ai();if(d.every(N=>N.present)){_(Le.success("extras already installed \u2014 nothing to do."));return}let m=_g();await _e.mkdir(m,{recursive:!0});let v=d.filter(N=>!N.present).map(N=>N.name),$=Fu(process.platform,process.arch),x=async(N,z)=>{let{code:M,stderr:re}=await Ri("npm",["install","--prefix",m,"--no-audit","--no-fund",...N]);M!==0&&k(`extras install failed while installing ${z} (npm exited ${M}).
4209
4209
  ${re.trim()}
4210
4210
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(z=>`${z}@${Uu[z]??"latest"}`);_(`installing ${N.join(", ")} \u2192 ${m}/node_modules \u2026`),await x(N,y.join(", "))}if(v.includes("isolated-vm")){let N=`isolated-vm@${Uu["isolated-vm"]}`;if(_(`installing ${N} \u2192 ${m}/node_modules \u2026`),await x(["--ignore-scripts",N],"isolated-vm"),Aw.includes($)){let M=`${qu}@${ZT()}`;_(`fetching ${M} (no upstream binary for ${$}) \u2026`);let{code:re}=await Ri("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",M]);re!==0&&_(Le.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let z=await Cw({home:m});z.length>0&&_(` ${Le.success("prebuilt")} ${z.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let T=await Ai(),P=T.filter(N=>!N.present).map(N=>N.name);if(P.includes("isolated-vm")){_(Le.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${Bu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await Ri("npm",["rebuild","--prefix",m,"isolated-vm"]);N===0&&(T=await Ai(),P=T.filter(z=>!z.present).map(z=>z.name))}P.length>0&&k(`npm succeeded but ${P.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${Bu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Le.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ro=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ro.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 m=d.target==="approved"?"approved":d.target==="auto"?"auto":null;m||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await _q(ye(process.cwd(),d.project??".")),$=Object.keys(v).length;!d.solution&&$===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await mg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await mg(["rev-parse","HEAD"]),T=d.gitRepo??process.env.GITHUB_REPOSITORY??await mg(["remote","get-url","origin"]),P=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:z,token:M}=await Y(d.baseUrl),re=new K({baseUrl:z,token:M}),U;try{U=await re.releaseDeploy({solutionId:d.solution??null,target:m,approvedBy:d.approvedBy??null,files:$>0?v:null,gitRepo:T,gitRef:P,gitSha:y,prUrl:N})}catch(ne){te(ne,"releases:write","release deploy"),ne instanceof le&&ne.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${m}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),d.follow&&await Au(()=>re.releaseStatus(U.releaseId),`release ${U.releaseId}`,d.intervalMs)}),ro.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,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&k(`release ${d} not found.`),N instanceof le&&N.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),te(N,"releases:write","pull a release"),k(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let T=ye(process.cwd(),m.dir),P=0;for(let[N,z]of[["owned",y.owned],["context",y.context]])for(let[M,re]of Object.entries(z)){let U=Ot(T,N,M);await _e.mkdir(Ur(U),{recursive:!0}),await _e.writeFile(U,re,"utf8"),P++}await _e.writeFile(Ot(T,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${T}
package/dist/turbobase.js CHANGED
@@ -4127,7 +4127,7 @@ ${o.map(B_).join(`
4127
4127
  `))}async function Th(t,e,r=zr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Br(e,r);if(!await ls(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await Y("publishing",()=>o.skillsPublish(n))}catch(a){G(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function xh(t,e,r=zr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Br(e,r);if(!await ls(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await Y("unpublishing",()=>o.skillsUnpublish(n))}catch(a){G(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Rh(t,e,r=zr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Br(e,r);if(await ls(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await Y("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function $h(t,e=zr){let r=await Br(t,e),n;try{n=await Y("reading the releases",()=>r.skillsReleases())}catch(o){G(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function Eh(t,e,r=zr){let n=[...new Set((t??[]).map(d=>d.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Br(e,r);if(!await ls(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4128
4128
  ${n.join(`
4129
4129
  `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let d of n)try{i.push(await Y(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),G(p,"skills:publish","delete a skill"),v(`delete failed on '${d}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(d=>d.wasPublished).map(d=>d.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Ph}from"node:fs";import{join as PS,relative as AS,resolve as CS,sep as IS}from"node:path";var OS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),NS=new Set([".mcp.json",".env"]);function LS(t){return NS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function jS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function DS(t){return t.includes(0)}async function Ah(t){let e=CS(t),r={},n=[],o=[],s=[];async function i(a){let l=await Ph.readdir(a,{withFileTypes:!0});for(let d of l){let p=PS(a,d.name);if(OS.has(d.name))continue;if(d.isDirectory()){await i(p);continue}if(!d.isFile())continue;let f=AS(e,p).split(IS).join("/");if(LS(d.name)){o.push(f);continue}let _=await Ph.readFile(p);if(!jS(_)){n.push(f);continue}DS(_)&&s.push(f),r[f]=_.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as US}from"node:crypto";var MS="/_tb/app-assets",qS=16,zS=/^[0-9a-f]{32}$/;function Ch(){return US(qS).toString("hex")}function BS(t){return zS.test(t)}function Ih(t){if(!BS(t))throw new Error(`not a build id: ${t}`);return`${MS}/${t}/`}var Oh=7;La();var ja=50*1024*1024;import cs from"node:fs/promises";import An from"node:path";var Da={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ua="@turbobase/isolated-vm-prebuilds";function Ma(t,e){return`${t}-${e}`}function qa(t=process.versions){return`abi${t.modules}`}var Nh=["darwin-x64","win32-arm64"];async function Lh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Ma(e,r),o=An.join(t.home,"node_modules"),s=An.join(o,...Ua.split("/"),"prebuilds",n),i=An.join(o,"isolated-vm","prebuilds",n),a;try{a=await cs.readdir(s)}catch{return[]}let l=[];await cs.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let p=An.join(i,d);try{await cs.copyFile(An.join(s,d),p,cs.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as FS}from"node:os";import{join as jh}from"node:path";import{promises as za}from"node:fs";function Uh(){let t=process.env.TURBOBASE_HOME??jh(FS(),".turbobase");return{dir:t,file:jh(t,"sandboxes.json")}}var HS={s:1e3,m:6e4,h:36e5,d:864e5};function KS(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*HS[e[2]]}function VS(t,e=Date.now()){return new Date(e+KS(t)).toISOString()}function GS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function WS(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 JS(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 YS="[REDACTED]",Cn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ba=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function XS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ba(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:YS:n[o]=s}return n}function ZS(t,e,r){return e.map(n=>XS(t,n,r))}var Dh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),QS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function ek(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Fa(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of QS)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=ek(t);if(!Dh.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Dh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function tk(t,e=rk){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function rk(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function nk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function ok(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ha(){let{file:t}=Uh();try{let e=await za.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Mh(t){let{dir:e,file:r}=Uh();await za.mkdir(e,{recursive:!0}),await za.writeFile(r,`${JSON.stringify(t,null,2)}
4130
- `,{mode:384})}async function sk(t){let e=await Ha();e.push(t),await Mh(e)}async function qh(t){let e=await Ha(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mh(e),n??null}async function ds(){return Ha()}function Ka(t,e=Date.now()){let r=[],n=[];for(let o of t)GS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function zh(t,e){Fa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=WS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>tk(d)))(e.fromTenant),i=nk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=JS(d.rows,n),f=ZS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:VS(e.ttl,o),sampleFraction:n,url:ok(s,e.baseUrl)};return await sk(l),l}async function Bh(t,e){Fa(t.target());let n=(await ds()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await qh(e),n):null}async function Va(t,e=Date.now()){Fa(t.target());let r=await ds(),{expired:n}=Ka(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await qh(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},$N=Object.keys(In).filter(t=>In[t].mintable);var AN=In.pat.prefix,ik=Object.entries(In).map(([t,e])=>[e.prefix,t]),ak=/^[A-Za-z0-9_-]{20,}$/;function lk(t){if(typeof t!="string")return null;for(let[e,r]of ik)if(t.startsWith(e)&&ak.test(t.slice(e.length)))return r;return null}function Fh(t){return lk(t)==="pat"}bn();var ck=8e3,dk={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 uk(t){return dk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function pk(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(ck)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Hh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Kh(t={},e=fetch){let r=await Lt(),{file:n}=jo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await pk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Hh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Hh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${uk(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function LA(t){let e=await Lt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function jA(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 DA(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 UA(t,e,r){let n=await xu({baseUrl:t,token:e}),o=(await Lt()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),DA(n.baseUrl),!r)return;let s=await jA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function MA(t){let e=await ca(await Sn(t),Ft(t)),r=Ta(e);return r||v(`${t}: ${xa(e)}`),{...r,sourceCode:e}}async function Ar(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(Ft(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Kb(t,e){if(Gb(t)!==".gitignore")return Ar(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Ar(t,e.content,e.executable,e.mode);let n=Ap(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function Fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Li(t){process.exit(t)}function qA(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 zA(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 BA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function Vb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Jd({includeInternal:t=!0}={}){let e=new NA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.39.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ga()}
4130
+ `,{mode:384})}async function sk(t){let e=await Ha();e.push(t),await Mh(e)}async function qh(t){let e=await Ha(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mh(e),n??null}async function ds(){return Ha()}function Ka(t,e=Date.now()){let r=[],n=[];for(let o of t)GS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function zh(t,e){Fa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=WS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>tk(d)))(e.fromTenant),i=nk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=JS(d.rows,n),f=ZS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:VS(e.ttl,o),sampleFraction:n,url:ok(s,e.baseUrl)};return await sk(l),l}async function Bh(t,e){Fa(t.target());let n=(await ds()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await qh(e),n):null}async function Va(t,e=Date.now()){Fa(t.target());let r=await ds(),{expired:n}=Ka(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await qh(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},$N=Object.keys(In).filter(t=>In[t].mintable);var AN=In.pat.prefix,ik=Object.entries(In).map(([t,e])=>[e.prefix,t]),ak=/^[A-Za-z0-9_-]{20,}$/;function lk(t){if(typeof t!="string")return null;for(let[e,r]of ik)if(t.startsWith(e)&&ak.test(t.slice(e.length)))return r;return null}function Fh(t){return lk(t)==="pat"}bn();var ck=8e3,dk={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 uk(t){return dk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function pk(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(ck)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Hh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Kh(t={},e=fetch){let r=await Lt(),{file:n}=jo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await pk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Hh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Hh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${uk(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function LA(t){let e=await Lt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function jA(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 DA(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 UA(t,e,r){let n=await xu({baseUrl:t,token:e}),o=(await Lt()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),DA(n.baseUrl),!r)return;let s=await jA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function MA(t){let e=await ca(await Sn(t),Ft(t)),r=Ta(e);return r||v(`${t}: ${xa(e)}`),{...r,sourceCode:e}}async function Ar(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(Ft(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Kb(t,e){if(Gb(t)!==".gitignore")return Ar(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Ar(t,e.content,e.executable,e.mode);let n=Ap(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function Fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Li(t){process.exit(t)}function qA(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 zA(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 BA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function Vb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Jd({includeInternal:t=!0}={}){let e=new NA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.39.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ga()}
4131
4131
  `),e.hook("preAction",(u,h)=>{Fp(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async u=>{let h=rt(u.baseUrl);u.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4132
4132
  ${$n} auth login --base-url ${h} --token tb_pat_\u2026`),Fh(u.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await UA(h,u.token,u.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async u=>Kh({probe:u.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async u=>{let h=u??await LA("Pick the active instance:"),w=await Do(h);if(!w){let T=await Lt();v(`no stored sign-in for ${rt(h)}.`+(T.length?` Stored: ${T.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async u=>{if(u.all){let T=await Lt();for(let S of T)await na(S.baseUrl);b(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await na(u.baseUrl);h||v(u.baseUrl?`no stored sign-in for ${rt(u.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ht();b(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T;try{T=await mr({baseUrl:h,token:w,recordsOnly:u.recordsOnly})}catch(g){let x=g instanceof Error?g.message:String(g);if(!u.recordsOnly&&/openapi\.json failed \(401/.test(x)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await mr({baseUrl:h,token:w,recordsOnly:!0})}catch($){v(`types generation failed: ${$ instanceof Error?$.message:String($)}`)}}else v(`types generation failed: ${x}`)}let S=se(process.cwd(),u.out);await ae.writeFile(S,T,"utf8"),b(`wrote ${S} (${T.split(`
4133
4133
  `).length} lines).`)}),Vp(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new URLSearchParams;u.records&&T.set("records",u.records),u.query&&T.set("query",u.query);let S=T.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});g.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let $=((await g.json()).markdown??"").trim(),A=se(process.cwd(),u.out),C=u.records?` records=${u.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
@@ -4157,7 +4157,7 @@ samples init: ${$} written, ${A} skipped.`)});let xt=e.command("guardrails").des
4157
4157
  `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(S.map(Di),{head:Wb})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),xt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T}),g;try{g=await S.guardrailCreate({name:u,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){G(x,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),xt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T}),g;try{g=await S.guardrailUpdate(u,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(x){G(x,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[u,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])xt.command(`${u} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,S)=>{let{baseUrl:g,token:x}=await B(S.baseUrl),$=new q({baseUrl:g,token:x});try{await $.guardrailUpdate(T,{status:h})}catch(A){G(A,"extensions:deploy",`${u} a guardrail`),v(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(T)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});xt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T});try{await S.guardrailDelete(u)}catch(g){G(g,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(u)} deleted`)}),xt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){G(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(g(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let x=u.trim().toLowerCase();x!=="allow"&&x!=="deny"&&v("posture must be 'allow' or 'deny'.");let $;try{$=await S.guardrailPostureSet(x)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(g($.mode))}`),$.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),xt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async u=>{let h;if(u.fields)try{h=JSON.parse(u.fields)}catch($){v(`--fields must be valid JSON: ${$ instanceof Error?$.message:String($)}`)}let{baseUrl:w,token:T}=await B(u.baseUrl),S=new q({baseUrl:w,token:T}),g;try{g=await S.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...h?{fields:h}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch($){G($,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${$ instanceof Error?$.message:String($)}`)}if(u.json)return b(JSON.stringify(g,null,2));let x=`${u.source}/${g.op??u.record}`;g.degraded?(b(`${m.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${g.reason}`))):g.allowed?b(`${m.green("\u2713")} ${x} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${x} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,h={})=>{let w=`${m.bold(u.table)} ${m.dim(u.displayName)}`;b(u.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let T of u.fields){let S=[T.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&T.claimedBy?.length?` ${m.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";b(` ${T.column.padEnd(28)} ${T.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&u.claimants.length>1&&b(m.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let h=u.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}v(`tables: ${u instanceof Error?u.message:String(u)}`)}let Yd=async u=>{let h=et(se(process.cwd(),u),"public","turbobase.json"),w=await ae.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let T;try{T=JSON.parse(w)}catch(g){v(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=T.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||v(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),S;try{S=await T.tablesList()}catch(g){G(g,"extensions:deploy","list tables"),v(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,h)=>{let w=await Yd(u??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:S}=await B(h.baseUrl),g=new q({baseUrl:T,token:S}),x;try{x=await Y("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch($){G($,"extensions:deploy","plan tables"),Ro($)}b(`claiming as ${m.bold(x.claimedBy)}`);for(let $ of x.tables)xo($,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,h)=>{let w=await Yd(u??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:S}=await B(h.baseUrl),g=new q({baseUrl:T,token:S}),x;try{x=await Y("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:w.tables}))}catch($){G($,"extensions:deploy","apply tables"),Ro($)}for(let $ of x.tables)xo($,{showClaimants:!0});b(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,h)=>[...h??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let w=h.field.map($=>{let[A,C,O]=$.split(":");return(!A||!C)&&v(`--field "${$}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&v(`--field "${$}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:T,token:S}=await B(h.baseUrl),g=new q({baseUrl:T,token:S}),x;try{x=await Y(`creating cr_${u}`,()=>g.tablesApply({tables:[{slug:u,displayName:h.name??u,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch($){G($,"extensions:deploy","create a table"),Ro($)}for(let $ of x.tables)xo($);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.confirm!==u&&v(`drop refused: --confirm "${h.confirm}" does not match "${u}".`);let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T}),g;try{g=await Y(`dropping cr_${u}`,()=>S.tablesDrop(u,h.confirm))}catch(x){G(x,"extensions:deploy","drop a table"),v(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!g.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let Ui=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ui.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async u=>{process.env.TURBOBASE_SANDBOX="1";let h=Kd(),w;try{w=await zh(h,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(T){T instanceof Cn&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Ui.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let h=Kd();await Va(h).catch(()=>[]);let w;try{w=await Bh(h,u)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}w||v(`no sandbox named '${u}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ui.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Kd(),h=await Va(u).catch(()=>[]),w=await ds(),{active:T}=Ka(w);if(T.length===0)b("no active sandboxes.");else{for(let S of T)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
4158
4158
  ${T.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Qo).action(async u=>{let{baseUrl:h,token:w}=await B(u.baseUrl),T=new q({baseUrl:h,token:w}),S;try{S=await Y("exporting instance config",()=>T.configExport())}catch($){$ instanceof Q&&($.status===401||$.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${$ instanceof Error?$.message:String($)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
4159
4159
  `,x=se(process.cwd(),u.out,xn);await ae.mkdir(Ft(x),{recursive:!0}),await ae.writeFile(x,g,"utf8"),b(`wrote ${u.out}/${xn} (${g.split(`
4160
- `).length} lines).`)});let Xd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Jb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Zd=()=>process.env.TURBOBASE_HOME?.trim()||et(OA(),".turbobase"),Yb=()=>"1.39.0",$o=async()=>Promise.all(Jb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Xd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?_e.success("installed"):_e.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
4160
+ `).length} lines).`)});let Xd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Jb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Zd=()=>process.env.TURBOBASE_HOME?.trim()||et(OA(),".turbobase"),Yb=()=>"1.39.1",$o=async()=>Promise.all(Jb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Xd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?_e.success("installed"):_e.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
4161
4161
  run \`${$n} ext extras install\` to fetch them into ${Zd()}.`)}),Xd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let u=await $o();if(u.every(A=>A.present)){b(_e.success("extras already installed \u2014 nothing to do."));return}let h=Zd();await ae.mkdir(h,{recursive:!0});let w=u.filter(A=>!A.present).map(A=>A.name),T=Ma(process.platform,process.arch),S=async(A,C)=>{let{code:O,stderr:W}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&v(`extras install failed while installing ${C} (npm exited ${O}).
4162
4162
  ${W.trim()}
4163
4163
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=w.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Da[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Da["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),Nh.includes(T)){let O=`${Ua}@${Yb()}`;b(`fetching ${O} (no upstream binary for ${T}) \u2026`);let{code:W}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&b(_e.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Lh({home:h});C.length>0&&b(` ${_e.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let x=await $o(),$=x.filter(A=>!A.present).map(A=>A.name);if($.includes("isolated-vm")){b(_e.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${qa()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await To("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(x=await $o(),$=x.filter(C=>!C.present).map(C=>C.name))}$.length>0&&v(`npm succeeded but ${$.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${qa()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(_e.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Cr=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");Cr.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async u=>{let h=u.target==="approved"?"approved":u.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${u.target}').`);let w=await WA(se(process.cwd(),u.project??".")),T=Object.keys(w).length;!u.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(u.ref?await Vd(["rev-parse",u.ref])??u.ref:null)??process.env.GITHUB_SHA??await Vd(["rev-parse","HEAD"]),x=u.gitRepo??process.env.GITHUB_REPOSITORY??await Vd(["remote","get-url","origin"]),$=u.gitRef??process.env.GITHUB_REF??null,A=u.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await B(u.baseUrl),W=new q({baseUrl:C,token:O}),N;try{N=await W.releaseDeploy({solutionId:u.solution??null,target:h,approvedBy:u.approvedBy??null,files:T>0?w:null,gitRepo:x,gitRef:$,gitSha:g,prUrl:A})}catch(J){G(J,"releases:write","release deploy"),J instanceof Q&&J.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${J instanceof Error?J.message:String(J)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),u.follow&&await $a(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,u.intervalMs)}),Cr.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),S=new q({baseUrl:w,token:T}),g;try{g=await S.releaseFiles(u)}catch(A){A instanceof Q&&A.status===404&&v(`release ${u} not found.`),A instanceof Q&&A.status===409&&v(`no built project was retained for release ${u}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),G(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let x=se(process.cwd(),h.dir),$=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[O,W]of Object.entries(C)){let N=et(x,A,O);await ae.mkdir(Ft(N),{recursive:!0}),await ae.writeFile(N,W,"utf8"),$++}await ae.writeFile(et(x,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),b(`pulled release ${g.releaseId} (${g.status}) \u2192 ${x}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turbobase/cli",
3
- "version": "1.39.0",
3
+ "version": "1.39.1",
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",