@allscale/cli 1.0.3 → 1.0.5

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/index.js CHANGED
@@ -1,17 +1,17 @@
1
- "use strict";var $n=Object.create;var se=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Mn=Object.getOwnPropertyNames;var Gn=Object.getPrototypeOf,Kn=Object.prototype.hasOwnProperty;var Yn=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mn(t))!Kn.call(e,o)&&o!==n&&se(e,o,{get:()=>t[o],enumerable:!(r=Fn(t,o))||r.enumerable});return e};var b=(e,t,n)=>(n=e!=null?$n(Gn(e)):{},yt(t||!e||!e.__esModule?se(n,"default",{value:e,enumerable:!0}):n,e)),qn=e=>yt(se({},"__esModule",{value:!0}),e);var Jo={};Yn(Jo,{AllscaleCommand:()=>ye,AllscaleError:()=>l,Args:()=>W.Args,Flags:()=>W.Flags,Transport:()=>Ae,decodeJwt:()=>wn,isExpired:()=>En,pickTokenStore:()=>Dn});module.exports=qn(Jo);var I=require("@oclif/core");var wt="public",Et="https://app.allscale.io";var St=["https://app.allscale.io"];var ve="Override the API base URL (public builds accept only https://app.allscale.io)";var Re="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function bt(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function At(e){return bt(e)!==null}function Ne(e){let t=bt(e);return t!==null&&St.includes(t.origin)}function J(){return"".trim()||void 0}function $(){return"public"}function v(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function xe(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Pe()}function Pe(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:c,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return o}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var jn="device-login",Hn=/^[A-Za-z0-9._-]{1,64}$/;function Ue(e){return Hn.test(e)?e:"<profile>"}function Wn(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ue(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ae(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function kt(e){let t=Ue(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Wn(e)}\` for headless automation.`}function Tt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${jn} --profile ${Ue(e)}\`.`}var Jn={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var zn=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function $e(e){return(typeof e=="string"?e:String(e??"")).replace(zn,"")}var Xn=64;function Be(e,t=new Map,n=0){if(typeof e=="string")return $e(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=Xn)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Be(c,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,c]of Object.entries(e))Object.defineProperty(i,s,{value:Be(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var l=class extends Error{code;details;constructor(t,n,r){super($e(n)),this.code=t,this.details=r&&Be(r),this.name="AllscaleError"}get exitCode(){return Jn[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function It(e){if(e instanceof l)return e;if(e instanceof Error){if(Qn(e)){let t=tr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var Vn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Zn=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Qn(e){if(er(e))return!0;let t=e.name??"";return Vn.has(t)?t==="CLIError"?De(e,"parse")||Lt(e.message):!0:Lt(e.message)}function er(e){if(!De(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&De(e,"parse")}function Lt(e){return e?$e(e).split(`
2
- `).some(t=>Zn.some(n=>n.test(t.trim()))):!1}function De(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function tr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ot(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var h=b(require("fs")),fe=b(require("path")),Bt=b(require("crypto"));var nr="...<truncated>",rr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,or=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Ye=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Fe=String.raw`(?:proxy[_-]?)?authorization`,ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Fe}"|'${Fe}'|${Fe})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),sr=/\b(https?:\/\/)[^\s/?#]+@/gi,ar=String.raw`(?:[A-Za-z0-9]+[_-])*`,cr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,vt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Ct=vt(ar),lr=vt(cr),ur=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ct}"|'${Ct}'|${lr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"gi"),Me=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,dr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Me}"|'${Me}'|${Me})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Ye}`,"g");function ce(e){return e.replace(sr,"$1<redacted>@").replace(rr,"<redacted-jwt>").replace(ir,"$1$2$3<redacted>").replace(ur,"$1$2<redacted>").replace(dr,"$1$2<redacted>").replace(or,"Bearer <redacted>")}var fr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function le(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return fr.test(t)}function Rt(e){let t="";for(let n of e){let r=n.codePointAt(0),o=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=o?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function ue(e,t,n=nr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let o=t-r,i="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>o)break;i+=c,s+=u}return`${i}${n}`}function E(e,t=16384){return ue(Rt(ce(e)),t)}var Ge=100,pr=8,hr=8*1024;function de(){return{remaining:hr}}function Ke(e,t){let n=Math.min(16384,t.remaining),r=ue(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function F(e,t,n=0,r={}){if(n>pr)return Ke("<truncated>",t);if(typeof e=="string"){let o=ce(e);return Ke(r.escapeControls?Rt(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,Ge),i=o.map(s=>F(s,t,n+1,r));return e.length>o.length&&i.push(Ke(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,c]of i.slice(0,Ge))o[s]=F(c,t,n+1,r);return i.length>Ge&&(o.output_truncated=!0),o}return e}var qe=require("process");var je=!1;function He(e){je=e}function Pt(){return je}var Nt="1";function G(e,t){if(je){let n={...e};delete n.version;let r=de(),o={event:n.event,...n},i=F(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:Nt,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Nt,event:i.event,output_truncated:!0})),qe.stderr.write(`${s}
4
- `)}else qe.stderr.write(t)}var xt="2",K=null,k=null,Y=!1,X=!1;function gr(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Bt.randomBytes(4).toString("hex");return fe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var We=64*1024*1024,mr=null;function Je(e={}){if(e.quiet&&(X=!0),Y)return;let t=gr();if(!t)return;K=null;let n=null;try{if((mr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=fe.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.statSync(r),d=u.mode&511;if(!u.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let o=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|o,384);let i=h.fstatSync(n),s=h.lstatSync(t);if(!i.isFile()||s.isSymbolicLink()||s.dev!==i.dev||s.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=i.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}X||G({event:"sidecar_disabled",reason:"open_failed",detail:E(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${E(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}K=t,k=n,Y=!0}var _r=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function yr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return _r.some(n=>n.test(t))}function Dt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=wr(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)yr(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function wr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Er(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Dt(e.url)}:e}function Sr(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=F(o,de()),s=JSON.stringify({version:xt,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:xt,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!Y||!K||k===null)return;let t=Er(e),n=Sr(t);try{if(h.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>We){Y=!1;try{h.closeSync(k)}catch{}k=null,X||G({event:"sidecar_disabled",reason:"size_limit",...K===null?{}:{path:E(K)},max_bytes:We},`${E(`[allscale] sidecar exceeded ${We} bytes; disabling it for the rest of this run. Rotate or remove ${K}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}h.appendFileSync(k,`${n}
7
- `)}catch(r){if(Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}try{X||G({event:"sidecar_disabled",reason:"write_failed",detail:E(r.message)},`${E(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var C=Dt;function Ut(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function V(){if(X=!1,Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}}function $t(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Ut()||!t}var Z=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),br=new Set(Array.from(Z).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Ar=Array.from(Z).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Lr=new Set(["--otp-stdin","--password-stdin"]);function ze(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let s=r.slice(0,i);if(Z.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Z.has(r)){t.push(r),n+1<e.length&&(Z.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(br.has(i)){t.push(`${i}<redacted>`);continue}}let o=Lr.has(r)?void 0:Ar.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Ft(e){y({type:"error",code:e.code,message:E(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),V()}var Q=J()??Et,j={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function R(e){return At(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Mt(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Xe(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ee(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Gt(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Kt(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function qt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(J()===void 0&&Q!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
- The CLI default is now ${Q} (production), but a saved profile wins over the default,
1
+ "use strict";var Wn=Object.create;var ae=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,Xn=Object.prototype.hasOwnProperty;var Zn=(e,t)=>{for(var n in t)ae(e,n,{get:t[n],enumerable:!0})},At=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zn(t))!Xn.call(e,o)&&o!==n&&ae(e,o,{get:()=>t[o],enumerable:!(r=Jn(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Wn(Vn(e)):{},At(t||!e||!e.__esModule?ae(n,"default",{value:e,enumerable:!0}):n,e)),Qn=e=>At(ae({},"__esModule",{value:!0}),e);var ci={};Zn(ci,{AllscaleCommand:()=>be,AllscaleError:()=>l,Args:()=>W.Args,Flags:()=>W.Flags,Transport:()=>ke,decodeJwt:()=>On,isExpired:()=>vn,pickTokenStore:()=>qn});module.exports=Qn(ci);var I=require("@oclif/core");var Lt="public",kt="https://app.allscale.io";var Tt=["https://app.allscale.io"];var Ne="Override the API base URL (public builds accept only https://app.allscale.io)";var xe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function It(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Ot(e){return It(e)!==null}function Pe(e){let t=It(e);return t!==null&&Tt.includes(t.origin)}function J(){return"".trim()||void 0}function U(){return"public"}function C(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function De(e){try{return new URL(e).origin}catch{return null}}function z(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Be()}function Be(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:c,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return o}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var er="device-login",tr=/^[A-Za-z0-9._-]{1,64}$/;function Fe(e){return tr.test(e)?e:"<profile>"}function V(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Fe(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ce(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Ct(e){let t=Fe(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${V(e)}\` for headless automation.`}function Rt(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${er} --profile ${Fe(e)}\`.`}var nr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1};var rr=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Me(e){return(typeof e=="string"?e:String(e??"")).replace(rr,"")}var or=64;function $e(e,t=new Map,n=0){if(typeof e=="string")return Me(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=or)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push($e(c,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,c]of Object.entries(e))Object.defineProperty(i,s,{value:$e(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var l=class extends Error{code;details;constructor(t,n,r){super(Me(n)),this.code=t,this.details=r&&$e(r),this.name="AllscaleError"}get exitCode(){return nr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Nt(e){if(e instanceof l)return e;if(e instanceof Error){if(ar(e)){let t=lr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var ir=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),sr=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function ar(e){if(cr(e))return!0;let t=e.name??"";return ir.has(t)?t==="CLIError"?Ue(e,"parse")||vt(e.message):!0:vt(e.message)}function cr(e){if(!Ue(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ue(e,"parse")}function vt(e){return e?Me(e).split(`
2
+ `).some(t=>sr.some(n=>n.test(t.trim()))):!1}function Ue(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function lr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function xt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var g=E(require("fs")),pe=E(require("path")),Mt=E(require("crypto"));var ur="...<truncated>",dr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,fr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,qe=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ge=String.raw`(?:proxy[_-]?)?authorization`,pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ge}"|'${Ge}'|${Ge})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${qe}`,"gi"),gr=/\b(https?:\/\/)[^\s/?#]+@/gi,hr=String.raw`(?:[A-Za-z0-9]+[_-])*`,mr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Bt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,Pt=Bt(hr),_r=Bt(mr),yr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Pt}"|'${Pt}'|${_r})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${qe}`,"gi"),Ke=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,br=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ke}"|'${Ke}'|${Ke})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${qe}`,"g");function le(e){return e.replace(gr,"$1<redacted>@").replace(dr,"<redacted-jwt>").replace(pr,"$1$2$3<redacted>").replace(yr,"$1$2<redacted>").replace(br,"$1$2<redacted>").replace(fr,"Bearer <redacted>")}var wr=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function ue(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return wr.test(t)}function Dt(e){let t="";for(let n of e){let r=n.codePointAt(0),o=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=o?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function de(e,t,n=ur){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let o=t-r,i="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>o)break;i+=c,s+=u}return`${i}${n}`}function w(e,t=16384){return de(Dt(le(e)),t)}var Ye=100,Sr=8,Er=8*1024;function fe(){return{remaining:Er}}function je(e,t){let n=Math.min(16384,t.remaining),r=de(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function F(e,t,n=0,r={}){if(n>Sr)return je("<truncated>",t);if(typeof e=="string"){let o=le(e);return je(r.escapeControls?Dt(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,Ye),i=o.map(s=>F(s,t,n+1,r));return e.length>o.length&&i.push(je(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,c]of i.slice(0,Ye))o[s]=F(c,t,n+1,r);return i.length>Ye&&(o.output_truncated=!0),o}return e}var He=require("process");var We=!1;function Je(e){We=e}function Ut(){return We}var $t="1";function G(e,t){if(We){let n={...e};delete n.version;let r=fe(),o={event:n.event,...n},i=F(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:$t,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:$t,event:i.event,output_truncated:!0})),He.stderr.write(`${s}
4
+ `)}else He.stderr.write(t)}var Ft="2",K=null,k=null,Y=!1,X=!1;function Ar(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=Mt.randomBytes(4).toString("hex");return pe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var ze=64*1024*1024,Lr=null;function Ve(e={}){if(e.quiet&&(X=!0),Y)return;let t=Ar();if(!t)return;K=null;let n=null;try{if((Lr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=pe.dirname(t);if(g.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=g.statSync(r),d=u.mode&511;if(!u.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let o=g.constants.O_NOFOLLOW??0;n=g.openSync(t,g.constants.O_APPEND|g.constants.O_CREAT|g.constants.O_WRONLY|(g.constants.O_NONBLOCK??0)|o,384);let i=g.fstatSync(n),s=g.lstatSync(t);if(!i.isFile()||s.isSymbolicLink()||s.dev!==i.dev||s.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=i.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);g.fchmodSync(n,384)}catch(r){if(n!==null)try{g.closeSync(n)}catch{}X||G({event:"sidecar_disabled",reason:"open_failed",detail:w(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${w(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}K=t,k=n,Y=!0}var kr=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function Tr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return kr.some(n=>n.test(t))}function Gt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=Ir(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Tr(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function Ir(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Or(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Gt(e.url)}:e}function vr(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=F(o,fe()),s=JSON.stringify({version:Ft,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Ft,timestamp:t,type:r,output_truncated:!0})),s}function y(e){if(!Y||!K||k===null)return;let t=Or(e),n=vr(t);try{if(g.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>ze){Y=!1;try{g.closeSync(k)}catch{}k=null,X||G({event:"sidecar_disabled",reason:"size_limit",...K===null?{}:{path:w(K)},max_bytes:ze},`${w(`[allscale] sidecar exceeded ${ze} bytes; disabling it for the rest of this run. Rotate or remove ${K}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}g.appendFileSync(k,`${n}
7
+ `)}catch(r){if(Y=!1,k!==null){try{g.closeSync(k)}catch{}k=null}try{X||G({event:"sidecar_disabled",reason:"write_failed",detail:w(r.message)},`${w(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var v=Gt;function Kt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Z(){if(X=!1,Y=!1,k!==null){try{g.closeSync(k)}catch{}k=null}}function Yt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Kt()||!t}var Q=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Cr=new Set(Array.from(Q).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Rr=Array.from(Q).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Nr=new Set(["--otp-stdin","--password-stdin"]);function Xe(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let s=r.slice(0,i);if(Q.has(s)){t.push(`${s}=<redacted>`);continue}}}if(Q.has(r)){t.push(r),n+1<e.length&&(Q.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Cr.has(i)){t.push(`${i}<redacted>`);continue}}let o=Nr.has(r)?void 0:Rr.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function jt(e){y({type:"error",code:e.code,message:w(e.message)}),y({type:"command-end",ok:!1,exitCode:e.exitCode}),Z()}var ee=J()??kt,q={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function R(e){return Ot(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function qt(){let e=process.env[q.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Ze(){let e=process.env[q.PROFILE]?.trim();return e&&e.length>0?e:void 0}function te(){let e=process.env[q.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Ht(){let e=process.env[q.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Wt(){let e=process.env[q.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Jt(){let e=process.env[q.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function zt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(J()===void 0&&ee!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${ee} (production), but a saved profile wins over the default,
10
10
  so this session still uses staging. That pin was written before the default changed, so it may just be
11
11
  the old default rather than a deliberate choice.
12
12
  To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
13
- To move to production, run: allscale device-login --api-base ${Q}
14
- `}var N=b(require("fs")),jt=b(require("os")),Ve=b(require("path")),Ze=b(require("@iarna/toml"));var Ir=".allscale",Or="config.toml";function Qe(){return Ve.join(jt.homedir(),Ir)}function Cr(){return Ve.join(Qe(),Or)}function pe(){let e=Cr();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return Ze.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Ht(e){return Object.keys(e.profile??{}).sort()}function Wt(e,t){return e.profile?.[t]}function Jt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function H(e){if(!Ne(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Re)}function he(e,t){H(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function zt(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ge(e){let t=Rr(e);if(t)throw new l("input.invalid",t.message)}function vr(){let e=J();if(e===void 0)return;let t=z();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Rr(e){let t=vr();if(t===void 0||v(e))return;let{endpoints:n,fromPairs:r}=t,o=R(e),i=n.map(c=>R(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Nr=require("@noble/hashes/sha3");var Xt=["USDT","USDC"];var Bi=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Pr="unknown_otp_id",xr="invalid_code",Br="expired_code";function Dr(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vt(e){return`Run \`allscale otp-send --email ${Dr(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var Ur=new Map([[Pr,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${Vt(t)}`],[xr,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[Br,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${Vt(t)}`]]);var Zt=[...Ur.keys()];var W=require("@oclif/core"),ye=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:$()==="public"}),"api-base":I.Flags.string({description:ve,helpGroup:"GLOBAL",hidden:$()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{He(this.jsonEnabled()),Je(),y({type:"session-start",command:this.id??"",argv:ze(this.argv)});let t=this.constructor;if($()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ee()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=$t(this.jsonEnabled()),r=this.argv.length===0&&!n&&Hr(t)?this.config.findCommand(this.id??""):void 0;if(r){V();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!Yt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let o=await this.runCommand();return y({type:"command-end",ok:!0}),V(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ot(o),{data:o})}catch(t){let n=It(t);Ft({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{He(!1)}}resolveSessionApiBaseChain(t){let n=pe(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||Xe()!==void 0,s=Jt(n,r,Xe()),c=Wt(n,s),u=$()==="public"&&ee()!==void 0,d=o??(u?void 0:ee()),f=d??c?.api_base??Q,p=qt({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,G({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||H(n),n}resolveContext(t){if($()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ee()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(H(o),ge(o)),{apiBase:o,profile:c,token:n??Mt(),insecureStorage:r||Gt(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${jr(t)}
15
- `)}};var $r=/_(removed|cleared|count|total)$/i;function Fr(e,t){return typeof t=="number"&&$r.test(e)}var Mr=new Set(Xt);function Gr(e,t){return e==="token_symbol"&&typeof t=="string"&&Mr.has(t)}var Kr=new Set(Zt);function Yr(e,t){return e==="otp_reason"&&typeof t=="string"&&Kr.has(t)}var me=100;function _e(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,me),r=n.map(o=>_e(o,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[o,i]of r.slice(0,me))n[o]=le(o)&&!Fr(o,i)&&!Gr(o,i)&&!Yr(o,i)?"<redacted>":_e(i,t+1);if(r.length>me){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-me} more keys`}return n}if(typeof e=="string"){let n=qr(e);return n!==void 0?E(JSON.stringify(_e(n,t+1))):E(e)}return e}function qr(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function jr(e){let t=Pt()?void 0:2,n=_e(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:E(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Hr(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}var we="allscale_access_token",et="allscale_refresh_token";function Qt(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function tt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function nt(e,t){return e.find(n=>n.name===t)?.value??null}var en=b(require("crypto")),tn=b(require("fs")),nn=b(require("path"));var Wr="key-id",Jr="x-allscale-cli-version",rt="cli-1",zr="aScaLe_cli_obf_v1",Xr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Vr(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var Zr=Vr(Xr,zr),rn=`Bearer ${Zr}`;function on(e,t){let n=xe(e);if(n!==null)return t.find(r=>xe(r.base)===n)}function Qr(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=on(e,t);if(r)return r.key;if(v(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:v(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function eo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?on(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&v(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():rt}if(!v(t[0].base))return rt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():rt}function to(){return"1.0.3"}function no(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function ot(e,t){let n=Qr(t);if(!n)throw no();let r=eo(t),o=Math.floor(Date.now()/1e3).toString(),i=en.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Jr]:to()};return r.length>0&&(s[Wr]=r),s}function sn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ro(e,t={}){let n;try{n=Ht(pe())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Tt(e)+(t.messageSuffix??""),{profile:e})}function an(e){if(e.profileExplicit){let t=ro(e.profile);if(t)return t}return new l("auth.no_token",kt(e.profile))}var oo=500,io=8,cn=100;function it(e,t=0){if(t>io)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,cn),r=n.map(o=>it(o,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,o]of Object.entries(e).slice(0,cn))n[r]=le(r)?"<redacted>":it(o,t+1);return n}return e}function so(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function ln(e,t=oo){let n=so(e),r=n===void 0?ce(e):JSON.stringify(it(n));return ue(r,t)}var st=256*1024,Ee=class extends l{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Se=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function at(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,L)=>{u=setTimeout(()=>{L(new Se(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:L,value:g}=f?await Promise.race([p,f]):await p;if(L)break;if(c+=g.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Se&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ao="X-AllScale-Api-Key",co=3e4,lo=32*1024*1024,uo=4*1024*1024;function fo(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function po(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function ho(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function hn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ho(e.status,e.url)}}var un="--dns-result-order=ipv4first";async function be(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((i||c)&&(o||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${un} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${un}`})}var Ae=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??co;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");H(this.opts.apiBase),ge(this.opts.apiBase);let o=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),i=fo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();zt(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=gn(t.path),u=s==="required"?!0:s==="none"?!1:yo(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw an({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=sn(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&he(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),L=Date.now();y({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(o,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(S){throw new l("transport.network",`Network error contacting ${C(o)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:g.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!i&&g.status===401&&!t._isRefresh&&!this.opts.override){let S=await po(this.refreshSingleFlight(),t.signal),ie=this.buildHeaders({attachAuth:u&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),Un=Date.now();y({type:"request",method:t.method??"GET",url:o});let Oe;try{Oe=await fetch(o,{method:t.method??"GET",headers:ie,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Ce){throw new l("transport.network",`Network error contacting ${C(o)} on refresh-retry: ${Ce instanceof Error?Ce.message:String(Ce)}`)}return y({type:"response",status:Oe.status,durationMs:Date.now()-Un}),dn(Oe,{withMetadata:n.withMetadata,authBearing:u,responseKind:fn(t)})}return dn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:fn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...ot(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=rn;let o=t.tokens;if(o?.agent_key)return r[ao]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=tt([{name:we,value:i}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(he(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ae()}.`);if(he(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=tt([{name:we,value:t.access_token},{name:et,value:t.refresh_token}]),o=ot("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(g){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}y({type:"response",status:u.status,durationMs:0});try{await hn(u)}catch(g){throw y({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await be(u);let w=await Ao(u);await be(u,w),_n(u.status,w),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw y({type:"refresh",ok:!1}),w}if(g)return y({type:"refresh",ok:!0,adopted:!0}),g;throw y({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ae()}.`,{status:u.status})}let d=Qt(u.headers),f=nt(d,we),p=nt(d,et);if(!f||!p)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let L={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,L),y({type:"refresh",ok:!0}),L}},go=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function gn(e){let t=e.split(/[?#]/,1)[0];return go.some(n=>t===n||t.startsWith(`${n}/`))}var mo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function _o(e){let t=e.split(/[?#]/,1)[0];return mo.some(n=>n.test(t))}function yo(e){return gn(e)||_o(e)}async function dn(e,t={}){await hn(e);let n=e.status>=200&&e.status<300;n||await be(e);let r=t.responseKind??"mutation",i=await at(e,n?r==="query"?lo:uo:st,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await be(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Lo(s)??`HTTP ${e.status}`;if(_n(e.status,s),So(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function fn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var wo=2014,pn=2004;function mn(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function Eo(e){return mn(e,wo)}function So(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&mn(t,pn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ae()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:pn})}var bo=1e4;async function Ao(e,t=bo){if(e.status>=200&&e.status<300)return"";try{return await at(e,st,{timeoutMs:t})}catch{return""}}function _n(e,t){if(!(e>=200&&e<300)&&Eo(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?ln(t):t})}function Lo(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}function wn(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let n;try{let r=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");n=JSON.parse(r)}catch{throw yn()}if(typeof n!="object"||n===null||Array.isArray(n))throw yn();return n}function yn(){return new l("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}function En(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Pn=b(require("path"));var ut=require("crypto"),a=b(require("fs")),_=b(require("path"));var Le=1024*1024,ko=5e3,To=20,Io=3e4,ct=4096,Oo=new Int32Array(new SharedArrayBuffer(4)),te=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ke(e){return e instanceof te}var A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Co=null;function x(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Te(){return(Co??process.platform)!=="win32"}function On(){if(!Te())throw x()}function Cn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ne(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function re(e,t){return e.dev===t.dev&&e.ino===t.ino}function vo(e){Atomics.wait(Oo,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function Ro(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&m(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!re(i,s))throw new Error("credential-store parent changed while it was being inspected");ne(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&m(i,"ENOENT")?new A:i}if(!re(n,o))throw r.retryOnPathChange?new A:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||o.nlink!==1))throw new te;if(ne(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function No(e,t){if(t.size>Le)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Le+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Le)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function bn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(m(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(m(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return No(t,r)}finally{t!==null&&a.default.closeSync(t)}}function An(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(m(o,"ENOENT")&&Cn(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Nn(_.dirname(e))}function Po(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new te;ne(t,"credential-store replacement target")}function xo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(m(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function Rn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Nn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Bo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Le)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),o=_.basename(e),i=null,s=null,c=!1;try{let u=xo(r,o);i=u.fd,s=u.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Rn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),Po(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Nn(r)}function Do(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Uo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function $o(e,t){if(t.size>ct)return null;let n=Buffer.alloc(ct+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>ct)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function B(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!re(n,t))throw new Error("credential-store lock changed while it was being inspected");ne(n,"credential-store lock"),a.default.unlinkSync(e)}function Ln(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(m(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new A}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=$o(n,o);return{state:(i?.target===t&&i?!vn(i.pid):Date.now()-o.mtimeMs>=Io)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function Fo(e,t){for(let n=0;n<8;n+=1){let r=(0,ut.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return Rn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Mo(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw m(r,"ENOENT")?new A:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!re(o,t))throw new A;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function kn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new A}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Go(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function P(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");vo(To)}function Tn(e){let t=_.dirname(e),n=_.basename(e),r=Do(e),o=Uo(e),i=Fo(t,n),s=Date.now()+ko,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(kn(o)){P(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=Mo(r,i.stats),c=!0}catch(p){if(u&&!c){try{B(r,i.stats)}catch{}u=!1}if(p instanceof A){P(s,!1);continue}if(!m(p,"EEXIST"))throw p;let L;try{L=Ln(r,n)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}if(L.state==="absent")continue;if(L.state==="stale"){let w;try{w=Go(o)}catch(S){if(S instanceof A){P(s,!1);continue}throw S}if(w!==null){try{let S;try{S=Ln(r,n)}catch(ie){if(ie instanceof A){P(s,!1);continue}throw ie}S.state==="stale"&&B(r,S.stats)}finally{lt(w)}continue}}let g;try{g=kn(o)}catch(w){if(w instanceof A){P(s,!1);continue}throw w}P(s,g)}}catch(p){f=p}try{B(i.claimPath,i.stats)}catch(p){!m(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function lt(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function Ko(e,t){let n=Ro(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function In(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=Ko(r,n);if(o===null||vn(o))continue;let i=_.join(t,r),s=null;try{try{s=a.default.openSync(i,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!re(c,u))continue;try{ne(c,"credential-store orphan")}catch{continue}B(i,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function oe(e,t,n){if(!Te()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw x();if(!Sn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw x()}});let s=Tn(e);try{return In(e),n({read:()=>bn(e),remove:()=>An(e),write:()=>{throw x()}})}finally{lt(s)}}if(!t.createParent){let i=!1;try{i=Cn(e)}catch{throw x()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw x()}})}throw x()}if(!Sn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=Tn(e);try{return In(e),n({read:()=>bn(e),remove:()=>An(e),write:i=>Bo(e,i)})}finally{lt(o)}}var dt="allscale-cli";function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xn(e){return gt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function U(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function ft(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Ie(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,pt=!1;function Yo(){return Kt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function qo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
- `,1)[0]==="Cannot find module 'keytar'"}function jo(){if(D!==void 0)return D;if(Yo())return pt=!1,D=null,D;try{D=require("keytar"),pt=!1}catch(e){pt=!qo(e),D=null}return D}var Ho="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function Bn(){let e=Te()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable",`${Ho} `+e+" Never silently downgrade in production.")}async function ht(e){try{return await e()}catch{throw Bn()}}var mt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ht(()=>this.keytar.getPassword(dt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw U("OS keychain")}if(!xn(r))throw U("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ht(()=>this.keytar.setPassword(dt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ht(()=>this.keytar.deletePassword(dt,t))}},Wo="credentials.json",_t=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Pn.join(Qe(),Wo)}read(t){let n;try{n=t.read()}catch(o){throw ke(o)?ft():U("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw U("plaintext file")}if(!gt(r)||!gt(r.profiles))throw U("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ke(r)?ft():Ie()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!xn(r))throw U("plaintext file");return r}}async get(t){try{return oe(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:U("plaintext file")}}async set(t,n){try{oe(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:Ie()}}async delete(t){try{oe(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Ie()}}async clearProfile(t){try{return oe(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:ke(n)?ft():Ie()}}};function Dn(e){if(e.insecureStorage)return On(),new _t(e.insecureFilePath);let t=jo();if(t)return new mt(t);throw Bn()}0&&(module.exports={AllscaleCommand,AllscaleError,Args,Flags,Transport,decodeJwt,isExpired,pickTokenStore});
13
+ To move to production, run: allscale device-login --api-base ${ee}
14
+ `}var N=E(require("fs")),Vt=E(require("os")),Qe=E(require("path")),et=E(require("@iarna/toml"));var Br=".allscale",Dr="config.toml";function tt(){return Qe.join(Vt.homedir(),Br)}function $r(){return Qe.join(tt(),Dr)}function ge(){let e=$r();if(!N.existsSync(e))return{};let t=N.readFileSync(e,"utf-8");try{return et.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Xt(e){return Object.keys(e.profile??{}).sort()}function Zt(e,t){return e.profile?.[t]}function Qt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function H(e){if(!Pe(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+xe)}function he(e,t){H(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let o=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function en(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function me(e){let t=Fr(e);if(t)throw new l("input.invalid",t.message)}function Ur(){let e=J();if(e===void 0)return;let t=z();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Fr(e){let t=Ur();if(t===void 0||C(e))return;let{endpoints:n,fromPairs:r}=t,o=R(e),i=n.map(c=>R(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var Mr=require("@noble/hashes/sha3");var tn=["USDT","USDC"];var zi=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Gr="unknown_otp_id",Kr="invalid_code",Yr="expired_code";function jr(e){return`'${e.replace(/'/g,"'\\''")}'`}function nn(e){return`Run \`allscale otp-send --email ${jr(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var qr=new Map([[Gr,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${nn(t)}`],[Kr,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[Yr,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${nn(t)}`]]);var rn=[...qr.keys()];var W=require("@oclif/core"),be=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:U()==="public"}),"api-base":I.Flags.string({description:Ne,helpGroup:"GLOBAL",hidden:U()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Je(this.jsonEnabled()),Ve(),y({type:"session-start",command:this.id??"",argv:Xe(this.argv)});let t=this.constructor;if(U()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(i=>i==="--api-base"||i.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&te()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=Yt(this.jsonEnabled()),r=this.argv.length===0&&!n&&eo(t)?this.config.findCommand(this.id??""):void 0;if(r){Z();let i=await(0,I.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new i(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!Jt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let o=await this.runCommand();return y({type:"command-end",ok:!0}),Z(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||xt(o),{data:o})}catch(t){let n=Nt(t);jt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Je(!1)}}resolveSessionApiBaseChain(t){let n=ge(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||Ze()!==void 0,s=Qt(n,r,Ze()),c=Zt(n,s),u=U()==="public"&&te()!==void 0,d=o??(u?void 0:te()),f=d??c?.api_base??ee,p=zt({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,G({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||H(n),n}resolveContext(t){if(U()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&te()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:o,explicitApiBase:i,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(H(o),me(o)),{apiBase:o,profile:c,token:n??qt(),insecureStorage:r||Ht(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${Qr(t)}
15
+ `)}};var Hr=/_(removed|cleared|count|total)$/i;function Wr(e,t){return typeof t=="number"&&Hr.test(e)}var Jr=new Set(tn);function zr(e,t){return e==="token_symbol"&&typeof t=="string"&&Jr.has(t)}var Vr=new Set(rn);function Xr(e,t){return e==="otp_reason"&&typeof t=="string"&&Vr.has(t)}var _e=100;function ye(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,_e),r=n.map(o=>ye(o,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[o,i]of r.slice(0,_e))n[o]=ue(o)&&!Wr(o,i)&&!zr(o,i)&&!Xr(o,i)?"<redacted>":ye(i,t+1);if(r.length>_e){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-_e} more keys`}return n}if(typeof e=="string"){let n=Zr(e);return n!==void 0?w(JSON.stringify(ye(n,t+1))):w(e)}return e}function Zr(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function Qr(e){let t=Ut()?void 0:2,n=ye(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:w(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function eo(e){if(e.requiresInput===!0)return!0;let t=o=>typeof o=="object"&&o!==null&&o.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(o=>t(o))||Object.values(r).some(o=>t(o))}var we="allscale_access_token",nt="allscale_refresh_token";function on(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),o=r===-1?n:n.slice(0,r),i=o.indexOf("=");return i===-1?null:{name:o.slice(0,i).trim(),value:o.slice(i+1).trim()}}).filter(n=>n!==null)}function rt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function ot(e,t){return e.find(n=>n.name===t)?.value??null}var sn=E(require("crypto")),an=E(require("fs")),cn=E(require("path"));var to="key-id",no="x-allscale-cli-version",it="cli-1",ro="aScaLe_cli_obf_v1",oo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function io(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),o=Buffer.alloc(n.length);for(let i=0;i<n.length;i++)o[i]=n[i]^r[i%r.length];return o.toString("utf8")}var so=io(oo,ro),ln=`Bearer ${so}`;function un(e,t){let n=De(e);if(n!==null)return t.find(r=>De(r.base)===n)}function ao(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=z();if(t.length>0){let r=un(e,t);if(r)return r.key;if(C(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:C(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function co(e){{let r="cli-1".trim();if(r.length>0)return r}let t=z();if(t.length>0){let r=e!==void 0?un(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&C(e)){let o=process.env.ALLSCALE_SIGNING_KEY;if(o&&o.trim().length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID;return i!==void 0?i.trim():it}if(!C(t[0].base))return it}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():it}function lo(){return"1.0.5"}function uo(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function st(e,t){let n=ao(t);if(!n)throw uo();let r=co(t),o=Math.floor(Date.now()/1e3).toString(),i=sn.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[no]:lo()};return r.length>0&&(s[to]=r),s}function dn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function fo(e,t={}){let n;try{n=Xt(ge())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Rt(e)+(t.messageSuffix??""),{profile:e})}function fn(e){if(e.profileExplicit){let t=fo(e.profile);if(t)return t}return new l("auth.no_token",Ct(e.profile))}var po=new Set;var go=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),at=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),ct=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Se(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function pn(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var ho=new Set(["cli_op:all"]),mo=new Set([...ho].map(Se));var Es=new Set([...[...go,...at,...po].map(Se),...ct,...mo]);var _o=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,yo=/is not available to API keys/i,gn=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function hn(e){if(typeof e!="string")return;let t=_o.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=yo.test(n),i=!o&&gn.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(u=>u.trim()).filter(u=>gn.test(u));s=c.length>0?c:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function mn(e){if(ct.has(Se(e)))return{kind:"ungrantable"};for(let t of at)if(pn(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function _n(e,t,n,r){let o=hn(e),i=o?.notAvailableToKeys===!0,s=o?.required??r?.scope,c=o?.granted,u=c===void 0?"":` This key holds ${c.length>0?c.join(", "):"no scopes"}.`;if(i||r?.ungrantableReason!==void 0){let d=r?.ungrantableReason!==void 0?`: ${r.ungrantableReason}`:"";return new l("auth.permission_denied",`${t} is not available to agent keys${d}. Re-authorizing will NOT help \u2014 no scope grants it.${u} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...n,missing_scopes:[],...c===void 0?{}:{granted_scopes:c},ungrantable:!0})}if(s!==void 0){let d=mn(s),f=d.kind==="ungrantable"?`\`${s}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:d.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${V()}\` with \`--scopes ${s}\`.`:`The browser approval screen does not offer \`${s}\`, so \`device-login\` cannot grant it \u2014 use \`${V()}\` with \`--scopes ${s}\`.`;return new l("auth.permission_denied",`The current agent key lacks \`${s}\`, required by ${t}.${u} ${f}`,{...n,missing_scopes:[s],...c===void 0?{}:{granted_scopes:c},...d.kind==="ungrantable"?{ungrantable:!0}:{}})}return new l("auth.permission_denied",`The current agent key does not have the scope required by ${t}.${u} Re-run \`allscale device-login\` (or \`${V()}\`) and grant the required scope.`,n)}var bo=500,wo=8,yn=100;function lt(e,t=0){if(t>wo)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,yn),r=n.map(o=>lt(o,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null);for(let[r,o]of Object.entries(e).slice(0,yn))n[r]=ue(r)?"<redacted>":lt(o,t+1);return n}return e}function So(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function bn(e,t=bo){let n=So(e),r=n===void 0?le(e):JSON.stringify(lt(n));return de(r,t)}var ut=256*1024,Ee=class extends l{constructor(t,n,r="backend-envelope"){let o=r==="successful-query",i=r==="successful-mutation";super(o?"transport.response_too_large":"backend.internal",o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...i?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Ae=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function dt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),o=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(o!==void 0&&o>t)throw e.body?.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,L)=>{u=setTimeout(()=>{L(new Ae(e.status,d))},d),u.unref?.()});try{for(;;){let p=i.read(),{done:L,value:h}=f?await Promise.race([p,f]):await p;if(L)break;if(c+=h.byteLength,c>t)throw i.cancel().catch(()=>{}),new Ee(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(p){throw p instanceof Ae&&i.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Eo="X-AllScale-Api-Key",Ao=3e4,Lo=32*1024*1024,ko=4*1024*1024;function To(e,t){let n=new AbortController,r=!1,o=()=>{n.abort(e?.reason)};e?.aborted?o():e?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e?.removeEventListener("abort",o)}}}function Io(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let o=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",o)})}):e}function Oo(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${v(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Ln(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Oo(e.status,e.url)}}var wn="--dns-result-order=ipv4first";async function Le(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",o=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",i=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((i||c)&&(o||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${wn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${wn}`})}var ke=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??Ao;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");H(this.opts.apiBase),me(this.opts.apiBase);let o=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),i=To(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new l("transport.timeout",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{i.dispose()}}async requestWithinDeadline(t,n,r){let o=new URL(t.path,this.opts.apiBase).toString();en(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=kn(t.path),u=s==="required"?!0:s==="none"?!1:No(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw fn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=dn(t.body),f=!!i||!!r?.access_token;u&&f&&!this.opts.override&&he(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),L=Date.now();y({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(o,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(S){throw new l("transport.network",`Network error contacting ${v(o)}: ${S instanceof Error?S.message:String(S)}`)}if(y({type:"response",status:h.status,durationMs:Date.now()-L}),u&&!!r?.access_token&&!i&&h.status===401&&!t._isRefresh&&!this.opts.override){let S=await Io(this.refreshSingleFlight(),t.signal),se=this.buildHeaders({attachAuth:u&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),Hn=Date.now();y({type:"request",method:t.method??"GET",url:o});let Ce;try{Ce=await fetch(o,{method:t.method??"GET",headers:se,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Re){throw new l("transport.network",`Network error contacting ${v(o)} on refresh-retry: ${Re instanceof Error?Re.message:String(Re)}`)}return y({type:"response",status:Ce.status,durationMs:Date.now()-Hn}),Sn(Ce,{withMetadata:n.withMetadata,authBearing:u,responseKind:En(t)})}return Sn(h,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!i,responseKind:En(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...st(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=ln;let o=t.tokens;if(o?.agent_key)return r[Eo]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=rt([{name:we,value:i}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(t){let n;try{n=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!n?.access_token||!n?.refresh_token||n.refresh_token===t.refresh_token)return null;if(he(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ce()}.`);if(he(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=rt([{name:we,value:t.access_token},{name:nt,value:t.refresh_token}]),o=st("",this.opts.apiBase);y({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,c=setTimeout(()=>{s=!0,i.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...o},signal:i.signal,redirect:"manual"})}catch(h){throw y({type:"refresh",ok:!1}),new l("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${v(n)} timed out after 10s with no response.`:`Network error during token refresh against ${v(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}y({type:"response",status:u.status,durationMs:0});try{await Ln(u)}catch(h){throw y({type:"refresh",ok:!1}),h}if(u.status!==200){let h=null;try{await Le(u);let b=await $o(u);await Le(u,b),Tn(u.status,b),u.status===401&&(h=await this.adoptConcurrentlyRotatedTokens(t))}catch(b){throw y({type:"refresh",ok:!1}),b}if(h)return y({type:"refresh",ok:!0,adopted:!0}),h;throw y({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ce()}.`,{status:u.status})}let d=on(u.headers),f=ot(d,we),p=ot(d,nt);if(!f||!p)throw y({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let L={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,L),y({type:"refresh",ok:!0}),L}},vo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function kn(e){let t=e.split(/[?#]/,1)[0];return vo.some(n=>t===n||t.startsWith(`${n}/`))}var Co=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Ro(e){let t=e.split(/[?#]/,1)[0];return Co.some(n=>n.test(t))}function No(e){return kn(e)||Ro(e)}async function Sn(e,t={}){await Ln(e);let n=e.status>=200&&e.status<300;n||await Le(e);let r=t.responseKind??"mutation",i=await dt(e,n?r==="query"?Lo:ko:ut,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Le(e,i);let s=null;if(i.length>0)try{s=JSON.parse(i)}catch{s={raw:i}}if(e.status>=200&&e.status<300){if(t.withMetadata){let u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Uo(s)??`HTTP ${e.status}`;if(Tn(e.status,s),Bo(e.status,s,t),ft(s,2102))throw _n(s.errors,"this API request",{status:e.status,backend_code:2102});if(e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function En(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var xo=2014,An=2004;function ft(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function Po(e){return ft(e,xo)}function Bo(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&ft(t,An))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ce()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:An})}var Do=1e4;async function $o(e,t=Do){if(e.status>=200&&e.status<300)return"";try{return await dt(e,ut,{timeoutMs:t})}catch{return""}}function Tn(e,t){if(!(e>=200&&e<300)&&Po(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?bn(t):t})}function Uo(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}function On(e){let t=e.split(".");if(t.length!==3)throw new l("auth.token_invalid","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");let n;try{let r=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");n=JSON.parse(r)}catch{throw In()}if(typeof n!="object"||n===null||Array.isArray(n))throw In();return n}function In(){return new l("auth.token_invalid","The provided token is not a valid JWT credential \u2014 its payload could not be decoded. Check the --token / ALLSCALE_TOKEN value, or re-authenticate to obtain a fresh session.")}function vn(e,t=Math.floor(Date.now()/1e3)){return typeof e.exp=="number"&&e.exp<t}var Kn=E(require("path"));var ht=require("crypto"),a=E(require("fs")),_=E(require("path"));var Te=1024*1024,Fo=5e3,Mo=20,Go=3e4,pt=4096,Ko=new Int32Array(new SharedArrayBuffer(4)),ne=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ie(e){return e instanceof ne}var A=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Yo=null;function P(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Oe(){return(Yo??process.platform)!=="win32"}function $n(){if(!Oe())throw P()}function Un(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(e,t){return typeof e=="object"&&e!==null&&e.code===t}function re(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function oe(e,t){return e.dev===t.dev&&e.ino===t.ino}function jo(e){Atomics.wait(Ko,0,0,e)}function Fn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function qo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(i){if(!t&&m(i,"ENOENT"))return!1;throw i}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let o=null;try{o=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let i=a.default.fstatSync(o),s=a.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!oe(i,s))throw new Error("credential-store parent changed while it was being inspected");re(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(o,448),c=a.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&a.default.closeSync(o)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let o;try{o=a.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&m(i,"ENOENT")?new A:i}if(!oe(n,o))throw r.retryOnPathChange?new A:new Error("credential-store target changed while it was being opened or is not a regular file");if(o.isSymbolicLink()||!o.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||o.nlink!==1))throw new ne;if(re(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let i=a.default.fstatSync(t);if((i.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return i}return n}function Ho(e,t){if(t.size>Te)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Te+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Te)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Rn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(m(o,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(m(i,"ENOENT"))return null;throw i}throw o}let n=a.default.fstatSync(t),r=O(e,t,n);return Ho(t,r)}finally{t!==null&&a.default.closeSync(t)}}function Nn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(o){if(m(o,"ENOENT")&&Un(e))return;throw o}let n=a.default.fstatSync(t),r=O(e,t,n);B(e,r)}finally{t!==null&&a.default.closeSync(t)}Gn(_.dirname(e))}function Wo(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ne;re(t,"credential-store replacement target")}function Jo(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(m(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function Mn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Gn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function zo(e,t){let n=Buffer.from(t,"utf8");if(n.length>Te)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),o=_.basename(e),i=null,s=null,c=!1;try{let u=Jo(r,o);i=u.fd,s=u.tempPath;let d=a.default.fstatSync(i);if((O(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Mn(i,n),a.default.fsyncSync(i),O(s,i,a.default.fstatSync(i));let p=i;i=null,a.default.closeSync(p),Wo(e),a.default.renameSync(s,e),c=!0}finally{if(i!==null)try{a.default.closeSync(i)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Gn(r)}function Vo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function Xo(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Zo(e,t){if(t.size>pt)return null;let n=Buffer.alloc(pt+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>pt)return null;let o;try{o=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof o!="object"||o===null||!Number.isSafeInteger(o.pid)||(o.pid??0)<=0||typeof o.nonce!="string"||!/^[a-f0-9]{24}$/.test(o.nonce??"")||typeof o.target!="string"?null:o}function B(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!oe(n,t))throw new Error("credential-store lock changed while it was being inspected");re(n,"credential-store lock"),a.default.unlinkSync(e)}function xn(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(m(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new A}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Zo(n,o);return{state:(i?.target===t&&i?!Fn(i.pid):Date.now()-o.mtimeMs>=Go)?"stale":"active",stats:o}}finally{n!==null&&a.default.closeSync(n)}}function Qo(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),o=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(o,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(o,s,c,{allowMultipleLinks:!0});return Mn(s,Buffer.from(JSON.stringify(i),"utf8")),a.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function ei(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw m(r,"ENOENT")?new A:r}try{let r=a.default.fstatSync(n),o=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!oe(o,t))throw new A;return{fd:n,lockPath:e,stats:o}}catch(r){throw a.default.closeSync(n),r}}function Pn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new A}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function ti(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{B(e,n)}catch{}throw a.default.closeSync(t),r}}function x(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");jo(Mo)}function Bn(e){let t=_.dirname(e),n=_.basename(e),r=Vo(e),o=Xo(e),i=Qo(t,n),s=Date.now()+Fo,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(Pn(o)){x(s,!0);continue}a.default.linkSync(i.claimPath,r),u=!0,d=ei(r,i.stats),c=!0}catch(p){if(u&&!c){try{B(r,i.stats)}catch{}u=!1}if(p instanceof A){x(s,!1);continue}if(!m(p,"EEXIST"))throw p;let L;try{L=xn(r,n)}catch(b){if(b instanceof A){x(s,!1);continue}throw b}if(L.state==="absent")continue;if(L.state==="stale"){let b;try{b=ti(o)}catch(S){if(S instanceof A){x(s,!1);continue}throw S}if(b!==null){try{let S;try{S=xn(r,n)}catch(se){if(se instanceof A){x(s,!1);continue}throw se}S.state==="stale"&&B(r,S.stats)}finally{gt(b)}continue}}let h;try{h=Pn(o)}catch(b){if(b instanceof A){x(s,!1);continue}throw b}x(s,h)}}catch(p){f=p}try{B(i.claimPath,i.stats)}catch(p){!m(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function gt(e){try{B(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function ni(e,t){let n=qo(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let o=Number(r[1]);return Number.isSafeInteger(o)&&o>0?o:null}function Dn(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let o=ni(r,n);if(o===null||Fn(o))continue;let i=_.join(t,r),s=null;try{try{s=a.default.openSync(i,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!oe(c,u))continue;try{re(c,"credential-store orphan")}catch{continue}B(i,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ie(e,t,n){if(!Oe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw P();if(!Cn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw P()}});let s=Bn(e);try{return Dn(e),n({read:()=>Rn(e),remove:()=>Nn(e),write:()=>{throw P()}})}finally{gt(s)}}if(!t.createParent){let i=!1;try{i=Un(e)}catch{throw P()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw P()}})}throw P()}if(!Cn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=Bn(e);try{return Dn(e),n({read:()=>Rn(e),remove:()=>Nn(e),write:i=>zo(e,i)})}finally{gt(o)}}var mt="allscale-cli";function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yn(e){return wt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function $(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function _t(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function ve(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var D,yt=!1;function ri(){return Wt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function oi(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function ii(){if(D!==void 0)return D;if(ri())return yt=!1,D=null,D;try{D=require("keytar"),yt=!1}catch(e){yt=!oi(e),D=null}return D}var si="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function jn(){let e=Oe()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable",`${si} `+e+" Never silently downgrade in production.")}async function bt(e){try{return await e()}catch{throw jn()}}var St=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await bt(()=>this.keytar.getPassword(mt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw $("OS keychain")}if(!Yn(r))throw $("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await bt(()=>this.keytar.setPassword(mt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await bt(()=>this.keytar.deletePassword(mt,t))}},ai="credentials.json",Et=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Kn.join(tt(),ai)}read(t){let n;try{n=t.read()}catch(o){throw Ie(o)?_t():$("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw $("plaintext file")}if(!wt(r)||!wt(r.profiles))throw $("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ie(r)?_t():ve()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Yn(r))throw $("plaintext file");return r}}async get(t){try{return ie(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:$("plaintext file")}}async set(t,n){try{ie(this.filePath,{createParent:!0},r=>{let o=this.read(r);this.profileTokens(o,t),o.profiles[t]=n,this.write(r,o)})}catch(r){throw r instanceof l?r:ve()}}async delete(t){try{ie(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:ve()}}async clearProfile(t){try{return ie(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Ie(n)?_t():ve()}}};function qn(e){if(e.insecureStorage)return $n(),new Et(e.insecureFilePath);let t=ii();if(t)return new St(t);throw jn()}0&&(module.exports={AllscaleCommand,AllscaleError,Args,Flags,Transport,decodeJwt,isExpired,pickTokenStore});
17
17
  //# sourceMappingURL=index.js.map
@@ -3169,5 +3169,5 @@
3169
3169
  ]
3170
3170
  }
3171
3171
  },
3172
- "version": "1.0.3"
3172
+ "version": "1.0.5"
3173
3173
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allscale/cli",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Command-line interface for AllScale — drives the same actions a user can take in app.allscale.io",
5
5
  "keywords": [
6
6
  "allscale",