@turbobase/cli 1.49.0 → 1.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +81 -68
- package/dist/turbobase.js +15 -2
- package/package.json +1 -1
package/dist/turbobase.js
CHANGED
|
@@ -1335,6 +1335,13 @@ export interface BatchResult<T = unknown> {
|
|
|
1335
1335
|
* (\`{ query, count: 'exact' }\`) to know how far. A sub-query whose own
|
|
1336
1336
|
* \`limit\` is 1000 or less can never carry it. */
|
|
1337
1337
|
truncated?: true;
|
|
1338
|
+
/** \`true\` when the instance ran out of time for the WHOLE batch before this
|
|
1339
|
+
* sub-query started, so it was never sent: \`ok\` is false and \`status\` is 504,
|
|
1340
|
+
* the same as a read that timed out, and this is how you tell the two apart.
|
|
1341
|
+
* Absent \u2014 never \`false\` \u2014 on every other result, so the check is
|
|
1342
|
+
* \`if (r.notRun)\`. Ask again for just these queries; re-sending the whole
|
|
1343
|
+
* batch re-runs the ones that came back and re-enters the same queue. */
|
|
1344
|
+
notRun?: true;
|
|
1338
1345
|
}
|
|
1339
1346
|
|
|
1340
1347
|
/** One element of the list you pass batch(): the same path-and-query string you
|
|
@@ -1464,6 +1471,7 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
|
|
|
1464
1471
|
contentRange?: string | null;
|
|
1465
1472
|
stitched?: { aliases: string[]; truncated: string[] };
|
|
1466
1473
|
truncated?: true;
|
|
1474
|
+
notRun?: true;
|
|
1467
1475
|
}[];
|
|
1468
1476
|
};
|
|
1469
1477
|
// \`ok\` \u2014 not \`status === 200\` \u2014 is what decides success, and a counted
|
|
@@ -1489,6 +1497,11 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
|
|
|
1489
1497
|
status: r.status,
|
|
1490
1498
|
count: r.count ?? null,
|
|
1491
1499
|
contentRange: r.contentRange ?? null,
|
|
1500
|
+
// Only when the instance set it, for the reason the happy arm gives
|
|
1501
|
+
// about \`truncated\`: a \`notRun: undefined\` key would make
|
|
1502
|
+
// \`'notRun' in r\` true on every sub-query that was tried and failed,
|
|
1503
|
+
// which is the one distinction this field exists to draw.
|
|
1504
|
+
...(r.notRun ? { notRun: true as const } : {}),
|
|
1492
1505
|
error:
|
|
1493
1506
|
typeof r.body === 'object' && r.body && 'error' in r.body
|
|
1494
1507
|
? String((r.body as { error: unknown }).error)
|
|
@@ -4365,7 +4378,7 @@ ${o.map(ZS).join(`
|
|
|
4365
4378
|
`))}async function om(e,t,r=Jr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Yr(t,r);if(!await _s(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",t))return;let i;try{i=await X("publishing",()=>o.skillsPublish(n))}catch(a){W(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&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),O(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function sm(e,t,r=Jr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Yr(t,r);if(!await _s(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",t))return;let i;try{i=await X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){W(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.`)),O(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function im(e,t,r=Jr){let n=Number(e);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${e}'). \`turbobase skills releases\` lists them.`);let o=await Yr(t,r);if(await _s(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",t))try{let i=await X("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){W(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function am(e,t=Jr){let r=await Yr(e,t),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){W(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){O("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 lm(e,t,r=Jr){let n=[...new Set((e??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Yr(t,r);if(!await _s(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4366
4379
|
${n.join(`
|
|
4367
4380
|
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",t))return;let i=[],a=[];for(let u of n)try{i.push(await X(`deleting ${u}`,()=>o.skillsDelete(u)))}catch(p){if(p instanceof Y&&p.status===404){a.push(u);continue}i.length>0&&O(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),W(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&O(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(O(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as cm}from"node:fs";import{join as Hk,relative as Vk,resolve as Kk,sep as Wk}from"node:path";var Gk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Jk=new Set([".mcp.json",".env"]);function Yk(e){return Jk.has(e)||e.startsWith(".env.")&&e!==".env.example"}function Xk(e){return Buffer.compare(Buffer.from(e.toString("utf8"),"utf8"),e)===0}function Zk(e){return e.includes(0)}async function Ja(e){let t=Kk(e),r={},n=[],o=[],s=[];async function i(a){let l=await cm.readdir(a,{withFileTypes:!0});for(let u of l){let p=Hk(a,u.name);if(Gk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=Vk(t,p).split(Wk).join("/");if(Yk(u.name)){o.push(g);continue}let x=await cm.readFile(p);if(!Xk(x)){n.push(g);continue}Zk(x)&&s.push(g),r[g]=x.toString("utf8")}}return await i(t),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as Qk}from"node:crypto";var ex="/_tb/app-assets",tx=16,rx=/^[0-9a-f]{32}$/;function dm(){return Qk(tx).toString("hex")}function nx(e){return rx.test(e)}function um(e){if(!nx(e))throw new Error(`not a build id: ${e}`);return`${ex}/${e}/`}var pm=7;Xa();var Za=50*1024*1024;import Ss from"node:fs/promises";import Mn from"node:path";var Qa={esbuild:"0.28.1","isolated-vm":"6.1.2"},el="@turbobase/isolated-vm-prebuilds";function tl(e,t){return`${e}-${t}`}function rl(e=process.versions){return`abi${e.modules}`}var hm=["darwin-x64","win32-arm64"];async function mm(e){let t=e.platform??process.platform,r=e.arch??process.arch,n=tl(t,r),o=Mn.join(e.home,"node_modules"),s=Mn.join(o,...el.split("/"),"prebuilds",n),i=Mn.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ss.readdir(s)}catch{return[]}let l=[];await Ss.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Mn.join(i,u);try{await Ss.copyFile(Mn.join(s,u),p,Ss.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as ox}from"node:os";import{join as fm}from"node:path";import{promises as nl}from"node:fs";function ym(){let e=process.env.TURBOBASE_HOME??fm(ox(),".turbobase");return{dir:e,file:fm(e,"sandboxes.json")}}var sx={s:1e3,m:6e4,h:36e5,d:864e5};function ix(e){let t=/^\s*(\d+)\s*([smhd])\s*$/.exec(e);if(!t)throw new Error(`invalid --ttl '${e}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${e}': duration must be a positive integer.`);return r*sx[t[2]]}function ax(e,t=Date.now()){return new Date(t+ix(e)).toISOString()}function lx(e,t=Date.now()){let r=Date.parse(e);return Number.isNaN(r)?!0:r<=t}function cx(e){let t=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(e);if(!t)throw new Error(`invalid --sample '${e}': expected a percent like 2% (or a bare number).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${e}': percent must be between 0 and 100.`);return r/100}function dx(e,t){if(t>=1)return[...e];if(t<=0||e.length===0)return[];let r=Math.max(1,Math.round(1/t)),n=[];for(let o=0;o<e.length;o+=r)n.push(e[o]);return n}var ux="[REDACTED]",qn=class extends Error{constructor(t){super(t),this.name="SandboxDataCopyUnavailableError"}},ol=class extends Error{table;column;constructor(t,r,n){super(`Refusing to copy ${t}.${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=t,this.column=r}};function px(e,t,r){let n={};for(let[o,s]of Object.entries(t)){let i=r[o];if(i===void 0)throw new ol(e,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:ux:n[o]=s}return n}function hx(e,t,r){return t.map(n=>px(e,n,r))}var gm=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),mx=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function fx(e){let t=e.trim();try{let o=new URL(t);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=t.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function sl(e){if(!e||!e.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let t=e.toLowerCase();for(let n of mx)if(t.includes(n))throw new Error(`local-only guard: target '${e}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=fx(e);if(!gm.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...gm].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function gx(e,t=yx){return`sbx-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${t()}`}function yx(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function bx(e){return`turbobase_${e.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function wx(e,t){return`${(t??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(e)}`}async function il(){let{file:e}=ym();try{let t=await nl.readFile(e,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r:[]}catch(t){if(t.code==="ENOENT")return[];throw t}}async function bm(e){let{dir:t,file:r}=ym();await nl.mkdir(t,{recursive:!0}),await nl.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
4368
|
-
`,{mode:384})}async function vx(e){let t=await il();t.push(e),await bm(t)}async function wm(e){let t=await il(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await bm(t),n??null}async function ks(){return il()}function al(e,t=Date.now()){let r=[],n=[];for(let o of e)lx(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function vm(e,t){sl(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=cx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>gx(u)))(t.fromTenant),i=bx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=dx(u.rows,n),g=hx(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ax(t.ttl,o),sampleFraction:n,url:wx(s,t.baseUrl)};return await vx(l),l}async function _m(e,t){sl(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await wm(t),n):null}async function ll(e,t=Date.now()){sl(e.target());let r=await ks(),{expired:n}=al(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await wm(s.name),o.push(s)}return o}var zn={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"}},nj=Object.keys(zn).filter(e=>zn[e].mintable);var ij=zn.pat.prefix,_x=Object.entries(zn).map(([e,t])=>[t.prefix,e]),Sx=/^[A-Za-z0-9_-]{20,}$/;function kx(e){if(typeof e!="string")return null;for(let[t,r]of _x)if(e.startsWith(t)&&Sx.test(e.slice(t.length)))return r;return null}function Sm(e){return kx(e)==="pat"}$n();var xx=8e3,Tx={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 Rx(e){return Tx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function $x(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(xx)})}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 km(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function xm(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),O(m.dim(`no sign-ins stored in ${n}.`));return}let o=await yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await $x(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),km(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${km(i.check)} (updated ${i.updatedAt})`);O(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(O(m.red(`${i.baseUrl}: ${Rx(i.check.reason)}.`)),O(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"&&O(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||O("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function iI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function aI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 lI(e){O(""),O("Sharing is ON. Two things reach the Turbobase product team from this instance:"),O(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),O(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),O(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),O(" about OUR platform, with instance name, user names and ids masked before they leave."),O(`Turn it off: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function cI(e,t,r){let n=await Yu({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),lI(n.baseUrl),!r)return;let s=await aI(n.baseUrl,t);s.ok||(s.kind==="wrong-host"?(O(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),O(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),O(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?O(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):O(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function dI(e){let t=await Sa(await Cn(e),Wt(e)),r=Ua(t);return r||v(`${e}: ${qa(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function zw(e,t){if(Fw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=sh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function du(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function uI(e){return{name:"turbobase ext test",cases:e.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 pI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function hI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function Bw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function gu({includeInternal:e=!0}={}){let t=new sI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.49.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",c=>c.command.parent?"":`${Pa()}
|
|
4381
|
+
`,{mode:384})}async function vx(e){let t=await il();t.push(e),await bm(t)}async function wm(e){let t=await il(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await bm(t),n??null}async function ks(){return il()}function al(e,t=Date.now()){let r=[],n=[];for(let o of e)lx(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function vm(e,t){sl(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=cx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>gx(u)))(t.fromTenant),i=bx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=dx(u.rows,n),g=hx(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ax(t.ttl,o),sampleFraction:n,url:wx(s,t.baseUrl)};return await vx(l),l}async function _m(e,t){sl(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await wm(t),n):null}async function ll(e,t=Date.now()){sl(e.target());let r=await ks(),{expired:n}=al(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await wm(s.name),o.push(s)}return o}var zn={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"}},nj=Object.keys(zn).filter(e=>zn[e].mintable);var ij=zn.pat.prefix,_x=Object.entries(zn).map(([e,t])=>[t.prefix,e]),Sx=/^[A-Za-z0-9_-]{20,}$/;function kx(e){if(typeof e!="string")return null;for(let[t,r]of _x)if(e.startsWith(t)&&Sx.test(e.slice(t.length)))return r;return null}function Sm(e){return kx(e)==="pat"}$n();var xx=8e3,Tx={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 Rx(e){return Tx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function $x(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(xx)})}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 km(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function xm(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),O(m.dim(`no sign-ins stored in ${n}.`));return}let o=await yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await $x(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),km(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${km(i.check)} (updated ${i.updatedAt})`);O(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(O(m.red(`${i.baseUrl}: ${Rx(i.check.reason)}.`)),O(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"&&O(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||O("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function iI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function aI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 lI(e){O(""),O("Sharing is ON. Two things reach the Turbobase product team from this instance:"),O(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),O(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),O(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),O(" about OUR platform, with instance name, user names and ids masked before they leave."),O(`Turn it off: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function cI(e,t,r){let n=await Yu({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),lI(n.baseUrl),!r)return;let s=await aI(n.baseUrl,t);s.ok||(s.kind==="wrong-host"?(O(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),O(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),O(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?O(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):O(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function dI(e){let t=await Sa(await Cn(e),Wt(e)),r=Ua(t);return r||v(`${e}: ${qa(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function zw(e,t){if(Fw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=sh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function du(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function uI(e){return{name:"turbobase ext test",cases:e.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 pI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function hI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function Bw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function gu({includeInternal:e=!0}={}){let t=new sI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.50.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",c=>c.command.parent?"":`${Pa()}
|
|
4369
4382
|
`),t.hook("preAction",(c,h)=>{vh(t.opts(),h.opts())});let r=t.command("auth").description("Sign in to an instance and manage stored credentials."),n=t.command("project").description("Set up the local project and the files an agent session reads."),o=t.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=t.command("kb").description("Write into the instance's knowledge base."),i=t.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 c=>{let h=st(c.baseUrl);c.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4370
4383
|
${Vr} auth login --base-url ${h} --token tb_pat_\u2026`),Sm(c.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await cI(h,c.token,c.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 c=>xm({probe:c.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async c=>{let h=c??await iI("Pick the active instance:"),w=await Jo(h);if(!w){let R=await Mt();v(`no stored sign-in for ${st(h)}.`+(R.length?` Stored: ${R.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${st(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 c=>{if(c.all){let R=await Mt();for(let S of R)await ga(S.baseUrl);b(`removed ${R.length} stored sign-in${R.length===1?"":"s"}.`);return}let h=await ga(c.baseUrl);h||v(c.baseUrl?`no stored sign-in for ${st(c.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await yt();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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R;try{R=await br({baseUrl:h,token:w,recordsOnly:c.recordsOnly})}catch(f){let _=f instanceof Error?f.message:String(f);if(!c.recordsOnly&&/openapi\.json failed \(401/.test(_)){O("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{R=await br({baseUrl:h,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${_}`)}let S=ne(process.cwd(),c.out);await ie.writeFile(S,R,"utf8"),b(`wrote ${S} (${R.split(`
|
|
4371
4384
|
`).length} lines).`)}),kh(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(c=>{let h=Th(ne(process.cwd(),c.dir));for(let w of h)b(Rh(w))}),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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new URLSearchParams;c.records&&R.set("records",c.records),c.query&&R.set("query",c.query);let S=R.toString(),f=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let E=((await f.json()).markdown??"").trim(),A=ne(process.cwd(),c.out),I=c.records?` records=${c.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
|
|
@@ -4395,7 +4408,7 @@ samples init: ${E} written, ${A} skipped.`)});let Ut=t.command("guardrails").des
|
|
|
4395
4408
|
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(lt(S.map(Hw),{head:Vw})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Ut.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).",c=>Number(c)).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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailCreate({name:c,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){W(_,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} created${f.status==="active"?"":m.dim(` (${f.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.actor?` actor=${f.actor}`:""}${f.when?` where ${f.when}`:""} @prio ${f.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${f.source==="*"?"<source>":f.source} --record <record>`))}),Ut.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.",c=>Number(c)).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(c,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:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailUpdate(c,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){W(_,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} updated`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.when?` where ${f.when}`:""} @prio ${f.priority}`))});for(let[c,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Ut.command(`${c} <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(R,S)=>{let{baseUrl:f,token:_}=await F(S.baseUrl),E=new z({baseUrl:f,token:_});try{await E.guardrailUpdate(R,{status:h})}catch(A){W(A,"extensions:deploy",`${c} a guardrail`),v(`${c} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(R)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});Ut.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R});try{await S.guardrailDelete(c)}catch(f){W(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(c)} deleted`)}),Ut.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(c===void 0){let A;try{A=await S.guardrailPostureGet()}catch(I){W(I,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}b(`guardrail posture: ${m.bold(f(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let _=c.trim().toLowerCase();_!=="allow"&&_!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(_)}catch(A){W(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(f(E.mode))}`),E.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Ut.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 c=>{let h;if(c.fields)try{h=JSON.parse(c.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:R}=await F(c.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailTest({source:c.source,record:c.record,...c.actor?{actor:c.actor}:{},...c.externalId?{externalId:c.externalId}:{},...h?{fields:h}:{},...c.op?{op:c.op}:{},...c.phase?{phase:c.phase}:{}})}catch(E){W(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(c.json)return b(JSON.stringify(f,null,2));let _=`${c.source}/${f.op??c.record}`;f.degraded?(b(`${m.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${_} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${_} \u2014 ${f.decision} by ${m.bold(f.blockedBy??"?")} at the ${f.phase} gate`),f.message&&b(m.dim(` ${f.message}`))),f.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),f.allowed||(process.exitCode=1)});let kn=t.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),jo=(c,h={})=>{let w=`${m.bold(c.table)} ${m.dim(c.displayName)}`;b(c.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let R of c.fields){let S=[R.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&R.claimedBy?.length?` ${m.dim(`\u2190 ${R.claimedBy.join(", ")}`)}`:"";b(` ${R.column.padEnd(28)} ${R.type}${S?` (${S})`:""}${f}`)}h.showClaimants&&c.claimants.length>1&&b(m.dim(` claimed by ${c.claimants.join(", ")}`))};function Do(c){if(c instanceof Y&&c.status===409){let h=c.body;h?.error==="table_conflict"&&h.message&&(O(h.message),process.exit(1))}v(`tables: ${c instanceof Error?c.message:String(c)}`)}let yu=async c=>{let h=nt(ne(process.cwd(),c),"public","turbobase.json"),w=await ie.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let R;try{R=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let S=R.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||v(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};kn.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.tablesList()}catch(f){W(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(c.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(lt(S.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),kn.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(c,h)=>{let w=await yu(c??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),c??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","plan tables"),Do(E)}b(`claiming as ${m.bold(_.claimedBy)}`);for(let E of _.tables)jo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),kn.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(c,h)=>{let w=await yu(c??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),c??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","apply tables"),Do(E)}for(let E of _.tables)jo(E,{showClaimants:!0});b(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),kn.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.",(c,h)=>[...h??[],c],[]).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(c,h)=>{let w=h.field.map(E=>{let[A,I,N]=E.split(":");return(!A||!I)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:I,...N==="required"?{required:!0}:{}}}),{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X(`creating cr_${c}`,()=>f.tablesApply({tables:[{slug:c,displayName:h.name??c,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){W(E,"extensions:deploy","create a table"),Do(E)}for(let E of _.tables)jo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),kn.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(c,h)=>{h.confirm!==c&&v(`drop refused: --confirm "${h.confirm}" does not match "${c}".`);let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await X(`dropping cr_${c}`,()=>S.tablesDrop(c,h.confirm))}catch(_){W(_,"extensions:deploy","drop a table"),v(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!f.removed)return b(`no table named "${c}" on this instance \u2014 nothing dropped.`);b(`dropped ${f.table} and every row in it.`)});let Zi=t.command("sandbox").description("Ephemeral local authoring sandboxes.");Zi.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 c=>{process.env.TURBOBASE_SANDBOX="1";let h=pu(),w;try{w=await vm(h,{fromTenant:c.from,ttl:c.ttl,sample:c.sample,baseUrl:c.baseUrl})}catch(R){R instanceof qn&&v(R.message),v(`sandbox create failed: ${R instanceof Error?R.message:String(R)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Zi.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async c=>{let h=pu();await ll(h).catch(()=>[]);let w;try{w=await _m(h,c)}catch(R){v(`sandbox destroy failed: ${R instanceof Error?R.message:String(R)}`)}w||v(`no sandbox named '${c}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Zi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let c=pu(),h=await ll(c).catch(()=>[]),w=await ks(),{active:R}=al(w);if(R.length===0)b("no active sandboxes.");else{for(let S of R)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
|
|
4396
4409
|
${R.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.",us).action(async c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await X("exporting instance config",()=>R.configExport())}catch(E){E instanceof Y&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let f=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
|
|
4397
4410
|
`,_=ne(process.cwd(),c.out,Ln);await ie.mkdir(Wt(_),{recursive:!0}),await ie.writeFile(_,f,"utf8"),b(`wrote ${c.out}/${Ln} (${f.split(`
|
|
4398
|
-
`).length} lines).`)});let bu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Kw=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],wu=()=>process.env.TURBOBASE_HOME?.trim()||nt(oI(),".turbobase"),Ww=()=>"1.
|
|
4411
|
+
`).length} lines).`)});let bu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Kw=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],wu=()=>process.env.TURBOBASE_HOME?.trim()||nt(oI(),".turbobase"),Ww=()=>"1.50.0",Uo=async()=>Promise.all(Kw.map(async c=>{try{return await import(c.name),{...c,present:!0}}catch{return{...c,present:!1}}}));bu.command("status").description("Report which optional native packages are installed.").action(async()=>{let c=await Uo();for(let h of c)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);c.some(h=>!h.present)&&b(`
|
|
4399
4412
|
run \`${Vr} ext extras install\` to fetch them into ${wu()}.`)}),bu.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let c=await Uo();if(c.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let h=wu();await ie.mkdir(h,{recursive:!0});let w=c.filter(A=>!A.present).map(A=>A.name),R=tl(process.platform,process.arch),S=async(A,I)=>{let{code:N,stderr:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);N!==0&&v(`extras install failed while installing ${I} (npm exited ${N}).
|
|
4400
4413
|
${M.trim()}
|
|
4401
4414
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},f=w.filter(A=>A!=="isolated-vm");if(f.length>0){let A=f.map(I=>`${I}@${Qa[I]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Qa["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),hm.includes(R)){let N=`${el}@${Ww()}`;b(`fetching ${N} (no upstream binary for ${R}) \u2026`);let{code:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",N]);M!==0&&b(ve.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let I=await mm({home:h});I.length>0&&b(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${R}`)}let _=await Uo(),E=_.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${R} / Node ${process.versions.node} (${rl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await No("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await Uo(),E=_.filter(I=>!I.present).map(I=>I.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${R} / Node ${process.versions.node} (${rl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let jr=t.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");jr.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 c=>{let h=c.target==="approved"?"approved":c.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${c.target}').`);let w=await wI(ne(process.cwd(),c.project??".")),R=Object.keys(w).length;!c.solution&&R===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(c.ref?await hu(["rev-parse",c.ref])??c.ref:null)??process.env.GITHUB_SHA??await hu(["rev-parse","HEAD"]),_=c.gitRepo??process.env.GITHUB_REPOSITORY??await hu(["remote","get-url","origin"]),E=c.gitRef??process.env.GITHUB_REF??null,A=c.prUrl??process.env.PR_URL??null,{baseUrl:I,token:N}=await F(c.baseUrl),M=new z({baseUrl:I,token:N}),L;try{L=await M.releaseDeploy({solutionId:c.solution??null,target:h,approvedBy:c.approvedBy??null,files:R>0?w:null,gitRepo:_,gitRef:E,gitSha:f,prUrl:A})}catch(J){W(J,"releases:write","release deploy"),J instanceof Y&&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 ${L.releaseId} enqueued \u2192 taskId=${L.taskId} (target=${h}`+(R>0?`, uploaded ${R} bundle file(s)`:", live-fetch")+")."),c.follow&&await Ba(()=>M.releaseStatus(L.releaseId),`release ${L.releaseId}`,c.intervalMs)}),jr.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.releaseFiles(c)}catch(A){A instanceof Y&&A.status===404&&v(`release ${c} not found.`),A instanceof Y&&A.status===409&&v(`no built project was retained for release ${c}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),W(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let _=ne(process.cwd(),h.dir),E=0;for(let[A,I]of[["owned",f.owned],["context",f.context]])for(let[N,M]of Object.entries(I)){let L=nt(_,A,N);await ie.mkdir(Wt(L),{recursive:!0}),await ie.writeFile(L,M,"utf8"),E++}await ie.writeFile(nt(_,".turbobase-release.json"),JSON.stringify({releaseId:f.releaseId,version:f.version,contentDigest:f.contentDigest},null,2),"utf8"),b(`pulled release ${f.releaseId} (${f.status}) \u2192 ${_}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turbobase/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.50.0",
|
|
4
4
|
"description": "Author, test, and deploy Turbobase extensions (hooks + conduits) against a tenant over HTTP + a personal access token.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|