@allscale/cli 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +113 -41
  2. package/bin/dev.js +11 -1
  3. package/bin/run-oclif.js +216 -27
  4. package/bin/run.js +19 -1
  5. package/dist/commands/build-info.js +13 -13
  6. package/dist/commands/claim-link/claim.js +14 -14
  7. package/dist/commands/claim-link/create.js +40 -37
  8. package/dist/commands/claim-link/get.js +26 -15
  9. package/dist/commands/claim-link/list.js +15 -15
  10. package/dist/commands/claim-link/status.js +13 -13
  11. package/dist/commands/describe.js +13 -13
  12. package/dist/commands/device-login.js +23 -24
  13. package/dist/commands/invoice/get.js +15 -15
  14. package/dist/commands/invoice/list.js +16 -16
  15. package/dist/commands/invoice/pay.js +40 -41
  16. package/dist/commands/invoice/received.js +16 -16
  17. package/dist/commands/invoice/send.js +42 -34
  18. package/dist/commands/invoice/sent.js +15 -15
  19. package/dist/commands/invoice/update.js +17 -15
  20. package/dist/commands/logout.js +14 -14
  21. package/dist/commands/operations.js +13 -13
  22. package/dist/commands/otp-login.js +21 -20
  23. package/dist/commands/otp-send.js +13 -13
  24. package/dist/commands/payout/send.js +14 -14
  25. package/dist/commands/payout/status.js +15 -15
  26. package/dist/commands/scope.js +17 -16
  27. package/dist/commands/store/create.js +17 -17
  28. package/dist/commands/transaction/get.js +15 -15
  29. package/dist/commands/transaction/list.js +15 -15
  30. package/dist/commands/wallet/list.js +15 -15
  31. package/dist/commands/wallet/send.js +40 -43
  32. package/dist/commands/whoami.js +14 -14
  33. package/dist/hooks/version-suffix.js +1 -1
  34. package/dist/index.js +14 -14
  35. package/dist/lib/help.js +7 -2
  36. package/dist/lib/output/audit-lifecycle.js +7 -0
  37. package/oclif.manifest.json +123 -292
  38. package/package.json +4 -6
  39. package/dist/commands/claim-link/preview.js +0 -18
