@burdenoff/cli-sdk 2026.526.2 → 2026.529.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.
- package/dist/{chunk-KTKHJORN.js → chunk-LZQBJDKZ.js} +1 -1
- package/dist/chunk-TCBALVP4.js +32 -0
- package/dist/core/index.cjs +7 -7
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{module-Bv5zhYt2.d.cts → module-DxCuik6L.d.cts} +1 -0
- package/dist/{module-Bv5zhYt2.d.ts → module-DxCuik6L.d.ts} +1 -0
- package/dist/modules/auth/index.cjs +4 -4
- package/dist/modules/auth/index.d.cts +1 -1
- package/dist/modules/auth/index.d.ts +1 -1
- package/dist/modules/auth/index.js +1 -1
- package/dist/modules/billing/index.cjs +2 -2
- package/dist/modules/billing/index.d.cts +1 -1
- package/dist/modules/billing/index.d.ts +1 -1
- package/dist/modules/billing/index.js +1 -1
- package/dist/modules/channels/index.cjs +4 -4
- package/dist/modules/channels/index.d.cts +1 -1
- package/dist/modules/channels/index.d.ts +1 -1
- package/dist/modules/channels/index.js +1 -1
- package/dist/modules/conversations/index.cjs +2 -2
- package/dist/modules/conversations/index.d.cts +1 -1
- package/dist/modules/conversations/index.d.ts +1 -1
- package/dist/modules/conversations/index.js +1 -1
- package/dist/modules/devportal/index.cjs +4 -4
- package/dist/modules/devportal/index.d.cts +1 -1
- package/dist/modules/devportal/index.d.ts +1 -1
- package/dist/modules/devportal/index.js +1 -1
- package/dist/modules/export/index.d.cts +1 -1
- package/dist/modules/export/index.d.ts +1 -1
- package/dist/modules/export/index.js +1 -1
- package/dist/modules/files/index.cjs +5 -5
- package/dist/modules/files/index.d.cts +1 -1
- package/dist/modules/files/index.d.ts +1 -1
- package/dist/modules/files/index.js +1 -1
- package/dist/modules/groups/index.cjs +4 -4
- package/dist/modules/groups/index.d.cts +1 -1
- package/dist/modules/groups/index.d.ts +1 -1
- package/dist/modules/groups/index.js +1 -1
- package/dist/modules/health/index.d.cts +1 -1
- package/dist/modules/health/index.d.ts +1 -1
- package/dist/modules/integrations/index.cjs +4 -4
- package/dist/modules/integrations/index.d.cts +1 -1
- package/dist/modules/integrations/index.d.ts +1 -1
- package/dist/modules/integrations/index.js +1 -1
- package/dist/modules/notifications/index.d.cts +1 -1
- package/dist/modules/notifications/index.d.ts +1 -1
- package/dist/modules/notifications/index.js +1 -1
- package/dist/modules/organizations/index.cjs +4 -4
- package/dist/modules/organizations/index.d.cts +1 -1
- package/dist/modules/organizations/index.d.ts +1 -1
- package/dist/modules/organizations/index.js +1 -1
- package/dist/modules/products/index.cjs +8 -8
- package/dist/modules/products/index.d.cts +1 -1
- package/dist/modules/products/index.d.ts +1 -1
- package/dist/modules/products/index.js +1 -1
- package/dist/modules/rbac/index.cjs +3 -3
- package/dist/modules/rbac/index.d.cts +1 -1
- package/dist/modules/rbac/index.d.ts +1 -1
- package/dist/modules/rbac/index.js +1 -1
- package/dist/modules/sandbox/index.d.cts +1 -1
- package/dist/modules/sandbox/index.d.ts +1 -1
- package/dist/modules/sandbox/index.js +1 -1
- package/dist/modules/scheduler/index.cjs +10 -10
- package/dist/modules/scheduler/index.d.cts +1 -1
- package/dist/modules/scheduler/index.d.ts +1 -1
- package/dist/modules/scheduler/index.js +1 -1
- package/dist/modules/security/index.cjs +7 -7
- package/dist/modules/security/index.d.cts +1 -1
- package/dist/modules/security/index.d.ts +1 -1
- package/dist/modules/security/index.js +1 -1
- package/dist/modules/store/index.cjs +2 -2
- package/dist/modules/store/index.d.cts +1 -1
- package/dist/modules/store/index.d.ts +1 -1
- package/dist/modules/store/index.js +1 -1
- package/dist/modules/support/index.cjs +2 -2
- package/dist/modules/support/index.d.cts +1 -1
- package/dist/modules/support/index.d.ts +1 -1
- package/dist/modules/support/index.js +1 -1
- package/dist/modules/tags/index.cjs +2 -2
- package/dist/modules/tags/index.d.cts +1 -1
- package/dist/modules/tags/index.d.ts +1 -1
- package/dist/modules/tags/index.js +1 -1
- package/dist/modules/tours/index.cjs +2 -2
- package/dist/modules/tours/index.d.cts +1 -1
- package/dist/modules/tours/index.d.ts +1 -1
- package/dist/modules/tours/index.js +1 -1
- package/dist/modules/vibecontrols/index.cjs +51 -51
- package/dist/modules/vibecontrols/index.d.cts +1 -1
- package/dist/modules/vibecontrols/index.d.ts +1 -1
- package/dist/modules/vibecontrols/index.js +1 -1
- package/dist/modules/workspaces/index.cjs +10 -10
- package/dist/modules/workspaces/index.d.cts +1 -1
- package/dist/modules/workspaces/index.d.ts +1 -1
- package/dist/modules/workspaces/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-RNWXATAC.js +0 -32
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$1,o,p,q as q$1}from'./chunk-
|
|
1
|
+
import {b as b$1,o,p,q as q$1}from'./chunk-TCBALVP4.js';var r=null;function T(t){r=t;}function e(){if(!r)throw new q$1("vibecontrols module helpers used before setHelpersContext was called");return r}function c(){let t=e();if(!t.auth.isAuthenticated())throw new p(`Authentication required. Run \`${t.productName} auth login\`.`)}async function q(t,n){return c(),e().gql.workspace.request(t,n)}async function w(t,n){return e().gql.global.request(t,n)}async function b(t,n){return e().gql.global.request(t,n)}function A(){e().gql.reset();}function v(t){let n=t instanceof Error?t.message:String(t);throw new o(n)}function I(t,n,p){e().output.formatAndOutput(t,n,p);}function k(t){e().output.printSuccess(t);}function E(t){e().output.printError(t);}function O(t){e().output.printInfo(t);}function S(t){e().output.printWarning(t);}function D(t){e().output.printJson(t);}function y(t){return e().output.formatStatus(t)}function N(t){return e().output.formatDate(t)}function R(t,n){return e().output.truncate(t,n)}function W(t,n){return e().output.confirm(t,n)}function F(t,n){e().output.printTable(t,n);}function L(){return e()}function V(){return e().auth.read()}function P(t){e().auth.write(t);}function _(){e().auth.clear();}function K(){return e().config.read()}function G(t){return e().config.get(t)}function Y(t,n){e().config.set(t,n);}function j(){return e().config.path()}var H=b$1;function J(){return e().config.resolveOIDC()}function B(t){return t?t.expiresAt?Date.now()>=t.expiresAt:false:e().auth.isTokenExpired()}export{J as A,B,T as a,q as b,w as c,b as d,A as e,v as f,I as g,k as h,E as i,O as j,S as k,D as l,y as m,N as n,R as o,W as p,F as q,L as r,V as s,P as t,_ as u,K as v,G as w,Y as x,j as y,H as z};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {existsSync,readFileSync,writeFileSync,chmodSync,unlinkSync,mkdirSync}from'fs';import {join}from'path';import {homedir}from'os';import {GraphQLClient}from'graphql-request';import C from'cross-fetch';import {Command}from'commander';var W=300*1e3;function S(e){let n=join(e,"auth.json");function r(){existsSync(e)||mkdirSync(e,{recursive:true,mode:448});}function t(){try{if(!existsSync(n))return null;let s=readFileSync(n,"utf8");return JSON.parse(s)}catch{return null}}function a(s){r(),writeFileSync(n,JSON.stringify(s,null,2),{encoding:"utf8",mode:384});try{chmodSync(n,384);}catch{}}function i(){try{existsSync(n)&&unlinkSync(n);}catch{}}function o(){let s=t();return s?.expiresAt?Date.now()>=s.expiresAt:false}function c(){let s=t();return s?.expiresAt?Date.now()+W>=s.expiresAt:false}function p(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()>=s.workspaceTokenExpiresAt:false}function d(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()+W>=s.workspaceTokenExpiresAt:false}function b(){return t()?.accessToken?!o():false}return {read:t,write:a,clear:i,isTokenExpired:o,isTokenExpiringSoon:c,isWorkspaceTokenExpired:p,isWorkspaceTokenExpiringSoon:d,isAuthenticated:b}}var ae=["workspaceEndpoint","globalEndpoint","oidcIssuer","clientId","defaultFormat","verbose","authServiceEndpoint"];function O(e){let n=join(homedir(),".config",e.configDirName),r=join(n,"config.json"),t={workspaceEndpoint:e.workspaceEndpointDefault,globalEndpoint:e.globalEndpointDefault};function a(){existsSync(n)||mkdirSync(n,{recursive:true,mode:448});}function i(s){if(e.envPrefix){let u=process.env[`${e.envPrefix}_${s}`];if(u)return u}let l=process.env[s];return l&&l.length>0?l:void 0}function o(){let s={};try{existsSync(r)&&(s=JSON.parse(readFileSync(r,"utf8")));}catch{}return {...t,...s,workspaceEndpoint:i("WORKSPACE_ENDPOINT")??s.workspaceEndpoint??t.workspaceEndpoint,globalEndpoint:i("GLOBAL_ENDPOINT")??s.globalEndpoint??t.globalEndpoint,oidcIssuer:i("OIDC_ISSUER")??s.oidcIssuer,clientId:i("CLIENT_ID")??s.clientId}}function c(s){a(),writeFileSync(r,JSON.stringify(s,null,2),{encoding:"utf8"});try{chmodSync(r,384);}catch{}}function p(s){return o()[s]}function d(s,l){let u=o();u[s]=l,c(u);}function b(){let s=o(),l=s.clientId||e.oidcClientId,u=s.oidcIssuer;if(!u){let k=s.globalEndpoint;k.includes("localhost")||k.includes("127.0.0.1")?u=k.replace(/\/graphql$/,"").replace(/\/global\/graphql$/,"/global"):u=e.oidcIssuerProd??"https://graphql.burdenoff.com/global";}return {oidcIssuer:u,clientId:l}}return {read:o,write:c,get:p,set:d,path:()=>r,dir:()=>n,resolveOIDC:b}}async function ce(e){let n=`${e.oidcIssuer}/oidc/device/code`,r=new URLSearchParams({client_id:e.clientId,scope:"openid profile email offline_access"}),t=await C(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Device code request failed (${t.status}): ${i}`)}let a=await t.json();return {deviceCode:a.device_code,userCode:a.user_code,verificationUri:a.verification_uri,verificationUriComplete:a.verification_uri_complete??null,expiresIn:a.expires_in,interval:a.interval??5}}async function ue(e,n,r){let t=`${r.oidcIssuer}/oauth/device/token`,a=n;for(;;){await new Promise(p=>setTimeout(p,a*1e3));let i=await C(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e,client_id:r.clientId}).toString()}),o=await i.json();if(i.ok&&o.access_token)return {accessToken:o.access_token,refreshToken:o.refresh_token??"",expiresIn:o.expires_in??3600};let c=o.error;switch(c){case "authorization_pending":continue;case "slow_down":a+=5;continue;case "expired_token":throw new Error("Device code has expired. Please try again.");case "access_denied":throw new Error("Authorization was denied by the user.");default:throw new Error(`Device code polling failed: ${o.error_description??c??"Unknown error"}`)}}}async function $(e,n,r,t){let i=await C(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`
|
|
2
|
+
mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
3
|
+
authenticateApp(input: $input) {
|
|
4
|
+
accessToken tokenType expiresIn scopes
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
`,variables:{input:{clientId:n,clientSecret:r,scopes:t}}})});if(!i.ok){let c=await i.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${i.status}): ${c}`)}let o=await i.json();if(o.errors?.length)throw new Error(`App authentication failed: ${o.errors[0]?.message??"unknown error"}`);if(!o.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return o.data.authenticateApp}async function D(e,n,r,t){let i=await C(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
8
|
+
mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
9
|
+
issueWorkspaceToken(input: $input) {
|
|
10
|
+
success token expiresAt scopes
|
|
11
|
+
error { code message }
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`,variables:{input:{workspaceId:r,organizationId:t}}})});if(!i.ok){let p=await i.text().catch(()=>"Unknown error");throw new Error(`Workspace token request failed (${i.status}): ${p}`)}let o=await i.json();if(o.errors?.length)throw new Error(`Workspace token failed: ${o.errors[0]?.message??"unknown error"}`);let c=o.data?.issueWorkspaceToken;if(!c?.success||!c.token){let p=c?.error?.message??"Unknown error";throw new Error(`Workspace token failed: ${p}`)}return {token:c.token,expiresAt:c.expiresAt??"",scopes:c.scopes??[]}}async function le(e,n){let t=await C(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
15
|
+
query MyWorkspaces($limit: Int) {
|
|
16
|
+
myWorkspaces(limit: $limit) {
|
|
17
|
+
items { id name slug tenantId organizationId }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
`,variables:{limit:50}})});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${t.status}): ${i}`)}let a=await t.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function pe(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return false}}async function de(e){try{if(!pe(e))return !1;let{execFile:n}=await import('child_process'),r=process.platform,t,a;return r==="darwin"?(t="open",a=[e]):r==="win32"?(t="cmd",a=["/c","start","",e]):(t="xdg-open",a=[e]),new Promise(i=>{n(t,a,o=>{i(!o);});})}catch{return false}}var ge=3e4,U=3,fe=1e3;function me(e){return new Promise(n=>setTimeout(n,e))}function ke(e){if(e instanceof TypeError)return true;if(e&&typeof e=="object"&&"response"in e){let n=e.response;if(n&&typeof n.status=="number"&&n.status>=500)return true}return false}function B(e){if(e&&typeof e=="object"&&"response"in e){let n=e,r=n.response?.errors?.[0],t=r?.extensions?.originalError?.message;if(t)return t;if(r?.message)return r.message;if(n.message)return n.message}return e instanceof Error?e.message:String(e)}function v(e){let n={};return e?.accessToken&&(n.Authorization=`Bearer ${e.accessToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}function z(e){let n=v(e);return e?.workspaceToken&&(n["X-Workspace-Authorization"]=`Bearer ${e.workspaceToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}async function P(e,n,r){let t;for(let a=0;a<U;a++)try{let i=new AbortController,o=setTimeout(()=>i.abort(),ge);try{return await e.request({document:n,variables:r,signal:i.signal})}finally{clearTimeout(o);}}catch(i){if(t=i,i&&typeof i=="object"&&"response"in i){let o=i.response;if(o&&typeof o.status=="number"&&o.status>=400&&o.status<500)break}if(ke(i)&&a<U-1){let o=fe*Math.pow(2,a);await me(o);continue}break}throw new Error(B(t))}function L(e,n){let r=null,t=null;function a(){let s=e.read(),l=n.read();return r=new GraphQLClient(s.workspaceEndpoint),r.setHeaders(z(l)),t=new GraphQLClient(s.globalEndpoint),t.setHeaders(v(l)),{workspace:r,global:t}}async function i(){let s=n.read();if(!s)return;if(s.authMethod==="client_credentials"&&s.clientId&&s.clientSecret){let y=e.read();try{let w=await $(y.globalEndpoint,s.clientId,s.clientSecret);n.write({...s,accessToken:w.accessToken,expiresAt:Date.now()+w.expiresIn*1e3}),r=null,t=null;}catch{}return}if(!s.refreshToken)return;let l=e.read(),u=new GraphQLClient(l.globalEndpoint);u.setHeaders({Authorization:`Bearer ${s.accessToken}`});let k=`
|
|
21
|
+
mutation RefreshToken($token: String!) {
|
|
22
|
+
refreshToken(token: $token) {
|
|
23
|
+
accessToken
|
|
24
|
+
refreshToken
|
|
25
|
+
expiresIn
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
`;try{let w=(await u.request(k,{token:s.refreshToken})).refreshToken;n.write({...s,accessToken:w.accessToken,refreshToken:w.refreshToken,expiresAt:Date.now()+w.expiresIn*1e3}),r=null,t=null;}catch{}}async function o(){let s=n.read();if(!s?.accessToken||!s.workspaceId||!s.organizationId)return;let l=e.read();try{let u=await D(l.workspaceEndpoint,s.accessToken,s.workspaceId,s.organizationId);n.write({...s,workspaceToken:u.token,workspaceTokenExpiresAt:new Date(u.expiresAt).getTime()}),r=null;}catch{}}async function c(){n.isTokenExpiringSoon()&&await i(),n.read()?.workspaceToken&&n.isWorkspaceTokenExpiringSoon()&&await o();}return {workspace:{async request(s,l){await c();let{workspace:u}=r?{workspace:r}:a();return u.setHeaders(z(n.read())),P(u,s,l)}},global:{async request(s,l){let{global:u}=t?{global:t}:a();return u.setHeaders(v(n.read())),P(u,s,l)}},workspaceAuthOnly:{async request(s,l){let u=e.read(),k=n.read(),y=new GraphQLClient(u.workspaceEndpoint);return y.setHeaders(v(k)),P(y,s,l)}},reset(){r=null,t=null;}}}function _(){return !!(process.stdout.isTTY&&process.stdin.isTTY)}function H(e){if(e.format){let n=e.format.toLowerCase();if(n==="json"||n==="table"||n==="yaml")return n}return _()?"table":"json"}function R(e){console.log(JSON.stringify(e,null,2));}function V(e,n){if(e.length===0)return;let r=e.map((i,o)=>{let c=i.length;for(let p of n){let d=p[o]??"";d.length>c&&(c=d.length);}return Math.min(c,50)}),t=r.map(i=>"-".repeat(i+2)).join("+"),a=i=>i.map((o,c)=>` ${(o??"").padEnd(r[c]??0)} `).join("|");console.log(a(e)),console.log(t);for(let i of n)console.log(a(i));}function q(e,n){let r=" ".repeat(n),t=[];for(let[a,i]of Object.entries(e))if(i==null)t.push(`${r}${a}: null`);else if(Array.isArray(i)){t.push(`${r}${a}:`);for(let o of i)typeof o=="object"&&o!==null?(t.push(`${r} -`),t.push(q(o,n+2))):t.push(`${r} - ${String(o)}`);}else typeof i=="object"?(t.push(`${r}${a}:`),t.push(q(i,n+1))):t.push(`${r}${a}: ${String(i)}`);return t.join(`
|
|
29
|
+
`)}function J(e){if(typeof e!="object"||e===null){console.log(String(e));return}console.log(q(e,0));}function we(e){console.log(`\u2713 ${e}`);}function Y(e){console.error(`\u2717 ${e}`);}function he(e){console.warn(`! ${e}`);}function ye(e){console.log(`\u2139 ${e}`);}function Ce(e){if(!e)return "-";try{return new Date(e).toLocaleString()}catch{return e}}function xe(e){if(!e)return "-";switch(e.toUpperCase()){case "ACTIVE":case "RUNNING":case "HEALTHY":return `\u2713 ${e}`;case "INACTIVE":case "STOPPED":case "PENDING":return `\u25CB ${e}`;case "ERROR":return `\u2717 ${e}`;case "ARCHIVED":return `\u2192 ${e}`;case "STARTING":return `\u25B6 ${e}`;case "TERMINATED":return `\u25A0 ${e}`;default:return e}}function be(e,n){return e?e.length<=n?e:e.substring(0,n-3)+"...":"-"}function Te(e,n,r){switch(H(e)){case "json":R(n);break;case "yaml":J(n);break;case "table":r?V(r.headers,r.rows):R(n);break}}async function ve(e,n){return n?true:_()?new Promise(r=>{process.stdout.write(`${e} [y/N] `),process.stdin.setEncoding("utf8"),process.stdin.once("data",t=>{let a=t.trim().toLowerCase();r(a==="y"||a==="yes");}),process.stdin.resume();}):(Y(`${e} Use --force to skip confirmation.`),false)}var N={isInteractive:_,getFormat:H,formatAndOutput:Te,printJson:R,printTable:V,printYaml:J,printSuccess:we,printError:Y,printWarning:he,printInfo:ye,formatDate:Ce,formatStatus:xe,truncate:be,confirm:ve};function j(e={}){let{verbose:n=false,quiet:r=false}=e;return {debug(t,...a){n&&console.error(`[debug] ${t}`,...a);},info(t,...a){r||console.error(`[info] ${t}`,...a);},warn(t,...a){console.error(`[warn] ${t}`,...a);},error(t,...a){console.error(`[error] ${t}`,...a);}}}function Ee(e){return e.includes("localhost")||e.includes("127.0.0.1")?"local":e.includes("alpha")||e.includes("staging")?"staging":"prod"}function Ie(e){return !!e&&typeof e.debug=="function"&&typeof e.info=="function"}function Ae(e){let n=O(e.defaults),r=S(n.dir()),t=L(n,r),a=e.output??N,i=Ie(e.logger)?e.logger:j(e.logger),o=e.env??Ee(n.read().workspaceEndpoint);return {productName:e.productName,productVersion:e.productVersion,defaults:e.defaults,config:n,auth:r,gql:t,output:a,logger:i,env:o}}var h=class extends Error{exitCode;hint;constructor(n,r){super(n),this.name="CliUserError",this.exitCode=r?.exitCode??1,this.hint=r?.hint;}},x=class extends h{constructor(n,r){super(n,{exitCode:2,hint:r?.hint??"Run `<product> auth login` to authenticate."}),this.name="CliAuthError";}},m=class extends Error{cause;constructor(n,r){super(n),this.name="CliInternalError",this.cause=r;}};var E=class extends m{constructor(n,r){super(`Module '${n}' declares dependency on '${r}', but '${r}' is not in the module list.`),this.name="MissingDependencyError";}},I=class extends m{constructor(n){super(`Circular dependency detected among modules: ${n.join(" -> ")}`),this.name="CircularDependencyError";}};function F(e){let n=new Map;for(let o of e){if(n.has(o.id))throw new m(`Duplicate module id: '${o.id}'`);n.set(o.id,o);}for(let o of e)for(let c of o.dependsOn??[])if(!n.has(c))throw new E(o.id,c);let r=[],t=new Set,a=new Set;function i(o,c){if(!a.has(o.id)){if(t.has(o.id))throw new I([...c,o.id]);t.add(o.id);for(let p of o.dependsOn??[]){let d=n.get(p);d&&i(d,[...c,o.id]);}t.delete(o.id),a.add(o.id),r.push(o);}}for(let o of e)i(o,[]);return r}function Oe(e,n,r){let t=new Command;t.name(r.name).description(r.description??"").version(r.version,"-v, --version").option("-f, --format <format>","Output format (json, table, yaml)").option("--verbose","Enable verbose logging").option("--no-color","Disable colored output");let a=F(n);for(let o of a)o.register(t,e);r.helpExamples?.length&&t.addHelpText("after",`
|
|
30
|
+
Examples:
|
|
31
|
+
`+r.helpExamples.map(o=>" "+o).join(`
|
|
32
|
+
`)),t.on("command:*",()=>{e.output.printError(`Invalid command: ${t.args.join(" ")}`),e.output.printInfo(`Run \`${r.name} --help\` for available commands.`),process.exit(1);});async function i(o=process.argv){try{await t.parseAsync(o),o.length<=2&&t.outputHelp();}catch(c){$e(e,c);}}return {program:t,run:i}}function $e(e,n){if(n instanceof x&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof h&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof m&&(e.output.printError(`Internal error: ${n.message}`),n.cause&&e.logger.debug("caused by:",n.cause),process.exit(70)),n&&typeof n=="object"&&"code"in n&&"exitCode"in n){let t=n.exitCode;process.exit(typeof t=="number"?t:0);}let r=n instanceof Error?n.message:String(n);e.output.printError(r),process.exit(1);}export{S as a,ae as b,O as c,ce as d,ue as e,$ as f,D as g,le as h,de as i,B as j,L as k,N as l,j as m,Ae as n,h as o,x as p,m as q,E as r,I as s,F as t,Oe as u};
|
package/dist/core/index.cjs
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
'use strict';var fs=require('fs'),path=require('path'),os=require('os'),graphqlRequest=require('graphql-request'),y=require('cross-fetch'),commander=require('commander');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var
|
|
1
|
+
'use strict';var fs=require('fs'),path=require('path'),os=require('os'),graphqlRequest=require('graphql-request'),y=require('cross-fetch'),commander=require('commander');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var F=300*1e3;function A(e){let n=path.join(e,"auth.json");function r(){fs.existsSync(e)||fs.mkdirSync(e,{recursive:true,mode:448});}function t(){try{if(!fs.existsSync(n))return null;let s=fs.readFileSync(n,"utf8");return JSON.parse(s)}catch{return null}}function a(s){r(),fs.writeFileSync(n,JSON.stringify(s,null,2),{encoding:"utf8",mode:384});try{fs.chmodSync(n,384);}catch{}}function i(){try{fs.existsSync(n)&&fs.unlinkSync(n);}catch{}}function o(){let s=t();return s?.expiresAt?Date.now()>=s.expiresAt:false}function c(){let s=t();return s?.expiresAt?Date.now()+F>=s.expiresAt:false}function p(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()>=s.workspaceTokenExpiresAt:false}function d(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()+F>=s.workspaceTokenExpiresAt:false}function x(){return t()?.accessToken?!o():false}return {read:t,write:a,clear:i,isTokenExpired:o,isTokenExpiringSoon:c,isWorkspaceTokenExpired:p,isWorkspaceTokenExpiringSoon:d,isAuthenticated:x}}var ie=["workspaceEndpoint","globalEndpoint","oidcIssuer","clientId","defaultFormat","verbose","authServiceEndpoint"];function S(e){let n=path.join(os.homedir(),".config",e.configDirName),r=path.join(n,"config.json"),t={workspaceEndpoint:e.workspaceEndpointDefault,globalEndpoint:e.globalEndpointDefault};function a(){fs.existsSync(n)||fs.mkdirSync(n,{recursive:true,mode:448});}function i(s){if(e.envPrefix){let u=process.env[`${e.envPrefix}_${s}`];if(u)return u}let l=process.env[s];return l&&l.length>0?l:void 0}function o(){let s={};try{fs.existsSync(r)&&(s=JSON.parse(fs.readFileSync(r,"utf8")));}catch{}return {...t,...s,workspaceEndpoint:i("WORKSPACE_ENDPOINT")??s.workspaceEndpoint??t.workspaceEndpoint,globalEndpoint:i("GLOBAL_ENDPOINT")??s.globalEndpoint??t.globalEndpoint,oidcIssuer:i("OIDC_ISSUER")??s.oidcIssuer,clientId:i("CLIENT_ID")??s.clientId}}function c(s){a(),fs.writeFileSync(r,JSON.stringify(s,null,2),{encoding:"utf8"});try{fs.chmodSync(r,384);}catch{}}function p(s){return o()[s]}function d(s,l){let u=o();u[s]=l,c(u);}function x(){let s=o(),l=s.clientId||e.oidcClientId,u=s.oidcIssuer;if(!u){let m=s.globalEndpoint;m.includes("localhost")||m.includes("127.0.0.1")?u=m.replace(/\/graphql$/,"").replace(/\/global\/graphql$/,"/global"):u=e.oidcIssuerProd??"https://graphql.burdenoff.com/global";}return {oidcIssuer:u,clientId:l}}return {read:o,write:c,get:p,set:d,path:()=>r,dir:()=>n,resolveOIDC:x}}async function ae(e){let n=`${e.oidcIssuer}/oidc/device/code`,r=new URLSearchParams({client_id:e.clientId,scope:"openid profile email offline_access"}),t=await y__default.default(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Device code request failed (${t.status}): ${i}`)}let a=await t.json();return {deviceCode:a.device_code,userCode:a.user_code,verificationUri:a.verification_uri,verificationUriComplete:a.verification_uri_complete??null,expiresIn:a.expires_in,interval:a.interval??5}}async function ce(e,n,r){let t=`${r.oidcIssuer}/oauth/device/token`,a=n;for(;;){await new Promise(p=>setTimeout(p,a*1e3));let i=await y__default.default(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e,client_id:r.clientId}).toString()}),o=await i.json();if(i.ok&&o.access_token)return {accessToken:o.access_token,refreshToken:o.refresh_token??"",expiresIn:o.expires_in??3600};let c=o.error;switch(c){case "authorization_pending":continue;case "slow_down":a+=5;continue;case "expired_token":throw new Error("Device code has expired. Please try again.");case "access_denied":throw new Error("Authorization was denied by the user.");default:throw new Error(`Device code polling failed: ${o.error_description??c??"Unknown error"}`)}}}async function O(e,n,r,t){let i=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`
|
|
2
2
|
mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
3
3
|
authenticateApp(input: $input) {
|
|
4
4
|
accessToken tokenType expiresIn scopes
|
|
5
5
|
}
|
|
6
6
|
}
|
|
7
|
-
`,variables:{input:{clientId:n,clientSecret:r,scopes:t}}})});if(!
|
|
7
|
+
`,variables:{input:{clientId:n,clientSecret:r,scopes:t}}})});if(!i.ok){let c=await i.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${i.status}): ${c}`)}let o=await i.json();if(o.errors?.length)throw new Error(`App authentication failed: ${o.errors[0]?.message??"unknown error"}`);if(!o.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return o.data.authenticateApp}async function $(e,n,r,t){let i=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
8
8
|
mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
9
9
|
issueWorkspaceToken(input: $input) {
|
|
10
10
|
success token expiresAt scopes
|
|
11
11
|
error { code message }
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
`,variables:{input:{workspaceId:r,organizationId:t}}})});if(!
|
|
14
|
+
`,variables:{input:{workspaceId:r,organizationId:t}}})});if(!i.ok){let p=await i.text().catch(()=>"Unknown error");throw new Error(`Workspace token request failed (${i.status}): ${p}`)}let o=await i.json();if(o.errors?.length)throw new Error(`Workspace token failed: ${o.errors[0]?.message??"unknown error"}`);let c=o.data?.issueWorkspaceToken;if(!c?.success||!c.token){let p=c?.error?.message??"Unknown error";throw new Error(`Workspace token failed: ${p}`)}return {token:c.token,expiresAt:c.expiresAt??"",scopes:c.scopes??[]}}async function ue(e,n){let t=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
15
15
|
query MyWorkspaces($limit: Int) {
|
|
16
16
|
myWorkspaces(limit: $limit) {
|
|
17
17
|
items { id name slug tenantId organizationId }
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
-
`,variables:{limit:50}})});if(!t.ok){let
|
|
20
|
+
`,variables:{limit:50}})});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${t.status}): ${i}`)}let a=await t.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function le(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return false}}async function pe(e){try{if(!le(e))return !1;let{execFile:n}=await import('child_process'),r=process.platform,t,a;return r==="darwin"?(t="open",a=[e]):r==="win32"?(t="cmd",a=["/c","start","",e]):(t="xdg-open",a=[e]),new Promise(i=>{n(t,a,o=>{i(!o);});})}catch{return false}}var de=3e4,M=3,ge=1e3;function fe(e){return new Promise(n=>setTimeout(n,e))}function me(e){if(e instanceof TypeError)return true;if(e&&typeof e=="object"&&"response"in e){let n=e.response;if(n&&typeof n.status=="number"&&n.status>=500)return true}return false}function z(e){if(e&&typeof e=="object"&&"response"in e){let n=e,r=n.response?.errors?.[0],t=r?.extensions?.originalError?.message;if(t)return t;if(r?.message)return r.message;if(n.message)return n.message}return e instanceof Error?e.message:String(e)}function T(e){let n={};return e?.accessToken&&(n.Authorization=`Bearer ${e.accessToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}function U(e){let n=T(e);return e?.workspaceToken&&(n["X-Workspace-Authorization"]=`Bearer ${e.workspaceToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}async function D(e,n,r){let t;for(let a=0;a<M;a++)try{let i=new AbortController,o=setTimeout(()=>i.abort(),de);try{return await e.request({document:n,variables:r,signal:i.signal})}finally{clearTimeout(o);}}catch(i){if(t=i,i&&typeof i=="object"&&"response"in i){let o=i.response;if(o&&typeof o.status=="number"&&o.status>=400&&o.status<500)break}if(me(i)&&a<M-1){let o=ge*Math.pow(2,a);await fe(o);continue}break}throw new Error(z(t))}function P(e,n){let r=null,t=null;function a(){let s=e.read(),l=n.read();return r=new graphqlRequest.GraphQLClient(s.workspaceEndpoint),r.setHeaders(U(l)),t=new graphqlRequest.GraphQLClient(s.globalEndpoint),t.setHeaders(T(l)),{workspace:r,global:t}}async function i(){let s=n.read();if(!s)return;if(s.authMethod==="client_credentials"&&s.clientId&&s.clientSecret){let h=e.read();try{let k=await O(h.globalEndpoint,s.clientId,s.clientSecret);n.write({...s,accessToken:k.accessToken,expiresAt:Date.now()+k.expiresIn*1e3}),r=null,t=null;}catch{}return}if(!s.refreshToken)return;let l=e.read(),u=new graphqlRequest.GraphQLClient(l.globalEndpoint);u.setHeaders({Authorization:`Bearer ${s.accessToken}`});let m=`
|
|
21
21
|
mutation RefreshToken($token: String!) {
|
|
22
22
|
refreshToken(token: $token) {
|
|
23
23
|
accessToken
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
expiresIn
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`;try{let k=(await
|
|
29
|
-
`)}function V(e){if(typeof e!="object"||e===null){console.log(String(e));return}console.log(
|
|
28
|
+
`;try{let k=(await u.request(m,{token:s.refreshToken})).refreshToken;n.write({...s,accessToken:k.accessToken,refreshToken:k.refreshToken,expiresAt:Date.now()+k.expiresIn*1e3}),r=null,t=null;}catch{}}async function o(){let s=n.read();if(!s?.accessToken||!s.workspaceId||!s.organizationId)return;let l=e.read();try{let u=await $(l.workspaceEndpoint,s.accessToken,s.workspaceId,s.organizationId);n.write({...s,workspaceToken:u.token,workspaceTokenExpiresAt:new Date(u.expiresAt).getTime()}),r=null;}catch{}}async function c(){n.isTokenExpiringSoon()&&await i(),n.read()?.workspaceToken&&n.isWorkspaceTokenExpiringSoon()&&await o();}return {workspace:{async request(s,l){await c();let{workspace:u}=r?{workspace:r}:a();return u.setHeaders(U(n.read())),D(u,s,l)}},global:{async request(s,l){let{global:u}=t?{global:t}:a();return u.setHeaders(T(n.read())),D(u,s,l)}},workspaceAuthOnly:{async request(s,l){let u=e.read(),m=n.read(),h=new graphqlRequest.GraphQLClient(u.workspaceEndpoint);return h.setHeaders(T(m)),D(h,s,l)}},reset(){r=null,t=null;}}}function q(){return !!(process.stdout.isTTY&&process.stdin.isTTY)}function B(e){if(e.format){let n=e.format.toLowerCase();if(n==="json"||n==="table"||n==="yaml")return n}return q()?"table":"json"}function L(e){console.log(JSON.stringify(e,null,2));}function H(e,n){if(e.length===0)return;let r=e.map((i,o)=>{let c=i.length;for(let p of n){let d=p[o]??"";d.length>c&&(c=d.length);}return Math.min(c,50)}),t=r.map(i=>"-".repeat(i+2)).join("+"),a=i=>i.map((o,c)=>` ${(o??"").padEnd(r[c]??0)} `).join("|");console.log(a(e)),console.log(t);for(let i of n)console.log(a(i));}function R(e,n){let r=" ".repeat(n),t=[];for(let[a,i]of Object.entries(e))if(i==null)t.push(`${r}${a}: null`);else if(Array.isArray(i)){t.push(`${r}${a}:`);for(let o of i)typeof o=="object"&&o!==null?(t.push(`${r} -`),t.push(R(o,n+2))):t.push(`${r} - ${String(o)}`);}else typeof i=="object"?(t.push(`${r}${a}:`),t.push(R(i,n+1))):t.push(`${r}${a}: ${String(i)}`);return t.join(`
|
|
29
|
+
`)}function V(e){if(typeof e!="object"||e===null){console.log(String(e));return}console.log(R(e,0));}function ke(e){console.log(`\u2713 ${e}`);}function J(e){console.error(`\u2717 ${e}`);}function we(e){console.warn(`! ${e}`);}function he(e){console.log(`\u2139 ${e}`);}function ye(e){if(!e)return "-";try{return new Date(e).toLocaleString()}catch{return e}}function Ce(e){if(!e)return "-";switch(e.toUpperCase()){case "ACTIVE":case "RUNNING":case "HEALTHY":return `\u2713 ${e}`;case "INACTIVE":case "STOPPED":case "PENDING":return `\u25CB ${e}`;case "ERROR":return `\u2717 ${e}`;case "ARCHIVED":return `\u2192 ${e}`;case "STARTING":return `\u25B6 ${e}`;case "TERMINATED":return `\u25A0 ${e}`;default:return e}}function xe(e,n){return e?e.length<=n?e:e.substring(0,n-3)+"...":"-"}function be(e,n,r){switch(B(e)){case "json":L(n);break;case "yaml":V(n);break;case "table":r?H(r.headers,r.rows):L(n);break}}async function Te(e,n){return n?true:q()?new Promise(r=>{process.stdout.write(`${e} [y/N] `),process.stdin.setEncoding("utf8"),process.stdin.once("data",t=>{let a=t.trim().toLowerCase();r(a==="y"||a==="yes");}),process.stdin.resume();}):(J(`${e} Use --force to skip confirmation.`),false)}var _={isInteractive:q,getFormat:B,formatAndOutput:be,printJson:L,printTable:H,printYaml:V,printSuccess:ke,printError:J,printWarning:we,printInfo:he,formatDate:ye,formatStatus:Ce,truncate:xe,confirm:Te};function N(e={}){let{verbose:n=false,quiet:r=false}=e;return {debug(t,...a){n&&console.error(`[debug] ${t}`,...a);},info(t,...a){r||console.error(`[info] ${t}`,...a);},warn(t,...a){console.error(`[warn] ${t}`,...a);},error(t,...a){console.error(`[error] ${t}`,...a);}}}function ve(e){return e.includes("localhost")||e.includes("127.0.0.1")?"local":e.includes("alpha")||e.includes("staging")?"staging":"prod"}function Ee(e){return !!e&&typeof e.debug=="function"&&typeof e.info=="function"}function Ie(e){let n=S(e.defaults),r=A(n.dir()),t=P(n,r),a=e.output??_,i=Ee(e.logger)?e.logger:N(e.logger),o=e.env??ve(n.read().workspaceEndpoint);return {productName:e.productName,productVersion:e.productVersion,defaults:e.defaults,config:n,auth:r,gql:t,output:a,logger:i,env:o}}var w=class extends Error{exitCode;hint;constructor(n,r){super(n),this.name="CliUserError",this.exitCode=r?.exitCode??1,this.hint=r?.hint;}},C=class extends w{constructor(n,r){super(n,{exitCode:2,hint:r?.hint??"Run `<product> auth login` to authenticate."}),this.name="CliAuthError";}},f=class extends Error{cause;constructor(n,r){super(n),this.name="CliInternalError",this.cause=r;}};var v=class extends f{constructor(n,r){super(`Module '${n}' declares dependency on '${r}', but '${r}' is not in the module list.`),this.name="MissingDependencyError";}},E=class extends f{constructor(n){super(`Circular dependency detected among modules: ${n.join(" -> ")}`),this.name="CircularDependencyError";}};function j(e){let n=new Map;for(let o of e){if(n.has(o.id))throw new f(`Duplicate module id: '${o.id}'`);n.set(o.id,o);}for(let o of e)for(let c of o.dependsOn??[])if(!n.has(c))throw new v(o.id,c);let r=[],t=new Set,a=new Set;function i(o,c){if(!a.has(o.id)){if(t.has(o.id))throw new E([...c,o.id]);t.add(o.id);for(let p of o.dependsOn??[]){let d=n.get(p);d&&i(d,[...c,o.id]);}t.delete(o.id),a.add(o.id),r.push(o);}}for(let o of e)i(o,[]);return r}function Se(e,n,r){let t=new commander.Command;t.name(r.name).description(r.description??"").version(r.version,"-v, --version").option("-f, --format <format>","Output format (json, table, yaml)").option("--verbose","Enable verbose logging").option("--no-color","Disable colored output");let a=j(n);for(let o of a)o.register(t,e);r.helpExamples?.length&&t.addHelpText("after",`
|
|
30
30
|
Examples:
|
|
31
31
|
`+r.helpExamples.map(o=>" "+o).join(`
|
|
32
|
-
`)),t.on("command:*",()=>{e.output.printError(`Invalid command: ${t.args.join(" ")}`),e.output.printInfo(`Run \`${r.name} --help\` for available commands.`),process.exit(1);});async function
|
|
32
|
+
`)),t.on("command:*",()=>{e.output.printError(`Invalid command: ${t.args.join(" ")}`),e.output.printInfo(`Run \`${r.name} --help\` for available commands.`),process.exit(1);});async function i(o=process.argv){try{await t.parseAsync(o),o.length<=2&&t.outputHelp();}catch(c){Oe(e,c);}}return {program:t,run:i}}function Oe(e,n){if(n instanceof C&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof w&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof f&&(e.output.printError(`Internal error: ${n.message}`),n.cause&&e.logger.debug("caused by:",n.cause),process.exit(70)),n&&typeof n=="object"&&"code"in n&&"exitCode"in n){let t=n.exitCode;process.exit(typeof t=="number"?t:0);}let r=n instanceof Error?n.message:String(n);e.output.printError(r),process.exit(1);}exports.CircularDependencyError=E;exports.CliAuthError=C;exports.CliInternalError=f;exports.CliUserError=w;exports.KNOWN_CONFIG_KEYS=ie;exports.MissingDependencyError=v;exports.buildContext=Ie;exports.clientCredentialsFlow=O;exports.createAuthStore=A;exports.createConfigStore=S;exports.createGqlClients=P;exports.createLogger=N;exports.createProgram=Se;exports.defaultOutputAdapter=_;exports.extractGqlErrorMessage=z;exports.fetchWorkspaces=ue;exports.issueWorkspaceToken=$;exports.openBrowser=pe;exports.pollForToken=ce;exports.sortModules=j;exports.startDeviceCodeFlow=ae;
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as CLIContext, C as CliModule } from '../module-
|
|
2
|
-
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from '../module-
|
|
1
|
+
import { a as CLIContext, C as CliModule } from '../module-DxCuik6L.cjs';
|
|
2
|
+
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from '../module-DxCuik6L.cjs';
|
|
3
3
|
import { Command } from 'commander';
|
|
4
4
|
import 'graphql-request';
|
|
5
5
|
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as CLIContext, C as CliModule } from '../module-
|
|
2
|
-
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from '../module-
|
|
1
|
+
import { a as CLIContext, C as CliModule } from '../module-DxCuik6L.js';
|
|
2
|
+
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from '../module-DxCuik6L.js';
|
|
3
3
|
import { Command } from 'commander';
|
|
4
4
|
import 'graphql-request';
|
|
5
5
|
|
package/dist/core/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as CircularDependencyError,p as CliAuthError,q as CliInternalError,o as CliUserError,b as KNOWN_CONFIG_KEYS,r as MissingDependencyError,n as buildContext,f as clientCredentialsFlow,a as createAuthStore,c as createConfigStore,k as createGqlClients,m as createLogger,u as createProgram,l as defaultOutputAdapter,j as extractGqlErrorMessage,h as fetchWorkspaces,g as issueWorkspaceToken,i as openBrowser,e as pollForToken,t as sortModules,d as startDeviceCodeFlow}from'../chunk-
|
|
1
|
+
export{s as CircularDependencyError,p as CliAuthError,q as CliInternalError,o as CliUserError,b as KNOWN_CONFIG_KEYS,r as MissingDependencyError,n as buildContext,f as clientCredentialsFlow,a as createAuthStore,c as createConfigStore,k as createGqlClients,m as createLogger,u as createProgram,l as defaultOutputAdapter,j as extractGqlErrorMessage,h as fetchWorkspaces,g as issueWorkspaceToken,i as openBrowser,e as pollForToken,t as sortModules,d as startDeviceCodeFlow}from'../chunk-TCBALVP4.js';
|
package/dist/index.cjs
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
'use strict';var fs=require('fs'),path=require('path'),os=require('os'),graphqlRequest=require('graphql-request'),y=require('cross-fetch'),commander=require('commander');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var
|
|
1
|
+
'use strict';var fs=require('fs'),path=require('path'),os=require('os'),graphqlRequest=require('graphql-request'),y=require('cross-fetch'),commander=require('commander');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var F=300*1e3;function A(e){let n=path.join(e,"auth.json");function r(){fs.existsSync(e)||fs.mkdirSync(e,{recursive:true,mode:448});}function t(){try{if(!fs.existsSync(n))return null;let s=fs.readFileSync(n,"utf8");return JSON.parse(s)}catch{return null}}function a(s){r(),fs.writeFileSync(n,JSON.stringify(s,null,2),{encoding:"utf8",mode:384});try{fs.chmodSync(n,384);}catch{}}function i(){try{fs.existsSync(n)&&fs.unlinkSync(n);}catch{}}function o(){let s=t();return s?.expiresAt?Date.now()>=s.expiresAt:false}function c(){let s=t();return s?.expiresAt?Date.now()+F>=s.expiresAt:false}function p(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()>=s.workspaceTokenExpiresAt:false}function g(){let s=t();return s?.workspaceTokenExpiresAt?Date.now()+F>=s.workspaceTokenExpiresAt:false}function x(){return t()?.accessToken?!o():false}return {read:t,write:a,clear:i,isTokenExpired:o,isTokenExpiringSoon:c,isWorkspaceTokenExpired:p,isWorkspaceTokenExpiringSoon:g,isAuthenticated:x}}var ie=["workspaceEndpoint","globalEndpoint","oidcIssuer","clientId","defaultFormat","verbose","authServiceEndpoint"];function S(e){let n=path.join(os.homedir(),".config",e.configDirName),r=path.join(n,"config.json"),t={workspaceEndpoint:e.workspaceEndpointDefault,globalEndpoint:e.globalEndpointDefault};function a(){fs.existsSync(n)||fs.mkdirSync(n,{recursive:true,mode:448});}function i(s){if(e.envPrefix){let u=process.env[`${e.envPrefix}_${s}`];if(u)return u}let l=process.env[s];return l&&l.length>0?l:void 0}function o(){let s={};try{fs.existsSync(r)&&(s=JSON.parse(fs.readFileSync(r,"utf8")));}catch{}return {...t,...s,workspaceEndpoint:i("WORKSPACE_ENDPOINT")??s.workspaceEndpoint??t.workspaceEndpoint,globalEndpoint:i("GLOBAL_ENDPOINT")??s.globalEndpoint??t.globalEndpoint,oidcIssuer:i("OIDC_ISSUER")??s.oidcIssuer,clientId:i("CLIENT_ID")??s.clientId}}function c(s){a(),fs.writeFileSync(r,JSON.stringify(s,null,2),{encoding:"utf8"});try{fs.chmodSync(r,384);}catch{}}function p(s){return o()[s]}function g(s,l){let u=o();u[s]=l,c(u);}function x(){let s=o(),l=s.clientId||e.oidcClientId,u=s.oidcIssuer;if(!u){let m=s.globalEndpoint;m.includes("localhost")||m.includes("127.0.0.1")?u=m.replace(/\/graphql$/,"").replace(/\/global\/graphql$/,"/global"):u=e.oidcIssuerProd??"https://graphql.burdenoff.com/global";}return {oidcIssuer:u,clientId:l}}return {read:o,write:c,get:p,set:g,path:()=>r,dir:()=>n,resolveOIDC:x}}async function ae(e){let n=`${e.oidcIssuer}/oidc/device/code`,r=new URLSearchParams({client_id:e.clientId,scope:"openid profile email offline_access"}),t=await y__default.default(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Device code request failed (${t.status}): ${i}`)}let a=await t.json();return {deviceCode:a.device_code,userCode:a.user_code,verificationUri:a.verification_uri,verificationUriComplete:a.verification_uri_complete??null,expiresIn:a.expires_in,interval:a.interval??5}}async function ce(e,n,r){let t=`${r.oidcIssuer}/oauth/device/token`,a=n;for(;;){await new Promise(p=>setTimeout(p,a*1e3));let i=await y__default.default(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e,client_id:r.clientId}).toString()}),o=await i.json();if(i.ok&&o.access_token)return {accessToken:o.access_token,refreshToken:o.refresh_token??"",expiresIn:o.expires_in??3600};let c=o.error;switch(c){case "authorization_pending":continue;case "slow_down":a+=5;continue;case "expired_token":throw new Error("Device code has expired. Please try again.");case "access_denied":throw new Error("Authorization was denied by the user.");default:throw new Error(`Device code polling failed: ${o.error_description??c??"Unknown error"}`)}}}async function O(e,n,r,t){let i=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`
|
|
2
2
|
mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
3
3
|
authenticateApp(input: $input) {
|
|
4
4
|
accessToken tokenType expiresIn scopes
|
|
5
5
|
}
|
|
6
6
|
}
|
|
7
|
-
`,variables:{input:{clientId:n,clientSecret:r,scopes:t}}})});if(!
|
|
7
|
+
`,variables:{input:{clientId:n,clientSecret:r,scopes:t}}})});if(!i.ok){let c=await i.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${i.status}): ${c}`)}let o=await i.json();if(o.errors?.length)throw new Error(`App authentication failed: ${o.errors[0]?.message??"unknown error"}`);if(!o.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return o.data.authenticateApp}async function $(e,n,r,t){let i=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
8
8
|
mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
9
9
|
issueWorkspaceToken(input: $input) {
|
|
10
10
|
success token expiresAt scopes
|
|
11
11
|
error { code message }
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
`,variables:{input:{workspaceId:r,organizationId:t}}})});if(!
|
|
14
|
+
`,variables:{input:{workspaceId:r,organizationId:t}}})});if(!i.ok){let p=await i.text().catch(()=>"Unknown error");throw new Error(`Workspace token request failed (${i.status}): ${p}`)}let o=await i.json();if(o.errors?.length)throw new Error(`Workspace token failed: ${o.errors[0]?.message??"unknown error"}`);let c=o.data?.issueWorkspaceToken;if(!c?.success||!c.token){let p=c?.error?.message??"Unknown error";throw new Error(`Workspace token failed: ${p}`)}return {token:c.token,expiresAt:c.expiresAt??"",scopes:c.scopes??[]}}async function ue(e,n){let t=await y__default.default(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({query:`
|
|
15
15
|
query MyWorkspaces($limit: Int) {
|
|
16
16
|
myWorkspaces(limit: $limit) {
|
|
17
17
|
items { id name slug tenantId organizationId }
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
-
`,variables:{limit:50}})});if(!t.ok){let
|
|
20
|
+
`,variables:{limit:50}})});if(!t.ok){let i=await t.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${t.status}): ${i}`)}let a=await t.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function le(e){try{let n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return false}}async function pe(e){try{if(!le(e))return !1;let{execFile:n}=await import('child_process'),r=process.platform,t,a;return r==="darwin"?(t="open",a=[e]):r==="win32"?(t="cmd",a=["/c","start","",e]):(t="xdg-open",a=[e]),new Promise(i=>{n(t,a,o=>{i(!o);});})}catch{return false}}var de=3e4,M=3,ge=1e3;function fe(e){return new Promise(n=>setTimeout(n,e))}function me(e){if(e instanceof TypeError)return true;if(e&&typeof e=="object"&&"response"in e){let n=e.response;if(n&&typeof n.status=="number"&&n.status>=500)return true}return false}function z(e){if(e&&typeof e=="object"&&"response"in e){let n=e,r=n.response?.errors?.[0],t=r?.extensions?.originalError?.message;if(t)return t;if(r?.message)return r.message;if(n.message)return n.message}return e instanceof Error?e.message:String(e)}function T(e){let n={};return e?.accessToken&&(n.Authorization=`Bearer ${e.accessToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}function U(e){let n=T(e);return e?.workspaceToken&&(n["X-Workspace-Authorization"]=`Bearer ${e.workspaceToken}`),e?.organizationId&&(n["x-org-id"]=e.organizationId),n}async function D(e,n,r){let t;for(let a=0;a<M;a++)try{let i=new AbortController,o=setTimeout(()=>i.abort(),de);try{return await e.request({document:n,variables:r,signal:i.signal})}finally{clearTimeout(o);}}catch(i){if(t=i,i&&typeof i=="object"&&"response"in i){let o=i.response;if(o&&typeof o.status=="number"&&o.status>=400&&o.status<500)break}if(me(i)&&a<M-1){let o=ge*Math.pow(2,a);await fe(o);continue}break}throw new Error(z(t))}function P(e,n){let r=null,t=null;function a(){let s=e.read(),l=n.read();return r=new graphqlRequest.GraphQLClient(s.workspaceEndpoint),r.setHeaders(U(l)),t=new graphqlRequest.GraphQLClient(s.globalEndpoint),t.setHeaders(T(l)),{workspace:r,global:t}}async function i(){let s=n.read();if(!s)return;if(s.authMethod==="client_credentials"&&s.clientId&&s.clientSecret){let h=e.read();try{let k=await O(h.globalEndpoint,s.clientId,s.clientSecret);n.write({...s,accessToken:k.accessToken,expiresAt:Date.now()+k.expiresIn*1e3}),r=null,t=null;}catch{}return}if(!s.refreshToken)return;let l=e.read(),u=new graphqlRequest.GraphQLClient(l.globalEndpoint);u.setHeaders({Authorization:`Bearer ${s.accessToken}`});let m=`
|
|
21
21
|
mutation RefreshToken($token: String!) {
|
|
22
22
|
refreshToken(token: $token) {
|
|
23
23
|
accessToken
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
expiresIn
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`;try{let k=(await
|
|
29
|
-
`)}function V(e){if(typeof e!="object"||e===null){console.log(String(e));return}console.log(
|
|
28
|
+
`;try{let k=(await u.request(m,{token:s.refreshToken})).refreshToken;n.write({...s,accessToken:k.accessToken,refreshToken:k.refreshToken,expiresAt:Date.now()+k.expiresIn*1e3}),r=null,t=null;}catch{}}async function o(){let s=n.read();if(!s?.accessToken||!s.workspaceId||!s.organizationId)return;let l=e.read();try{let u=await $(l.workspaceEndpoint,s.accessToken,s.workspaceId,s.organizationId);n.write({...s,workspaceToken:u.token,workspaceTokenExpiresAt:new Date(u.expiresAt).getTime()}),r=null;}catch{}}async function c(){n.isTokenExpiringSoon()&&await i(),n.read()?.workspaceToken&&n.isWorkspaceTokenExpiringSoon()&&await o();}return {workspace:{async request(s,l){await c();let{workspace:u}=r?{workspace:r}:a();return u.setHeaders(U(n.read())),D(u,s,l)}},global:{async request(s,l){let{global:u}=t?{global:t}:a();return u.setHeaders(T(n.read())),D(u,s,l)}},workspaceAuthOnly:{async request(s,l){let u=e.read(),m=n.read(),h=new graphqlRequest.GraphQLClient(u.workspaceEndpoint);return h.setHeaders(T(m)),D(h,s,l)}},reset(){r=null,t=null;}}}function q(){return !!(process.stdout.isTTY&&process.stdin.isTTY)}function B(e){if(e.format){let n=e.format.toLowerCase();if(n==="json"||n==="table"||n==="yaml")return n}return q()?"table":"json"}function L(e){console.log(JSON.stringify(e,null,2));}function H(e,n){if(e.length===0)return;let r=e.map((i,o)=>{let c=i.length;for(let p of n){let g=p[o]??"";g.length>c&&(c=g.length);}return Math.min(c,50)}),t=r.map(i=>"-".repeat(i+2)).join("+"),a=i=>i.map((o,c)=>` ${(o??"").padEnd(r[c]??0)} `).join("|");console.log(a(e)),console.log(t);for(let i of n)console.log(a(i));}function R(e,n){let r=" ".repeat(n),t=[];for(let[a,i]of Object.entries(e))if(i==null)t.push(`${r}${a}: null`);else if(Array.isArray(i)){t.push(`${r}${a}:`);for(let o of i)typeof o=="object"&&o!==null?(t.push(`${r} -`),t.push(R(o,n+2))):t.push(`${r} - ${String(o)}`);}else typeof i=="object"?(t.push(`${r}${a}:`),t.push(R(i,n+1))):t.push(`${r}${a}: ${String(i)}`);return t.join(`
|
|
29
|
+
`)}function V(e){if(typeof e!="object"||e===null){console.log(String(e));return}console.log(R(e,0));}function ke(e){console.log(`\u2713 ${e}`);}function J(e){console.error(`\u2717 ${e}`);}function we(e){console.warn(`! ${e}`);}function he(e){console.log(`\u2139 ${e}`);}function ye(e){if(!e)return "-";try{return new Date(e).toLocaleString()}catch{return e}}function Ce(e){if(!e)return "-";switch(e.toUpperCase()){case "ACTIVE":case "RUNNING":case "HEALTHY":return `\u2713 ${e}`;case "INACTIVE":case "STOPPED":case "PENDING":return `\u25CB ${e}`;case "ERROR":return `\u2717 ${e}`;case "ARCHIVED":return `\u2192 ${e}`;case "STARTING":return `\u25B6 ${e}`;case "TERMINATED":return `\u25A0 ${e}`;default:return e}}function xe(e,n){return e?e.length<=n?e:e.substring(0,n-3)+"...":"-"}function be(e,n,r){switch(B(e)){case "json":L(n);break;case "yaml":V(n);break;case "table":r?H(r.headers,r.rows):L(n);break}}async function Te(e,n){return n?true:q()?new Promise(r=>{process.stdout.write(`${e} [y/N] `),process.stdin.setEncoding("utf8"),process.stdin.once("data",t=>{let a=t.trim().toLowerCase();r(a==="y"||a==="yes");}),process.stdin.resume();}):(J(`${e} Use --force to skip confirmation.`),false)}var _={isInteractive:q,getFormat:B,formatAndOutput:be,printJson:L,printTable:H,printYaml:V,printSuccess:ke,printError:J,printWarning:we,printInfo:he,formatDate:ye,formatStatus:Ce,truncate:xe,confirm:Te};function N(e={}){let{verbose:n=false,quiet:r=false}=e;return {debug(t,...a){n&&console.error(`[debug] ${t}`,...a);},info(t,...a){r||console.error(`[info] ${t}`,...a);},warn(t,...a){console.error(`[warn] ${t}`,...a);},error(t,...a){console.error(`[error] ${t}`,...a);}}}function ve(e){return e.includes("localhost")||e.includes("127.0.0.1")?"local":e.includes("alpha")||e.includes("staging")?"staging":"prod"}function Ee(e){return !!e&&typeof e.debug=="function"&&typeof e.info=="function"}function Ie(e){let n=S(e.defaults),r=A(n.dir()),t=P(n,r),a=e.output??_,i=Ee(e.logger)?e.logger:N(e.logger),o=e.env??ve(n.read().workspaceEndpoint);return {productName:e.productName,productVersion:e.productVersion,defaults:e.defaults,config:n,auth:r,gql:t,output:a,logger:i,env:o}}var w=class extends Error{exitCode;hint;constructor(n,r){super(n),this.name="CliUserError",this.exitCode=r?.exitCode??1,this.hint=r?.hint;}},C=class extends w{constructor(n,r){super(n,{exitCode:2,hint:r?.hint??"Run `<product> auth login` to authenticate."}),this.name="CliAuthError";}},f=class extends Error{cause;constructor(n,r){super(n),this.name="CliInternalError",this.cause=r;}};var v=class extends f{constructor(n,r){super(`Module '${n}' declares dependency on '${r}', but '${r}' is not in the module list.`),this.name="MissingDependencyError";}},E=class extends f{constructor(n){super(`Circular dependency detected among modules: ${n.join(" -> ")}`),this.name="CircularDependencyError";}};function j(e){let n=new Map;for(let o of e){if(n.has(o.id))throw new f(`Duplicate module id: '${o.id}'`);n.set(o.id,o);}for(let o of e)for(let c of o.dependsOn??[])if(!n.has(c))throw new v(o.id,c);let r=[],t=new Set,a=new Set;function i(o,c){if(!a.has(o.id)){if(t.has(o.id))throw new E([...c,o.id]);t.add(o.id);for(let p of o.dependsOn??[]){let g=n.get(p);g&&i(g,[...c,o.id]);}t.delete(o.id),a.add(o.id),r.push(o);}}for(let o of e)i(o,[]);return r}function Se(e,n,r){let t=new commander.Command;t.name(r.name).description(r.description??"").version(r.version,"-v, --version").option("-f, --format <format>","Output format (json, table, yaml)").option("--verbose","Enable verbose logging").option("--no-color","Disable colored output");let a=j(n);for(let o of a)o.register(t,e);r.helpExamples?.length&&t.addHelpText("after",`
|
|
30
30
|
Examples:
|
|
31
31
|
`+r.helpExamples.map(o=>" "+o).join(`
|
|
32
|
-
`)),t.on("command:*",()=>{e.output.printError(`Invalid command: ${t.args.join(" ")}`),e.output.printInfo(`Run \`${r.name} --help\` for available commands.`),process.exit(1);});async function
|
|
32
|
+
`)),t.on("command:*",()=>{e.output.printError(`Invalid command: ${t.args.join(" ")}`),e.output.printInfo(`Run \`${r.name} --help\` for available commands.`),process.exit(1);});async function i(o=process.argv){try{await t.parseAsync(o),o.length<=2&&t.outputHelp();}catch(c){Oe(e,c);}}return {program:t,run:i}}function Oe(e,n){if(n instanceof C&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof w&&(e.output.printError(n.message),n.hint&&e.output.printInfo(n.hint),process.exit(n.exitCode)),n instanceof f&&(e.output.printError(`Internal error: ${n.message}`),n.cause&&e.logger.debug("caused by:",n.cause),process.exit(70)),n&&typeof n=="object"&&"code"in n&&"exitCode"in n){let t=n.exitCode;process.exit(typeof t=="number"?t:0);}let r=n instanceof Error?n.message:String(n);e.output.printError(r),process.exit(1);}exports.CircularDependencyError=E;exports.CliAuthError=C;exports.CliInternalError=f;exports.CliUserError=w;exports.KNOWN_CONFIG_KEYS=ie;exports.MissingDependencyError=v;exports.buildContext=Ie;exports.clientCredentialsFlow=O;exports.createAuthStore=A;exports.createConfigStore=S;exports.createGqlClients=P;exports.createLogger=N;exports.createProgram=Se;exports.defaultOutputAdapter=_;exports.extractGqlErrorMessage=z;exports.fetchWorkspaces=ue;exports.issueWorkspaceToken=$;exports.openBrowser=pe;exports.pollForToken=ce;exports.sortModules=j;exports.startDeviceCodeFlow=ae;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, a as CLIContext, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, C as CliModule, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from './module-
|
|
1
|
+
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, a as CLIContext, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, C as CliModule, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from './module-DxCuik6L.cjs';
|
|
2
2
|
export { ClientCredentialsResult, CreateProgramOptions, DeviceCodeResponse, DeviceCodeTokenResult, OIDCConfig, ProgramFactoryResult, clientCredentialsFlow, createProgram, fetchWorkspaces, issueWorkspaceToken, openBrowser, pollForToken, startDeviceCodeFlow } from './core/index.cjs';
|
|
3
3
|
import 'commander';
|
|
4
4
|
import 'graphql-request';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, a as CLIContext, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, C as CliModule, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from './module-
|
|
1
|
+
export { A as AuthStore, B as BuildContextOptions, b as CLIConfig, a as CLIContext, c as CircularDependencyError, d as CliAuthError, e as CliInternalError, C as CliModule, f as CliUserError, g as ConfigStore, E as Environment, G as GqlClient, h as GqlClients, K as KNOWN_CONFIG_KEYS, L as Logger, i as LoggerOptions, M as MissingDependencyError, O as OutputAdapter, j as OutputFormat, P as ProductDefaults, S as StoredAuth, T as TableConfig, k as buildContext, l as createAuthStore, m as createConfigStore, n as createGqlClients, o as createLogger, p as defaultOutputAdapter, q as extractGqlErrorMessage, s as sortModules } from './module-DxCuik6L.js';
|
|
2
2
|
export { ClientCredentialsResult, CreateProgramOptions, DeviceCodeResponse, DeviceCodeTokenResult, OIDCConfig, ProgramFactoryResult, clientCredentialsFlow, createProgram, fetchWorkspaces, issueWorkspaceToken, openBrowser, pollForToken, startDeviceCodeFlow } from './core/index.js';
|
|
3
3
|
import 'commander';
|
|
4
4
|
import 'graphql-request';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as CircularDependencyError,p as CliAuthError,q as CliInternalError,o as CliUserError,b as KNOWN_CONFIG_KEYS,r as MissingDependencyError,n as buildContext,f as clientCredentialsFlow,a as createAuthStore,c as createConfigStore,k as createGqlClients,m as createLogger,u as createProgram,l as defaultOutputAdapter,j as extractGqlErrorMessage,h as fetchWorkspaces,g as issueWorkspaceToken,i as openBrowser,e as pollForToken,t as sortModules,d as startDeviceCodeFlow}from'./chunk-
|
|
1
|
+
export{s as CircularDependencyError,p as CliAuthError,q as CliInternalError,o as CliUserError,b as KNOWN_CONFIG_KEYS,r as MissingDependencyError,n as buildContext,f as clientCredentialsFlow,a as createAuthStore,c as createConfigStore,k as createGqlClients,m as createLogger,u as createProgram,l as defaultOutputAdapter,j as extractGqlErrorMessage,h as fetchWorkspaces,g as issueWorkspaceToken,i as openBrowser,e as pollForToken,t as sortModules,d as startDeviceCodeFlow}from'./chunk-TCBALVP4.js';
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
accessToken tokenType expiresIn scopes
|
|
5
5
|
}
|
|
6
6
|
}
|
|
7
|
-
`,variables:{input:{clientId:s,clientSecret:i,scopes:r}}})});if(!p.ok){let u=await p.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${p.status}): ${u}`)}let c=await p.json();if(c.errors?.length)throw new Error(`App authentication failed: ${c.errors[0]?.message??"unknown error"}`);if(!c.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return c.data.authenticateApp}async function
|
|
7
|
+
`,variables:{input:{clientId:s,clientSecret:i,scopes:r}}})});if(!p.ok){let u=await p.text().catch(()=>"Unknown error");throw new Error(`App authentication failed (${p.status}): ${u}`)}let c=await p.json();if(c.errors?.length)throw new Error(`App authentication failed: ${c.errors[0]?.message??"unknown error"}`);if(!c.data?.authenticateApp?.accessToken)throw new Error("App authentication failed: no access token returned");return c.data.authenticateApp}async function v(n,s,i,r){let p=await Y__default.default(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:`
|
|
8
8
|
mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
9
9
|
issueWorkspaceToken(input: $input) {
|
|
10
10
|
success token expiresAt scopes
|
|
@@ -17,13 +17,13 @@
|
|
|
17
17
|
items { id name slug tenantId organizationId }
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
-
`,variables:{limit:50}})});if(!r.ok){let p=await r.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${r.status}): ${p}`)}let a=await r.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function fe(n){try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}async function rt(n){try{if(!fe(n))return !1;let{execFile:s}=await import('child_process'),i=process.platform,r,a;return i==="darwin"?(r="open",a=[n]):i==="win32"?(r="cmd",a=["/c","start","",n]):(r="xdg-open",a=[n]),new Promise(p=>{s(r,a,c=>{p(!c);});})}catch{return false}}var E=class extends Error{exitCode;hint;constructor(s,i){super(s),this.name="CliUserError",this.exitCode=i?.exitCode??1,this.hint=i?.hint;}};var k=class extends Error{cause;constructor(s,i){super(s),this.name="CliInternalError",this.cause=i;}};var St=null;function Ct(n){St=n;}function T(){if(!St)throw new k("vibecontrols module helpers used before setHelpersContext was called");return St}async function l(n,s){return T().gql.global.request(n,s)}async function Et(n,s){return T().gql.global.request(n,s)}function b(){T().gql.reset();}function d(n){let s=n instanceof Error?n.message:String(n);throw new E(s)}function g(n,s,i){T().output.formatAndOutput(n,s,i);}function I(n){T().output.printSuccess(n);}function x(n){T().output.printInfo(n);}function
|
|
20
|
+
`,variables:{limit:50}})});if(!r.ok){let p=await r.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch workspaces (${r.status}): ${p}`)}let a=await r.json();if(a.errors?.length)throw new Error(`Failed to fetch workspaces: ${a.errors[0]?.message??"unknown error"}`);return a.data?.myWorkspaces?.items??[]}function fe(n){try{let s=new URL(n);return s.protocol==="http:"||s.protocol==="https:"}catch{return false}}async function rt(n){try{if(!fe(n))return !1;let{execFile:s}=await import('child_process'),i=process.platform,r,a;return i==="darwin"?(r="open",a=[n]):i==="win32"?(r="cmd",a=["/c","start","",n]):(r="xdg-open",a=[n]),new Promise(p=>{s(r,a,c=>{p(!c);});})}catch{return false}}var E=class extends Error{exitCode;hint;constructor(s,i){super(s),this.name="CliUserError",this.exitCode=i?.exitCode??1,this.hint=i?.hint;}};var k=class extends Error{cause;constructor(s,i){super(s),this.name="CliInternalError",this.cause=i;}};var St=null;function Ct(n){St=n;}function T(){if(!St)throw new k("vibecontrols module helpers used before setHelpersContext was called");return St}async function l(n,s){return T().gql.global.request(n,s)}async function Et(n,s){return T().gql.global.request(n,s)}function b(){T().gql.reset();}function d(n){let s=n instanceof Error?n.message:String(n);throw new E(s)}function g(n,s,i){T().output.formatAndOutput(n,s,i);}function I(n){T().output.printSuccess(n);}function x(n){T().output.printInfo(n);}function R(n){T().output.printWarning(n);}function j(n){T().output.printJson(n);}function X(n){return T().output.formatStatus(n)}function h(n){return T().output.formatDate(n)}function q(n,s){return T().output.truncate(n,s)}function F(){return T().auth.read()}function N(n){T().auth.write(n);}function _t(){T().auth.clear();}function M(){return T().config.read()}function kt(){return T().config.resolveOIDC()}function bt(n){return n?n.expiresAt?Date.now()>=n.expiresAt:false:T().auth.isTokenExpired()}var Rt="mutation { signOut }",Pt=`
|
|
21
21
|
mutation RefreshToken($token: String!) {
|
|
22
22
|
refreshToken(token: $token) { accessToken refreshToken expiresIn }
|
|
23
23
|
}
|
|
24
|
-
`;function Wt(n){let s=n.command("auth").description("Authentication commands");s.command("login").description("Authenticate with VibeControls").option("--client-credentials","Authenticate as an app with client ID and secret").option("--workspace-id <id>","Workspace ID (for app auth)").action(async i=>{try{i.clientCredentials?await Oe(i.workspaceId):await he();}catch(r){d(r);}}),s.command("logout").description("Revoke tokens and clear stored auth").action(async()=>{try{if(F()?.accessToken)try{await Et(
|
|
24
|
+
`;function Wt(n){let s=n.command("auth").description("Authentication commands");s.command("login").description("Authenticate with VibeControls").option("--client-credentials","Authenticate as an app with client ID and secret").option("--workspace-id <id>","Workspace ID (for app auth)").action(async i=>{try{i.clientCredentials?await Oe(i.workspaceId):await he();}catch(r){d(r);}}),s.command("logout").description("Revoke tokens and clear stored auth").action(async()=>{try{if(F()?.accessToken)try{await Et(Rt);}catch{R("Server-side logout failed, clearing local tokens");}_t(),b(),I("Logged out successfully");}catch(i){d(i);}}),s.command("status").description("Show current auth state").option("-f, --format <format>","Output format (json, table)").action(i=>{let r=F(),a=M(),p=!!r?.accessToken,c=r?.accessToken?bt(r):false,u=r?.expiresAt?h(new Date(r.expiresAt).toISOString()):"-",m=r?.authMethod==="client_credentials"?"Client Credentials":"OAuth2 Device Code",t=r?.workspaceTokenExpiresAt?h(new Date(r.workspaceTokenExpiresAt).toISOString()):"-";g(i,{authenticated:p,method:m,expired:c,expiresAt:u,workspaceId:r?.workspaceId??"-",organizationId:r?.organizationId??"-",workspaceTokenExpiresAt:t,workspaceEndpoint:a.workspaceEndpoint,globalEndpoint:a.globalEndpoint},{headers:["Key","Value"],rows:[["Authenticated",String(p)],["Method",m],["Expired",String(c)],["Expires At",u],["Workspace ID",r?.workspaceId??"-"],["Organization ID",r?.organizationId??"-"],["Workspace Token Expires",t],["Workspace Endpoint",a.workspaceEndpoint],["Global Endpoint",a.globalEndpoint]]});}),s.command("token").description("Print access token to stdout").option("--workspace","Print workspace token instead").action(i=>{let r=F();if(i.workspace){if(!r?.workspaceToken)throw new E("No workspace token. Set a workspace: vibecontrols workspace set <id>");process.stdout.write(r.workspaceToken);return}if(!r?.accessToken)throw new E("Not authenticated. Run: vibecontrols auth login");process.stdout.write(r.accessToken);}),s.command("refresh").description("Force token refresh").action(async()=>{try{let i=F();if(!i?.refreshToken&&i?.authMethod!=="client_credentials")throw new E("No refresh token available. Run: vibecontrols auth login");if(i?.authMethod==="client_credentials"&&i.clientId&&i.clientSecret){let p=M(),c=await G(p.globalEndpoint,i.clientId,i.clientSecret);N({...i,accessToken:c.accessToken,expiresAt:Date.now()+c.expiresIn*1e3}),b(),I("App token refreshed successfully"),i.workspaceId&&i.organizationId&&await Ht();return}let a=(await Et(Pt,{token:i.refreshToken})).refreshToken;N({...i,accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3}),b(),I("Token refreshed successfully"),i.workspaceId&&i.organizationId&&await Ht();}catch(i){d(i);}});}async function Ht(){let n=F();if(!n?.accessToken||!n.workspaceId||!n.organizationId)return;let s=M();try{let i=await v(s.workspaceEndpoint,n.accessToken,n.workspaceId,n.organizationId);N({...n,workspaceToken:i.token,workspaceTokenExpiresAt:new Date(i.expiresAt).getTime()}),b(),I("Workspace token refreshed");}catch{R("Workspace token refresh failed \u2014 workspace operations may require re-login");}}async function he(){let n=M(),{oidcIssuer:s,clientId:i}=kt(),r={...n,oidcIssuer:s,clientId:i};x("Starting device code authentication...");let a=await ot(r);console.log(""),console.log(` Open: ${a.verificationUri}`),console.log(` Code: ${a.userCode}`),console.log(""),await rt(a.verificationUriComplete??a.verificationUri)?x("Browser opened"):R("Could not open browser \u2014 open the URL manually"),x("Waiting for authorization...");let c=await it(a.deviceCode,a.interval,r),u=c.accessToken,m=Date.now()+c.expiresIn*1e3;x("Fetching workspaces...");try{let t=await z(n.globalEndpoint,u);if(t.length===0){N({accessToken:u,refreshToken:c.refreshToken,expiresAt:m,authMethod:"device_code"}),b(),I("Authentication successful (no workspaces found)");return}let e=t[0];if(t.length>1){console.log(`
|
|
25
25
|
Available workspaces:`),t.forEach((nt,$t)=>console.log(` ${$t+1}. ${nt.name} (${nt.slug})`));let A=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),S=await new Promise(nt=>{A.question(`
|
|
26
|
-
Select workspace [1-${t.length}]: `,$t=>{A.close(),nt($t.trim());});}),O=parseInt(S,10)-1;O>=0&&O<t.length&&(e=t[O]);}x(`Using workspace: ${e.name} (${e.id})`);let o=await
|
|
26
|
+
Select workspace [1-${t.length}]: `,$t=>{A.close(),nt($t.trim());});}),O=parseInt(S,10)-1;O>=0&&O<t.length&&(e=t[O]);}x(`Using workspace: ${e.name} (${e.id})`);let o=await v(n.workspaceEndpoint,u,e.id,e.organizationId);N({accessToken:u,refreshToken:c.refreshToken,expiresAt:m,workspaceToken:o.token,workspaceTokenExpiresAt:new Date(o.expiresAt).getTime(),workspaceId:e.id,organizationId:e.organizationId,authMethod:"device_code"}),b(),I("Authentication successful");}catch(t){N({accessToken:u,refreshToken:c.refreshToken,expiresAt:m,authMethod:"device_code"}),b(),I("Authentication successful"),R(`Workspace token not obtained: ${t instanceof Error?t.message:String(t)}`),x("Set workspace manually: vibecontrols workspace set <id>");}}async function Oe(n){let s=M(),r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),a=await new Promise(A=>{r.question("Client ID: ",S=>A(S.trim()));}),p=await new Promise(A=>{r.question("Client Secret: ",S=>{r.close(),A(S.trim());});});if(!a||!p)throw new E("Client ID and secret cannot be empty");x("Authenticating app...");let c=await G(s.globalEndpoint,a,p),u=c.accessToken,m=Date.now()+c.expiresIn*1e3,t,e,o=n,$;if(o)try{let S=(await z(s.globalEndpoint,u)).find(O=>O.id===o);if(S){$=S.organizationId;let O=await v(s.workspaceEndpoint,u,o,$);t=O.token,e=new Date(O.expiresAt).getTime(),x(`Workspace token issued for: ${S.name}`);}else R(`Workspace ${o} not found \u2014 skipping workspace token`),o=void 0;}catch(A){R(`Workspace token failed: ${A instanceof Error?A.message:String(A)}`);}N({accessToken:u,refreshToken:"",expiresAt:m,workspaceToken:t,workspaceTokenExpiresAt:e,workspaceId:o,organizationId:$,authMethod:"client_credentials",clientId:a,clientSecret:p}),b(),I("App authentication successful");}var Yt=`
|
|
27
27
|
query currentUser {
|
|
28
28
|
currentUser {
|
|
29
29
|
id email firstName lastName username phoneNumber name
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {Lc,Mc}from'../../chunk-REBBLQFS.js';import {a,f,s,d,k,u,e,h,v,B,n,g,t,c,o as o$1,m,l,j,A}from'../../chunk-
|
|
1
|
+
import {Lc,Mc}from'../../chunk-REBBLQFS.js';import {a,f,s,d,k,u,e,h,v,B,n,g,t,c,o as o$1,m,l,j,A}from'../../chunk-LZQBJDKZ.js';import {q,o,f as f$1,h as h$1,g as g$1,d as d$1,i,e as e$1}from'../../chunk-TCBALVP4.js';function X(s$1){let u$1=s$1.command("auth").description("Authentication commands");u$1.command("login").description("Authenticate with VibeControls").option("--client-credentials","Authenticate as an app with client ID and secret").option("--workspace-id <id>","Workspace ID (for app auth)").action(async i=>{try{i.clientCredentials?await Ce(i.workspaceId):await Ue();}catch(r){f(r);}}),u$1.command("logout").description("Revoke tokens and clear stored auth").action(async()=>{try{if(s()?.accessToken)try{await d(Lc);}catch{k("Server-side logout failed, clearing local tokens");}u(),e(),h("Logged out successfully");}catch(i){f(i);}}),u$1.command("status").description("Show current auth state").option("-f, --format <format>","Output format (json, table)").action(i=>{let r=s(),p=v(),I=!!r?.accessToken,m=r?.accessToken?B(r):false,f=r?.expiresAt?n(new Date(r.expiresAt).toISOString()):"-",h=r?.authMethod==="client_credentials"?"Client Credentials":"OAuth2 Device Code",e=r?.workspaceTokenExpiresAt?n(new Date(r.workspaceTokenExpiresAt).toISOString()):"-";g(i,{authenticated:I,method:h,expired:m,expiresAt:f,workspaceId:r?.workspaceId??"-",organizationId:r?.organizationId??"-",workspaceTokenExpiresAt:e,workspaceEndpoint:p.workspaceEndpoint,globalEndpoint:p.globalEndpoint},{headers:["Key","Value"],rows:[["Authenticated",String(I)],["Method",h],["Expired",String(m)],["Expires At",f],["Workspace ID",r?.workspaceId??"-"],["Organization ID",r?.organizationId??"-"],["Workspace Token Expires",e],["Workspace Endpoint",p.workspaceEndpoint],["Global Endpoint",p.globalEndpoint]]});}),u$1.command("token").description("Print access token to stdout").option("--workspace","Print workspace token instead").action(i=>{let r=s();if(i.workspace){if(!r?.workspaceToken)throw new o("No workspace token. Set a workspace: vibecontrols workspace set <id>");process.stdout.write(r.workspaceToken);return}if(!r?.accessToken)throw new o("Not authenticated. Run: vibecontrols auth login");process.stdout.write(r.accessToken);}),u$1.command("refresh").description("Force token refresh").action(async()=>{try{let i=s();if(!i?.refreshToken&&i?.authMethod!=="client_credentials")throw new o("No refresh token available. Run: vibecontrols auth login");if(i?.authMethod==="client_credentials"&&i.clientId&&i.clientSecret){let I=v(),m=await f$1(I.globalEndpoint,i.clientId,i.clientSecret);t({...i,accessToken:m.accessToken,expiresAt:Date.now()+m.expiresIn*1e3}),e(),h("App token refreshed successfully"),i.workspaceId&&i.organizationId&&await J();return}let p=(await d(Mc,{token:i.refreshToken})).refreshToken;t({...i,accessToken:p.accessToken,refreshToken:p.refreshToken,expiresAt:Date.now()+p.expiresIn*1e3}),e(),h("Token refreshed successfully"),i.workspaceId&&i.organizationId&&await J();}catch(i){f(i);}});}async function J(){let s$1=s();if(!s$1?.accessToken||!s$1.workspaceId||!s$1.organizationId)return;let u=v();try{let i=await g$1(u.workspaceEndpoint,s$1.accessToken,s$1.workspaceId,s$1.organizationId);t({...s$1,workspaceToken:i.token,workspaceTokenExpiresAt:new Date(i.expiresAt).getTime()}),e(),h("Workspace token refreshed");}catch{k("Workspace token refresh failed \u2014 workspace operations may require re-login");}}async function Ue(){let s=v(),{oidcIssuer:u,clientId:i$1}=A(),r={...s,oidcIssuer:u,clientId:i$1};j("Starting device code authentication...");let p=await d$1(r);console.log(""),console.log(` Open: ${p.verificationUri}`),console.log(` Code: ${p.userCode}`),console.log(""),await i(p.verificationUriComplete??p.verificationUri)?j("Browser opened"):k("Could not open browser \u2014 open the URL manually"),j("Waiting for authorization...");let m=await e$1(p.deviceCode,p.interval,r),f=m.accessToken,h$2=Date.now()+m.expiresIn*1e3;j("Fetching workspaces...");try{let e$1=await h$1(s.globalEndpoint,f);if(e$1.length===0){t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,authMethod:"device_code"}),e(),h("Authentication successful (no workspaces found)");return}let t$1=e$1[0];if(e$1.length>1){console.log(`
|
|
2
2
|
Available workspaces:`),e$1.forEach((O,$)=>console.log(` ${$+1}. ${O.name} (${O.slug})`));let A=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),g=await new Promise(O=>{A.question(`
|
|
3
3
|
Select workspace [1-${e$1.length}]: `,$=>{A.close(),O($.trim());});}),S=parseInt(g,10)-1;S>=0&&S<e$1.length&&(t$1=e$1[S]);}j(`Using workspace: ${t$1.name} (${t$1.id})`);let n=await g$1(s.workspaceEndpoint,f,t$1.id,t$1.organizationId);t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,workspaceToken:n.token,workspaceTokenExpiresAt:new Date(n.expiresAt).getTime(),workspaceId:t$1.id,organizationId:t$1.organizationId,authMethod:"device_code"}),e(),h("Authentication successful");}catch(e$1){t({accessToken:f,refreshToken:m.refreshToken,expiresAt:h$2,authMethod:"device_code"}),e(),h("Authentication successful"),k(`Workspace token not obtained: ${e$1 instanceof Error?e$1.message:String(e$1)}`),j("Set workspace manually: vibecontrols workspace set <id>");}}async function Ce(s){let u=v(),r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(A=>{r.question("Client ID: ",g=>A(g.trim()));}),I=await new Promise(A=>{r.question("Client Secret: ",g=>{r.close(),A(g.trim());});});if(!p||!I)throw new o("Client ID and secret cannot be empty");j("Authenticating app...");let m=await f$1(u.globalEndpoint,p,I),f=m.accessToken,h$2=Date.now()+m.expiresIn*1e3,e$1,t$1,n=s,l;if(n)try{let g=(await h$1(u.globalEndpoint,f)).find(S=>S.id===n);if(g){l=g.organizationId;let S=await g$1(u.workspaceEndpoint,f,n,l);e$1=S.token,t$1=new Date(S.expiresAt).getTime(),j(`Workspace token issued for: ${g.name}`);}else k(`Workspace ${n} not found \u2014 skipping workspace token`),n=void 0;}catch(A){k(`Workspace token failed: ${A instanceof Error?A.message:String(A)}`);}t({accessToken:f,refreshToken:"",expiresAt:h$2,workspaceToken:e$1,workspaceTokenExpiresAt:t$1,workspaceId:n,organizationId:l,authMethod:"client_credentials",clientId:p,clientSecret:I}),e(),h("App authentication successful");}var Q=`
|
|
4
4
|
query currentUser {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';require('graphql-request'),require('cross-fetch'),require('commander');var p=class extends Error{exitCode;hint;constructor(i,d){super(i),this.name="CliUserError",this.exitCode=d?.exitCode??1,this.hint=d?.hint;}};var l=class extends Error{cause;constructor(i,d){super(i),this.name="CliInternalError",this.cause=d;}};var b=null;function
|
|
1
|
+
'use strict';require('graphql-request'),require('cross-fetch'),require('commander');var p=class extends Error{exitCode;hint;constructor(i,d){super(i),this.name="CliUserError",this.exitCode=d?.exitCode??1,this.hint=d?.hint;}};var l=class extends Error{cause;constructor(i,d){super(i),this.name="CliInternalError",this.cause=d;}};var b=null;function P(r){b=r;}function g(){if(!b)throw new l("vibecontrols module helpers used before setHelpersContext was called");return b}async function s(r,i){return g().gql.global.request(r,i)}function a(r){let i=r instanceof Error?r.message:String(r);throw new p(i)}function c(r,i,d){g().output.formatAndOutput(r,i,d);}function f(r){g().output.printSuccess(r);}function D(r){g().output.printInfo(r);}function I(r){return g().output.formatStatus(r)}function x(r){return g().output.formatDate(r)}function m(r,i){return g().output.truncate(r,i)}var k=`
|
|
2
2
|
query GetDefaultBillingAccount {
|
|
3
3
|
getDefaultBillingAccount {
|
|
4
4
|
id creditAmount currency
|
|
@@ -102,4 +102,4 @@
|
|
|
102
102
|
id name limits currentUsageSum reusable
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
|
-
`;async function w(){let r=await s(k);if(!r.getDefaultBillingAccount?.id)throw new p("No default billing account on file. Pass --account <id> explicitly.");return r.getDefaultBillingAccount.id}function z(r){let i=r.command("billing").description("Billing: subscriptions, invoices, credits"),d=i.command("subscriptions").description("Subscriptions");d.command("list").description("List active subscriptions").option("--account <id>","Billing account id (defaults to current)").option("-f, --format <format>").action(async t=>{try{let e=t.account??await w(),n=await s(O,{billingAccountId:e});c(t,n.getActiveSubscriptions,{headers:["ID","Status","Plan","Seats","NextBilling"],rows:n.getActiveSubscriptions.map(o=>[m(o.id,12),
|
|
105
|
+
`;async function w(){let r=await s(k);if(!r.getDefaultBillingAccount?.id)throw new p("No default billing account on file. Pass --account <id> explicitly.");return r.getDefaultBillingAccount.id}function z(r){let i=r.command("billing").description("Billing: subscriptions, invoices, credits"),d=i.command("subscriptions").description("Subscriptions");d.command("list").description("List active subscriptions").option("--account <id>","Billing account id (defaults to current)").option("-f, --format <format>").action(async t=>{try{let e=t.account??await w(),n=await s(O,{billingAccountId:e});c(t,n.getActiveSubscriptions,{headers:["ID","Status","Plan","Seats","NextBilling"],rows:n.getActiveSubscriptions.map(o=>[m(o.id,12),I(o.status),o.plan?.name??"-",String(o.seatCount??"-"),x(o.nextBillingDate)])});}catch(e){a(e);}}),d.command("get").description("Get a subscription").argument("<id>").option("-f, --format <format>").action(async(t,e)=>{try{let n=await s(R,{id:t});if(!n.getSubscription)throw new p(`Subscription ${t} not found`);c(e,n.getSubscription);}catch(n){a(n);}}),d.command("upgrade").description("Change subscription seat count").argument("<id>").requiredOption("--seats <n>","Target seat count",t=>parseInt(t,10)).option("-f, --format <format>").action(async(t,e)=>{try{let n={subscriptionId:t,seatCount:e.seats},o=await s(_,{input:n});f(`Seat count updated to ${o.updateSubscriptionSeats.seatCount}`),c(e,o.updateSubscriptionSeats);}catch(n){a(n);}}),d.command("cancel").description("Cancel a subscription").argument("<id>").option("--reason <s>").action(async(t,e)=>{try{let n={subscriptionId:t,reason:e.reason},o=await s($,{input:n});f("Subscription canceled"),c({},o.cancelSubscription);}catch(n){a(n);}});let T=i.command("plans").description("Plans");T.command("list").description("List available plans").option("--product <id>").option("-f, --format <format>").action(async t=>{try{let e={};t.product&&(e.productId=t.product);let n=await s(L,{filter:Object.keys(e).length?e:void 0});c(t,n.getAllPlans,{headers:["ID","Name","Price","Currency","Duration"],rows:n.getAllPlans.map(o=>[m(o.id,12),o.name,String(o.price??"-"),o.currency??"-",o.duration??"-"])});}catch(e){a(e);}}),T.command("get").description("Get a plan").argument("<id>").option("-f, --format <format>").action(async(t,e)=>{try{let n=await s(N,{id:t});if(!n.getPlan)throw new p(`Plan ${t} not found`);c(e,n.getPlan);}catch(n){a(n);}}),i.command("addons").description("Addons").command("list").description("List addons").option("--product <id>").option("--limit <n>","Page size",t=>parseInt(t,10),50).option("-f, --format <format>").action(async t=>{try{let e={};t.product&&(e.productId=t.product);let n=await s(q,{filter:Object.keys(e).length?e:void 0,limit:t.limit});c(t,n.getAllAddOns);}catch(e){a(e);}});let y=i.command("invoices").description("Invoices");y.command("list").description("List invoices").option("--account <id>").option("--page <n>","",t=>parseInt(t,10),1).option("--page-size <n>","",t=>parseInt(t,10),20).option("-f, --format <format>").action(async t=>{try{let e=t.account??await w(),n=await s(G,{billingAccountId:e,page:t.page,pageSize:t.pageSize});c(t,n.getPaginatedInvoices.invoices,{headers:["ID","#","Status","Total","Currency","Paid"],rows:n.getPaginatedInvoices.invoices.map(o=>[m(o.id,12),o.invoiceNumber??"-",I(o.status),String(o.total??"-"),o.currency??"-",x(o.paidAt)])});}catch(e){a(e);}}),y.command("get").description("Get an invoice").argument("<id>").option("-f, --format <format>").action(async(t,e)=>{try{let n=await s(A,{id:t});if(!n.getInvoice)throw new p(`Invoice ${t} not found`);c(e,n.getInvoice);}catch(n){a(n);}}),y.command("download").description("Print invoice PDF URL (browser-only download)").argument("<id>").action(async t=>{try{let e=await s(A,{id:t});if(!e.getInvoice?.pdfUrl)throw new p(`Invoice ${t} has no pdfUrl`);D("PDF URL:"),console.log(e.getInvoice.pdfUrl);}catch(e){a(e);}});let h=i.command("payment-methods").description("Payment methods");h.command("list").description("List payment methods").option("--account <id>").option("-f, --format <format>").action(async t=>{try{let e=t.account??await w(),n=await s(M,{billingAccountId:e});c(t,n.getPaymentMethods,{headers:["ID","Type","Brand","Last4","Default","Verified"],rows:n.getPaymentMethods.map(o=>[m(o.id,12),o.type,o.brand??"-",o.last4??"-",String(!!o.isDefault),String(!!o.isVerified)])});}catch(e){a(e);}}),h.command("add").description("Add a payment method (card metadata only \u2014 providers handle secrets)").requiredOption("--type <t>","CREDIT_CARD|BANK|UPI","CREDIT_CARD").requiredOption("--last4 <s>").option("--brand <s>","Visa|MasterCard|...").option("--expiry-month <n>","",t=>parseInt(t,10)).option("--expiry-year <n>","",t=>parseInt(t,10)).option("--account <id>").option("--default","Make it the default").option("-f, --format <format>").action(async t=>{try{let n={billingAccountId:t.account??await w(),type:t.type.toUpperCase(),last4:t.last4,brand:t.brand,expiryMonth:t.expiryMonth,expiryYear:t.expiryYear,isDefault:!!t.default},o=await s(U,{input:n});f("Payment method added"),c(t,o.addPaymentMethod);}catch(e){a(e);}}),h.command("remove").description("Remove a payment method").argument("<id>").action(async t=>{try{await s(F,{id:t}),f("Payment method removed");}catch(e){a(e);}});let C=i.command("credits").description("Credits & withdrawal");C.command("balance").description("Show current credit balance").option("-f, --format <format>").action(async t=>{try{let e=await s(k);c(t,e.getDefaultBillingAccount);}catch(e){a(e);}}),C.command("grant").description("Grant credits to a billing account (admin)").requiredOption("--account <id>").requiredOption("--amount <n>","Amount",t=>parseFloat(t)).option("--reason <s>").action(async t=>{try{let e={billingAccountId:t.account,amount:t.amount,reason:t.reason??"cli-grant"};await s(B,{input:e}),f("Credits granted");}catch(e){a(e);}}),C.command("withdraw").description("Request a credit withdrawal").requiredOption("--account <id>").requiredOption("--amount <n>","Amount",t=>parseFloat(t)).requiredOption("--payout <id>","Payout account id").action(async t=>{try{let e={billingAccountId:t.account,creditAmount:t.amount,payoutAccountId:t.payout};await s(W,{input:e}),f("Withdrawal requested");}catch(e){a(e);}}),i.command("refunds").description("Pending refunds").option("--page <n>","",t=>parseInt(t,10),0).option("--page-size <n>","",t=>parseInt(t,10),20).option("-f, --format <format>").action(async t=>{try{let e=await s(j,{page:t.page,pageSize:t.pageSize});c(t,e.getPendingRefunds.records);}catch(e){a(e);}}),i.command("quota").description("Quotas for a subscription").argument("<subscriptionId>").option("-f, --format <format>").action(async(t,e)=>{try{let n=await s(V,{subscriptionId:t});c(e,n.getAllQuotasOfSub);}catch(n){a(n);}});}var it={id:"billing",version:"1.0.0",displayName:"Billing",dependsOn:["auth"],register(r,i){P(i),z(r);}},we=it;module.exports=we;
|