@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/README.md +5 -1
- package/dist/commands/claim-link/claim.js +12 -12
- package/dist/commands/claim-link/create.js +28 -28
- package/dist/commands/claim-link/get.js +11 -11
- package/dist/commands/claim-link/list.js +10 -10
- package/dist/commands/claim-link/status.js +12 -12
- package/dist/commands/describe.js +3 -3
- package/dist/commands/device-login.js +20 -20
- package/dist/commands/invoice/get.js +11 -11
- package/dist/commands/invoice/list.js +11 -11
- package/dist/commands/invoice/pay.js +44 -44
- package/dist/commands/invoice/received.js +11 -11
- package/dist/commands/invoice/send.js +23 -23
- package/dist/commands/invoice/sent.js +10 -10
- package/dist/commands/invoice/update.js +11 -11
- package/dist/commands/operations.js +6 -6
- package/dist/commands/otp-login.js +14 -14
- package/dist/commands/otp-send.js +10 -10
- package/dist/commands/payout/send.js +9 -9
- package/dist/commands/payout/status.js +11 -11
- package/dist/commands/store/create.js +12 -12
- package/dist/commands/transaction/get.js +11 -11
- package/dist/commands/transaction/list.js +10 -10
- package/dist/commands/wallet/list.js +11 -11
- package/dist/commands/wallet/send.js +27 -27
- package/dist/index.js +13 -13
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var w=T(require("fs")),
|
|
4
|
-
`)}else
|
|
5
|
-
`);return}se=t,C=n,ae=!0}var
|
|
1
|
+
"use strict";var so=Object.create;var Ie=Object.defineProperty;var ao=Object.getOwnPropertyDescriptor;var lo=Object.getOwnPropertyNames;var co=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var po=(e,t)=>{for(var n in t)Ie(e,n,{get:t[n],enumerable:!0})},rn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lo(t))!uo.call(e,o)&&o!==n&&Ie(e,o,{get:()=>t[o],enumerable:!(r=ao(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?so(co(e)):{},rn(t||!e||!e.__esModule?Ie(n,"default",{value:e,enumerable:!0}):n,e)),fo=e=>rn(Ie({},"__esModule",{value:!0}),e);var Xs={};po(Xs,{default:()=>Xe});module.exports=fo(Xs);var $=require("@oclif/core");var on="public",sn="https://app.allscale.io";var an=["https://app.allscale.io"];var et="Override the API base URL (public builds accept only https://app.allscale.io)",ln="Override the base URL of the printed /cli confirmation link (defaults to the session API base). Accepts only the trusted AllScale origin; invalid values report the allowed origin.";var pe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function cn(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 un(e){return cn(e)!==null}function te(e){let t=cn(e);return t!==null&&an.includes(t.origin)}function tt(e){return te(e)}function fe(){return"".trim()||void 0}function ne(){return"public"}function H(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function rt(e){try{return new URL(e).origin}catch{return null}}function he(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return nt()}function nt(){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:l,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:l,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 st="device-login",ho=/^[A-Za-z0-9._-]{1,64}$/;function at(e){return ho.test(e)?e:"<profile>"}function ge(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":at(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ve(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function pn(e){let t=at(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${ge(e)}\` for headless automation.`}function fn(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${st} --profile ${at(e)}\`.`}var go={"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 mo=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 lt(e){return(typeof e=="string"?e:String(e??"")).replace(mo,"")}var _o=64;function ot(e,t=new Map,n=0){if(typeof e=="string")return lt(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=_o)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let l of e)s.push(ot(l,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,l]of Object.entries(e))Object.defineProperty(i,s,{value:ot(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var a=class extends Error{code;details;constructor(t,n,r){super(lt(n)),this.code=t,this.details=r&&ot(r),this.name="AllscaleError"}get exitCode(){return go[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function hn(e){if(e instanceof a)return e;if(e instanceof Error){if(bo(e)){let t=So(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var yo=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),wo=[/^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 bo(e){if(Eo(e))return!0;let t=e.name??"";return yo.has(t)?t==="CLIError"?it(e,"parse")||dn(e.message):!0:dn(e.message)}function Eo(e){if(!it(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&it(e,"parse")}function dn(e){return e?lt(e).split(`
|
|
2
|
+
`).some(t=>wo.some(n=>n.test(t.trim()))):!1}function it(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function So(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function gn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var w=T(require("fs")),Pe=T(require("path")),Sn=T(require("crypto"));var Ao="...<truncated>",ko=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Lo=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ft=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ct=String.raw`(?:proxy[_-]?)?authorization`,To=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ct}"|'${ct}'|${ct})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ft}`,"gi"),Oo=/\b(https?:\/\/)[^\s/?#]+@/gi,Io=String.raw`(?:[A-Za-z0-9]+[_-])*`,vo=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,_n=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)`,mn=_n(Io),Ro=_n(vo),Co=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mn}"|'${mn}'|${Ro})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ft}`,"gi"),ut=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)`,No=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ut}"|'${ut}'|${ut})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ft}`,"g");function Re(e){return e.replace(Oo,"$1<redacted>@").replace(ko,"<redacted-jwt>").replace(To,"$1$2$3<redacted>").replace(Co,"$1$2<redacted>").replace(No,"$1$2<redacted>").replace(Lo,"Bearer <redacted>")}var xo=/(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 Ce(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xo.test(t)}function yn(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 Ne(e,t,n=Ao){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",u=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(u+p>t)break;l+=d,u+=p}return l}let o=t-r,i="",s=0;for(let l of e){let u=Buffer.byteLength(l,"utf8");if(s+u>o)break;i+=l,s+=u}return`${i}${n}`}function O(e,t=16384){return Ne(yn(Re(e)),t)}var dt=100,Po=8,Bo=8*1024;function xe(){return{remaining:Bo}}function pt(e,t){let n=Math.min(16384,t.remaining),r=Ne(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function re(e,t,n=0,r={}){if(n>Po)return pt("<truncated>",t);if(typeof e=="string"){let o=Re(e);return pt(r.escapeControls?yn(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,dt),i=o.map(s=>re(s,t,n+1,r));return e.length>o.length&&i.push(pt(`<${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,l]of i.slice(0,dt))o[s]=re(l,t,n+1,r);return i.length>dt&&(o.output_truncated=!0),o}return e}var ht=require("process");var gt=!1;function mt(e){gt=e}function bn(){return gt}var wn="1";function ie(e,t){if(gt){let n={...e};delete n.version;let r=xe(),o={event:n.event,...n},i=re(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:wn,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:wn,event:i.event,output_truncated:!0})),ht.stderr.write(`${s}
|
|
4
|
+
`)}else ht.stderr.write(t)}var En="2",se=null,C=null,ae=!1,me=!1;function Do(){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=Sn.randomBytes(4).toString("hex");return Pe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var _t=64*1024*1024,$o=null;function yt(e={}){if(e.quiet&&(me=!0),ae)return;let t=Do();if(!t)return;se=null;let n=null;try{if(($o??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(w.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=w.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=w.constants.O_NOFOLLOW??0;n=w.openSync(t,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|o,384);let i=w.fstatSync(n),s=w.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 l=i.mode&511;if((l&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${l.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);w.fchmodSync(n,384)}catch(r){if(n!==null)try{w.closeSync(n)}catch{}me||ie({event:"sidecar_disabled",reason:"open_failed",detail:O(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${O(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}se=t,C=n,ae=!0}var Uo=[/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 Fo(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Uo.some(n=>n.test(t))}function An(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=Mo(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Fo(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function Mo(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Go(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:An(e.url)}:e}function Ko(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=re(o,xe()),s=JSON.stringify({version:En,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:En,timestamp:t,type:r,output_truncated:!0})),s}function m(e){if(!ae||!se||C===null)return;let t=Go(e),n=Ko(t);try{if(w.fstatSync(C).size+Buffer.byteLength(n,"utf8")+1>_t){ae=!1;try{w.closeSync(C)}catch{}C=null,me||ie({event:"sidecar_disabled",reason:"size_limit",...se===null?{}:{path:O(se)},max_bytes:_t},`${O(`[allscale] sidecar exceeded ${_t} bytes; disabling it for the rest of this run. Rotate or remove ${se}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
6
|
`);return}w.appendFileSync(C,`${n}
|
|
7
|
-
`)}catch(r){if(ae=!1,C!==null){try{w.closeSync(C)}catch{}C=null}try{
|
|
8
|
-
`)}catch{}}}var M=
|
|
9
|
-
The CLI default is now ${
|
|
7
|
+
`)}catch(r){if(ae=!1,C!==null){try{w.closeSync(C)}catch{}C=null}try{me||ie({event:"sidecar_disabled",reason:"write_failed",detail:O(r.message)},`${O(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var M=An;function kn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function _e(){if(me=!1,ae=!1,C!==null){try{w.closeSync(C)}catch{}C=null}}function Ln(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||kn()||!t}var ye=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"]),Ho=new Set(Array.from(ye).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),jo=Array.from(ye).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Yo=new Set(["--otp-stdin","--password-stdin"]);function wt(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(ye.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ye.has(r)){t.push(r),n+1<e.length&&(ye.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(Ho.has(i)){t.push(`${i}<redacted>`);continue}}let o=Yo.has(r)?void 0:jo.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Tn(e){m({type:"error",code:e.code,message:O(e.message)}),m({type:"command-end",ok:!1,exitCode:e.exitCode}),_e()}var we=fe()??sn,ce={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 j(e){return un(e)?new URL(e).origin:null}function I(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function On(){let e=process.env[ce.TOKEN]?.trim();return e&&e.length>0?e:void 0}function bt(){let e=process.env[ce.PROFILE]?.trim();return e&&e.length>0?e:void 0}function be(){let e=process.env[ce.API_BASE]?.trim();return e&&e.length>0?e:void 0}function In(){let e=process.env[ce.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vn(){let e=process.env[ce.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Rn(){let e=process.env[ce.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Cn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(fe()===void 0&&we!==""&&"".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 ${we} (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 ${
|
|
14
|
-
`}var Y=T(require("fs")),
|
|
15
|
-
`)}};var ni=/_(removed|cleared|count|total)$/i;function ri(e,t){return typeof t=="number"&&ni.test(e)}var oi=new Set($e);function ii(e,t){return e==="token_symbol"&&typeof t=="string"&&oi.has(t)}var si=new Set(jn);function ai(e,t){return e==="otp_reason"&&typeof t=="string"&&si.has(t)}var Ue=100;function Fe(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ue),r=n.map(o=>Fe(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,Ue))n[o]=Re(o)&&!ri(o,i)&&!ii(o,i)&&!ai(o,i)?"<redacted>":Fe(i,t+1);if(r.length>Ue){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-Ue} more keys`}return n}if(typeof e=="string"){let n=li(e);return n!==void 0?O(JSON.stringify(Fe(n,t+1))):O(e)}return e}function li(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 ci(e){let t=mn()?void 0:2,n=Fe(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:O(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function ui(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 $r=require("crypto"),A=require("process");var G=/^0x[0-9a-fA-F]{64}$/,di=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function Yn(e){return typeof e=="string"&&di.includes(e)}var or=T(require("path"));var Lt=require("crypto"),l=T(require("fs")),E=T(require("path"));var Me=1024*1024,pi=5e3,fi=20,hi=3e4,At=4096,gi=new Int32Array(new SharedArrayBuffer(4)),Ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ge(e){return e instanceof Ee}var v=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},mi=null;function J(){return new a("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 Ke(){return(mi??process.platform)!=="win32"}function Qn(){if(!Ke())throw J()}function er(e){try{return l.default.lstatSync(e),!1}catch(t){if(!b(t,"ENOENT"))throw t}try{let t=l.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(b(t,"ENOENT"))return!0;throw t}}function b(e,t){return typeof e=="object"&&e!==null&&e.code===t}function Se(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function Ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function _i(e){Atomics.wait(gi,0,0,e)}function tr(e){try{return process.kill(e,0),!0}catch(t){return!b(t,"ESRCH")}}function yi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qn(e,t){let n=E.dirname(e);t&&l.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=l.default.lstatSync(n)}catch(i){if(!t&&b(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=l.default.openSync(n,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0));let i=l.default.fstatSync(o),s=l.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Ae(i,s))throw new Error("credential-store parent changed while it was being inspected");Se(i,"credential-store parent");let c=i;if((i.mode&63)!==0&&E.basename(n)===".allscale"&&(l.default.fchmodSync(o,448),c=l.default.fstatSync(o)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&l.default.closeSync(o)}return!0}function U(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=l.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&b(i,"ENOENT")?new v:i}if(!Ae(n,o))throw r.retryOnPathChange?new v: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 Ee;if(Se(n,"credential-store file"),process.platform!=="win32"){l.default.fchmodSync(t,384);let i=l.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 wi(e,t){if(t.size>Me)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Me+1),r=0;for(;r<n.length;){let o=l.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Me)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Wn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT"))try{if(l.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(b(i,"ENOENT"))return null;throw i}throw o}let n=l.default.fstatSync(t),r=U(e,t,n);return wi(t,r)}finally{t!==null&&l.default.closeSync(t)}}function Jn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT")&&er(e))return;throw o}let n=l.default.fstatSync(t),r=U(e,t,n);z(e,r)}finally{t!==null&&l.default.closeSync(t)}rr(E.dirname(e))}function bi(e){let t;try{t=l.default.lstatSync(e)}catch(n){if(b(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 Ee;Se(t,"credential-store replacement target")}function Ei(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:l.default.openSync(o,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(b(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function nr(e,t){let n=0;for(;n<t.length;){let r=l.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 rr(e){if(process.platform==="win32")return;let t=null;try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_DIRECTORY??0)|(l.default.constants.O_NOFOLLOW??0)),l.default.fsyncSync(t)}catch{}finally{if(t!==null)try{l.default.closeSync(t)}catch{}}}function Si(e,t){let n=Buffer.from(t,"utf8");if(n.length>Me)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),o=E.basename(e),i=null,s=null,c=!1;try{let u=Ei(r,o);i=u.fd,s=u.tempPath;let d=l.default.fstatSync(i);if((U(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");nr(i,n),l.default.fsyncSync(i),U(s,i,l.default.fstatSync(i));let h=i;i=null,l.default.closeSync(h),bi(e),l.default.renameSync(s,e),c=!0}finally{if(i!==null)try{l.default.closeSync(i)}catch{}if(!c&&s!==null)try{l.default.unlinkSync(s)}catch{}}rr(r)}function Ai(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function ki(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function Li(e,t){if(t.size>At)return null;let n=Buffer.alloc(At+1),r=0;for(;r<n.length;){let i=l.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>At)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 z(e,t){let n=l.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!Ae(n,t))throw new Error("credential-store lock changed while it was being inspected");Se(n,"credential-store lock"),l.default.unlinkSync(e)}function zn(e,t){let n=null;try{try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(u){if(b(u,"ENOENT"))try{let d=l.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new v}catch(d){if(b(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=l.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Li(n,o);return{state:(i?.target===t&&i?!tr(i.pid):Date.now()-o.mtimeMs>=hi)?"stale":"active",stats:o}}finally{n!==null&&l.default.closeSync(n)}}function Ti(e,t){for(let n=0;n<8;n+=1){let r=(0,Lt.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=l.default.openSync(o,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_WRONLY|(l.default.constants.O_NOFOLLOW??0),384);let c=l.default.fstatSync(s),u=U(o,s,c,{allowMultipleLinks:!0});return nr(s,Buffer.from(JSON.stringify(i),"utf8")),l.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(c){if(b(c,"EEXIST"))continue;try{l.default.unlinkSync(o)}catch{}throw c}finally{s!==null&&l.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Oi(e,t){let n;try{n=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(r){throw b(r,"ENOENT")?new v:r}try{let r=l.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Ae(o,t))throw new v;return{fd:n,lockPath:e,stats:o}}catch(r){throw l.default.closeSync(n),r}}function Vn(e){let t=null;try{try{t=l.default.openSync(e,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(n){if(b(n,"ENOENT"))try{let r=l.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new v}catch(r){if(b(r,"ENOENT"))return!1;throw r}throw n}return U(e,t,l.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&l.default.closeSync(t)}}function Ii(e){let t;try{t=l.default.openSync(e,l.default.constants.O_CREAT|l.default.constants.O_EXCL|l.default.constants.O_RDWR|(l.default.constants.O_NOFOLLOW??0),384)}catch(r){if(b(r,"EEXIST"))return null;throw r}let n=null;try{n=l.default.fstatSync(t);let r=U(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{z(e,n)}catch{}throw l.default.closeSync(t),r}}function W(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");_i(fi)}function Xn(e){let t=E.dirname(e),n=E.basename(e),r=Ai(e),o=ki(e),i=Ti(t,n),s=Date.now()+pi,c=!1,u=!1,d=null,p;try{for(;d===null;)try{if(Vn(o)){W(s,!0);continue}l.default.linkSync(i.claimPath,r),u=!0,d=Oi(r,i.stats),c=!0}catch(h){if(u&&!c){try{z(r,i.stats)}catch{}u=!1}if(h instanceof v){W(s,!1);continue}if(!b(h,"EEXIST"))throw h;let g;try{g=zn(r,n)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=Ii(o)}catch(_){if(_ instanceof v){W(s,!1);continue}throw _}if(y!==null){try{let _;try{_=zn(r,n)}catch(k){if(k instanceof v){W(s,!1);continue}throw k}_.state==="stale"&&z(r,_.stats)}finally{kt(y)}continue}}let f;try{f=Vn(o)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}W(s,f)}}catch(h){p=h}try{z(i.claimPath,i.stats)}catch(h){!b(h,"ENOENT")&&!c&&p===void 0&&(p=h)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function kt(e){try{z(e.lockPath,e.stats)}finally{l.default.closeSync(e.fd)}}function vi(e,t){let n=yi(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 Zn(e){let t=E.dirname(e),n=E.basename(e);for(let r of l.default.readdirSync(t)){let o=vi(r,n);if(o===null||tr(o))continue;let i=E.join(t,r),s=null;try{try{s=l.default.openSync(i,l.default.constants.O_RDONLY|(l.default.constants.O_NOFOLLOW??0)|(l.default.constants.O_NONBLOCK??0))}catch(d){if(b(d,"ENOENT")||b(d,"ELOOP"))continue;throw d}let c=l.default.fstatSync(s),u=l.default.lstatSync(i);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!Ae(c,u))continue;try{Se(c,"credential-store orphan")}catch{continue}z(i,c)}catch(c){if(!b(c,"ENOENT"))throw c}finally{s!==null&&l.default.closeSync(s)}}}function ke(e,t,n){if(!Ke()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw J();if(!qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw J()}});let s=Xn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:()=>{throw J()}})}finally{kt(s)}}if(!t.createParent){let i=!1;try{i=er(e)}catch{throw J()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw J()}})}throw J()}if(!qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=Xn(e);try{return Zn(e),n({read:()=>Wn(e),remove:()=>Jn(e),write:i=>Si(e,i)})}finally{kt(o)}}var Tt="allscale-cli";function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ir(e){return Rt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("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 Ot(){return new a("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 He(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var V,It=!1;function Ri(){return Ln()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Ci(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 Ni(){if(V!==void 0)return V;if(Ri())return It=!1,V=null,V;try{V=require("keytar"),It=!1}catch(e){It=!Ci(e),V=null}return V}var xi="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function sr(){let e=Ke()?"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 a("storage.unavailable",`${xi} `+e+" Never silently downgrade in production.")}async function vt(e){try{return await e()}catch{throw sr()}}var Ct=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await vt(()=>this.keytar.getPassword(Tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!ir(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await vt(()=>this.keytar.setPassword(Tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await vt(()=>this.keytar.deletePassword(Tt,t))}},Pi="credentials.json",Nt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??or.join(Et(),Pi)}read(t){let n;try{n=t.read()}catch(o){throw Ge(o)?Ot():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Rt(r)||!Rt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ge(r)?Ot():He()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!ir(r))throw X("plaintext file");return r}}async get(t){try{return ke(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{ke(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 a?r:He()}}async delete(t){try{ke(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 a?n:He()}}async clearProfile(t){try{return ke(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 a?n:Ge(n)?Ot():He()}}};function ar(e){if(e.insecureStorage)return Qn(),new Nt(e.insecureFilePath);let t=Ni();if(t)return new Ct(t);throw sr()}var xt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function je(){return new xt}var Ye="allscale_access_token",Pt="allscale_refresh_token";function lr(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 Bt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Dt(e,t){return e.find(n=>n.name===t)?.value??null}var cr=T(require("crypto")),ur=T(require("fs")),dr=T(require("path"));var Bi="key-id",Di="x-allscale-cli-version",$t="cli-1",$i="aScaLe_cli_obf_v1",Ui="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Fi(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 Mi=Fi(Ui,$i),pr=`Bearer ${Mi}`;function fr(e,t){let n=tt(e);if(n!==null)return t.find(r=>tt(r.base)===n)}function Gi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=fr(e,t);if(r)return r.key;if(H(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:H(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 Ki(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?fr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&H(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():$t}if(!H(t[0].base))return $t}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():$t}function Hi(){return"1.0.3"}function ji(){return new a("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 Ut(e,t){let n=Gi(t);if(!n)throw ji();let r=Ki(t),o=Math.floor(Date.now()/1e3).toString(),i=cr.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Di]:Hi()};return r.length>0&&(s[Bi]=r),s}function hr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Yi(e,t={}){let n;try{n=vn(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",cn(e)+(t.messageSuffix??""),{profile:e})}function gr(e){if(e.profileExplicit){let t=Yi(e.profile);if(t)return t}return new a("auth.no_token",ln(e.profile))}var qi=500,Wi=8,mr=100;function Ft(e,t=0){if(t>Wi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,mr),r=n.map(o=>Ft(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,mr))n[r]=Re(r)?"<redacted>":Ft(o,t+1);return n}return e}function Ji(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 _r(e,t=qi){let n=Ji(e),r=n===void 0?ve(e):JSON.stringify(Ft(n));return Ce(r,t)}var Mt=256*1024,qe=class extends a{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"}},We=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 Gt(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 qe(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,p=d===void 0?void 0:new Promise((h,g)=>{u=setTimeout(()=>{g(new We(e.status,d))},d),u.unref?.()});try{for(;;){let h=i.read(),{done:g,value:f}=p?await Promise.race([h,p]):await h;if(g)break;if(c+=f.byteLength,c>t)throw i.cancel().catch(()=>{}),new qe(e.status,t,n.oversizeKind);s.push(Buffer.from(f))}}catch(h){throw h instanceof We&&i.cancel(h).catch(()=>{}),h}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var zi="X-AllScale-Api-Key",Vi=3e4,Xi=32*1024*1024,Zi=4*1024*1024;function Qi(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 es(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 ts(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(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 Sr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ts(e.status,e.url)}}var yr="--dns-result-order=ipv4first";async function Je(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 p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("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=${yr} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${yr}`})}var Z=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??Vi;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");q(this.opts.apiBase),De(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=Qi(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(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();Nn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=Ar(t.path),u=s==="required"?!0:s==="none"?!1:os(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw gr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=hr(t.body),p=!!i||!!r?.access_token;u&&p&&!this.opts.override&&Be(this.opts.apiBase,r?.api_base);let h=this.buildHeaders({attachAuth:u&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();m({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let f;try{f=await fetch(o,{method:t.method??"GET",headers:h,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(_){throw new a("transport.network",`Network error contacting ${M(o)}: ${_ instanceof Error?_.message:String(_)}`)}if(m({type:"response",status:f.status,durationMs:Date.now()-g}),u&&!!r?.access_token&&!i&&f.status===401&&!t._isRefresh&&!this.opts.override){let _=await es(this.refreshSingleFlight(),t.signal),k=this.buildHeaders({attachAuth:u&&!!_.access_token,bodyForSig:d,tokens:_,extra:t.headers}),x=Date.now();m({type:"request",method:t.method??"GET",url:o});let L;try{L=await fetch(o,{method:t.method??"GET",headers:k,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(K){throw new a("transport.network",`Network error contacting ${M(o)} on refresh-retry: ${K instanceof Error?K.message:String(K)}`)}return m({type:"response",status:L.status,durationMs:Date.now()-x}),wr(L,{withMetadata:n.withMetadata,authBearing:u,responseKind:br(t)})}return wr(f,{withMetadata:n.withMetadata,authBearing:u&&p,agentKeyAuth:u&&!!i,responseKind:br(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ut(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=pr;let o=t.tokens;if(o?.agent_key)return r[zi]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=Bt([{name:Ye,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(Be(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${Ie()}.`);if(Be(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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=Bt([{name:Ye,value:t.access_token},{name:Pt,value:t.refresh_token}]),o=Ut("",this.opts.apiBase);m({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(f){throw m({type:"refresh",ok:!1}),new a("transport.network",s&&f instanceof Error&&f.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${f instanceof Error?f.message:String(f)}`)}finally{clearTimeout(c)}m({type:"response",status:u.status,durationMs:0});try{await Sr(u)}catch(f){throw m({type:"refresh",ok:!1}),f}if(u.status!==200){let f=null;try{await Je(u);let y=await cs(u);await Je(u,y),Lr(u.status,y),u.status===401&&(f=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw m({type:"refresh",ok:!1}),y}if(f)return m({type:"refresh",ok:!0,adopted:!0}),f;throw m({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Ie()}.`,{status:u.status})}let d=lr(u.headers),p=Dt(d,Ye),h=Dt(d,Pt);if(!p||!h)throw m({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:h};return await this.opts.tokenStore.set(this.opts.profile,g),m({type:"refresh",ok:!0}),g}},ns=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Ar(e){let t=e.split(/[?#]/,1)[0];return ns.some(n=>t===n||t.startsWith(`${n}/`))}var rs=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Kt(e){let t=e.split(/[?#]/,1)[0];return rs.some(n=>n.test(t))}function os(e){return Ar(e)||Kt(e)}async function wr(e,t={}){await Sr(e);let n=e.status>=200&&e.status<300;n||await Je(e);let r=t.responseKind??"mutation",i=await Gt(e,n?r==="query"?Xi:Zi:Mt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Je(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,p)=>{u[p]=d}),{status:e.status,headers:u,body:s}}return s}let c=us(s)??`HTTP ${e.status}`;if(Lr(e.status,s),as(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new a("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 a(u,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function br(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var is=2014,Er=2004;function kr(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 ss(e){return kr(e,is)}function as(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&kr(t,Er))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Ie()} 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:Er})}var ls=1e4;async function cs(e,t=ls){if(e.status>=200&&e.status<300)return"";try{return await Gt(e,Mt,{timeoutMs:t})}catch{return""}}function Lr(e,t){if(!(e>=200&&e<300)&&ss(t))throw new a("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"?_r(t):t})}function us(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)}var ds=/^\/(api\/)?(v1\/)?public\//;function Ht(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ds.test(n),o=n&&Kt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new Z({apiBase:e.apiBase,tokenStore:ar({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new Z({apiBase:e.apiBase,tokenStore:je(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var N={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},ps=new Set(Object.values(N));async function Tr(e,t,n){let{body:r,headers:o}=await gs(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:fs(o)}}function fs(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function jt(e,t){return hs(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function hs(e,t,n,r){let o;try{o=await e.request({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return Ir(o,r)}async function gs(e,t,n,r){let o;try{o=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Or(i,r);if(s!==null)throw s}throw i}return{body:Ir(o.body,r),headers:o.headers??{}}}function Or(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,o=typeof r.code=="number"?r.code:void 0;if(o===void 0||o===0||!ps.has(o))return null;let i=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return vr(o,i,t)}function Ir(e,t){if(e.code!==void 0&&e.code!==0)throw vr(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function vr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case N.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case N.CLI_OP_EXPIRED:return new a("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:r});case N.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case N.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_INVALID_PAYLOAD:case N.CLI_OP_SELF_TRANSFER:case N.CLI_OP_INSUFFICIENT_BALANCE:case N.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case N.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var Nr=require("child_process");function Rr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var ms=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function _s(e,t,n,r){if(Rr(e.CI)||ms.some(s=>Rr(e[s])))return"ci";let i=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!i?"ssh":n===!0||r===!0?null:"no-tty"}function ys(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+t+n:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+t+n:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+t+n}async function xr(e,t={}){if(!Qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${I(e)}`);let n=t._env??process.env,r=t._platform??process.platform,o=n.BROWSER?.trim();if(o&&o.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let i=o?null:_s(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(i)throw new a("wallet.requires_browser_auth",ys(i));if(r==="linux"&&!n.DISPLAY&&!o)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let s=ws(r,o);await bs(s.command,[...s.args,e])}function ws(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function bs(e,t){return new Promise((n,r)=>{let o;try{o=(0,Nr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Cr(e,s));return}let i=!1;o.once("error",s=>{i||(i=!0,r(Cr(e,s)))}),setImmediate(()=>{i||(i=!0,o.unref(),n())})})}function Cr(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Pr=T(require("http"));var Es=9e4,Ss=16*1024;function Br(e){let t=e.timeoutMs??Es;return new Promise((n,r)=>{let o=!1,i=!1,s=null,c,u,d=new Promise((h,g)=>{c=h,u=g}),p=Pr.createServer((h,g)=>{As(h,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>o,tryConsume:()=>o?!1:(o=!0,!0),onSuccess:f=>{s&&clearTimeout(s),c(f),p.close()}})});p.on("error",h=>{let g=new a("transport.network",`Loopback listener error: ${h.message}`);i?u(g):r(g),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let h=p.address();if(!h||typeof h=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let g=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,f=g!=null?Math.max(1,Math.min(t,g)):t,y=g!=null&&g<=t;s=setTimeout(()=>{u(new a("wallet.bridge_timeout",`Bridge timed out after ${f}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},f),s.unref?.(),i=!0,n({port:h.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function As(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let o=0,i=[],s=!1;e.on("data",c=>{if(!s){if(o+=c.length,o>Ss){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}i.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(i).toString("utf-8"),u;try{u=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!u||typeof u!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=u,p=typeof d.state=="string"?d.state:"",h=typeof d.result_token=="string"?d.result_token:void 0,g=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!ks(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(h===void 0&&g===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:h,result_data:g})}),e.on("error",()=>{s||(s=!0)})}function ks(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Yt(e){try{return JSON.parse(e),!0}catch{return!1}}function Dr(){let e=process.stdin,t="",n=!1,r=()=>{},o=250,i=null,s=()=>{i&&(clearTimeout(i),i=null)},c=()=>{s(),i=setTimeout(()=>{n||(u(),r(t.trim()))},o),i.unref?.()},u=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",h),e.pause()},d=f=>{if(n)return;s(),t+=f.toString();let y=t.trim(),_=t.length-t.trimStart().length,k=t.indexOf(`
|
|
17
|
-
`,_),x=k===-1?"":t.slice(_,k).trim();if(y.startsWith("{")){if(
|
|
18
|
-
`).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(K))){
|
|
19
|
-
`)&&(u(),r(""))},p=()=>{if(n)return;let f=t.trim();if(!f){u();return}u(),r(f)},h=()=>{n||u()},g=new Promise(f=>{r=f});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",h),{promise:g,cancel:()=>{n||u()}}}function
|
|
20
|
-
`),
|
|
21
|
-
`),
|
|
22
|
-
`),
|
|
23
|
-
`);let
|
|
24
|
-
`)},15e3);
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${we}
|
|
14
|
+
`}var Y=T(require("fs")),Nn=T(require("os")),Et=T(require("path")),St=T(require("@iarna/toml"));var Jo=".allscale",zo="config.toml";function At(){return Et.join(Nn.homedir(),Jo)}function Vo(){return Et.join(At(),zo)}function Be(){let e=Vo();if(!Y.existsSync(e))return{};let t=Y.readFileSync(e,"utf-8");try{return St.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function xn(e){return Object.keys(e.profile??{}).sort()}function Pn(e,t){return e.profile?.[t]}function Bn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function q(e){if(!te(e))throw new a("input.invalid",`Refusing to send credentials to API base ${I(e)}. `+pe)}function De(e,t){q(e);let n=j(e),r=typeof t=="string"?j(t):null;if(n&&r===n)return;let o=typeof t=="string"?I(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${I(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function Dn(e,t){let n=j(e),r=j(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${I(t)} because it is outside the configured API origin ${I(e)}.`)}function $e(e){let t=Zo(e);if(t)throw new a("input.invalid",t.message)}function Xo(){let e=fe();if(e===void 0)return;let t=he();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Zo(e){let t=Xo();if(t===void 0||H(e))return;let{endpoints:n,fromPairs:r}=t,o=j(e),i=n.map(l=>j(l)).filter(l=>l!==null);if(o!==null&&i.includes(o))return;let s=n.map(l=>I(l)).join(", ");return{message:r?`Refusing to send to ${I(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 ${I(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var $n=require("@noble/hashes/sha3");function Un(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Qo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Fn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Ue=["USDT","USDC"];function Mn(e){return Qo[e.toLowerCase()]??null}function Gn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function Kn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,$n.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let o=0;o<t.length;o+=1){let i=t[o];if(!/[a-fA-F]/.test(i))continue;let s=Number.parseInt(r[o],16)>=8;if(s&&i!==i.toUpperCase()||!s&&i!==i.toLowerCase())return!1}return!0}var ue="0x1234567890abcdef1234567890abcdef12345678";function ei(e){return e.toLowerCase()===ue}function Hn(e,t="--to"){if(ei(e))throw new a("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var ti=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function jn(e){return ti.has(e.toLowerCase())}function kt(e,t){let r={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return r?`${r}/${t}`:""}function Yn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function qn(e){return e===1?"USDT":"USDC"}var ni="unknown_otp_id",ri="invalid_code",oi="expired_code";function ii(e){return`'${e.replace(/'/g,"'\\''")}'`}function Wn(e){return`Run \`allscale otp-send --email ${ii(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var si=new Map([[ni,(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. ${Wn(t)}`],[ri,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.`],[oi,(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. ${Wn(t)}`]]);var Jn=[...si.keys()];var P=require("@oclif/core"),Ee=class e extends $.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:$.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:$.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ne()==="public"}),"api-base":$.Flags.string({description:et,helpGroup:"GLOBAL",hidden:ne()==="public"}),"insecure-storage":$.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{mt(this.jsonEnabled()),yt(),m({type:"session-start",command:this.id??"",argv:wt(this.argv)});let t=this.constructor;if(ne()==="public"){if(this.argv.some(i=>i==="--token"||i.startsWith("--token=")))throw new a("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 a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&be()!==void 0)throw new a("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=Ln(this.jsonEnabled()),r=this.argv.length===0&&!n&&gi(t)?this.config.findCommand(this.id??""):void 0;if(r){_e();let i=await(0,$.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&&!Rn())throw this.argv.length>0&&await this.parse(),new a("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 m({type:"command-end",ok:!0}),_e(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||gn(o),{data:o})}catch(t){let n=hn(t);Tn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{mt(!1)}}resolveSessionApiBaseChain(t){let n=Be(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||bt()!==void 0,s=Bn(n,r,bt()),l=Pn(n,s),u=ne()==="public"&&be()!==void 0,d=o??(u?void 0:be()),p=d??l?.api_base??we,h=Cn({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return h&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ie({event:"legacy_staging_profile",api_base:p,profile:s},h)),{apiBase:p,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:l?.api_base,profile:s,profileExplicit:i}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||q(n),n}resolveContext(t){if(ne()==="public"){if(t.token!==void 0)throw new a("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 a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&be()!==void 0)throw new a("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:l,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(o),$e(o)),{apiBase:o,profile:l,token:n??On(),insecureStorage:r||In(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${hi(t)}
|
|
15
|
+
`)}};var ai=/_(removed|cleared|count|total)$/i;function li(e,t){return typeof t=="number"&&ai.test(e)}var ci=new Set(Ue);function ui(e,t){return e==="token_symbol"&&typeof t=="string"&&ci.has(t)}var di=new Set(Jn);function pi(e,t){return e==="otp_reason"&&typeof t=="string"&&di.has(t)}var Fe=100;function Me(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Fe),r=n.map(o=>Me(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,Fe))n[o]=Ce(o)&&!li(o,i)&&!ui(o,i)&&!pi(o,i)?"<redacted>":Me(i,t+1);if(r.length>Fe){let o="<truncated>";for(;o in n;)o=`<${o}>`;n[o]=`${r.length-Fe} more keys`}return n}if(typeof e=="string"){let n=fi(e);return n!==void 0?O(JSON.stringify(Me(n,t+1))):O(e)}return e}function fi(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 hi(e){let t=bn()?void 0:2,n=Me(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:O(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function gi(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 jr=require("crypto"),A=require("process");var G=/^0x[0-9a-fA-F]{64}$/,mi=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function zn(e){return typeof e=="string"&&mi.includes(e)}var lr=T(require("path"));var Ot=require("crypto"),c=T(require("fs")),E=T(require("path"));var Ge=1024*1024,_i=5e3,yi=20,wi=3e4,Lt=4096,bi=new Int32Array(new SharedArrayBuffer(4)),Se=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ke(e){return e instanceof Se}var v=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ei=null;function J(){return new a("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 He(){return(Ei??process.platform)!=="win32"}function rr(){if(!He())throw J()}function or(e){try{return c.default.lstatSync(e),!1}catch(t){if(!b(t,"ENOENT"))throw t}try{let t=c.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(b(t,"ENOENT"))return!0;throw t}}function b(e,t){return typeof e=="object"&&e!==null&&e.code===t}function Ae(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ke(e,t){return e.dev===t.dev&&e.ino===t.ino}function Si(e){Atomics.wait(bi,0,0,e)}function ir(e){try{return process.kill(e,0),!0}catch(t){return!b(t,"ESRCH")}}function Ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vn(e,t){let n=E.dirname(e);t&&c.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=c.default.lstatSync(n)}catch(i){if(!t&&b(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=c.default.openSync(n,c.default.constants.O_RDONLY|(c.default.constants.O_DIRECTORY??0)|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0));let i=c.default.fstatSync(o),s=c.default.lstatSync(n);if(!i.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ke(i,s))throw new Error("credential-store parent changed while it was being inspected");Ae(i,"credential-store parent");let l=i;if((i.mode&63)!==0&&E.basename(n)===".allscale"&&(c.default.fchmodSync(o,448),l=c.default.fstatSync(o)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{o!==null&&c.default.closeSync(o)}return!0}function U(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=c.default.lstatSync(e)}catch(i){throw r.retryOnPathChange&&b(i,"ENOENT")?new v:i}if(!ke(n,o))throw r.retryOnPathChange?new v: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 Se;if(Ae(n,"credential-store file"),process.platform!=="win32"){c.default.fchmodSync(t,384);let i=c.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 ki(e,t){if(t.size>Ge)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ge+1),r=0;for(;r<n.length;){let o=c.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Ge)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Xn(e){let t=null;try{try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT"))try{if(c.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(i){if(b(i,"ENOENT"))return null;throw i}throw o}let n=c.default.fstatSync(t),r=U(e,t,n);return ki(t,r)}finally{t!==null&&c.default.closeSync(t)}}function Zn(e){let t=null;try{try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(o){if(b(o,"ENOENT")&&or(e))return;throw o}let n=c.default.fstatSync(t),r=U(e,t,n);z(e,r)}finally{t!==null&&c.default.closeSync(t)}ar(E.dirname(e))}function Li(e){let t;try{t=c.default.lstatSync(e)}catch(n){if(b(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 Se;Ae(t,"credential-store replacement target")}function Ti(e,t){for(let n=0;n<8;n+=1){let r=(0,Ot.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:c.default.openSync(o,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_WRONLY|(c.default.constants.O_NOFOLLOW??0),384),tempPath:o}}catch(i){if(b(i,"EEXIST"))continue;throw i}}throw new Error("could not allocate a unique credential-store temp file")}function sr(e,t){let n=0;for(;n<t.length;){let r=c.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 ar(e){if(process.platform==="win32")return;let t=null;try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_DIRECTORY??0)|(c.default.constants.O_NOFOLLOW??0)),c.default.fsyncSync(t)}catch{}finally{if(t!==null)try{c.default.closeSync(t)}catch{}}}function Oi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ge)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),o=E.basename(e),i=null,s=null,l=!1;try{let u=Ti(r,o);i=u.fd,s=u.tempPath;let d=c.default.fstatSync(i);if((U(s,i,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");sr(i,n),c.default.fsyncSync(i),U(s,i,c.default.fstatSync(i));let h=i;i=null,c.default.closeSync(h),Li(e),c.default.renameSync(s,e),l=!0}finally{if(i!==null)try{c.default.closeSync(i)}catch{}if(!l&&s!==null)try{c.default.unlinkSync(s)}catch{}}ar(r)}function Ii(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function vi(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function Ri(e,t){if(t.size>Lt)return null;let n=Buffer.alloc(Lt+1),r=0;for(;r<n.length;){let i=c.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Lt)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 z(e,t){let n=c.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ke(n,t))throw new Error("credential-store lock changed while it was being inspected");Ae(n,"credential-store lock"),c.default.unlinkSync(e)}function Qn(e,t){let n=null;try{try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(u){if(b(u,"ENOENT"))try{let d=c.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new v}catch(d){if(b(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=c.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),i=Ri(n,o);return{state:(i?.target===t&&i?!ir(i.pid):Date.now()-o.mtimeMs>=wi)?"stale":"active",stats:o}}finally{n!==null&&c.default.closeSync(n)}}function Ci(e,t){for(let n=0;n<8;n+=1){let r=(0,Ot.randomBytes)(12).toString("hex"),o=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),i={pid:process.pid,nonce:r,target:t},s=null;try{s=c.default.openSync(o,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_WRONLY|(c.default.constants.O_NOFOLLOW??0),384);let l=c.default.fstatSync(s),u=U(o,s,l,{allowMultipleLinks:!0});return sr(s,Buffer.from(JSON.stringify(i),"utf8")),c.default.fsyncSync(s),{claimPath:o,metadata:i,stats:u}}catch(l){if(b(l,"EEXIST"))continue;try{c.default.unlinkSync(o)}catch{}throw l}finally{s!==null&&c.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ni(e,t){let n;try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(r){throw b(r,"ENOENT")?new v:r}try{let r=c.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ke(o,t))throw new v;return{fd:n,lockPath:e,stats:o}}catch(r){throw c.default.closeSync(n),r}}function er(e){let t=null;try{try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(n){if(b(n,"ENOENT"))try{let r=c.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new v}catch(r){if(b(r,"ENOENT"))return!1;throw r}throw n}return U(e,t,c.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&c.default.closeSync(t)}}function xi(e){let t;try{t=c.default.openSync(e,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_RDWR|(c.default.constants.O_NOFOLLOW??0),384)}catch(r){if(b(r,"EEXIST"))return null;throw r}let n=null;try{n=c.default.fstatSync(t);let r=U(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{z(e,n)}catch{}throw c.default.closeSync(t),r}}function W(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");Si(yi)}function tr(e){let t=E.dirname(e),n=E.basename(e),r=Ii(e),o=vi(e),i=Ci(t,n),s=Date.now()+_i,l=!1,u=!1,d=null,p;try{for(;d===null;)try{if(er(o)){W(s,!0);continue}c.default.linkSync(i.claimPath,r),u=!0,d=Ni(r,i.stats),l=!0}catch(h){if(u&&!l){try{z(r,i.stats)}catch{}u=!1}if(h instanceof v){W(s,!1);continue}if(!b(h,"EEXIST"))throw h;let g;try{g=Qn(r,n)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}if(g.state==="absent")continue;if(g.state==="stale"){let y;try{y=xi(o)}catch(_){if(_ instanceof v){W(s,!1);continue}throw _}if(y!==null){try{let _;try{_=Qn(r,n)}catch(k){if(k instanceof v){W(s,!1);continue}throw k}_.state==="stale"&&z(r,_.stats)}finally{Tt(y)}continue}}let f;try{f=er(o)}catch(y){if(y instanceof v){W(s,!1);continue}throw y}W(s,f)}}catch(h){p=h}try{z(i.claimPath,i.stats)}catch(h){!b(h,"ENOENT")&&!l&&p===void 0&&(p=h)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function Tt(e){try{z(e.lockPath,e.stats)}finally{c.default.closeSync(e.fd)}}function Pi(e,t){let n=Ai(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 nr(e){let t=E.dirname(e),n=E.basename(e);for(let r of c.default.readdirSync(t)){let o=Pi(r,n);if(o===null||ir(o))continue;let i=E.join(t,r),s=null;try{try{s=c.default.openSync(i,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(d){if(b(d,"ENOENT")||b(d,"ELOOP"))continue;throw d}let l=c.default.fstatSync(s),u=c.default.lstatSync(i);if(!l.isFile()||u.isSymbolicLink()||!u.isFile()||!ke(l,u))continue;try{Ae(l,"credential-store orphan")}catch{continue}z(i,l)}catch(l){if(!b(l,"ENOENT"))throw l}finally{s!==null&&c.default.closeSync(s)}}}function Le(e,t,n){if(!He()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw J();if(!Vn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw J()}});let s=tr(e);try{return nr(e),n({read:()=>Xn(e),remove:()=>Zn(e),write:()=>{throw J()}})}finally{Tt(s)}}if(!t.createParent){let i=!1;try{i=or(e)}catch{throw J()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw J()}})}throw J()}if(!Vn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=tr(e);try{return nr(e),n({read:()=>Xn(e),remove:()=>Zn(e),write:i=>Oi(e,i)})}finally{Tt(o)}}var It="allscale-cli";function Nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cr(e){return Nt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("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 vt(){return new a("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 je(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var V,Rt=!1;function Bi(){return vn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Di(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 $i(){if(V!==void 0)return V;if(Bi())return Rt=!1,V=null,V;try{V=require("keytar"),Rt=!1}catch(e){Rt=!Di(e),V=null}return V}var Ui="OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable).";function ur(){let e=He()?"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 a("storage.unavailable",`${Ui} `+e+" Never silently downgrade in production.")}async function Ct(e){try{return await e()}catch{throw ur()}}var xt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Ct(()=>this.keytar.getPassword(It,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!cr(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Ct(()=>this.keytar.setPassword(It,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Ct(()=>this.keytar.deletePassword(It,t))}},Fi="credentials.json",Pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??lr.join(At(),Fi)}read(t){let n;try{n=t.read()}catch(o){throw Ke(o)?vt():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Nt(r)||!Nt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ke(r)?vt():je()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!cr(r))throw X("plaintext file");return r}}async get(t){try{return Le(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{Le(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 a?r:je()}}async delete(t){try{Le(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 a?n:je()}}async clearProfile(t){try{return Le(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 a?n:Ke(n)?vt():je()}}};function dr(e){if(e.insecureStorage)return rr(),new Pt(e.insecureFilePath);let t=$i();if(t)return new xt(t);throw ur()}var Bt=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ye(){return new Bt}var qe="allscale_access_token",Dt="allscale_refresh_token";function pr(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 $t(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Ut(e,t){return e.find(n=>n.name===t)?.value??null}var fr=T(require("crypto")),hr=T(require("fs")),gr=T(require("path"));var Mi="key-id",Gi="x-allscale-cli-version",Ft="cli-1",Ki="aScaLe_cli_obf_v1",Hi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function ji(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 Yi=ji(Hi,Ki),mr=`Bearer ${Yi}`;function _r(e,t){let n=rt(e);if(n!==null)return t.find(r=>rt(r.base)===n)}function qi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=_r(e,t);if(r)return r.key;if(H(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:H(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 Wi(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?_r(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&H(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():Ft}if(!H(t[0].base))return Ft}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Ft}function Ji(){return"1.0.5"}function zi(){return new a("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 Mt(e,t){let n=qi(t);if(!n)throw zi();let r=Wi(t),o=Math.floor(Date.now()/1e3).toString(),i=fr.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Gi]:Ji()};return r.length>0&&(s[Mi]=r),s}function yr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Vi(e,t={}){let n;try{n=xn(Be())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",fn(e)+(t.messageSuffix??""),{profile:e})}function wr(e){if(e.profileExplicit){let t=Vi(e.profile);if(t)return t}return new a("auth.no_token",pn(e.profile))}var Xi=new Set;var Zi=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"]),Gt=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"]),Kt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function We(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function br(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Qi=new Set(["cli_op:all"]),es=new Set([...Qi].map(We));var yl=new Set([...[...Zi,...Gt,...Xi].map(We),...Kt,...es]);var ts=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,ns=/is not available to API keys/i,Er=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Sr(e){if(typeof e!="string")return;let t=ts.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),o=ns.test(n),i=!o&&Er.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let l=r.split(",").map(u=>u.trim()).filter(u=>Er.test(u));s=l.length>0?l:void 0}if(!(i===void 0&&!o))return{required:i,granted:s,notAvailableToKeys:o}}function Ar(e){if(Kt.has(We(e)))return{kind:"ungrantable"};for(let t of Gt)if(br(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Ht(e,t,n,r){let o=Sr(e),i=o?.notAvailableToKeys===!0,s=o?.required??r?.scope,l=o?.granted,u=l===void 0?"":` This key holds ${l.length>0?l.join(", "):"no scopes"}.`;if(i||r?.ungrantableReason!==void 0){let d=r?.ungrantableReason!==void 0?`: ${r.ungrantableReason}`:"";return new a("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:[],...l===void 0?{}:{granted_scopes:l},ungrantable:!0})}if(s!==void 0){let d=Ar(s),p=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 \`${ge()}\` with \`--scopes ${s}\`.`:`The browser approval screen does not offer \`${s}\`, so \`device-login\` cannot grant it \u2014 use \`${ge()}\` with \`--scopes ${s}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${s}\`, required by ${t}.${u} ${p}`,{...n,missing_scopes:[s],...l===void 0?{}:{granted_scopes:l},...d.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${t}.${u} Re-run \`allscale device-login\` (or \`${ge()}\`) and grant the required scope.`,n)}var rs=500,os=8,kr=100;function jt(e,t=0){if(t>os)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,kr),r=n.map(o=>jt(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,kr))n[r]=Ce(r)?"<redacted>":jt(o,t+1);return n}return e}function is(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 Lr(e,t=rs){let n=is(e),r=n===void 0?Re(e):JSON.stringify(jt(n));return Ne(r,t)}var Yt=256*1024,Je=class extends a{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"}},ze=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 qt(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 Je(e.status,t,n.oversizeKind);if(!e.body)return"";let i=e.body.getReader(),s=[],l=0,u,d=n.timeoutMs,p=d===void 0?void 0:new Promise((h,g)=>{u=setTimeout(()=>{g(new ze(e.status,d))},d),u.unref?.()});try{for(;;){let h=i.read(),{done:g,value:f}=p?await Promise.race([h,p]):await h;if(g)break;if(l+=f.byteLength,l>t)throw i.cancel().catch(()=>{}),new Je(e.status,t,n.oversizeKind);s.push(Buffer.from(f))}}catch(h){throw h instanceof ze&&i.cancel(h).catch(()=>{}),h}finally{u!==void 0&&clearTimeout(u);try{i.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var ss="X-AllScale-Api-Key",as=3e4,ls=32*1024*1024,cs=4*1024*1024;function us(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 ds(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 ps(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${M(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 Rr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ps(e.status,e.url)}}var Tr="--dns-result-order=ipv4first";async function Ve(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)??"",l=/^\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||l)&&(o||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("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=${Tr} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Tr}`})}var Z=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??as;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");q(this.opts.apiBase),$e(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=us(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:i.signal},n,o)}catch(s){throw i.timedOut()?new a("transport.timeout",`Request to ${M(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${M(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();Dn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",l=Cr(t.path),u=s==="required"?!0:s==="none"?!1:gs(t.path);if((l||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw wr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=yr(t.body),p=!!i||!!r?.access_token;u&&p&&!this.opts.override&&De(this.opts.apiBase,r?.api_base);let h=this.buildHeaders({attachAuth:u&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();m({type:"request",method:t.method??"GET",url:o,...t._isRefresh?{refresh:!0}:{}});let f;try{f=await fetch(o,{method:t.method??"GET",headers:h,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(_){throw new a("transport.network",`Network error contacting ${M(o)}: ${_ instanceof Error?_.message:String(_)}`)}if(m({type:"response",status:f.status,durationMs:Date.now()-g}),u&&!!r?.access_token&&!i&&f.status===401&&!t._isRefresh&&!this.opts.override){let _=await ds(this.refreshSingleFlight(),t.signal),k=this.buildHeaders({attachAuth:u&&!!_.access_token,bodyForSig:d,tokens:_,extra:t.headers}),x=Date.now();m({type:"request",method:t.method??"GET",url:o});let L;try{L=await fetch(o,{method:t.method??"GET",headers:k,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(K){throw new a("transport.network",`Network error contacting ${M(o)} on refresh-retry: ${K instanceof Error?K.message:String(K)}`)}return m({type:"response",status:L.status,durationMs:Date.now()-x}),Or(L,{withMetadata:n.withMetadata,authBearing:u,responseKind:Ir(t)})}return Or(f,{withMetadata:n.withMetadata,authBearing:u&&p,agentKeyAuth:u&&!!i,responseKind:Ir(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Mt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=mr;let o=t.tokens;if(o?.agent_key)return r[ss]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=$t([{name:qe,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(De(this.opts.apiBase,n.api_base),n.agent_key)throw new a("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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${ve()}.`);if(De(this.opts.apiBase,t.api_base),t.agent_key)throw new a("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=$t([{name:qe,value:t.access_token},{name:Dt,value:t.refresh_token}]),o=Mt("",this.opts.apiBase);m({type:"request",method:"POST",url:n,refresh:!0});let i=new AbortController,s=!1,l=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(f){throw m({type:"refresh",ok:!1}),new a("transport.network",s&&f instanceof Error&&f.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${f instanceof Error?f.message:String(f)}`)}finally{clearTimeout(l)}m({type:"response",status:u.status,durationMs:0});try{await Rr(u)}catch(f){throw m({type:"refresh",ok:!1}),f}if(u.status!==200){let f=null;try{await Ve(u);let y=await bs(u);await Ve(u,y),Nr(u.status,y),u.status===401&&(f=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw m({type:"refresh",ok:!1}),y}if(f)return m({type:"refresh",ok:!0,adopted:!0}),f;throw m({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ve()}.`,{status:u.status})}let d=pr(u.headers),p=Ut(d,qe),h=Ut(d,Dt);if(!p||!h)throw m({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:h};return await this.opts.tokenStore.set(this.opts.profile,g),m({type:"refresh",ok:!0}),g}},fs=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Cr(e){let t=e.split(/[?#]/,1)[0];return fs.some(n=>t===n||t.startsWith(`${n}/`))}var hs=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Wt(e){let t=e.split(/[?#]/,1)[0];return hs.some(n=>n.test(t))}function gs(e){return Cr(e)||Wt(e)}async function Or(e,t={}){await Rr(e);let n=e.status>=200&&e.status<300;n||await Ve(e);let r=t.responseKind??"mutation",i=await qt(e,n?r==="query"?ls:cs:Yt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ve(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,p)=>{u[p]=d}),{status:e.status,headers:u,body:s}}return s}let l=Es(s)??`HTTP ${e.status}`;if(Nr(e.status,s),ys(e.status,s,t),Jt(s,2102))throw Ht(s.errors,"this API request",{status:e.status,backend_code:2102});if(e.status===401){if(t.agentKeyAuth)throw new a("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 a(u,l,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",l,{status:403,body:s}):e.status===404?new a("not_found",l,{status:404,body:s}):e.status===429?new a("rate_limited",l,{status:429,body:s}):e.status>=500?new a("backend.internal",l,{status:e.status,body:s}):new a("input.invalid",l,{status:e.status,body:s})}function Ir(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var ms=2014,vr=2004;function Jt(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 _s(e){return Jt(e,ms)}function ys(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Jt(t,vr))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ve()} 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:vr})}var ws=1e4;async function bs(e,t=ws){if(e.status>=200&&e.status<300)return"";try{return await qt(e,Yt,{timeoutMs:t})}catch{return""}}function Nr(e,t){if(!(e>=200&&e<300)&&_s(t))throw new a("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"?Lr(t):t})}function Es(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)}var Ss=/^\/(api\/)?(v1\/)?public\//;function zt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Ss.test(n),o=n&&Wt(n),i=r&&!o&&!t.forceAuth;if(e.token)return new Z({apiBase:e.apiBase,tokenStore:Ye(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(i)return new Z({apiBase:e.apiBase,tokenStore:Ye(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new Z({apiBase:e.apiBase,tokenStore:dr({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(o)return new Z({apiBase:e.apiBase,tokenStore:Ye(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var N={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},As=new Set(Object.values(N));async function xr(e,t,n){let{body:r,headers:o}=await Ts(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:ks(o)}}function ks(e){let t=e.date??e.Date??Object.entries(e).find(([r])=>r.toLowerCase()==="date")?.[1];if(t===void 0)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}async function Vt(e,t){return Ls(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function Ls(e,t,n,r){let o;try{o=await e.request({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Pr(i,r);if(s!==null)throw s}throw i}return Br(o,r)}async function Ts(e,t,n,r){let o;try{o=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(i){if(i instanceof a){let s=Pr(i,r);if(s!==null)throw s}throw i}return{body:Br(o.body,r),headers:o.headers??{}}}function Pr(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,o=typeof r.code=="number"?r.code:void 0;if(o===void 0||o===0||!As.has(o))return null;let i=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return Dr(o,i,t)}function Br(e,t){if(e.code!==void 0&&e.code!==0)throw Dr(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function Dr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case N.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case N.CLI_OP_EXPIRED:return new a("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:r});case N.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case N.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_INVALID_PAYLOAD:case N.CLI_OP_SELF_TRANSFER:case N.CLI_OP_INSUFFICIENT_BALANCE:case N.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case N.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case N.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var Fr=require("child_process");function $r(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Os=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Is(e,t,n,r){if($r(e.CI)||Os.some(s=>$r(e[s])))return"ci";let i=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!i?"ssh":n===!0||r===!0?null:"no-tty"}function vs(e){let t=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",n=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+t+n:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+t+n:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+t+n}async function Mr(e,t={}){if(!tt(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${I(e)}`);let n=t._env??process.env,r=t._platform??process.platform,o=n.BROWSER?.trim();if(o&&o.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let i=o?null:Is(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(i)throw new a("wallet.requires_browser_auth",vs(i));if(r==="linux"&&!n.DISPLAY&&!o)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let s=Rs(r,o);await Cs(s.command,[...s.args,e])}function Rs(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Cs(e,t){return new Promise((n,r)=>{let o;try{o=(0,Fr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Ur(e,s));return}let i=!1;o.once("error",s=>{i||(i=!0,r(Ur(e,s)))}),setImmediate(()=>{i||(i=!0,o.unref(),n())})})}function Ur(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Gr=T(require("http"));var Ns=9e4,xs=16*1024;function Kr(e){let t=e.timeoutMs??Ns;return new Promise((n,r)=>{let o=!1,i=!1,s=null,l,u,d=new Promise((h,g)=>{l=h,u=g}),p=Gr.createServer((h,g)=>{Ps(h,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>o,tryConsume:()=>o?!1:(o=!0,!0),onSuccess:f=>{s&&clearTimeout(s),l(f),p.close()}})});p.on("error",h=>{let g=new a("transport.network",`Loopback listener error: ${h.message}`);i?u(g):r(g),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let h=p.address();if(!h||typeof h=="string"){p.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let g=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,f=g!=null?Math.max(1,Math.min(t,g)):t,y=g!=null&&g<=t;s=setTimeout(()=>{u(new a("wallet.bridge_timeout",`Bridge timed out after ${f}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),p.close()},f),s.unref?.(),i=!0,n({port:h.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function Ps(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let l={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(l["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,l)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let o=0,i=[],s=!1;e.on("data",l=>{if(!s){if(o+=l.length,o>xs){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}i.push(l)}}),e.on("end",()=>{if(s)return;let l=Buffer.concat(i).toString("utf-8"),u;try{u=JSON.parse(l)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!u||typeof u!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=u,p=typeof d.state=="string"?d.state:"",h=typeof d.result_token=="string"?d.result_token:void 0,g=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!Bs(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(h===void 0&&g===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:h,result_data:g})}),e.on("error",()=>{s||(s=!0)})}function Bs(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function Xt(e){try{return JSON.parse(e),!0}catch{return!1}}function Hr(){let e=process.stdin,t="",n=!1,r=()=>{},o=250,i=null,s=()=>{i&&(clearTimeout(i),i=null)},l=()=>{s(),i=setTimeout(()=>{n||(u(),r(t.trim()))},o),i.unref?.()},u=()=>{n=!0,s(),e.off("data",d),e.off("end",p),e.off("error",h),e.pause()},d=f=>{if(n)return;s(),t+=f.toString();let y=t.trim(),_=t.length-t.trimStart().length,k=t.indexOf(`
|
|
17
|
+
`,_),x=k===-1?"":t.slice(_,k).trim();if(y.startsWith("{")){if(Xt(y)){u(),r(y);return}if(k===-1){l();return}if(!Xt(x)&&!x.endsWith("}")){let L=t.slice(k+1),K=L.split(`
|
|
18
|
+
`).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(K))){l();return}}u(),r(Xt(x)?x:t.slice(_).trim());return}if(k!==-1){u(),r(x);return}else!y&&t.includes(`
|
|
19
|
+
`)&&(u(),r(""))},p=()=>{if(n)return;let f=t.trim();if(!f){u();return}u(),r(f)},h=()=>{n||u()},g=new Promise(f=>{r=f});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",h),{promise:g,cancel:()=>{n||u()}}}function Ds(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function Yr(e){let t=zt(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Ks(n),o=e._openBrowser??Mr,i=e._startListener??Kr,s=e.mode??"ack",l=e._readPaste!==void 0||process.stdin.isTTY===!0,u=(0,jr.randomBytes)(32).toString("hex"),d=Date.now(),p=await xr(t,e.op,e.payload);m({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let g=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,f=2147483647,_=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,k=9e5,x=6e4,L=g!=null&&Number.isFinite(g)&&g>0?g:null,K=Math.max(0,Math.round((L??0)/1e3)),R=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=R!=null&&R<=f?R:null,B,de,Qt=!1,en=!1,tn=!1;if(L!=null){let S=Math.min(L,f),D=L>f;F!=null&&F<S?(B=F,de="caller"):(B=S,de=D?"timer_ceiling":"op_ttl",Qt=!D&&R!=null&&R>S)}else{let S=p.expires_at*1e3-d,D=Number.isFinite(S)?Math.min(Math.max(S,x),k):k,Q=F??_;Q>D?(B=D,de="op_ttl_unverified",en=R!=null&&R>D):(B=Q,de=F!=null?"caller":"unknown_ttl"),tn=R!=null&&F==null}let to=de==="op_ttl",no=L!=null?`~${K}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${no}, waiting up to ${Math.round(B/1e3)}s for confirmation).
|
|
20
|
+
`),Qt&&A.stderr.write(`Note: the confirmation wait of ${R}ms is longer than the confirmation link's remaining life (${Math.round(B/1e3)}s, from the server's stated expiry and its own clock), so the wait was capped at that.
|
|
21
|
+
`),en&&A.stderr.write(`Note: the confirmation wait of ${R}ms is longer than the confirmation link's remaining life (~${Math.round(B/1e3)}s), so the wait was capped at that. No server-relative TTL was available, so that figure is the link's stated expiry read against THIS machine's clock \u2014 approximate: short if your clock runs fast, long if it runs slow.
|
|
22
|
+
`),tn&&A.stderr.write(`Note: the requested confirmation wait of ${R}ms is outside the usable range (1ms-${f}ms), so it was ignored and the wait fell back to ~${Math.round(B/1e3)}s.
|
|
23
|
+
`);let Ze=await i({state:u,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),ro=Ze.awaitResult.then(S=>({source:"loopback",...S}),S=>({source:"listener_error",error:S})),oo=Date.now(),nn=setInterval(()=>{let S=Math.floor((Date.now()-oo)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${S}s elapsed)
|
|
24
|
+
`)},15e3);nn.unref?.();let Te,Qe=e.signal===void 0?void 0:Ds(e.signal);try{let S=Ms(n,{op_id:p.op_id,port:Ze.port,state:u});m({type:"bridge_browser_open",url:S});let D=s==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(A.stderr.write(l?e.autoOpen===!1?`
|
|
25
25
|
Confirm this in your browser. Open the URL below on any device where
|
|
26
26
|
you're signed in to AllScale (local auto-open is disabled):
|
|
27
27
|
|
|
@@ -44,17 +44,17 @@ back from another device:
|
|
|
44
44
|
`),e.autoOpen===!1)A.stderr.write(`(browser auto-open skipped \u2014 use the link above)
|
|
45
45
|
`);else try{await o(S),A.stderr.write(`(opened in your default browser)
|
|
46
46
|
`)}catch{A.stderr.write(`(no local browser to open \u2014 use the link above)
|
|
47
|
-
`)}
|
|
47
|
+
`)}l?A.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
|
|
48
48
|
reach this machine (e.g. you opened the link elsewhere over SSH), copy
|
|
49
49
|
the ${D} the page shows, paste it here, and press Enter:
|
|
50
50
|
|
|
51
51
|
`):A.stderr.write(`stdin is non-interactive; waiting for the browser callback.
|
|
52
52
|
|
|
53
|
-
`),
|
|
54
|
-
`),await
|
|
55
|
-
`),await
|
|
53
|
+
`),l&&(Te=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:Hr());let Q=[ro];Te!==void 0&&Q.push(Te.promise.then(io=>({source:"paste",line:io}))),Qe!==void 0&&Q.push(Qe.promise);let ee=await Promise.race(Q);if(ee.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(ee.source==="listener_error")throw $s(ee.error,to);if(ee.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
|
|
54
|
+
`),await Us(t,s,ee);let Oe=ee.line.trim();if(!Oe)throw new a("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(s==="ack"&&Oe.startsWith("{"))throw new a("wallet.bridge_invalid_response","Pasted value looks like JSON, not a confirmation token. Copy the single-line token the /cli page shows, not the result JSON.");if(s==="ack"&&/\s/.test(Oe))throw new a("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return A.stderr.write(`Received pasted ${D}; processing\u2026
|
|
55
|
+
`),await Fs(t,s,Oe,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(nn),Qe?.cleanup(),Te?.cancel(),Ze.close()}}function $s(e,t){let r=(e instanceof a&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:t;return e instanceof a&&e.code==="wallet.bridge_timeout"&&r?new a("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} That was the confirmation link's own lifetime, so it has expired or is about to; a longer --bridge-timeout cannot extend a link past its lifetime.`,e.details):e instanceof a&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new a("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function Us(e,t,n){if(t==="ack"){if(!n.result_token)throw new a("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");m({type:"bridge_result_received",source:"loopback"});let r=await Vt(e,n.result_token);return m({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),A.stderr.write(`Verified by broker.
|
|
56
56
|
`),{ack:r,result_data:n.result_data}}if(!n.result_data)throw new a("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return m({type:"bridge_result_received",source:"loopback"}),m({type:"bridge_data_received",source:"loopback"}),A.stderr.write(`Result received from browser.
|
|
57
|
-
`),{result_data:n.result_data}}async function
|
|
58
|
-
`),{ack:i}}let o;try{o=
|
|
59
|
-
`),{result_data:o}}function vs(e,t){let n=new URL("/cli",Fr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}function Rs(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&G.test(e))return{tx_hash:e};throw new a("input.invalid",t.acceptBareTxHashPaste===!1?"Paste the complete JSON result object from the /cli page. A bare transaction hash is not accepted for this operation because it cannot distinguish confirmed, reverted, or unknown status.":`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function Cs(e){return Fr(e).origin}function Fr(e){if(!te(e))throw new a("input.invalid",`Refusing browser base ${I(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${pe}`);return new URL(e)}var Mr=["outcome","transaction_hash","error_code"],Ns=["transaction_hash","error_code"];function Gr(e){if(e.outcome==="confirmed")return Ns.some(r=>Object.prototype.hasOwnProperty.call(e,r))||typeof e.tx_hash!="string"||!G.test(e.tx_hash)?null:{outcome:"confirmed",transactionHash:e.tx_hash};if(Object.keys(e).length!==Mr.length||!Mr.every(r=>Object.prototype.hasOwnProperty.call(e,r)))return null;let n=e.transaction_hash;return typeof n!="string"||!G.test(n)?null:e.outcome==="failed"&&e.error_code==="transaction_reverted"?{outcome:"failed",transactionHash:n,errorCode:"transaction_reverted"}:e.outcome==="ambiguous"&&(e.error_code==="receipt_confirmation_timeout"||e.error_code==="receipt_confirmation_unavailable")?{outcome:"ambiguous",transactionHash:n,errorCode:e.error_code}:null}var xs=new Set;var Ps=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"]),Kr=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"]),Hr=new Set(["payroll","admin:user","admin:org","admin:audit"]);function qt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var Bs=new Set(["cli_op:all"]),Ds=new Set([...Bs].map(qt));var Wl=new Set([...[...Ps,...Kr,...xs].map(qt),...Hr,...Ds]);var Wt=8100,$s=new Set([Wt]),ac=new Set([...$s,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Us=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Fs=/^0(?:\.0+)?$/,jr=128;function Yr(e,t,n={}){if(t.length>jr)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${jr} characters.`);let r=t.trim();if(!Us.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&Fs.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function qr(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function Ms(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${ot}\` to refresh the session, then retry.`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Gs(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_op_expired",`${e.message.replace(/\.?$/,".")} No signed payment came back before the link expired. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run the command to get a fresh confirmation link; raising --bridge-timeout will not help, as the link cannot outlive the broker's op TTL.`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Ks(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the transfer status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Wr(e,t){return!(e instanceof a)||!Yn(e.code)?null:e.code==="wallet.bridge_timeout"?Ms(e,t):e.code==="wallet.bridge_op_expired"?Gs(e,t):Ks(e,t)}var Hs=require("crypto");var Jr=128;function zr(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Jr)throw new a("input.invalid",`--idempotency-key must contain 1-${Jr} characters after trimming.`);return t}var ze=class e extends be{static description="Withdraw a stablecoin from your AllScale wallet to an EVM address. The transfer is confirmed in the browser; the CLI prints the transaction hash and explorer URL only after its on-chain receipt confirms. Needs `wallet:all` on an agent key: it registers the withdrawal op (`wallet:read_only` alone cannot). Every transfer still requires your in-browser confirmation.";static examples=[`$ allscale wallet send --idempotency-key order-1042 --to ${ue} --amount 100 --chain ethereum`,`$ allscale wallet send --idempotency-key order-1043 --to ${ue} --amount 50 --chain polygon --stable-coin USDC`,`$ allscale wallet send --idempotency-key order-1044 --to ${ue} --amount 1 --chain base --bridge-timeout 240000`,`$ allscale wallet send --idempotency-key order-1045 --to ${ue} --amount 1 --chain bsc # over SSH: open the printed URL on any device, paste the full result JSON back`];static flags={to:P.Flags.string({helpGroup:"REQUIRED",description:"Recipient EVM address (0x followed by 40 hex characters).",required:!0}),amount:P.Flags.string({helpGroup:"REQUIRED",description:"Amount to send as a decimal string (e.g. '100', '1.50'). Min 0.1; at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:P.Flags.string({helpGroup:"REQUIRED",description:"EVM chain to send on.",options:[...Bn],required:!0}),"idempotency-key":P.Flags.string({helpGroup:"REQUIRED",description:"Stable key for retrying this same logical transfer (1-128 characters); use a new key for an intentional second payment.",required:!0}),"stable-coin":P.Flags.string({description:"Stablecoin to withdraw.",options:[...$e],default:"USDT"}),"bridge-timeout":P.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life (~5 min, shared by the loopback and paste channels); pass this to abort sooner. The browser only returns after the on-chain receipt confirms (it may poll for up to ~2 min after signing), so a shortened deadline must budget for the signing ceremony PLUS that receipt wait. It can only shorten the wait \u2014 a value above the op's remaining life is clamped to it, because the confirmation link cannot outlive its broker op. If the server's response carries no timestamp to measure that life against, the CLI says so on stderr and bounds the wait instead: with no --bridge-timeout a withdraw waits up to 240s (budgeting the signing ceremony plus the receipt wait) and may be shortened by the best-effort bound from the stated expiry; an explicit value is honoured up to that same bound (clamped to 60s-15min), or 15min when the expiry itself is unreadable.",min:1e3}),"browser-base":P.Flags.string({description:nn}),...be.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=zr(t["idempotency-key"]);if(!n)throw new a("input.invalid","--idempotency-key is required so a retry reuses the same on-chain anti-replay id.");let r=t.to.trim();if(!Un(r))throw new a("input.invalid",`--to is not a valid EVM address: '${r}' (expected 0x followed by 40 hex characters and a valid EIP-55 checksum when mixed-case).`);if(Mn(r))throw new a("input.invalid","--to is a zero/burn address; funds sent there cannot be recovered.");Fn(r);let o=Yr("--amount",t.amount),[i,s=""]=o.split(".");if(i==="0"&&(s[0]??"0")==="0")throw new a("input.invalid",`--amount must be at least 0.1; got '${o}'.`);let c=Dn(t.chain);if(c===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let u=$n(t["stable-coin"]);if(u===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);qr("--amount",o,Pn(c,u));let d={chain:c,to_address:r,amount:o,stable_coin:u,idempotency_key:n},p=this.resolveContext(t),h;try{h=await Ur({ctx:p,op:"withdraw_token",mode:"data",payload:d,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1})}catch(_){throw Wr(_,{to_address:d.to_address,idempotency_key:n})??_}let g=h.result_data??{},f=Gr(g);if(!f){let _=typeof g.transaction_hash=="string"&&G.test(g.transaction_hash)?g.transaction_hash:typeof g.tx_hash=="string"&&G.test(g.tx_hash)?g.tx_hash:void 0;throw new a("wallet.bridge_invalid_response","Browser returned an unconfirmed or invalid withdrawal result. A transaction hash alone does not prove receipt confirmation; inspect the destination on-chain before retrying.",{..._?{transaction_hash:_}:{},to_address:r,idempotency_key:n})}if(f.outcome!=="confirmed"){let _={outcome:f.outcome,error_code:f.errorCode,transaction_hash:f.transactionHash,chain:c,to_address:r,idempotency_key:h.idempotency_key??n,explorer_url:St(c,f.transactionHash)||void 0};if(f.outcome==="failed")throw new a("wallet.transaction_reverted",`The transaction was broadcast (tx ${f.transactionHash}) but reverted on-chain, so the transfer did not complete. Inspect the transaction and correct the cause before submitting another transfer; do not retry this command automatically.`,_);let k=f.errorCode==="receipt_confirmation_timeout"?"receipt confirmation timed out":"the receipt confirmation provider was unavailable";throw new a("wallet.transaction_status_unknown",`The transaction was broadcast (tx ${f.transactionHash}), but its on-chain status is unknown because ${k}. Do not retry this transfer blindly; inspect the transaction hash in your wallet or explorer before deciding whether another submission is needed.`,_)}let y=f.transactionHash;return{tx_hash:y,chain:c,chain_name:Gn(c),to_address:r,amount:o,stable_coin:u,stable_coin_name:Kn(u),explorer_url:St(c,y)||void 0,idempotency_key:h.idempotency_key??n}}};
|
|
57
|
+
`),{result_data:n.result_data}}async function Fs(e,t,n,r){if(t==="ack"){m({type:"bridge_result_received",source:"paste"});let i=await Vt(e,n);return m({type:"bridge_verified",op_id:i.op_id,source:"paste"}),A.stderr.write(`Verified by broker.
|
|
58
|
+
`),{ack:i}}let o;try{o=Gs(n,{acceptBareTxHashPaste:r})}catch(i){throw i instanceof a&&i.code==="input.invalid"?new a("wallet.bridge_invalid_response",i.message):i}return m({type:"bridge_result_received",source:"paste"}),m({type:"bridge_data_received",source:"paste"}),A.stderr.write(`Result accepted.
|
|
59
|
+
`),{result_data:o}}function Ms(e,t){let n=new URL("/cli",qr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}function Gs(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&G.test(e))return{tx_hash:e};throw new a("input.invalid",t.acceptBareTxHashPaste===!1?"Paste the complete JSON result object from the /cli page. A bare transaction hash is not accepted for this operation because it cannot distinguish confirmed, reverted, or unknown status.":`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function Ks(e){return qr(e).origin}function qr(e){if(!te(e))throw new a("input.invalid",`Refusing browser base ${I(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${pe}`);return new URL(e)}var Wr=["outcome","transaction_hash","error_code"],Hs=["transaction_hash","error_code"];function Jr(e){if(e.outcome==="confirmed")return Hs.some(r=>Object.prototype.hasOwnProperty.call(e,r))||typeof e.tx_hash!="string"||!G.test(e.tx_hash)?null:{outcome:"confirmed",transactionHash:e.tx_hash};if(Object.keys(e).length!==Wr.length||!Wr.every(r=>Object.prototype.hasOwnProperty.call(e,r)))return null;let n=e.transaction_hash;return typeof n!="string"||!G.test(n)?null:e.outcome==="failed"&&e.error_code==="transaction_reverted"?{outcome:"failed",transactionHash:n,errorCode:"transaction_reverted"}:e.outcome==="ambiguous"&&(e.error_code==="receipt_confirmation_timeout"||e.error_code==="receipt_confirmation_unavailable")?{outcome:"ambiguous",transactionHash:n,errorCode:e.error_code}:null}var Zt=8100,js=new Set([Zt]),mc=new Set([...js,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Ys=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,qs=/^0(?:\.0+)?$/,zr=128;function Vr(e,t,n={}){if(t.length>zr)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${zr} characters.`);let r=t.trim();if(!Ys.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&qs.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Xr(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function Ws(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${st}\` to refresh the session, then retry.`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Js(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_op_expired",`${e.message.replace(/\.?$/,".")} No signed payment came back before the link expired. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run the command to get a fresh confirmation link; raising --bridge-timeout will not help, as the link cannot outlive the broker's op TTL.`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function zs(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the transfer status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...n.broker_code!==void 0?{broker_code:n.broker_code}:{},...t})}function Zr(e,t){return!(e instanceof a)||!zn(e.code)?null:e.code==="wallet.bridge_timeout"?Ws(e,t):e.code==="wallet.bridge_op_expired"?Js(e,t):zs(e,t)}var Vs=require("crypto");var Qr=128;function eo(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Qr)throw new a("input.invalid",`--idempotency-key must contain 1-${Qr} characters after trimming.`);return t}var Xe=class e extends Ee{static description="Withdraw a stablecoin from your AllScale wallet to an EVM address. The transfer is confirmed in the browser; the CLI prints the transaction hash and explorer URL only after its on-chain receipt confirms. Needs `wallet:all` on an agent key: it registers the withdrawal op (`wallet:read_only` alone cannot). Every transfer still requires your in-browser confirmation.";static examples=[`$ allscale wallet send --idempotency-key order-1042 --to ${ue} --amount 100 --chain ethereum`,`$ allscale wallet send --idempotency-key order-1043 --to ${ue} --amount 50 --chain polygon --stable-coin USDC`,`$ allscale wallet send --idempotency-key order-1044 --to ${ue} --amount 1 --chain base --bridge-timeout 240000`,`$ allscale wallet send --idempotency-key order-1045 --to ${ue} --amount 1 --chain bsc # over SSH: open the printed URL on any device, paste the full result JSON back`];static flags={to:P.Flags.string({helpGroup:"REQUIRED",description:"Recipient EVM address (0x followed by 40 hex characters).",required:!0}),amount:P.Flags.string({helpGroup:"REQUIRED",description:"Amount to send as a decimal string (e.g. '100', '1.50'). Min 0.1; at most 6 effective decimals, or 18 on BSC.",required:!0}),chain:P.Flags.string({helpGroup:"REQUIRED",description:"EVM chain to send on.",options:[...Fn],required:!0}),"idempotency-key":P.Flags.string({helpGroup:"REQUIRED",description:"Stable key for retrying this same logical transfer (1-128 characters); use a new key for an intentional second payment.",required:!0}),"stable-coin":P.Flags.string({description:"Stablecoin to withdraw.",options:[...Ue],default:"USDT"}),"bridge-timeout":P.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life (~5 min, shared by the loopback and paste channels); pass this to abort sooner. The browser only returns after the on-chain receipt confirms (it may poll for up to ~2 min after signing), so a shortened deadline must budget for the signing ceremony PLUS that receipt wait. It can only shorten the wait \u2014 a value above the op's remaining life is clamped to it, because the confirmation link cannot outlive its broker op. If the server's response carries no timestamp to measure that life against, the CLI says so on stderr and bounds the wait instead: with no --bridge-timeout a withdraw waits up to 240s (budgeting the signing ceremony plus the receipt wait) and may be shortened by the best-effort bound from the stated expiry; an explicit value is honoured up to that same bound (clamped to 60s-15min), or 15min when the expiry itself is unreadable.",min:1e3}),"browser-base":P.Flags.string({description:ln}),...Ee.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=eo(t["idempotency-key"]);if(!n)throw new a("input.invalid","--idempotency-key is required so a retry reuses the same on-chain anti-replay id.");let r=t.to.trim();if(!Kn(r))throw new a("input.invalid",`--to is not a valid EVM address: '${r}' (expected 0x followed by 40 hex characters and a valid EIP-55 checksum when mixed-case).`);if(jn(r))throw new a("input.invalid","--to is a zero/burn address; funds sent there cannot be recovered.");Hn(r);let o=Vr("--amount",t.amount),[i,s=""]=o.split(".");if(i==="0"&&(s[0]??"0")==="0")throw new a("input.invalid",`--amount must be at least 0.1; got '${o}'.`);let l=Mn(t.chain);if(l===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let u=Gn(t["stable-coin"]);if(u===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);Xr("--amount",o,Un(l,u));let d={chain:l,to_address:r,amount:o,stable_coin:u,idempotency_key:n},p=this.resolveContext(t),h;try{h=await Yr({ctx:p,op:"withdraw_token",mode:"data",payload:d,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1})}catch(_){throw Zr(_,{to_address:d.to_address,idempotency_key:n})??_}let g=h.result_data??{},f=Jr(g);if(!f){let _=typeof g.transaction_hash=="string"&&G.test(g.transaction_hash)?g.transaction_hash:typeof g.tx_hash=="string"&&G.test(g.tx_hash)?g.tx_hash:void 0;throw new a("wallet.bridge_invalid_response","Browser returned an unconfirmed or invalid withdrawal result. A transaction hash alone does not prove receipt confirmation; inspect the destination on-chain before retrying.",{..._?{transaction_hash:_}:{},to_address:r,idempotency_key:n})}if(f.outcome!=="confirmed"){let _={outcome:f.outcome,error_code:f.errorCode,transaction_hash:f.transactionHash,chain:l,to_address:r,idempotency_key:h.idempotency_key??n,explorer_url:kt(l,f.transactionHash)||void 0};if(f.outcome==="failed")throw new a("wallet.transaction_reverted",`The transaction was broadcast (tx ${f.transactionHash}) but reverted on-chain, so the transfer did not complete. Inspect the transaction and correct the cause before submitting another transfer; do not retry this command automatically.`,_);let k=f.errorCode==="receipt_confirmation_timeout"?"receipt confirmation timed out":"the receipt confirmation provider was unavailable";throw new a("wallet.transaction_status_unknown",`The transaction was broadcast (tx ${f.transactionHash}), but its on-chain status is unknown because ${k}. Do not retry this transfer blindly; inspect the transaction hash in your wallet or explorer before deciding whether another submission is needed.`,_)}let y=f.transactionHash;return{tx_hash:y,chain:l,chain_name:Yn(l),to_address:r,amount:o,stable_coin:u,stable_coin_name:qn(u),explorer_url:kt(l,y)||void 0,idempotency_key:h.idempotency_key??n}}};
|
|
60
60
|
//# sourceMappingURL=send.js.map
|