@@ -1,63 +1,60 @@
1
- "use strict";var Zr=Object.create;var Te=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var ri=(e,t)=>{for(var n in t)Te(e,n,{get:t[n],enumerable:!0})},Qt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ei(t))!ni.call(e,i)&&i!==n&&Te(e,i,{get:()=>t[i],enumerable:!(r=Qr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Zr(ti(e)):{},Qt(t||!e||!e.__esModule?Te(n,"default",{value:e,enumerable:!0}):n,e)),ii=e=>Qt(Te({},"__esModule",{value:!0}),e);var Es={};ri(Es,{default:()=>et});module.exports=ii(Es);var Vr=require("process");var B=require("@oclif/core");var en="public",nt="https://app.allscale.io";var Le=["https://app.allscale.io"];var rt="Override the API base URL (public builds accept only https://app.allscale.io)";var it="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";var le={"app.allscale.io":{authProxyConfigId:"918de955-34ae-4914-914d-5732611edbe7",apiBaseUrl:"https://api.turnkey.com",authProxyUrl:"https://authproxy.turnkey.com"}};function tn(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 nn(e){return tn(e)!==null}function X(e){let t=tn(e);return t!==null&&Le.includes(t.origin)}function ot(e){return X(e)}function ue(){return"".trim()||void 0}function de(){return"public"}function M(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function at(e){try{return new URL(e).origin}catch{return null}}function pe(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return st()}function st(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:c,keyId:l}=o;if(typeof a!="string"||a.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:a.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}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 rn="`allscale device-login` (or `allscale otp-login` for headless automation)",on="Headless signing needs a legacy JWT session, which this build cannot create \u2014 drop `--headless` to sign through the browser bridge.";var sn="drop `--headless` and use the browser-bridge flow with an agent-key session.",an="allscale device-login",ct=" Requires an existing legacy JWT session, which this build cannot create \u2014 use the browser-bridge flow instead.";var dt="device-login";function ln(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function pt(){return rn}function Oe(){return on}function un(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+sn:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${ln()}\` for headless automation`+"."}function dn(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${dt} --profile ${e}\`.`}var si={"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_expired":5,"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_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},ai=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 ft(e){return(typeof e=="string"?e:String(e??"")).replace(ai,"")}var ci=64;function lt(e,t=new Map,n=0){if(typeof e=="string")return ft(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ci)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let c of e)a.push(lt(c,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,c]of Object.entries(e))Object.defineProperty(o,a,{value:lt(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(t,n,r){super(ft(n)),this.code=t,this.details=r&&lt(r),this.name="AllscaleError"}get exitCode(){return si[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function pn(e){if(e instanceof s)return e;if(e instanceof Error){if(di(e)){let t=fi(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new s("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var li=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),ui=[/^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 di(e){if(pi(e))return!0;let t=e.name??"";return li.has(t)?t==="CLIError"?ut(e,"parse")||cn(e.message):!0:cn(e.message)}function pi(e){if(!ut(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&ut(e,"parse")}function cn(e){return e?ft(e).split(`
2
- `).some(t=>ui.some(n=>n.test(t.trim()))):!1}function ut(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function fi(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function fn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var b=A(require("fs")),ve=A(require("path")),bn=A(require("crypto"));var gi="...<truncated>",hi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,mi=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,wt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,gt=String.raw`(?:proxy[_-]?)?authorization`,yi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${gt}"|'${gt}'|${gt})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${wt}`,"gi"),_i=/\b(https?:\/\/)[^\s/?#]+@/gi,ht=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,wi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ht}"|'${ht}'|${ht})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${wt}`,"gi"),mt=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)`,bi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mt}"|'${mt}'|${mt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${wt}`,"g");function gn(e){return e.replace(_i,"$1<redacted>@").replace(hi,"<redacted-jwt>").replace(yi,"$1$2$3<redacted>").replace(wi,"$1$2<redacted>").replace(bi,"$1$2<redacted>").replace(mi,"Bearer <redacted>")}function hn(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function mn(e,t,n=gi){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let p=Buffer.byteLength(d,"utf8");if(l+p>t)break;c+=d,l+=p}return c}let i=t-r,o="",a=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(a+l>i)break;o+=c,a+=l}return`${o}${n}`}function P(e,t=16384){return mn(hn(gn(e)),t)}var yt=100,ki=8,Si=8*1024;function Ie(){return{remaining:Si}}function _t(e,t){let n=Math.min(16384,t.remaining),r=mn(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function Z(e,t,n=0,r={}){if(n>ki)return _t("<truncated>",t);if(typeof e=="string"){let i=gn(e);return _t(r.escapeControls?hn(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,yt),o=i.map(a=>Z(a,t,n+1,r));return e.length>i.length&&o.push(_t(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,c]of o.slice(0,yt))i[a]=Z(c,t,n+1,r);return o.length>yt&&(i.output_truncated=!0),i}return e}var bt=require("process");var kt=!1;function St(e){kt=e}function _n(){return kt}var yn="1";function ee(e,t){if(kt){let n={...e};delete n.version;let r=Ie(),i={event:n.event,...n},o=Z(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:yn,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:yn,event:o.event,output_truncated:!0})),bt.stderr.write(`${a}
4
- `)}else bt.stderr.write(t)}var wn="2",te=null,x=null,ne=!1;function Ei(){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=bn.randomBytes(4).toString("hex");return ve.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Et=64*1024*1024,Ai=null;function kn(){if(ne)return;let e=Ei();if(!e)return;te=null;let t=null;try{if((Ai??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ve.dirname(e);if(b.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=b.statSync(n),l=c.mode&511;if(!c.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let r=b.constants.O_NOFOLLOW??0;t=b.openSync(e,b.constants.O_APPEND|b.constants.O_CREAT|b.constants.O_WRONLY|(b.constants.O_NONBLOCK??0)|r,384);let i=b.fstatSync(t),o=b.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.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 a=i.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);b.fchmodSync(t,384)}catch(n){if(t!==null)try{b.closeSync(t)}catch{}ee({event:"sidecar_disabled",reason:"open_failed",detail:P(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${P(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}te=e,x=t,ne=!0}var Ti=[/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 Li(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Ti.some(n=>n.test(t))}function Sn(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=Oi(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Li(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Oi(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Ii(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Sn(e.url)}:e}function vi(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=Z(i,Ie()),a=JSON.stringify({version:wn,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:wn,timestamp:t,type:r,output_truncated:!0})),a}function w(e){if(!ne||!te||x===null)return;let t=Ii(e),n=vi(t);try{if(b.fstatSync(x).size+Buffer.byteLength(n,"utf8")+1>Et){ne=!1;try{b.closeSync(x)}catch{}x=null,ee({event:"sidecar_disabled",reason:"size_limit",...te===null?{}:{path:P(te)},max_bytes:Et},`${P(`[allscale] sidecar exceeded ${Et} bytes; disabling it for the rest of this run. Rotate or remove ${te}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}b.appendFileSync(x,`${n}
7
- `)}catch(r){if(ne=!1,x!==null){try{b.closeSync(x)}catch{}x=null}try{ee({event:"sidecar_disabled",reason:"write_failed",detail:P(r.message)},`${P(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var D=Sn;function En(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Ce(){if(ne=!1,x!==null){try{b.closeSync(x)}catch{}x=null}}function An(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||En()||!t}var fe=ue()??nt,ie={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 U(e){return nn(e)?new URL(e).origin:null}function v(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Tn(){let e=process.env[ie.TOKEN]?.trim();return e&&e.length>0?e:void 0}function At(){let e=process.env[ie.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Re(){let e=process.env[ie.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Ln(){let e=process.env[ie.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function On(){let e=process.env[ie.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function In(){let e=process.env[ie.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vn(e){let t,n;try{t=new URL(e),n=new URL(nt)}catch{return}if(t.host===n.host)return;let r=le[t.host],i=le[n.host];if(!(r===void 0||i===void 0||r.authProxyConfigId!==i.authProxyConfigId))return`Notice: session ${t.origin} signs against the production Turnkey org (mainnet \u2014 real funds).
9
- `}function Cn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(ue()===void 0&&fe!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
10
- The CLI default is now ${fe} (production), but a saved profile wins over the default,
1
+ "use strict";var Zr=Object.create;var Te=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var eo=Object.getOwnPropertyNames;var to=Object.getPrototypeOf,no=Object.prototype.hasOwnProperty;var ro=(e,t)=>{for(var n in t)Te(e,n,{get:t[n],enumerable:!0})},Xt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of eo(t))!no.call(e,o)&&o!==n&&Te(e,o,{get:()=>t[o],enumerable:!(r=Qr(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Zr(to(e)):{},Xt(t||!e||!e.__esModule?Te(n,"default",{value:e,enumerable:!0}):n,e)),oo=e=>Xt(Te({},"__esModule",{value:!0}),e);var Cs={};ro(Cs,{default:()=>ze});module.exports=oo(Cs);var $=require("@oclif/core");var Zt="public",Qt="https://app.allscale.io";var en=["https://app.allscale.io"];var Ze="Override the API base URL (public builds accept only https://app.allscale.io)",tn="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 de="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function nn(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 rn(e){return nn(e)!==null}function te(e){let t=nn(e);return t!==null&&en.includes(t.origin)}function Qe(e){return te(e)}function pe(){return"".trim()||void 0}function fe(){return"public"}function Y(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",io=/^[A-Za-z0-9._-]{1,64}$/;function it(e){return io.test(e)?e:"<profile>"}function sn(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 an(e){let t=it(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${sn(e)}\` for headless automation.`}function ln(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 so={"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_expired":5,"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},ao=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(ao,"")}var lo=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>=lo)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 so[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function cn(e){if(e instanceof a)return e;if(e instanceof Error){if(po(e)){let t=ho(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 co=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),uo=[/^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 po(e){if(fo(e))return!0;let t=e.name??"";return co.has(t)?t==="CLIError"?rt(e,"parse")||on(e.message):!0:on(e.message)}function fo(e){if(!rt(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&rt(e,"parse")}function on(e){return e?st(e).split(`
2
+ `).some(t=>uo.some(n=>n.test(t.trim()))):!1}function rt(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function ho(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function un(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var y=T(require("fs")),Ne=T(require("path")),_n=T(require("crypto"));var go="...<truncated>",mo=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,_o=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,dt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,at=String.raw`(?:proxy[_-]?)?authorization`,wo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${at}"|'${at}'|${at})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${dt}`,"gi"),yo=/\b(https?:\/\/)[^\s/?#]+@/gi,bo=String.raw`(?:[A-Za-z0-9]+[_-])*`,Eo=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,pn=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)`,dn=pn(bo),So=pn(Eo),Ao=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${dn}"|'${dn}'|${So})\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)`,ko=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${lt}"|'${lt}'|${lt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${dt}`,"g");function Oe(e){return e.replace(yo,"$1<redacted>@").replace(mo,"<redacted-jwt>").replace(wo,"$1$2$3<redacted>").replace(Ao,"$1$2<redacted>").replace(ko,"$1$2<redacted>").replace(_o,"Bearer <redacted>")}var Lo=/(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 Lo.test(t)}function fn(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=go){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 I(e,t=16384){return Ce(fn(Oe(e)),t)}var ct=100,To=8,Io=8*1024;function ve(){return{remaining:Io}}function ut(e,t){let n=Math.min(16384,t.remaining),r=Ce(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function ne(e,t,n=0,r={}){if(n>To)return ut("<truncated>",t);if(typeof e=="string"){let o=Oe(e);return ut(r.escapeControls?fn(o):o,t)}if(Array.isArray(e)){let o=e.slice(0,ct),i=o.map(s=>ne(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]=ne(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 gn(){return ft}var hn="1";function oe(e,t){if(ft){let n={...e};delete n.version;let r=ve(),o={event:n.event,...n},i=ne(o,r,0,{escapeControls:!0}),s=JSON.stringify({version:hn,...i});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:hn,event:i.event,output_truncated:!0})),pt.stderr.write(`${s}
4
+ `)}else pt.stderr.write(t)}var mn="2",ie=null,v=null,se=!1,ge=!1;function Oo(){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=_n.randomBytes(4).toString("hex");return Ne.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var gt=64*1024*1024,Ro=null;function mt(e={}){if(e.quiet&&(ge=!0),se)return;let t=Oo();if(!t)return;ie=null;let n=null;try{if((Ro??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=Ne.dirname(t);if(y.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=y.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=y.constants.O_NOFOLLOW??0;n=y.openSync(t,y.constants.O_APPEND|y.constants.O_CREAT|y.constants.O_WRONLY|(y.constants.O_NONBLOCK??0)|o,384);let i=y.fstatSync(n),s=y.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`);y.fchmodSync(n,384)}catch(r){if(n!==null)try{y.closeSync(n)}catch{}ge||oe({event:"sidecar_disabled",reason:"open_failed",detail:I(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${I(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}ie=t,v=n,se=!0}var Co=[/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 vo(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Co.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=No(t.pathname);let o=n;t.pathname!==r&&(o=!0);for(let[i]of t.searchParams)vo(i)&&(t.searchParams.set(i,"<redacted>"),o=!0);return o?t.toString():e}catch{return e}}function No(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function xo(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:wn(e.url)}:e}function Po(e){let t=new Date().toISOString(),n=e,{type:r,...o}=n,i=ne(o,ve()),s=JSON.stringify({version:mn,timestamp:t,type:r,...i});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:mn,timestamp:t,type:r,output_truncated:!0})),s}function m(e){if(!se||!ie||v===null)return;let t=xo(e),n=Po(t);try{if(y.fstatSync(v).size+Buffer.byteLength(n,"utf8")+1>gt){se=!1;try{y.closeSync(v)}catch{}v=null,ge||oe({event:"sidecar_disabled",reason:"size_limit",...ie===null?{}:{path:I(ie)},max_bytes:gt},`${I(`[allscale] sidecar exceeded ${gt} bytes; disabling it for the rest of this run. Rotate or remove ${ie}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}y.appendFileSync(v,`${n}
7
+ `)}catch(r){if(se=!1,v!==null){try{y.closeSync(v)}catch{}v=null}try{ge||oe({event:"sidecar_disabled",reason:"write_failed",detail:I(r.message)},`${I(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var M=wn;function yn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function me(){if(ge=!1,se=!1,v!==null){try{y.closeSync(v)}catch{}v=null}}function bn(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||yn()||!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"]),Bo=new Set(Array.from(_e).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Do=Array.from(_e).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),$o=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(Bo.has(i)){t.push(`${i}<redacted>`);continue}}let o=$o.has(r)?void 0:Do.find(i=>r.length>i.length&&r.startsWith(i));if(o){t.push(`${o}<redacted>`);continue}t.push(r)}return t}function En(e){m({type:"error",code:e.code,message:I(e.message)}),m({type:"command-end",ok:!1,exitCode:e.exitCode}),me()}var we=pe()??Qt,le={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 G(e){return rn(e)?new URL(e).origin:null}function O(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Sn(){let e=process.env[le.TOKEN]?.trim();return e&&e.length>0?e:void 0}function wt(){let e=process.env[le.PROFILE]?.trim();return e&&e.length>0?e:void 0}function xe(){let e=process.env[le.API_BASE]?.trim();return e&&e.length>0?e:void 0}function An(){let e=process.env[le.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function kn(){let e=process.env[le.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Ln(){let e=process.env[le.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Tn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:o}=e;if(pe()===void 0&&we!==""&&"".length!==0&&!n&&o!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${we} (production), but a saved profile wins over the default,
11
10
  so this session still uses staging. That pin was written before the default changed, so it may just be
12
11
  the old default rather than a deliberate choice.
13
- To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
14
- To move to production, run: ${an} --api-base ${fe}
15
- `}var oe=A(require("fs")),Rn=A(require("os")),Tt=A(require("path")),Lt=A(require("@iarna/toml"));var Pi=".allscale",xi="config.toml";function ge(){return Tt.join(Rn.homedir(),Pi)}function Ni(){return Tt.join(ge(),xi)}function Pe(){let e=Ni();if(!oe.existsSync(e))return{};let t=oe.readFileSync(e,"utf-8");try{return Lt.parse(t)}catch(n){throw new s("internal",`Failed to parse ${e}: ${n.message}`)}}function Pn(e){return Object.keys(e.profile??{}).sort()}function xn(e,t){return e.profile?.[t]}function Nn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new s("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function N(e){if(!X(e))throw new s("input.invalid",`Refusing to send credentials to API base ${v(e)}. `+it)}function he(e,t){N(e);let n=U(e),r=typeof t=="string"?U(t):null;if(n&&r===n)return;let i=typeof t=="string"?v(t):"<missing origin binding>";throw new s("input.invalid",`Refusing to send stored credentials: API base ${v(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Bn(e,t){let n=U(e),r=U(t);if(!(n&&r===n))throw new s("input.invalid",`Refusing API request to ${v(t)} because it is outside the configured API origin ${v(e)}.`)}function G(e){let t=ue();if(t===void 0||M(e))return;let n=U(e),r=pe();if(r.length>0){let o=r.map(c=>U(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let a=r.map(c=>v(c.base)).join(", ");throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=U(t);if(!(n!==null&&n===i))throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for ${v(t)}. Re-login against this build's environment, or use a build for that one.`)}var $n=require("@noble/hashes/sha3");function Dn(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Bi={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Un=["ethereum","bsc","base","polygon","arbitrum","optimism"],xe=["USDT","USDC"];function Fn(e){return Bi[e.toLowerCase()]??null}function Mn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function Gn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,$n.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let i=0;i<t.length;i+=1){let o=t[i];if(!/[a-fA-F]/.test(o))continue;let a=Number.parseInt(r[i],16)>=8;if(a&&o!==o.toUpperCase()||!a&&o!==o.toLowerCase())return!1}return!0}var $i=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Kn(e){return $i.has(e.toLowerCase())}function Hn(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 jn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Yn(e){return e===1?"USDT":"USDC"}var C=require("@oclif/core"),me=class e extends B.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:B.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:B.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:de()==="public"}),"api-base":B.Flags.string({description:rt,helpGroup:"GLOBAL",hidden:de()==="public"}),"insecure-storage":B.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{St(this.jsonEnabled()),kn(),w({type:"session-start",command:this.id??"",argv:Ui(this.argv)});let t=this.constructor;if(de()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new s("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(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Re()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!In())throw this.argv.length>0&&await this.parse(),new s("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. The real access boundary is enforced server-side by the key's scope regardless.");let n=An(this.jsonEnabled()),r=this.argv.length===0&&!n&&qi(t)?this.config.findCommand(this.id??""):void 0;if(r){Ce();let o=await(0,B.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return w({type:"command-end",ok:!0}),Ce(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||fn(i),{data:i})}catch(t){let n=pn(t);w({type:"error",code:n.code,message:P(n.message)}),w({type:"command-end",ok:!1,exitCode:n.exitCode}),Ce(),this.emitError(n),process.exitCode=n.exitCode;return}finally{St(!1)}}resolveSessionApiBaseChain(t){let n=Pe(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||At()!==void 0,a=Nn(n,r,At()),c=xn(n,a),l=i??Re(),d=l??c?.api_base??fe,p=Cn({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ee({event:"legacy_staging_profile",api_base:d,profile:a},p)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||N(n),n}resolveContext(t){if(de()==="public"){if(t.token!==void 0)throw new s("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 s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Re()!==void 0)throw new s("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:i,explicitApiBase:o,profile:a,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(N(i),G(i)),{apiBase:i,profile:a,token:n??Tn(),insecureStorage:r||Ln(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${Yi(t)}
16
- `)}},Be=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"]),Di=new Set(Array.from(Be).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Ui(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 o=r.slice(0,i);if(Be.has(o)){t.push(`${o}=<redacted>`);continue}}}if(Be.has(r)){t.push(r),n+1<e.length&&(Be.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(Di.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Fi=/(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 Mi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fi.test(t)}var Gi=/_(removed|cleared|count|total)$/i;function Ki(e,t){return typeof t=="number"&&Gi.test(e)}var Hi=new Set(xe);function ji(e,t){return e==="token_symbol"&&typeof t=="string"&&Hi.has(t)}var Ne=100;function Ot(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ne),r=n.map(i=>Ot(i,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[i,o]of r.slice(0,Ne))n[i]=Mi(i)&&!Ki(i,o)&&!ji(i,o)?"<redacted>":Ot(o,t+1);if(r.length>Ne){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ne} more keys`}return n}return typeof e=="string"?P(e):e}function Yi(e){let t=_n()?void 0:2,n=Ot(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:P(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function qi(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var Lr=require("crypto"),L=require("process");var ir=A(require("path"));var Ct=require("crypto"),u=A(require("fs")),E=A(require("path"));var $e=1024*1024,Ji=5e3,Wi=20,zi=3e4,It=4096,Vi=new Int32Array(new SharedArrayBuffer(4)),ye=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function De(e){return e instanceof ye}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Xi=null;function H(){return new s("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 Ue(){return(Xi??process.platform)!=="win32"}function Qn(){if(!Ue())throw H()}function er(e){try{return u.default.lstatSync(e),!1}catch(t){if(!S(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(E.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(S(t,"ENOENT"))return!0;throw t}}function S(e,t){return typeof e=="object"&&e!==null&&e.code===t}function _e(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function we(e,t){return e.dev===t.dev&&e.ino===t.ino}function Zi(e){Atomics.wait(Vi,0,0,e)}function tr(e){try{return process.kill(e,0),!0}catch(t){return!S(t,"ESRCH")}}function Qi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qn(e,t){let n=E.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&S(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=u.default.openSync(n,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0));let o=u.default.fstatSync(i),a=u.default.lstatSync(n);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!we(o,a))throw new Error("credential-store parent changed while it was being inspected");_e(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&E.basename(n)===".allscale"&&(u.default.fchmodSync(i,448),c=u.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&u.default.closeSync(i)}return!0}function $(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 i;try{i=u.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&S(o,"ENOENT")?new R:o}if(!we(n,i))throw r.retryOnPathChange?new R:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.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||i.nlink!==1))throw new ye;if(_e(n,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(t,384);let o=u.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function eo(e,t){if(t.size>$e)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc($e+1),r=0;for(;r<n.length;){let i=u.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>$e)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Jn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(S(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(S(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=$(e,t,n);return eo(t,r)}finally{t!==null&&u.default.closeSync(t)}}function Wn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(S(i,"ENOENT")&&er(e))return;throw i}let n=u.default.fstatSync(t),r=$(e,t,n);j(e,r)}finally{t!==null&&u.default.closeSync(t)}rr(E.dirname(e))}function to(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(S(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 ye;_e(t,"credential-store replacement target")}function no(e,t){for(let n=0;n<8;n+=1){let r=(0,Ct.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(S(o,"EEXIST"))continue;throw o}}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=u.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=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(t)}catch{}finally{if(t!==null)try{u.default.closeSync(t)}catch{}}}function ro(e,t){let n=Buffer.from(t,"utf8");if(n.length>$e)throw new Error("credential-store file exceeds the maximum supported size");let r=E.dirname(e),i=E.basename(e),o=null,a=null,c=!1;try{let l=no(r,i);o=l.fd,a=l.tempPath;let d=u.default.fstatSync(o);if(($(a,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");nr(o,n),u.default.fsyncSync(o),$(a,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),to(e),u.default.renameSync(a,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&a!==null)try{u.default.unlinkSync(a)}catch{}}rr(r)}function io(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock`)}function oo(e){return E.join(E.dirname(e),`.${E.basename(e)}.lock-recovery`)}function so(e,t){if(t.size>It)return null;let n=Buffer.alloc(It+1),r=0;for(;r<n.length;){let o=u.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>It)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function j(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!we(n,t))throw new Error("credential-store lock changed while it was being inspected");_e(n,"credential-store lock"),u.default.unlinkSync(e)}function zn(e,t){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(l){if(S(l,"ENOENT"))try{let d=u.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new R}catch(d){if(S(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=$(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=so(n,i);return{state:(o?.target===t&&o?!tr(o.pid):Date.now()-i.mtimeMs>=zi)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function ao(e,t){for(let n=0;n<8;n+=1){let r=(0,Ct.randomBytes)(12).toString("hex"),i=E.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},a=null;try{a=u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384);let c=u.default.fstatSync(a),l=$(i,a,c,{allowMultipleLinks:!0});return nr(a,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(a),{claimPath:i,metadata:o,stats:l}}catch(c){if(S(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{a!==null&&u.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function co(e,t){let n;try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){throw S(r,"ENOENT")?new R:r}try{let r=u.default.fstatSync(n),i=$(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!we(i,t))throw new R;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function Vn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(n){if(S(n,"ENOENT"))try{let r=u.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(S(r,"ENOENT"))return!1;throw r}throw n}return $(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function lo(e){let t;try{t=u.default.openSync(e,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_RDWR|(u.default.constants.O_NOFOLLOW??0),384)}catch(r){if(S(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=$(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{j(e,n)}catch{}throw u.default.closeSync(t),r}}function K(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");Zi(Wi)}function Xn(e){let t=E.dirname(e),n=E.basename(e),r=io(e),i=oo(e),o=ao(t,n),a=Date.now()+Ji,c=!1,l=!1,d=null,p;try{for(;d===null;)try{if(Vn(i)){K(a,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=co(r,o.stats),c=!0}catch(f){if(l&&!c){try{j(r,o.stats)}catch{}l=!1}if(f instanceof R){K(a,!1);continue}if(!S(f,"EEXIST"))throw f;let g;try{g=zn(r,n)}catch(m){if(m instanceof R){K(a,!1);continue}throw m}if(g.state==="absent")continue;if(g.state==="stale"){let m;try{m=lo(i)}catch(k){if(k instanceof R){K(a,!1);continue}throw k}if(m!==null){try{let k;try{k=zn(r,n)}catch(T){if(T instanceof R){K(a,!1);continue}throw T}k.state==="stale"&&j(r,k.stats)}finally{vt(m)}continue}}let h;try{h=Vn(i)}catch(m){if(m instanceof R){K(a,!1);continue}throw m}K(a,h)}}catch(f){p=f}try{j(o.claimPath,o.stats)}catch(f){!S(f,"ENOENT")&&!c&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function vt(e){try{j(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function uo(e,t){let n=Qi(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 i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Zn(e){let t=E.dirname(e),n=E.basename(e);for(let r of u.default.readdirSync(t)){let i=uo(r,n);if(i===null||tr(i))continue;let o=E.join(t,r),a=null;try{try{a=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(S(d,"ENOENT")||S(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(a),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!we(c,l))continue;try{_e(c,"credential-store orphan")}catch{continue}j(o,c)}catch(c){if(!S(c,"ENOENT"))throw c}finally{a!==null&&u.default.closeSync(a)}}}function be(e,t,n){if(!Ue()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw H();if(!qn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw H()}});let a=Xn(e);try{return Zn(e),n({read:()=>Jn(e),remove:()=>Wn(e),write:()=>{throw H()}})}finally{vt(a)}}if(!t.createParent){let o=!1;try{o=er(e)}catch{throw H()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw H()}})}throw H()}if(!qn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Xn(e);try{return Zn(e),n({read:()=>Jn(e),remove:()=>Wn(e),write:o=>ro(e,o)})}finally{vt(i)}}var Rt="allscale-cli";function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function or(e){return Bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function q(e){return new s("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 Pt(){return new s("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 Fe(){return new s("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var Y,xt=!1;function po(){return On()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function fo(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
17
- `,1)[0]==="Cannot find module 'keytar'"}function go(){if(Y!==void 0)return Y;if(po())return xt=!1,Y=null,Y;try{Y=require("keytar"),xt=!1}catch(e){xt=!fo(e),Y=null}return Y}function sr(){let e=Ue()?"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 s("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 Nt(e){try{return await e()}catch{throw sr()}}var $t=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await Nt(()=>this.keytar.getPassword(Rt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw q("OS keychain")}if(!or(r))throw q("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await Nt(()=>this.keytar.setPassword(Rt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await Nt(()=>this.keytar.deletePassword(Rt,t))}},ho="credentials.json",Dt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??ir.join(ge(),ho)}read(t){let n;try{n=t.read()}catch(i){throw De(i)?Pt():q("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw q("plaintext file")}if(!Bt(r)||!Bt(r.profiles))throw q("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw De(r)?Pt():Fe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!or(r))throw q("plaintext file");return r}}async get(t){try{return be(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof s?n:q("plaintext file")}}async set(t,n){try{be(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof s?r:Fe()}}async delete(t){try{be(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 s?n:Fe()}}async clearProfile(t){try{return be(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 s?n:De(n)?Pt():Fe()}}};function Me(e){if(e.insecureStorage)return Qn(),new Dt(e.insecureFilePath);let t=go();if(t)return new $t(t);throw sr()}var Ut=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new s("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Ge(){return new Ut}var J="allscale_access_token",Ft="allscale_refresh_token";function Ke(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function ke(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Mt(e,t){return e.find(n=>n.name===t)?.value??null}var ar=A(require("crypto")),cr=A(require("fs")),lr=A(require("path"));var mo="key-id",yo="x-allscale-cli-version",Gt="cli-1",_o="aScaLe_cli_obf_v1",wo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function bo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var ko=bo(wo,_o),He=`Bearer ${ko}`;function ur(e,t){let n=at(e);if(n!==null)return t.find(r=>at(r.base)===n)}function So(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=pe();if(t.length>0){let r=ur(e,t);if(r)return r.key;if(M(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:M(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Eo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=pe();if(t.length>0){let r=e!==void 0?ur(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&M(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Gt}if(!M(t[0].base))return Gt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Gt}function Ao(){return"0.1.0"}function To(){return new s("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 se(e,t){let n=So(t);if(!n)throw To();let r=Eo(t),i=Math.floor(Date.now()/1e3).toString(),o=ar.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),a={timestamp:i,"secret-key":o,[yo]:Ao()};return r.length>0&&(a[mo]=r),a}function Se(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Lo(e,t={}){let n;try{n=Pn(Pe())}catch{return}if(!(n.length===0||n.includes(e)))return new s("auth.unknown_profile",dn(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function je(e){if(e.profileExplicit){let t=Lo(e.profile);if(t)return t}return new s("auth.no_token",un(e.profile,e.flow))}var Je=256*1024,Ye=class extends s{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`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.`:o?`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,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},qe=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 Kt(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"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Ye(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],c=0,l,d=n.timeoutMs,p=d===void 0?void 0:new Promise((f,g)=>{l=setTimeout(()=>{g(new qe(e.status,d))},d),l.unref?.()});try{for(;;){let f=o.read(),{done:g,value:h}=p?await Promise.race([f,p]):await f;if(g)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new Ye(e.status,t,n.oversizeKind);a.push(Buffer.from(h))}}catch(f){throw f instanceof qe&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(a,c).toString("utf8")}var Oo="X-AllScale-Api-Key",Io=3e4,vo=32*1024*1024,Co=4*1024*1024;function Ro(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function Po(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function xo(e,t){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${D(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 Ht(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}xo(e.status,e.url)}}var dr="--dns-result-order=ipv4first";async function We(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),a=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),l=/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(a);if(!((o||c)&&(i||t!==void 0&&l)))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 s("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=${dr} 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=${dr}`})}var W=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??Io;if(!Number.isFinite(r)||r<1)throw new s("input.invalid","HTTP request timeout must be a positive number of milliseconds.");N(this.opts.apiBase),G(this.opts.apiBase);let i=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),o=Ro(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(a){throw o.timedOut()?new s("transport.timeout",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(a instanceof s)?new s("transport.network",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();Bn(this.opts.apiBase,i);let o=r?.agent_key,a=t.auth??"auto",c=hr(t.path),l=a==="required"?!0:a==="none"?!1:$o(t.path);if((c||a==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw je({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Se(t.body),p=!!o||!!r?.access_token;l&&p&&!this.opts.override&&he(this.opts.apiBase,r?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:d,tokens:r,extra:t.headers}),g=Date.now();w({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:f,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(k){throw new s("transport.network",`Network error contacting ${D(i)}: ${k instanceof Error?k.message:String(k)}`)}if(w({type:"response",status:h.status,durationMs:Date.now()-g}),l&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let k=await Po(this.refreshSingleFlight(),t.signal),T=this.buildHeaders({attachAuth:l&&!!k.access_token,bodyForSig:d,tokens:k,extra:t.headers}),y=Date.now();w({type:"request",method:t.method??"GET",url:i});let _;try{_=await fetch(i,{method:t.method??"GET",headers:T,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(O){throw new s("transport.network",`Network error contacting ${D(i)} on refresh-retry: ${O instanceof Error?O.message:String(O)}`)}return w({type:"response",status:_.status,durationMs:Date.now()-y}),pr(_,{withMetadata:n.withMetadata,authBearing:l,responseKind:fr(t)})}return pr(h,{withMetadata:n.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:fr(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...se(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=He;let i=t.tokens;if(i?.agent_key)return r[Oo]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=ke([{name:J,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new s("auth.token_expired",`No refresh token available; log in again \u2014 ${pt()}.`);if(he(this.opts.apiBase,t.api_base),t.agent_key)throw new s("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=ke([{name:J,value:t.access_token},{name:Ft,value:t.refresh_token}]),i=se("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,a=!1,c=setTimeout(()=>{a=!0,o.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw w({type:"refresh",ok:!1}),new s("transport.network",a&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${D(n)} timed out after 10s with no response.`:`Network error during token refresh against ${D(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}w({type:"response",status:l.status,durationMs:0});try{await Ht(l)}catch(h){throw w({type:"refresh",ok:!1}),h}if(l.status!==200){w({type:"refresh",ok:!1}),await We(l);let h=await mr(l);throw await We(l,h),z(l.status,h),new s("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${pt()}.`,{status:l.status})}let d=Ke(l.headers),p=Mt(d,J),f=Mt(d,Ft);if(!p||!f)throw w({type:"refresh",ok:!1}),new s("auth.token_expired","Refresh response did not include new access/refresh cookies.");let g={...t,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,g),w({type:"refresh",ok:!0}),g}},No=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function hr(e){let t=e.split(/[?#]/,1)[0];return No.some(n=>t===n||t.startsWith(`${n}/`))}var Bo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function jt(e){let t=e.split(/[?#]/,1)[0];return Bo.some(n=>n.test(t))}function $o(e){return hr(e)||jt(e)}async function pr(e,t={}){await Ht(e);let n=e.status>=200&&e.status<300;n||await We(e);let r=t.responseKind??"mutation",o=await Kt(e,n?r==="query"?vo:Co:Je,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await We(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,p)=>{l[p]=d}),{status:e.status,headers:l,body:a}}return a}let c=Fo(a)??`HTTP ${e.status}`;if(z(e.status,a),e.status===401){if(t.agentKeyAuth)throw new s("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new s(l,c,{status:401,body:a})}throw e.status===403?new s("auth.permission_denied",c,{status:403,body:a}):e.status===404?new s("not_found",c,{status:404,body:a}):e.status===429?new s("rate_limited",c,{status:429,body:a}):e.status>=500?new s("backend.internal",c,{status:e.status,body:a}):new s("input.invalid",c,{status:e.status,body:a})}function fr(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var gr=2014;function Do(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===gr||n===String(gr)}var Uo=1e4;async function mr(e,t=Uo){if(e.status>=200&&e.status<300)return"";try{return await Kt(e,Je,{timeoutMs:t})}catch{return""}}function z(e,t){if(!(e>=200&&e<300)&&Do(t))throw new s("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"?t.slice(0,500):t})}function Fo(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 Mo=/^\/(api\/)?(v1\/)?public\//;function Yt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Mo.test(n),i=n&&jt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new W({apiBase:e.apiBase,tokenStore:Me({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(i)return new W({apiBase:e.apiBase,tokenStore:Ge(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var ae={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_TOKEN_CONSUMED:7411},Go=new Set(Object.values(ae));async function yr(e,t,n){return _r(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init")}async function qt(e,t){return _r(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function _r(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof s){let a=Ko(o,r);if(a!==null)throw a}throw o}return Ho(i,r)}function Ko(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,i=typeof r.code=="number"?r.code:void 0;if(i===void 0||i===0||!Go.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return wr(i,o,t)}function Ho(e,t){if(e.code!==void 0&&e.code!==0)throw wr(e.code,e.message,t);if(e.data===void 0)throw new s("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function wr(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case ae.CLI_OP_NOT_FOUND:return new s("not_found",r,{broker_code:e});case ae.CLI_OP_EXPIRED:return new s("wallet.bridge_timeout",r,{broker_code:e});case ae.CLI_OP_UNAUTHORIZED:return new s("auth.permission_denied",r,{broker_code:e});case ae.CLI_OP_UNKNOWN_TYPE:return new s("input.invalid",r,{broker_code:e});case ae.CLI_OP_TOKEN_CONSUMED:return new s("input.invalid",r,{broker_code:e});default:return new s("backend.internal",r,{broker_code:e})}}var kr=require("child_process");async function Sr(e,t={}){if(!ot(e))throw new s("input.invalid",`Refusing to launch browser for untrusted origin: ${v(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new s("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.");if(r==="linux"&&!n.DISPLAY&&!i)throw new s("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 o=jo(r,i);await Yo(o.command,[...o.args,e])}function jo(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 Yo(e,t){return new Promise((n,r)=>{let i;try{i=(0,kr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(a){r(br(e,a));return}let o=!1;i.once("error",a=>{o||(o=!0,r(br(e,a)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function br(e,t){return new s("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var Er=A(require("http"));var qo=9e4,Jo=16*1024;function Ar(e){let t=e.timeoutMs??qo;return new Promise((n,r)=>{let i=!1,o=!1,a=null,c,l,d=new Promise((f,g)=>{c=f,l=g}),p=Er.createServer((f,g)=>{Wo(f,g,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:h=>{a&&clearTimeout(a),c(h),p.close()}})});p.on("error",f=>{let g=new s("transport.network",`Loopback listener error: ${f.message}`);o?l(g):r(g),a&&clearTimeout(a)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),r(new s("transport.network","Failed to read loopback listener port"));return}a=setTimeout(()=>{l(new s("wallet.bridge_timeout",`Bridge timed out after ${t}ms waiting for browser callback.`)),p.close()},t),a.unref?.(),o=!0,n({port:f.port,awaitResult:d,close:()=>{a&&clearTimeout(a),p.close()}})})})}function Wo(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 i=0,o=[],a=!1;e.on("data",c=>{if(!a){if(i+=c.length,i>Jo){a=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(a)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=l,p=typeof d.state=="string"?d.state:"",f=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(!zo(p,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(f===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:f,result_data:g})}),e.on("error",()=>{a||(a=!0)})}function zo(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 Tr(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,a=()=>{o&&(clearTimeout(o),o=null)},c=()=>{a(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,a(),e.off("data",d),e.off("end",p),e.off("error",f),e.pause()},d=h=>{if(n)return;a(),t+=h.toString();let m=t.trim(),k=t.length-t.trimStart().length,T=t.indexOf(`
18
- `,k),y=T===-1?"":t.slice(k,T).trim();if(m.startsWith("{")){if(Jt(m)){l(),r(m);return}if(T===-1){c();return}if(!Jt(y)&&!y.endsWith("}")){let _=t.slice(T+1),O=_.split(`
19
- `).find(Ee=>Ee.trim()!=="")??"";if(y==="{"&&(!/\S/.test(_)||/^\s*"[^"]*"\s*:/.test(_)||/^\s*"[^"]*$/.test(O))){c();return}}l(),r(Jt(y)?y:t.slice(k).trim());return}if(T!==-1){l(),r(y);return}else!m&&t.includes(`
20
- `)&&(l(),r(""))},p=()=>{if(n)return;let h=t.trim();if(!h){l();return}l(),r(h)},f=()=>{n||l()},g=new Promise(h=>{r=h});return e.resume(),e.on("data",d),e.on("end",p),e.on("error",f),{promise:g,cancel:()=>{n||l()}}}function Vo(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 Or(e){let t=Yt(e.ctx),n=e.browserBase??e.ctx.apiBase,r=rs(n),i=e._openBrowser??Sr,o=e._startListener??Ar,a=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,Lr.randomBytes)(32).toString("hex"),d=await yr(t,e.op,e.payload);w({type:"bridge_init",op_id:d.op_id,expires_at:d.expires_at});let p=d.expires_at-Math.floor(Date.now()/1e3),f=Number.isFinite(p)?Math.max(0,p):0,g=Math.min(Math.max(6e4,f*1e3),2147483647),h=e.timeoutMs!=null&&e.timeoutMs>0&&e.timeoutMs<=2147483647?e.timeoutMs:g;L.stderr.write(`Bridge op registered (op_id=${d.op_id}, op TTL ~${f}s, waiting up to ${Math.round(h/1e3)}s for confirmation).
21
- `);let m=await o({state:l,expectedOrigin:r,timeoutMs:h}),k=m.awaitResult.then(I=>({source:"loopback",...I}),I=>({source:"listener_error",error:I})),T=Date.now(),y=setInterval(()=>{let I=Math.floor((Date.now()-T)/1e3);L.stderr.write(`Still waiting for confirmation\u2026 (${I}s elapsed)
22
- `)},15e3);y.unref?.();let _,O=e.signal===void 0?void 0:Vo(e.signal);try{let I=es(n,{op_id:d.op_id,port:m.port,state:l});w({type:"bridge_browser_open",url:I});let Ee=a==="ack"?"confirmation token":"result";if(L.stderr.write(c?e.autoOpen===!1?`
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 ${we}
14
+ `}var j=T(require("fs")),In=T(require("os")),yt=T(require("path")),bt=T(require("@iarna/toml"));var Mo=".allscale",Go="config.toml";function Et(){return yt.join(In.homedir(),Mo)}function Ho(){return yt.join(Et(),Go)}function Pe(){let e=Ho();if(!j.existsSync(e))return{};let t=j.readFileSync(e,"utf-8");try{return bt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function On(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 ${O(e)}. `+de)}function Be(e,t){q(e);let n=G(e),r=typeof t=="string"?G(t):null;if(n&&r===n)return;let o=typeof t=="string"?O(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${O(e)} does not match their bound origin ${o}. Re-login against the intended API base before retrying.`)}function vn(e,t){let n=G(e),r=G(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${O(t)} because it is outside the configured API origin ${O(e)}.`)}function De(e){let t=pe();if(t===void 0||Y(e))return;let n=G(e),r=he();if(r.length>0){let i=r.map(c=>G(c.base)).filter(c=>c!==null);if(n!==null&&i.includes(n))return;let s=r.map(c=>O(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${O(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.`)}let o=G(t);if(!(n!==null&&n===o))throw new a("input.invalid",`Refusing to send to ${O(e)} \u2014 this build only signs for ${O(t)}. Re-login against this build's environment, or use a build for that one.`)}var Nn=require("@noble/hashes/sha3");function xn(e,t){switch(t){case 1:case 2:return e===6?18:6}}var Ko={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Pn=["ethereum","bsc","base","polygon","arbitrum","optimism"],$e=["USDT","USDC"];function Bn(e){return Ko[e.toLowerCase()]??null}function Dn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}function $n(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,Nn.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 ce="0x1234567890abcdef1234567890abcdef12345678";function Yo(e){return e.toLowerCase()===ce}function Un(e,t="--to"){if(Yo(e))throw new a("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var jo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Fn(e){return jo.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 Mn(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Gn(e){return e===1?"USDT":"USDC"}var P=require("@oclif/core"),ye=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:fe()==="public"}),"api-base":$.Flags.string({description:Ze,helpGroup:"GLOBAL",hidden:fe()==="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(fe()==="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&&xe()!==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=bn(this.jsonEnabled()),r=this.argv.length===0&&!n&&Zo(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&&!Ln())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()||un(o),{data:o})}catch(t){let n=cn(t);En({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||wt()!==void 0,s=Cn(n,r,wt()),c=Rn(n,s),u=o??xe(),d=u??c?.api_base??we,p=Tn({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,oe({event:"legacy_staging_profile",api_base:d,profile:s},p)),{apiBase:d,explicitApiBase: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(fe()==="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&&xe()!==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,profile:s,profileApiBase:c,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(o),De(o)),{apiBase:o,profile:s,token:n??Sn(),insecureStorage:r||An(),apiBaseSource:i!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Xo(t)}
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(w.startsWith("{")){if(jt(w)){u(),r(w);return}if(k===-1){c();return}if(!jt(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(jt(x)?x:t.slice(_).trim());return}if(k!==-1){u(),r(x);return}else!w&&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 ps(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 Br(e){let t=Kt(e.ctx),n=e.browserBase??e.ctx.apiBase,r=ws(n),o=e._openBrowser??Cr,i=e._startListener??Nr,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,u=(0,Pr.randomBytes)(32).toString("hex"),d=Date.now(),p=await Ar(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)),C=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=C!=null&&C<=f?C:null,B,ue,Wt=!1,Jt=!1,zt=!1;if(L!=null){let S=Math.min(L,f),D=L>f;F!=null&&F<S?(B=F,ue="caller"):(B=S,ue=D?"timer_ceiling":"op_ttl",Wt=!D&&C!=null&&C>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,ue="op_ttl_unverified",Jt=C!=null&&C>D):(B=Q,ue=F!=null?"caller":"unknown_ttl"),zt=C!=null&&F==null}let Wr=ue==="op_ttl",Jr=L!=null?`~${K}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${Jr}, waiting up to ${Math.round(B/1e3)}s for confirmation).
20
+ `),Wt&&A.stderr.write(`Note: the confirmation wait of ${C}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
+ `),Jt&&A.stderr.write(`Note: the confirmation wait of ${C}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
+ `),zt&&A.stderr.write(`Note: the requested confirmation wait of ${C}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})),Vr=Date.now(),Vt=setInterval(()=>{let S=Math.floor((Date.now()-Vr)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${S}s elapsed)
24
+ `)},15e3);Vt.unref?.();let ke,Xe=e.signal===void 0?void 0:ps(e.signal);try{let S=ms(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?`
23
25
  Confirm this in your browser. Open the URL below on any device where
24
26
  you're signed in to AllScale (local auto-open is disabled):
25
27
 
26
- ${I}
28
+ ${S}
27
29
 
28
30
  `:`
29
31
  Confirm this in your browser. The URL is below \u2014 it auto-opens if a
30
32
  browser is available on this machine; otherwise open it on any device
31
33
  where you're signed in to AllScale:
32
34
 
33
- ${I}
35
+ ${S}
34
36
 
35
37
  `:`
36
38
  Confirm this in a browser on this machine. The callback must reach the
37
39
  local listener; non-interactive stdin cannot accept a result pasted
38
40
  back from another device:
39
41
 
40
- ${I}
42
+ ${S}
41
43
 
42
- `),e.autoOpen===!1)L.stderr.write(`(browser auto-open skipped \u2014 use the link above)
43
- `);else try{await i(I),L.stderr.write(`(opened in your default browser)
44
- `)}catch{L.stderr.write(`(no local browser to open \u2014 use the link above)
45
- `)}c?L.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
44
+ `),e.autoOpen===!1)A.stderr.write(`(browser auto-open skipped \u2014 use the link above)
45
+ `);else try{await o(S),A.stderr.write(`(opened in your default browser)
46
+ `)}catch{A.stderr.write(`(no local browser to open \u2014 use the link above)
47
+ `)}c?A.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
46
48
  reach this machine (e.g. you opened the link elsewhere over SSH), copy
47
- the ${Ee} the page shows, paste it here, and press Enter:
48
-
49
- `):L.stderr.write(`stdin is non-interactive; waiting for the browser callback.
50
-
51
- `),c&&(_=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:Tr());let tt=[k];_!==void 0&&tt.push(_.promise.then(Xr=>({source:"paste",line:Xr}))),O!==void 0&&tt.push(O.promise);let V=await Promise.race(tt);if(V.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(V.source==="listener_error")throw Xo(V.error);if(V.source==="loopback")return L.stderr.write(`Browser returned result; processing\u2026
52
- `),await Zo(t,a,V);let Ae=V.line.trim();if(!Ae)throw new s("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(a==="ack"&&Ae.startsWith("{"))throw new s("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(a==="ack"&&/\s/.test(Ae))throw new s("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 L.stderr.write(`Received pasted ${Ee}; processing\u2026
53
- `),await Qo(t,a,Ae)}finally{clearInterval(y),O?.cleanup(),_?.cancel(),m.close()}}function Xo(e){return e instanceof s&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_invalid_response")?e:new s("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 Zo(e,t,n){if(t==="ack"){if(!n.result_token)throw new s("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");w({type:"bridge_result_received",source:"loopback"});let r=await qt(e,n.result_token);return w({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),L.stderr.write(`Verified by broker.
54
- `),{ack:r,result_data:n.result_data}}if(!n.result_data)throw new s("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return w({type:"bridge_result_received",source:"loopback"}),w({type:"bridge_data_received",source:"loopback"}),L.stderr.write(`Result received from browser.
55
- `),{result_data:n.result_data}}async function Qo(e,t,n){if(t==="ack"){w({type:"bridge_result_received",source:"paste"});let i=await qt(e,n);return w({type:"bridge_verified",op_id:i.op_id,source:"paste"}),L.stderr.write(`Verified by broker.
56
- `),{ack:i}}let r;try{r=ns(n)}catch(i){throw i instanceof s&&i.code==="input.invalid"?new s("wallet.bridge_invalid_response",i.message):i}return w({type:"bridge_result_received",source:"paste"}),w({type:"bridge_data_received",source:"paste"}),L.stderr.write(`Result accepted.
57
- `),{result_data:r}}function es(e,t){let n=new URL("/cli",Ir(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()}var ts=/^0x[0-9a-fA-F]{64}$/;function ns(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(ts.test(e))return{tx_hash:e};throw new s("input.invalid",`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function rs(e){return Ir(e).origin}function Ir(e){if(!X(e))throw new s("input.invalid",`Refusing browser base ${v(e)}: bridge state and operation identifiers may only be sent to an exact trusted AllScale origin (${Le.join(", ")}) or an explicit loopback development origin. It must not contain embedded URL userinfo.`);return new URL(e)}var ze=/^0x[0-9a-fA-F]{64}$/,is=["wallet.bridge_timeout","wallet.bridge_invalid_response","wallet.headless_sign_failed"];function vr(e){return typeof e=="string"&&is.includes(e)}var os=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,ss=/^0(?:\.0+)?$/,Cr=128;function Rr(e,t,n={}){if(t.length>Cr)throw new s("input.invalid",`${e} is too long; decimal values may contain at most ${Cr} characters.`);let r=t.trim();if(!os.test(r))throw new s("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&ss.test(r))throw new s("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Pr(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new s("input.invalid",`${e} supports at most ${n} effective decimal places for the selected token and chain; got '${t}'. The CLI will not round a funds amount.`);return t}var Wt=require("process");function xr(e){let t=e.split(".");if(t.length!==3)throw new s("auth.token_expired","Stored token is not a valid JWT.");try{let n=Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(n)}catch(n){throw new s("auth.token_expired",`Failed to decode JWT payload: ${n.message}`)}}var ce="ALLSCALE_OTP";function Br(e,t){if(typeof e=="string"&&e.trim().length>0||t)return!0;let n=process.env[ce];return!!(typeof n=="string"&&n.trim().length>0||process.stdin.isTTY)}async function $r(e,t){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(t){let r=process.env[ce];return typeof r=="string"&&r.trim().length>0&&Wt.stderr.write(`warning: --otp-stdin is set, so ${ce} is ignored (stdin takes precedence).
58
- `),Nr()}let n=process.env[ce];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(process.stdin.isTTY)return Wt.stderr.write("OTP code: "),Nr()}var as=1024;async function Nr(){let e="";try{for await(let t of process.stdin){e+=t;let n=e.indexOf(`
59
- `);if(n!==-1)return e.slice(0,n).trim();if(Buffer.byteLength(e,"utf-8")>=as)throw new s("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(t){throw t instanceof s?t:new s("input.invalid",`Failed to read OTP from stdin: ${t instanceof Error?t.message:String(t)}`)}return e.trim()}var jr=require("crypto"),Yr=require("@turnkey/crypto"),Qe=require("@turnkey/api-key-stamper"),qr=require("@turnkey/http");var F=A(require("fs")),Dr=A(require("path")),Ur=require("crypto");var cs="device_id";function Fr(){let e=null,t=null;try{e=ge(),t=Dr.join(e,cs)}catch{}try{if(t){let r=F.readFileSync(t,"utf-8");if(r.length>70)throw new Error("oversized device_id");let i=r.split(`
60
- `)[0].trim();if(i&&/^cli_[0-9a-f]{32}$/.test(i))return i}}catch{}let n=`cli_${(0,Ur.randomBytes)(16).toString("hex")}`;try{if(!e||!t)throw new Error("persistence unavailable");F.mkdirSync(e,{recursive:!0,mode:448}),F.writeFileSync(t,`${n}
61
- `,{mode:384});try{F.chmodSync(t,384)}catch{}}catch{}return n}var ls=require("crypto");var Mr=128;function Ve(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Mr)throw new s("input.invalid",`--idempotency-key must contain 1-${Mr} characters after trimming.`);return t}var Gr=le;function us(e){let t="";try{t=new URL(e).host}catch{}let n=Gr[t];if(!n)throw new s("wallet.headless_config_missing",`Headless signing has no Turnkey config for '${t||"(unparseable URL)"}'. Supported hosts: ${Object.keys(Gr).join(", ")}. Upgrade the CLI or contact support.`);if(!n.apiBaseUrl.startsWith("https:")||!n.authProxyUrl.startsWith("https:"))throw new s("wallet.headless_config_missing",`Headless Turnkey config for '${t}' has a non-HTTPS URL \u2014 refusing to send credentials.`);return n}var ds=1,Jr=4,ps="CLIENT_SIGNATURE_SCHEME_API_P256",fs="900",Xt=3e4,gs=9e4,Kr=12e4,Xe=256*1024;async function Ze(e,t,n,r){if(!n.startsWith("/")||n.startsWith("//"))throw new s("backend.internal",`secureFetch: path must be root-relative with a single leading '/' (got '${n.split("?")[0]}')`);let i=new URL(n,e).toString(),o=n.split("?")[0],a=r.body===void 0?"":Se(r.body),c=se(a,e),l=[{name:J,value:r.accessToken},...(r.extraCookies??[]).map(g=>({name:g.name,value:g.value}))],d;try{d=await fetch(i,{method:t,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},Authorization:He,Cookie:ke(l),...c},body:r.body===void 0?void 0:a,redirect:"manual",signal:AbortSignal.timeout(r.timeoutMs??Xt)})}catch(g){throw new s("transport.network",`Network error contacting AllScale API (${o}): ${g instanceof Error?g.message:String(g)}`)}let p=await Wr(d,o),f=null;if(p)try{f=JSON.parse(p)}catch{f=null}return{status:d.status,json:f,setCookies:Ke(d.headers)}}async function Wr(e,t){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Xe)throw new s("backend.internal",`Response body from ${t} declares ${n} bytes (over the ${Xe} cap); refusing to read.`);if(!e.body)return"";let r=[],i=0;try{for await(let o of e.body){if(i+=o.byteLength,i>Xe)throw new s("backend.internal",`Response body from ${t} is too large (over the ${Xe}-byte cap); refusing to parse.`);r.push(Buffer.from(o))}}catch(o){if(o instanceof s)throw o}return Buffer.concat(r).toString("utf-8")}async function zt(e,t,n,r){if(!t.startsWith("/")||t.startsWith("//"))throw new s("backend.internal",`authProxyPost: path must be root-relative with a single leading '/' (got '${t.split("?")[0]}')`);let i;try{i=await fetch(new URL(t,e.authProxyUrl).toString(),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Proxy-Config-ID":e.authProxyConfigId},body:JSON.stringify(n),redirect:"manual",signal:AbortSignal.timeout(Xt)})}catch(c){throw new s("transport.network",`Network error contacting Turnkey auth proxy (${r}): ${c instanceof Error?c.message:String(c)}`)}let o=await Wr(i,`Turnkey ${r}`),a={};if(o)try{let c=JSON.parse(o);a=c&&typeof c=="object"&&!Array.isArray(c)?c:{}}catch{a={}}if(i.status<200||i.status>=300){let c=i.status===401&&r==="otp_verify"?"Invalid or expired OTP code \u2014 re-request the code and try again.":i.status===400&&r==="otp_verify"?"Malformed OTP code \u2014 check the code format and try again.":i.status===400&&r==="otp_init"?"Turnkey rejected the account email for OTP delivery \u2014 the account may not be set up for email OTP; contact support.":`Turnkey ${r} failed: HTTP ${i.status}`,l=i.status===429?"rate_limited":i.status>=500?"backend.internal":r==="otp_verify"&&(i.status===400||i.status===401)?"input.invalid":"backend.internal";throw new s(l,c,{status:i.status,where:r})}return a}function hs(e){try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Vt(e){return e===401?"auth.token_expired":e===429?"rate_limited":"backend.internal"}function Hr(e){let t=new Map;for(let n of e)n.name!==J&&t.set(n.name,n);return[...t.values()]}async function ms(e){if(N(e.apiBase),G(e.apiBase),e.token)return e.token;let n=await Me({insecureStorage:e.insecureStorage}).get(e.profile);if((n?.access_token||n?.agent_key)&&he(e.apiBase,n.api_base),n?.agent_key)throw new s("auth.permission_denied","Headless signing requires the user token from a legacy JWT session; agent keys do not contain it. The CLI no longer issues cookie sessions \u2014 use the browser-bridge flow instead (omit --headless).");if(!n?.access_token)throw je({profile:e.profile,profileExplicit:e.profileExplicit,flow:"headless"});return n.access_token}async function ys(e,t){let n=xr(t).user_id,r=typeof n=="string"?n:"";if(!r)throw new s("auth.no_token","Access token has no user_id; re-login.");let o=await Ze(e.apiBase,"POST","/api/secure/graphql",{accessToken:t,body:{query:"query($id:String!){business(id_str:$id){email turnkey{auth_type turnkey_sub_org_id turnkey_session_user_id}}}",variables:{id:r}}});if(o.status!==200)throw z(o.status,o.json),new s(Vt(o.status),`Failed to load account turnkey info (HTTP ${o.status}).`,{http_status:o.status});if(o.json?.errors?.length){let c=o.json.errors.some(l=>/unauth|forbidden|expired|denied|not.?allowed/i.test(l?.message??""));throw new s(c?"auth.token_expired":"backend.internal",c?`Account info query was rejected (authorization) \u2014 the access token may be stale. ${Oe()}`:"Account info query returned GraphQL errors.",{http_status:o.status,graphql_error_count:o.json.errors.length})}if(!o.json?.data?.business)throw new s("backend.internal",`Account info query returned no business data \u2014 the account may not exist or the access token may be stale. ${Oe()}`,{http_status:o.status});let a=o.json.data.business.turnkey;return{businessId:r,email:o.json.data.business.email??"",authType:a?.auth_type??0,subOrgId:a?.turnkey_sub_org_id??"",sessionUserId:a?.turnkey_session_user_id??""}}function _s(e){return(e&ds)!==0&&(e&Jr)===0}async function zr(e,t){let{ctx:n}=e;N(n.apiBase),G(n.apiBase);let r=us(n.apiBase),i=vn(n.apiBase);if(i!==void 0&&process.stderr.write(i),(e.otp?.trim()||process.env[ce]?.trim())&&!e.otpId?.trim()&&!e.otpStdin)throw new s("input.invalid","--otp / ALLSCALE_OTP without --otp-id always fails for headless signing: the CLI emails a fresh OTP at run time that a pre-set value can't match. Use --otp-stdin (pipe the just-emailed code), add --otp-id, or unset ALLSCALE_OTP to use the interactive prompt.");let a=Ve(typeof e.payload.idempotency_key=="string"?e.payload.idempotency_key:void 0);if(!a)throw new s("input.invalid","Headless signing requires a caller-stable idempotency key.");let c=await ms(n),l=await ys(n,c);if(!_s(l.authType))throw new s("wallet.headless_not_supported",(l.authType&Jr)!==0?"This account has a passkey enabled, which can't sign headless. Omit --headless to use the browser flow.":"This account isn't eligible for headless signing (it needs Turnkey email-OTP enabled and no passkey). Omit --headless to use the browser flow.");if(!l.email)throw new s("backend.internal","Account has no email for OTP delivery.");if(!l.subOrgId||!l.sessionUserId)throw new s("wallet.headless_setup_required","Account has no Turnkey session user yet \u2014 sign in once on the web app to provision it, then retry --headless.");let d=Fr(),p=await Ze(n.apiBase,"GET",`/api/v1/secure/turnkey/sessions/current/status?device_id_str=${encodeURIComponent(d)}`,{accessToken:c});if(p.status!==200)throw z(p.status,p.json),new s(Vt(p.status),`Failed to get Turnkey session status (HTTP ${p.status}).`,{http_status:p.status});if(!p.json?.data?.public_key)throw new s("backend.internal","Turnkey session status returned no session public key \u2014 the backend may need to re-provision it; contact support.",{http_status:p.status});let f=p.json.data.public_key,g=Hr(p.setCookies);if(g.length===0)throw new s("backend.internal","get_session_status returned no session cookie (only the access-token cookie, or none at all); cannot continue headless.");let h=(0,jr.randomUUID)();await ws({env:r,runId:h,subOrgId:l.subOrgId,sessionUserId:l.sessionUserId,email:l.email,sessionPublicKey:f,otp:e.otp,otpStdin:!!e.otpStdin,otpId:e.otpId,resolveOtp:t});let m=await Ze(n.apiBase,"POST","/api/v1/secure/turnkey/sessions/current:activate",{accessToken:c,body:{device_id_str:d},extraCookies:g});if(m.status!==200)throw z(m.status,m.json),new s(Vt(m.status),`Failed to activate Turnkey session (HTTP ${m.status}).`,{http_status:m.status});if(typeof m.json?.data?.expires_at_ts!="number")throw new s("backend.internal","Turnkey session did not activate (empty, unreadable, or no-expiry response); not attempting to sign.",{http_status:m.status});let k=Hr(m.setCookies),T=k.length?k:g,y=a,_;try{_=await Ze(n.apiBase,"POST","/api/v1/secure/web3/transfers:gasless-evm-token",{accessToken:c,body:{chain:e.payload.chain,to_address:e.payload.to_address,amount:e.payload.amount,stable_coin:e.payload.stable_coin,device_id_str:d,idempotency_key:y},extraCookies:T,timeoutMs:gs})}catch{throw new s("wallet.headless_sign_failed","Headless signed transfer network call failed; the transaction may have been broadcast \u2014 verify on-chain before retrying.",{idempotency_key:y})}let O=_.json?.data?.tx_hash;if(_.status!==200||typeof O!="string"||!ze.test(O))throw new s("wallet.headless_sign_failed",`Headless signed transfer failed (HTTP ${_.status}). The transaction may have been broadcast \u2014 verify on-chain before retrying.`,{idempotency_key:y,..._.status===401?{recovery_hint:`HTTP 401 usually means the AllScale access token expired and the transfer was rejected before broadcast \u2014 if nothing shows on-chain, re-login and retry. ${Oe()}`}:{}});return{result_data:{tx_hash:O},idempotency_key:y}}async function ws(e){let{env:t}=e,n,r;try{n=(0,Yr.generateP256KeyPair)(),r=new Qe.ApiKeyStamper({apiPublicKey:n.publicKey,apiPrivateKey:n.privateKey})}catch{throw new s("backend.internal","Failed to generate the ephemeral Turnkey login key.")}let i=e.otpId?.trim(),o=i||(await zt(t,"/v1/otp_init",{otpType:"OTP_TYPE_EMAIL",contact:e.email},"otp_init")).otpId;if(!o)throw new s("backend.internal","Turnkey otp_init returned no otpId.");let a;if(e.otpStdin){let y,_=e.resolveOtp(e.otp,e.otpStdin);try{a=await Promise.race([_,new Promise((O,I)=>{y=setTimeout(()=>I(new s("input.invalid","Timed out waiting for the OTP on stdin (--otp-stdin). Pipe the emailed code within "+Math.round(Kr/1e3)+"s.")),Kr)})])}finally{y&&clearTimeout(y),_.catch(()=>{})}}else a=await e.resolveOtp(e.otp,e.otpStdin);if(!a)throw new s("input.invalid","No OTP code provided. Pass --otp, set ALLSCALE_OTP, or pipe via --otp-stdin.");let c=await zt(t,"/v1/otp_verify",{otpId:o,otpCode:a,publicKey:n.publicKey},"otp_verify").catch(y=>{let _=y instanceof s?y.details?.status:void 0;throw y instanceof s&&y.code==="input.invalid"&&i&&_===401?new s(y.code,y.message+" If you passed --otp-id, the prior otpId may itself have expired; re-run WITHOUT --otp-id to start a fresh OTP flow.",y.details):y});if(!c.verificationToken)throw new s("backend.internal","Turnkey otp_verify returned no verificationToken.");let l=hs(c.verificationToken);if(typeof l.id!="string"||l.id.length===0)throw new s("backend.internal","Turnkey verification token has no id.");let d=JSON.stringify({login:{publicKey:n.publicKey},tokenId:l.id,type:"USAGE_TYPE_LOGIN"}),p;try{p=await r.sign(d,Qe.SignatureFormat.Raw)}catch{throw new s("backend.internal","Failed to stamp the Turnkey login request.")}let f={message:d,publicKey:n.publicKey,scheme:ps,signature:p};await zt(t,"/v1/otp_login",{verificationToken:c.verificationToken,publicKey:n.publicKey,clientSignature:f,organizationId:e.subOrgId},"otp_login");let g=new qr.TurnkeyClient({baseUrl:t.apiBaseUrl},r),h,m,k=g.createApiKeys({type:"ACTIVITY_TYPE_CREATE_API_KEYS_V2",timestampMs:String(Date.now()),organizationId:e.subOrgId,parameters:{apiKeys:[{apiKeyName:`cli-headless-${e.runId}`,publicKey:e.sessionPublicKey,curveType:"API_KEY_CURVE_P256",expirationSeconds:fs}],userId:e.sessionUserId}});try{h=await Promise.race([k,new Promise((y,_)=>{m=setTimeout(()=>_(new s("transport.network","Network error contacting Turnkey API (createApiKeys): timed out. A key registration may still be in flight \u2014 wait \u2265 30s before retrying.",{activity:"createApiKeys",hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"})),Xt)})])}catch(y){if(y instanceof s)throw y;let _=y instanceof TypeError||y instanceof DOMException&&y.name==="AbortError"||y instanceof Error&&(y.name==="FetchError"||y.constructor.name==="FetchError");throw new s(_?"transport.network":"backend.internal",_?"Network error contacting Turnkey API (createApiKeys). A key registration may still be in flight \u2014 wait \u2265 30s before retrying.":"Turnkey API rejected the createApiKeys request.",{activity:"createApiKeys",..._?{hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"}:{}})}finally{m&&clearTimeout(m),k.catch(()=>{})}if(!h.activity?.result?.createApiKeysResult?.apiKeyIds?.[0])throw new s("backend.internal","Turnkey createApiKeys returned no apiKeyId.",{activity_status:h.activity?.status})}function bs(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the invoice status BEFORE retrying: if the transfer already shows there, do NOT run this command again (contact support with the invoice id) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${dt}\` to refresh the session, then retry.`,{...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 s("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the invoice 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 Ss(e,t){let n=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.headless_sign_failed",`${e.message.replace(/\.?$/,".")} First check ${t.payment_id?"the invoice status":"the destination address on-chain"} \u2014 if the transfer shows there, do NOT run this command again (give the ids below to support).`,{...t,...n.recovery_hint!==void 0?{recovery_hint:n.recovery_hint}:{},...n.idempotency_key!==void 0?{idempotency_key:n.idempotency_key}:{}})}function Zt(e,t){return!(e instanceof s)||!vr(e.code)?null:e.code==="wallet.bridge_timeout"?bs(e,t):e.code==="wallet.headless_sign_failed"?Ss(e,t):ks(e,t)}var et=class e extends me{static description="Withdraw a stablecoin from your AllScale wallet to an EVM address. Confirms in the browser by default; the CLI prints the transaction hash and explorer URL when the network accepts the transfer. Accounts with Turnkey email-OTP enabled and no passkey can sign without a browser via --headless."+ct;static examples=["$ allscale wallet send --idempotency-key order-1042 --to 0xabc... --amount 100 --chain ethereum","$ allscale wallet send --idempotency-key order-1043 --to 0xabc... --amount 50 --chain polygon --stable-coin USDC","$ allscale wallet send --idempotency-key order-1044 --to 0xabc... --amount 1 --chain base --bridge-timeout 300000","$ allscale wallet send --idempotency-key order-1045 --to 0xabc... --amount 1 --chain bsc # over SSH: open the printed URL on any device, paste the tx hash back","$ allscale wallet send --to 0xabc... --amount 1 --chain base --headless --otp-stdin --idempotency-key order-1042 # reuse the same key only when retrying this operation"];static flags={to:C.Flags.string({helpGroup:"REQUIRED",description:"Recipient EVM address (0x\u2026 40-hex).",required:!0}),amount:C.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:C.Flags.string({helpGroup:"REQUIRED",description:"EVM chain to send on.",options:[...Un],required:!0}),"idempotency-key":C.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":C.Flags.string({description:"Stablecoin to withdraw.",options:[...xe],default:"USDT"}),"bridge-timeout":C.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the full broker op TTL (~5 min, shared by the loopback and paste channels); pass this to abort sooner. (Browser-bridge only \u2014 not valid with --headless.)",min:1e3,exclusive:["headless"]}),"browser-base":C.Flags.string({description:"Override the base URL of the printed /cli confirmation link (defaults to the session API base). (Browser-bridge only \u2014 not valid with --headless.)",exclusive:["headless"]}),headless:C.Flags.boolean({description:`Sign without a browser via Turnkey email-OTP (accounts with email-OTP enabled and no passkey; passkey accounts must use the browser flow). Supply the OTP via --otp-stdin (recommended for automation) or interactively; --otp / ALLSCALE_OTP work ONLY combined with --otp-id. This removes the in-browser human confirmation, so use it only on a trusted machine.${ct}`,default:!1}),otp:C.Flags.string({description:"Turnkey signing OTP code (with --headless). Only works combined with --otp-id (an externally-triggered flow): without --otp-id the CLI emails a FRESH code at run time, so any pre-set --otp / ALLSCALE_OTP value is stale and fails with 'Invalid or expired OTP code'. For automation prefer --otp-stdin (CLI emails; pipe the fresh code back). Passing --otp as a flag also exposes it in shell history AND the process list (ps / /proc/<pid>/cmdline).",exclusive:["otp-stdin"],dependsOn:["headless"]}),"otp-stdin":C.Flags.boolean({description:"Read the Turnkey signing OTP as one line from stdin (with --headless).",default:!1,dependsOn:["headless"]}),"otp-id":C.Flags.string({dependsOn:["headless"],description:"Skip the OTP-send step and reuse a prior Turnkey otpId (with --headless). The OTP code itself is still required via --otp / ALLSCALE_OTP / --otp-stdin."}),...me.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=Ve(t["idempotency-key"]);if(!n)throw new s("input.invalid","--idempotency-key is required so a retry reuses the same on-chain anti-replay id.");if(!t.headless&&(t.otp||t["otp-stdin"]||t["otp-id"]))throw new s("input.invalid","--otp / --otp-stdin / --otp-id require --headless.");if(t.otp?.trim()&&Vr.stderr.write(`warning: --otp passes the code via argv (visible in shell history and the process list); prefer --otp-stdin.
62
- `),t.headless&&!Br(t.otp,t["otp-stdin"]))throw new s("input.invalid","Headless signing needs an OTP source: pass --otp, set ALLSCALE_OTP, use --otp-stdin, or run interactively.");let r=t.to.trim();if(!Gn(r))throw new s("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(Kn(r))throw new s("input.invalid","--to is a zero/burn address; funds sent there cannot be recovered.");let i=Rr("--amount",t.amount),[o,a=""]=i.split(".");if(o==="0"&&(a[0]??"0")==="0")throw new s("input.invalid",`--amount must be at least 0.1; got '${i}'.`);let c=Fn(t.chain);if(c===null)throw new s("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let l=Mn(t["stable-coin"]);if(l===null)throw new s("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);Pr("--amount",i,Dn(c,l));let d={chain:c,to_address:r,amount:i,stable_coin:l,idempotency_key:n},p=this.resolveContext(t),f;if(t.headless)f=await zr({ctx:p,payload:d,otp:t.otp,otpStdin:t["otp-stdin"],otpId:t["otp-id"]},$r).catch(m=>{throw Zt(m,{to_address:d.to_address,...n?{idempotency_key:n}:{}})??m});else try{f=await Or({ctx:p,op:"withdraw_token",mode:"data",payload:d,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"]})}catch(m){throw Zt(m,{to_address:d.to_address,idempotency_key:n})??m}let g=f.result_data??{},h=typeof g.tx_hash=="string"&&ze.test(g.tx_hash)?g.tx_hash:null;if(!h)throw t.headless?new s("wallet.headless_sign_failed","Headless signing returned no usable tx_hash \u2014 the transaction may have been broadcast; verify on-chain before retrying.",{to_address:r,...f.idempotency_key?{idempotency_key:f.idempotency_key}:{}}):new s("wallet.bridge_invalid_response","Browser returned no tx_hash for the withdrawal. The transaction may have been broadcast; check the destination on-chain before retrying.",{to_address:r,idempotency_key:n});return{tx_hash:h,chain:c,chain_name:jn(c),to_address:r,amount:i,stable_coin:l,stable_coin_name:Yn(l),explorer_url:Hn(c,h)||void 0,idempotency_key:f.idempotency_key??n}}};
49
+ the ${D} the page shows, paste it here, and press Enter:
50
+
51
+ `):A.stderr.write(`stdin is non-interactive; waiting for the browser callback.
52
+
53
+ `),c&&(ke=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:xr());let Q=[zr];ke!==void 0&&Q.push(ke.promise.then(Xr=>({source:"paste",line:Xr}))),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 fs(ee.error,Wr);if(ee.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
54
+ `),await hs(t,s,ee);let Le=ee.line.trim();if(!Le)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"&&Le.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(Le))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 gs(t,s,Le,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(Vt),Xe?.cleanup(),ke?.cancel(),Ve.close()}}function fs(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 hs(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 Yt(e,n.result_token);return m({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),A.stderr.write(`Verified by broker.
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 gs(e,t,n,r){if(t==="ack"){m({type:"bridge_result_received",source:"paste"});let i=await Yt(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=_s(n,{acceptBareTxHashPaste:r})}catch(i){throw i instanceof a&&i.code==="input.invalid"?new a("wallet.bridge_invalid_response",i.message):i}return m({type:"bridge_result_received",source:"paste"}),m({type:"bridge_data_received",source:"paste"}),A.stderr.write(`Result accepted.
59
+ `),{result_data:o}}function ms(e,t){let n=new URL("/cli",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}}};
63
60
  //# sourceMappingURL=send.js.map