@allscale/cli 1.0.1 → 1.0.3
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 +92 -12
- package/dist/commands/build-info.js +12 -12
- package/dist/commands/claim-link/claim.js +10 -10
- package/dist/commands/claim-link/create.js +31 -31
- package/dist/commands/claim-link/get.js +13 -13
- package/dist/commands/claim-link/list.js +12 -12
- package/dist/commands/claim-link/status.js +11 -11
- package/dist/commands/describe.js +11 -11
- package/dist/commands/device-login.js +28 -27
- package/dist/commands/invoice/get.js +12 -12
- package/dist/commands/invoice/list.js +12 -12
- package/dist/commands/invoice/pay.js +41 -37
- package/dist/commands/invoice/received.js +12 -12
- package/dist/commands/invoice/send.js +29 -29
- package/dist/commands/invoice/sent.js +11 -11
- package/dist/commands/invoice/update.js +13 -13
- package/dist/commands/logout.js +19 -13
- package/dist/commands/operations.js +11 -11
- package/dist/commands/otp-login.js +17 -17
- package/dist/commands/otp-send.js +11 -11
- package/dist/commands/payout/send.js +14 -14
- package/dist/commands/payout/status.js +12 -12
- package/dist/commands/scope.js +16 -16
- package/dist/commands/store/create.js +16 -16
- package/dist/commands/transaction/get.js +12 -12
- package/dist/commands/transaction/list.js +12 -12
- package/dist/commands/wallet/list.js +12 -12
- package/dist/commands/wallet/send.js +27 -27
- package/dist/commands/whoami.js +14 -12
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +11 -11
- package/dist/lib/help.js +10 -7
- package/oclif.manifest.json +24 -11
- package/package.json +1 -1
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(t=>
|
|
3
|
-
`)}var
|
|
4
|
-
`)}else pt.stderr.write(t)}var
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}
|
|
7
|
-
`)}catch(r){if(
|
|
8
|
-
`)}catch{}}}var M=wn;function
|
|
9
|
-
The CLI default is now ${
|
|
1
|
+
"use strict";var to=Object.create;var Oe=Object.defineProperty;var no=Object.getOwnPropertyDescriptor;var ro=Object.getOwnPropertyNames;var oo=Object.getPrototypeOf,io=Object.prototype.hasOwnProperty;var so=(e,t)=>{for(var n in t)Oe(e,n,{get:t[n],enumerable:!0})},Zt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ro(t))!io.call(e,o)&&o!==n&&Oe(e,o,{get:()=>t[o],enumerable:!(r=no(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?to(oo(e)):{},Zt(t||!e||!e.__esModule?Oe(n,"default",{value:e,enumerable:!0}):n,e)),ao=e=>Zt(Oe({},"__esModule",{value:!0}),e);var js={};so(js,{default:()=>ze});module.exports=ao(js);var $=require("@oclif/core");var Qt="public",en="https://app.allscale.io";var tn=["https://app.allscale.io"];var Ze="Override the API base URL (public builds accept only https://app.allscale.io)",nn="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 rn(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 on(e){return rn(e)!==null}function te(e){let t=rn(e);return t!==null&&tn.includes(t.origin)}function Qe(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 tt(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 et()}function et(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let o=[];for(let i of r){if(typeof i!="object"||i===null)continue;let{base:s,key:c,keyId:u}=i;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.trim():"";o.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return o}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var ot="device-login",lo=/^[A-Za-z0-9._-]{1,64}$/;function it(e){return lo.test(e)?e:"<profile>"}function an(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":it(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Ie(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function ln(e){let t=it(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${an(e)}\` for headless automation.`}function cn(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${ot} --profile ${it(e)}\`.`}var co={"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 uo=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 st(e){return(typeof e=="string"?e:String(e??"")).replace(uo,"")}var po=64;function nt(e,t=new Map,n=0){if(typeof e=="string")return st(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=po)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(nt(c,t,n+1));return s}let o=Object.getPrototypeOf(e);if(o!==Object.prototype&&o!==null)return e;let i={};t.set(e,i);for(let[s,c]of Object.entries(e))Object.defineProperty(i,s,{value:nt(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return i}var a=class extends Error{code;details;constructor(t,n,r){super(st(n)),this.code=t,this.details=r&&nt(r),this.name="AllscaleError"}get exitCode(){return co[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function un(e){if(e instanceof a)return e;if(e instanceof Error){if(go(e)){let t=_o(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 fo=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),ho=[/^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 go(e){if(mo(e))return!0;let t=e.name??"";return fo.has(t)?t==="CLIError"?rt(e,"parse")||sn(e.message):!0:sn(e.message)}function mo(e){if(!rt(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&rt(e,"parse")}function sn(e){return e?st(e).split(`
|
|
2
|
+
`).some(t=>ho.some(n=>n.test(t.trim()))):!1}function rt(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function _o(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function dn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var w=T(require("fs")),xe=T(require("path")),yn=T(require("crypto"));var yo="...<truncated>",wo=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,bo=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,dt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,at=String.raw`(?:proxy[_-]?)?authorization`,Eo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${at}"|'${at}'|${at})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${dt}`,"gi"),So=/\b(https?:\/\/)[^\s/?#]+@/gi,Ao=String.raw`(?:[A-Za-z0-9]+[_-])*`,ko=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,fn=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)`,pn=fn(Ao),Lo=fn(ko),To=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${pn}"|'${pn}'|${Lo})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${dt}`,"gi"),lt=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)`,Oo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${lt}"|'${lt}'|${lt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${dt}`,"g");function ve(e){return e.replace(So,"$1<redacted>@").replace(wo,"<redacted-jwt>").replace(Eo,"$1$2$3<redacted>").replace(To,"$1$2<redacted>").replace(Oo,"$1$2<redacted>").replace(bo,"Bearer <redacted>")}var Io=/(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 Re(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Io.test(t)}function hn(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 Ce(e,t,n=yo){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(u+p>t)break;c+=d,u+=p}return c}let o=t-r,i="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>o)break;i+=c,s+=u}return`${i}${n}`}function O(e,t=16384){return Ce(hn(ve(e)),t)}var ct=100,vo=8,Ro=8*1024;function Ne(){return{remaining:Ro}}function ut(e,t){let n=Math.min(16384,t.remaining),r=Ce(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function re(e,t,n=0,r={}){if(n>vo)return ut("<truncated>",t);if(typeof e=="string"){let o=ve(e);return ut(r.escapeControls?hn(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,ct),i=o.map(s=>re(s,t,n+1,r));return e.length>o.length&&i.push(ut(`<${e.length-o.length} more items truncated>`,t)),i}if(e!==null&&typeof e=="object"){let o=Object.create(null),i=Object.entries(e);for(let[s,c]of i.slice(0,ct))o[s]=re(c,t,n+1,r);return i.length>ct&&(o.output_truncated=!0),o}return e}var pt=require("process");var ft=!1;function ht(e){ft=e}function mn(){return ft}var gn="1";function ie(e,t){if(ft){let n={...e};delete n.version;let r=Ne(),o={event:n.event,...n},i=re(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:gn,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:gn,event:i.event,output_truncated:!0})),pt.stderr.write(`${s}
|
|
4
|
+
`)}else pt.stderr.write(t)}var _n="2",se=null,C=null,ae=!1,ge=!1;function Co(){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=yn.randomBytes(4).toString("hex");return xe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var gt=64*1024*1024,No=null;function mt(e={}){if(e.quiet&&(ge=!0),ae)return;let t=Co();if(!t)return;se=null;let n=null;try{if((No??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=xe.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 c=i.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);w.fchmodSync(n,384)}catch(r){if(n!==null)try{w.closeSync(n)}catch{}ge||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 xo=[/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 Po(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.some(n=>n.test(t))}function wn(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=Bo(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)Po(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function Bo(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Do(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:wn(e.url)}:e}function $o(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=re(o,Ne()),s=JSON.stringify({version:_n,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:_n,timestamp:t,type:r,output_truncated:!0})),s}function m(e){if(!ae||!se||C===null)return;let t=Do(e),n=$o(t);try{if(w.fstatSync(C).size+Buffer.byteLength(n,"utf8")+1>gt){ae=!1;try{w.closeSync(C)}catch{}C=null,ge||ie({event:"sidecar_disabled",reason:"size_limit",...se===null?{}:{path:O(se)},max_bytes:gt},`${O(`[allscale] sidecar exceeded ${gt} 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
|
+
`);return}w.appendFileSync(C,`${n}
|
|
7
|
+
`)}catch(r){if(ae=!1,C!==null){try{w.closeSync(C)}catch{}C=null}try{ge||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=wn;function bn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function me(){if(ge=!1,ae=!1,C!==null){try{w.closeSync(C)}catch{}C=null}}function En(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||bn()||!t}var _e=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"]),Uo=new Set(Array.from(_e).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Fo=Array.from(_e).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Mo=new Set(["--otp-stdin","--password-stdin"]);function _t(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(_e.has(s)){t.push(`${s}=<redacted>`);continue}}}if(_e.has(r)){t.push(r),n+1<e.length&&(_e.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(Uo.has(i)){t.push(`${i}<redacted>`);continue}}let o=Mo.has(r)?void 0:Fo.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function Sn(e){m({type:"error",code:e.code,message:O(e.message)}),m({type:"command-end",ok:!1,exitCode:e.exitCode}),me()}var ye=fe()??en,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 on(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 An(){let e=process.env[ce.TOKEN]?.trim();return e&&e.length>0?e:void 0}function yt(){let e=process.env[ce.PROFILE]?.trim();return e&&e.length>0?e:void 0}function we(){let e=process.env[ce.API_BASE]?.trim();return e&&e.length>0?e:void 0}function kn(){let e=process.env[ce.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Ln(){let e=process.env[ce.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Tn(){let e=process.env[ce.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function On(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(fe()===void 0&&ye!==""&&"".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 ${ye} (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
|
|
15
|
-
`)}};var qo=/_(removed|cleared|count|total)$/i;function Wo(e,t){return typeof t=="number"&&qo.test(e)}var Jo=new Set($e);function zo(e,t){return e==="token_symbol"&&typeof t=="string"&&Jo.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)&&!Wo(o,i)&&!zo(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=Vo(e);return n!==void 0?I(JSON.stringify(Fe(n,t+1))):I(e)}return e}function Vo(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 Xo(e){let t=gn()?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:I(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Zo(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 Pr=require("crypto"),A=require("process");var H=/^0x[0-9a-fA-F]{64}$/,Qo=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function Hn(e){return typeof e=="string"&&Qo.includes(e)}var tr=T(require("path"));var Lt=require("crypto"),l=T(require("fs")),E=T(require("path"));var Me=1024*1024,ei=5e3,ti=20,ni=3e4,At=4096,ri=new Int32Array(new SharedArrayBuffer(4)),be=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ge(e){return e instanceof be}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},oi=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(oi??process.platform)!=="win32"}function Vn(){if(!He())throw J()}function Xn(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 Ee(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function Se(e,t){return e.dev===t.dev&&e.ino===t.ino}function ii(e){Atomics.wait(ri,0,0,e)}function Zn(e){try{return process.kill(e,0),!0}catch(t){return!b(t,"ESRCH")}}function si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kn(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()||!Se(i,s))throw new Error("credential-store parent changed while it was being inspected");Ee(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 R:i}if(!Se(n,o))throw r.retryOnPathChange?new R: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 be;if(Ee(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 ai(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 Yn(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 ai(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")&&Xn(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)}er(E.dirname(e))}function li(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 be;Ee(t,"credential-store replacement target")}function ci(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 Qn(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 er(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 ui(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=ci(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");Qn(i,n),l.default.fsyncSync(i),U(s,i,l.default.fstatSync(i));let h=i;i=null,l.default.closeSync(h),li(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{}}er(r)}function di(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function pi(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function fi(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()||!Se(n,t))throw new Error("credential-store lock changed while it was being inspected");Ee(n,"credential-store lock"),l.default.unlinkSync(e)}function qn(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 R}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=fi(n,o);return{state:(i?.target===t&&i?!Zn(i.pid):Date.now()-o.mtimeMs>=ni)?"stale":"active",stats:o}}finally{n!==null&&l.default.closeSync(n)}}function hi(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 Qn(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 gi(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 R:r}try{let r=l.default.fstatSync(n),o=U(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Se(o,t))throw new R;return{fd:n,lockPath:e,stats:o}}catch(r){throw l.default.closeSync(n),r}}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(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 R}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 mi(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");ii(ti)}function Jn(e){let t=E.dirname(e),n=E.basename(e),r=di(e),o=pi(e),i=hi(t,n),s=Date.now()+ei,c=!1,u=!1,d=null,p;try{for(;d===null;)try{if(Wn(o)){W(s,!0);continue}l.default.linkSync(i.claimPath,r),u=!0,d=gi(r,i.stats),c=!0}catch(h){if(u&&!c){try{z(r,i.stats)}catch{}u=!1}if(h instanceof R){W(s,!1);continue}if(!b(h,"EEXIST"))throw h;let g;try{g=qn(r,n)}catch(w){if(w instanceof R){W(s,!1);continue}throw w}if(g.state==="absent")continue;if(g.state==="stale"){let w;try{w=mi(o)}catch(_){if(_ instanceof R){W(s,!1);continue}throw _}if(w!==null){try{let _;try{_=qn(r,n)}catch(k){if(k instanceof R){W(s,!1);continue}throw k}_.state==="stale"&&z(r,_.stats)}finally{kt(w)}continue}}let f;try{f=Wn(o)}catch(w){if(w instanceof R){W(s,!1);continue}throw w}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 _i(e,t){let n=si(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=_i(r,n);if(o===null||Zn(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()||!Se(c,u))continue;try{Ee(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 Ae(e,t,n){if(!He()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw J();if(!Kn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw J()}});let s=Jn(e);try{return zn(e),n({read:()=>Yn(e),remove:()=>jn(e),write:()=>{throw J()}})}finally{kt(s)}}if(!t.createParent){let i=!1;try{i=Xn(e)}catch{throw J()}if(i)return n({read:()=>null,remove:()=>{},write:()=>{throw J()}})}throw J()}if(!Kn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let o=Jn(e);try{return zn(e),n({read:()=>Yn(e),remove:()=>jn(e),write:i=>ui(e,i)})}finally{kt(o)}}var Tt="allscale-cli";function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e){return Ct(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 It(){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 Ke(){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,Ot=!1;function wi(){return kn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function yi(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 bi(){if(V!==void 0)return V;if(wi())return Ot=!1,V=null,V;try{V=require("keytar"),Ot=!1}catch(e){Ot=!yi(e),V=null}return V}function rr(){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","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Rt(e){try{return await e()}catch{throw rr()}}var vt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Rt(()=>this.keytar.getPassword(Tt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!nr(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Rt(()=>this.keytar.setPassword(Tt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Rt(()=>this.keytar.deletePassword(Tt,t))}},Ei="credentials.json",Nt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??tr.join(Et(),Ei)}read(t){let n;try{n=t.read()}catch(o){throw Ge(o)?It():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Ct(r)||!Ct(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ge(r)?It():Ke()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!nr(r))throw X("plaintext file");return r}}async get(t){try{return Ae(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{Ae(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:Ke()}}async delete(t){try{Ae(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:Ke()}}async clearProfile(t){try{return Ae(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)?It():Ke()}}};function or(e){if(e.insecureStorage)return Vn(),new Nt(e.insecureFilePath);let t=bi();if(t)return new vt(t);throw rr()}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 Ye(){return new xt}var je="allscale_access_token",Pt="allscale_refresh_token";function ir(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 sr=T(require("crypto")),ar=T(require("fs")),lr=T(require("path"));var Si="key-id",Ai="x-allscale-cli-version",$t="cli-1",ki="aScaLe_cli_obf_v1",Li="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Ti(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 Ii=Ti(Li,ki),cr=`Bearer ${Ii}`;function ur(e,t){let n=tt(e);if(n!==null)return t.find(r=>tt(r.base)===n)}function Oi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=he();if(t.length>0){let r=ur(e,t);if(r)return r.key;if(Y(e)){let o=process.env.ALLSCALE_SIGNING_KEY;return o&&o.trim().length>0?o:Y(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 Ri(e){{let r="cli-1".trim();if(r.length>0)return r}let t=he();if(t.length>0){let r=e!==void 0?ur(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&Y(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(!Y(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 Ci(){return"1.0.1"}function vi(){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=Oi(t);if(!n)throw vi();let r=Ri(t),o=Math.floor(Date.now()/1e3).toString(),i=sr.createHash("sha256").update(`${n}${o}${e}`).digest("hex"),s={timestamp:o,"secret-key":i,[Ai]:Ci()};return r.length>0&&(s[Si]=r),s}function dr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Ni(e,t={}){let n;try{n=On(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",ln(e)+(t.messageSuffix??""),{profile:e})}function pr(e){if(e.profileExplicit){let t=Ni(e.profile);if(t)return t}return new a("auth.no_token",an(e.profile))}var xi=500,Pi=8,fr=100;function Ft(e,t=0){if(t>Pi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,fr),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,fr))n[r]=Re(r)?"<redacted>":Ft(o,t+1);return n}return e}function Bi(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 hr(e,t=xi){let n=Bi(e),r=n===void 0?Oe(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 Di="X-AllScale-Api-Key",$i=3e4,Ui=32*1024*1024,Fi=4*1024*1024;function Mi(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 Gi(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 Hi(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 yr(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Hi(e.status,e.url)}}var gr="--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=${gr} 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=${gr}`})}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??$i;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=Mi(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();vn(this.opts.apiBase,o);let i=r?.agent_key,s=t.auth??"auto",c=br(t.path),u=s==="required"?!0:s==="none"?!1:ji(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!i)throw pr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=dr(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 Gi(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}),mr(L,{withMetadata:n.withMetadata,authBearing:u,responseKind:_r(t)})}return mr(f,{withMetadata:n.withMetadata,authBearing:u&&p,agentKeyAuth:u&&!!i,responseKind:_r(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=cr;let o=t.tokens;if(o?.agent_key)return r[Di]=o.agent_key,r;let i=o?.access_token;i&&(r.Cookie=Bt([{name:je,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:je,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 yr(u)}catch(f){throw m({type:"refresh",ok:!1}),f}if(u.status!==200){let f=null;try{await Je(u);let w=await Vi(u);await Je(u,w),Sr(u.status,w),u.status===401&&(f=await this.adoptConcurrentlyRotatedTokens(t))}catch(w){throw m({type:"refresh",ok:!1}),w}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=ir(u.headers),p=Dt(d,je),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}},Ki=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function br(e){let t=e.split(/[?#]/,1)[0];return Ki.some(n=>t===n||t.startsWith(`${n}/`))}var Yi=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Ht(e){let t=e.split(/[?#]/,1)[0];return Yi.some(n=>n.test(t))}function ji(e){return br(e)||Ht(e)}async function mr(e,t={}){await yr(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"?Ui:Fi: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=Xi(s)??`HTTP ${e.status}`;if(Sr(e.status,s),Ji(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 _r(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var qi=2014,wr=2004;function Er(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 Wi(e){return Er(e,qi)}function Ji(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Er(t,wr))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:wr})}var zi=1e4;async function Vi(e,t=zi){if(e.status>=200&&e.status<300)return"";try{return await Gt(e,Mt,{timeoutMs:t})}catch{return""}}function Sr(e,t){if(!(e>=200&&e<300)&&Wi(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"?hr(t):t})}function Xi(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 Zi=/^\/(api\/)?(v1\/)?public\//;function Kt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Zi.test(n),o=n&&Ht(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:or({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},Qi=new Set(Object.values(N));async function Ar(e,t,n){let{body:r,headers:o}=await ns(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:es(o)}}function es(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 Yt(e,t){return ts(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function ts(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=kr(i,r);if(s!==null)throw s}throw i}return Lr(o,r)}async function ns(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=kr(i,r);if(s!==null)throw s}throw i}return{body:Lr(o.body,r),headers:o.headers??{}}}function kr(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||!Qi.has(o))return null;let i=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return Tr(o,i,t)}function Lr(e,t){if(e.code!==void 0&&e.code!==0)throw Tr(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 Tr(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 Rr=require("child_process");function Ir(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var rs=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function os(e,t,n,r){if(Ir(e.CI)||rs.some(s=>Ir(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 is(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 Cr(e,t={}){if(!Qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${O(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:os(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(i)throw new a("wallet.requires_browser_auth",is(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=ss(r,o);await as(s.command,[...s.args,e])}function ss(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 as(e,t){return new Promise((n,r)=>{let o;try{o=(0,Rr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Or(e,s));return}let i=!1;o.once("error",s=>{i||(i=!0,r(Or(e,s)))}),setImmediate(()=>{i||(i=!0,o.unref(),n())})})}function Or(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 vr=T(require("http"));var ls=9e4,cs=16*1024;function Nr(e){let t=e.timeoutMs??ls;return new Promise((n,r)=>{let o=!1,i=!1,s=null,c,u,d=new Promise((h,g)=>{c=h,u=g}),p=vr.createServer((h,g)=>{us(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,w=g!=null&&g<=t;s=setTimeout(()=>{u(new a("wallet.bridge_timeout",`Bridge timed out after ${f}ms waiting for browser callback.`,{bridge_deadline:w?"op_ttl":"duration"})),p.close()},f),s.unref?.(),i=!0,n({port:h.port,awaitResult:d,close:()=>{s&&clearTimeout(s),p.close()}})})})}function us(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>cs){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(!ds(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 ds(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 jt(e){try{return JSON.parse(e),!0}catch{return!1}}function xr(){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 w=t.trim(),_=t.length-t.trimStart().length,k=t.indexOf(`
|
|
17
|
-
`,_),x=k===-1?"":t.slice(_,k).trim();if(
|
|
18
|
-
`).find(F=>F.trim()!=="")??"";if(x==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(K))){c();return}}u(),r(
|
|
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 Ve=await i({state:u,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),
|
|
24
|
-
`)},15e3);
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${ye}
|
|
14
|
+
`}var Y=T(require("fs")),In=T(require("os")),wt=T(require("path")),bt=T(require("@iarna/toml"));var Ho=".allscale",jo="config.toml";function Et(){return wt.join(In.homedir(),Ho)}function Yo(){return wt.join(Et(),jo)}function Pe(){let e=Yo();if(!Y.existsSync(e))return{};let t=Y.readFileSync(e,"utf-8");try{return bt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function vn(e){return Object.keys(e.profile??{}).sort()}function Rn(e,t){return e.profile?.[t]}function Cn(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 Be(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 Nn(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 De(e){let t=Wo(e);if(t)throw new a("input.invalid",t.message)}function qo(){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 Wo(e){let t=qo();if(t===void 0||H(e))return;let{endpoints:n,fromPairs:r}=t,o=j(e),i=n.map(c=>j(c)).filter(c=>c!==null);if(o!==null&&i.includes(o))return;let s=n.map(c=>I(c)).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 xn=require("@noble/hashes/sha3");function Pn(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Jo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Bn=["ethereum","bsc","base","polygon","arbitrum","optimism"],$e=["USDT","USDC"];function Dn(e){return Jo[e.toLowerCase()]??null}function $n(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function Un(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,xn.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 zo(e){return e.toLowerCase()===ue}function Fn(e,t="--to"){if(zo(e))throw new a("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var Vo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Mn(e){return Vo.has(e.toLowerCase())}function St(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 Gn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Kn(e){return e===1?"USDT":"USDC"}var Xo="unknown_otp_id",Zo="invalid_code",Qo="expired_code";function ei(e){return`'${e.replace(/'/g,"'\\''")}'`}function Hn(e){return`Run \`allscale otp-send --email ${ei(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var ti=new Map([[Xo,(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. ${Hn(t)}`],[Zo,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.`],[Qo,(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. ${Hn(t)}`]]);var jn=[...ti.keys()];var P=require("@oclif/core"),be=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:Ze,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{ht(this.jsonEnabled()),mt(),m({type:"session-start",command:this.id??"",argv:_t(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&&we()!==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=En(this.jsonEnabled()),r=this.argv.length===0&&!n&&ui(t)?this.config.findCommand(this.id??""):void 0;if(r){me();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&&!Tn())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}),me(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||dn(o),{data:o})}catch(t){let n=un(t);Sn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{ht(!1)}}resolveSessionApiBaseChain(t){let n=Pe(),r=t.profile??void 0,o=t["api-base"]??void 0,i=r!==void 0||yt()!==void 0,s=Cn(n,r,yt()),c=Rn(n,s),u=ne()==="public"&&we()!==void 0,d=o??(u?void 0:we()),p=d??c?.api_base??ye,h=On({resolvedApiBase:p,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.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:c?.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&&we()!==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:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(o),De(o)),{apiBase:o,profile:c,token:n??An(),insecureStorage:r||kn(),apiBaseSource:i!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${ci(t)}
|
|
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(Yt(y)){u(),r(y);return}if(k===-1){c();return}if(!Yt(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))){c();return}}u(),r(Yt(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 Ls(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 Ur(e){let t=Ht(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Cs(n),o=e._openBrowser??xr,i=e._startListener??Br,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,u=(0,$r.randomBytes)(32).toString("hex"),d=Date.now(),p=await Tr(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,Jt=!1,zt=!1,Vt=!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",Jt=!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",zt=R!=null&&R>D):(B=Q,de=F!=null?"caller":"unknown_ttl"),Vt=R!=null&&F==null}let Vr=de==="op_ttl",Xr=L!=null?`~${K}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${Xr}, waiting up to ${Math.round(B/1e3)}s for confirmation).
|
|
20
|
+
`),Jt&&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
|
+
`),zt&&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
|
+
`),Vt&&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 Ve=await i({state:u,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),Zr=Ve.awaitResult.then(S=>({source:"loopback",...S}),S=>({source:"listener_error",error:S})),Qr=Date.now(),Xt=setInterval(()=>{let S=Math.floor((Date.now()-Qr)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${S}s elapsed)
|
|
24
|
+
`)},15e3);Xt.unref?.();let Le,Xe=e.signal===void 0?void 0:Ls(e.signal);try{let S=vs(n,{op_id:p.op_id,port:Ve.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(c?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
|
|
|
@@ -50,11 +50,11 @@ 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
|
-
`),c&&(
|
|
54
|
-
`),await
|
|
55
|
-
`),await
|
|
53
|
+
`),c&&(Le=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:Dr());let Q=[Zr];Le!==void 0&&Q.push(Le.promise.then(eo=>({source:"paste",line:eo}))),Xe!==void 0&&Q.push(Xe.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 Ts(ee.error,Vr);if(ee.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
|
|
54
|
+
`),await Os(t,s,ee);let Te=ee.line.trim();if(!Te)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"&&Te.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(Te))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 Is(t,s,Te,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(Xt),Xe?.cleanup(),Le?.cancel(),Ve.close()}}function Ts(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 Os(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 jt(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 ms(e,t){let n=new URL("/cli",Dr(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 _s(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&H.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 ws(e){return Dr(e).origin}function Dr(e){if(!te(e))throw new a("input.invalid",`Refusing browser base ${O(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${de}`);return new URL(e)}var $r=["outcome","transaction_hash","error_code"],ys=["transaction_hash","error_code"];function Ur(e){if(e.outcome==="confirmed")return ys.some(r=>Object.prototype.hasOwnProperty.call(e,r))||typeof e.tx_hash!="string"||!H.test(e.tx_hash)?null:{outcome:"confirmed",transactionHash:e.tx_hash};if(Object.keys(e).length!==$r.length||!$r.every(r=>Object.prototype.hasOwnProperty.call(e,r)))return null;let n=e.transaction_hash;return typeof n!="string"||!H.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 bs=new Set;var Es=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"]),Fr=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Mr=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 Ss=new Set(["cli_op:all"]),As=new Set([...Ss].map(qt));var Cl=new Set([...[...Es,...Fr,...bs].map(qt),...Mr,...As]);var ks=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Ls=/^0(?:\.0+)?$/,Gr=128;function Hr(e,t,n={}){if(t.length>Gr)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Gr} characters.`);let r=t.trim();if(!ks.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&Ls.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Kr(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 Ts(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 Is(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 Os(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 Yr(e,t){return!(e instanceof a)||!Hn(e.code)?null:e.code==="wallet.bridge_timeout"?Ts(e,t):e.code==="wallet.bridge_op_expired"?Is(e,t):Os(e,t)}var Rs=require("crypto");var jr=128;function qr(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 ye{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.";static examples=[`$ allscale wallet send --idempotency-key order-1042 --to ${ce} --amount 100 --chain ethereum`,`$ allscale wallet send --idempotency-key order-1043 --to ${ce} --amount 50 --chain polygon --stable-coin USDC`,`$ allscale wallet send --idempotency-key order-1044 --to ${ce} --amount 1 --chain base --bridge-timeout 240000`,`$ allscale wallet send --idempotency-key order-1045 --to ${ce} --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:[...Pn],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:tn}),...ye.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=qr(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(!$n(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(Fn(r))throw new a("input.invalid","--to is a zero/burn address; funds sent there cannot be recovered.");Un(r);let o=Hr("--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=Bn(t.chain);if(c===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let u=Dn(t["stable-coin"]);if(u===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);Kr("--amount",o,xn(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 Br({ctx:p,op:"withdraw_token",mode:"data",payload:d,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1})}catch(_){throw Yr(_,{to_address:d.to_address,idempotency_key:n})??_}let g=h.result_data??{},f=Ur(g);if(!f){let _=typeof g.transaction_hash=="string"&&H.test(g.transaction_hash)?g.transaction_hash:typeof g.tx_hash=="string"&&H.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 w=f.transactionHash;return{tx_hash:w,chain:c,chain_name:Mn(c),to_address:r,amount:o,stable_coin:u,stable_coin_name:Gn(u),explorer_url:St(c,w)||void 0,idempotency_key:h.idempotency_key??n}}};
|
|
57
|
+
`),{result_data:n.result_data}}async function Is(e,t,n,r){if(t==="ack"){m({type:"bridge_result_received",source:"paste"});let i=await jt(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=Rs(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 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}}};
|
|
60
60
|
//# sourceMappingURL=send.js.map
|