@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,60 +1,63 @@
1
- "use strict";var Yr=Object.create;var _e=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var jr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var Jr=(e,t)=>{for(var n in t)_e(e,n,{get:t[n],enumerable:!0})},Ft=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jr(t))!zr.call(e,i)&&i!==n&&_e(e,i,{get:()=>t[i],enumerable:!(r=qr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Yr(Wr(e)):{},Ft(t||!e||!e.__esModule?_e(n,"default",{value:e,enumerable:!0}):n,e)),Xr=e=>Ft(_e({},"__esModule",{value:!0}),e);var Vs={};Jr(Vs,{default:()=>Ge});module.exports=Xr(Vs);var v=require("@oclif/core");var Mt="public",Gt="https://app.allscale.io";var ye=["https://app.allscale.io"];var Ke="Override the API base URL (public builds accept only https://app.allscale.io)";var Ye="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Ht(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 Kt(e){return Ht(e)!==null}function W(e){let t=Ht(e);return t!==null&&ye.includes(t.origin)}function qe(e){return W(e)}function ie(){return"".trim()||void 0}function oe(){return"public"}function $(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function We(e){try{return new URL(e).origin}catch{return null}}function se(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return je()}function je(){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:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.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 Yt="`allscale device-login` (or `allscale otp-login` for headless automation)";var qt="drop `--headless` and use the browser-bridge flow with an agent-key session.",jt="allscale device-login";var Zr="device-login";function ae(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Xe(){return Yt}function zt(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 `+qt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${ae()}\` for headless automation`+"."}function Jt(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 ${Zr} --profile ${e}\`.`}var Qr={"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},ei=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 Ve(e){return(typeof e=="string"?e:String(e??"")).replace(ei,"")}var ti=64;function ze(e,t=new Map,n=0){if(typeof e=="string")return Ve(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ti)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ze(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ze(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(Ve(n)),this.code=t,this.details=r&&ze(r),this.name="AllscaleError"}get exitCode(){return Qr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Xt(e){if(e instanceof a)return e;if(e instanceof Error){if(ii(e)){let t=si(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 ni=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),ri=[/^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 ii(e){if(oi(e))return!0;let t=e.name??"";return ni.has(t)?t==="CLIError"?Je(e,"parse")||Wt(e.message):!0:Wt(e.message)}function oi(e){if(!Je(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Je(e,"parse")}function Wt(e){return e?Ve(e).split(`
2
- `).some(t=>ri.some(n=>n.test(t.trim()))):!1}function Je(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function si(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Vt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var y=A(require("fs")),ke=A(require("path")),on=A(require("crypto"));var ai="...<truncated>",li=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,ci=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,rt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ze=String.raw`(?:proxy[_-]?)?authorization`,ui=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ze}"|'${Ze}'|${Ze})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${rt}`,"gi"),di=/\b(https?:\/\/)[^\s/?#]+@/gi,Qe=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)`,pi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Qe}"|'${Qe}'|${Qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"gi"),et=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)`,fi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${et}"|'${et}'|${et})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"g");function Zt(e){return e.replace(di,"$1<redacted>@").replace(li,"<redacted-jwt>").replace(ui,"$1$2$3<redacted>").replace(pi,"$1$2<redacted>").replace(fi,"$1$2<redacted>").replace(ci,"Bearer <redacted>")}function Qt(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 en(e,t,n=ai){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 f=Buffer.byteLength(d,"utf8");if(l+f>t)break;c+=d,l+=f}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function N(e,t=16384){return en(Qt(Zt(e)),t)}var tt=100,mi=8,gi=8*1024;function we(){return{remaining:gi}}function nt(e,t){let n=Math.min(16384,t.remaining),r=en(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function z(e,t,n=0,r={}){if(n>mi)return nt("<truncated>",t);if(typeof e=="string"){let i=Zt(e);return nt(r.escapeControls?Qt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,tt),o=i.map(s=>z(s,t,n+1,r));return e.length>i.length&&o.push(nt(`<${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[s,c]of o.slice(0,tt))i[s]=z(c,t,n+1,r);return o.length>tt&&(i.output_truncated=!0),i}return e}var it=require("process");var ot=!1;function st(e){ot=e}function nn(){return ot}var tn="1";function X(e,t){if(ot){let n={...e};delete n.version;let r=we(),i={event:n.event,...n},o=z(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:tn,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:tn,event:o.event,output_truncated:!0})),it.stderr.write(`${s}
4
- `)}else it.stderr.write(t)}var rn="2",V=null,x=null,Z=!1;function hi(){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=on.randomBytes(4).toString("hex");return ke.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var at=64*1024*1024,_i=null;function sn(){if(Z)return;let e=hi();if(!e)return;V=null;let t=null;try{if((_i??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ke.dirname(e);if(y.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=y.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=y.constants.O_NOFOLLOW??0;t=y.openSync(e,y.constants.O_APPEND|y.constants.O_CREAT|y.constants.O_WRONLY|(y.constants.O_NONBLOCK??0)|r,384);let i=y.fstatSync(t),o=y.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 s=i.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);y.fchmodSync(t,384)}catch(n){if(t!==null)try{y.closeSync(t)}catch{}X({event:"sidecar_disabled",reason:"open_failed",detail:N(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${N(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}V=e,x=t,Z=!0}var yi=[/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 wi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return yi.some(n=>n.test(t))}function an(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=ki(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)wi(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function ki(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function bi(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:an(e.url)}:e}function Si(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=z(i,we()),s=JSON.stringify({version:rn,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:rn,timestamp:t,type:r,output_truncated:!0})),s}function _(e){if(!Z||!V||x===null)return;let t=bi(e),n=Si(t);try{if(y.fstatSync(x).size+Buffer.byteLength(n,"utf8")+1>at){Z=!1;try{y.closeSync(x)}catch{}x=null,X({event:"sidecar_disabled",reason:"size_limit",...V===null?{}:{path:N(V)},max_bytes:at},`${N(`[allscale] sidecar exceeded ${at} bytes; disabling it for the rest of this run. Rotate or remove ${V}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}y.appendFileSync(x,`${n}
7
- `)}catch(r){if(Z=!1,x!==null){try{y.closeSync(x)}catch{}x=null}try{X({event:"sidecar_disabled",reason:"write_failed",detail:N(r.message)},`${N(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var D=an;function ln(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function be(){if(Z=!1,x!==null){try{y.closeSync(x)}catch{}x=null}}function cn(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||ln()||!t}var le=ie()??Gt,ee={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 Kt(e)?new URL(e).origin:null}function L(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function un(){let e=process.env[ee.TOKEN]?.trim();return e&&e.length>0?e:void 0}function lt(){let e=process.env[ee.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Se(){let e=process.env[ee.API_BASE]?.trim();return e&&e.length>0?e:void 0}function dn(){let e=process.env[ee.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function pn(){let e=process.env[ee.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function fn(){let e=process.env[ee.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function mn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(ie()===void 0&&le!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
- The CLI default is now ${le} (production), but a saved profile wins over the default,
1
+ "use strict";var wi=Object.create;var Oe=Object.defineProperty;var yi=Object.getOwnPropertyDescriptor;var bi=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,ki=Object.prototype.hasOwnProperty;var Ei=(e,t)=>{for(var n in t)Oe(e,n,{get:t[n],enumerable:!0})},an=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of bi(t))!ki.call(e,i)&&i!==n&&Oe(e,i,{get:()=>t[i],enumerable:!(r=yi(t,i))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?wi(Si(e)):{},an(t||!e||!e.__esModule?Oe(n,"default",{value:e,enumerable:!0}):n,e)),Ai=e=>an(Oe({},"__esModule",{value:!0}),e);var Ya={};Ei(Ya,{default:()=>nt});module.exports=Ai(Ya);var U=require("@oclif/core");var ln="public",cn="https://app.allscale.io";var un=["https://app.allscale.io"];var de=[];var ot="Override the API base URL (public builds accept only https://app.allscale.io)";var fe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function dn(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 fn(e){return dn(e)!==null}function ee(e){let t=dn(e);return t!==null&&un.includes(t.origin)}function st(e){return ee(e)}function pe(){return"".trim()||void 0}function me(){return"public"}function H(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function lt(e){try{return new URL(e).origin}catch{return null}}function ge(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return at()}function at(){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:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.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 Li="device-login",Ti=/^[A-Za-z0-9._-]{1,64}$/;function dt(e){return Ti.test(e)?e:"<profile>"}function he(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":dt(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Re(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function mn(e){let t=dt(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${he(e)}\` for headless automation.`}function gn(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${Li} --profile ${dt(e)}\`.`}var Ii={"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},Ci=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(Ci,"")}var Oi=64;function ct(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>=Oi)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ct(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ct(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(ft(n)),this.code=t,this.details=r&&ct(r),this.name="AllscaleError"}get exitCode(){return Ii[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function hn(e){if(e instanceof a)return e;if(e instanceof Error){if(vi(e)){let t=xi(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 Ri=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Ni=[/^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 vi(e){if(Pi(e))return!0;let t=e.name??"";return Ri.has(t)?t==="CLIError"?ut(e,"parse")||pn(e.message):!0:pn(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 pn(e){return e?ft(e).split(`
2
+ `).some(t=>Ni.some(n=>n.test(t.trim()))):!1}function ut(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function xi(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function _n(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var w=T(require("fs")),Be=T(require("path")),An=T(require("crypto"));var Bi="...<truncated>",Di=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Ui=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,_t=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,pt=String.raw`(?:proxy[_-]?)?authorization`,$i=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${pt}"|'${pt}'|${pt})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${_t}`,"gi"),Fi=/\b(https?:\/\/)[^\s/?#]+@/gi,Mi=String.raw`(?:[A-Za-z0-9]+[_-])*`,Gi=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,yn=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)`,wn=yn(Mi),Ki=yn(Gi),Hi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${wn}"|'${wn}'|${Ki})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"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)`,Yi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${mt}"|'${mt}'|${mt})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${_t}`,"g");function Ne(e){return e.replace(Fi,"$1<redacted>@").replace(Di,"<redacted-jwt>").replace($i,"$1$2$3<redacted>").replace(Hi,"$1$2<redacted>").replace(Yi,"$1$2<redacted>").replace(Ui,"Bearer <redacted>")}var qi=/(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 ve(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return qi.test(t)}function bn(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 Pe(e,t,n=Bi){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 f=Buffer.byteLength(d,"utf8");if(l+f>t)break;c+=d,l+=f}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function I(e,t=16384){return Pe(bn(Ne(e)),t)}var gt=100,ji=8,Wi=8*1024;function xe(){return{remaining:Wi}}function ht(e,t){let n=Math.min(16384,t.remaining),r=Pe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function te(e,t,n=0,r={}){if(n>ji)return ht("<truncated>",t);if(typeof e=="string"){let i=Ne(e);return ht(r.escapeControls?bn(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,gt),o=i.map(s=>te(s,t,n+1,r));return e.length>i.length&&o.push(ht(`<${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[s,c]of o.slice(0,gt))i[s]=te(c,t,n+1,r);return o.length>gt&&(i.output_truncated=!0),i}return e}var wt=require("process");var yt=!1;function bt(e){yt=e}function kn(){return yt}var Sn="1";function re(e,t){if(yt){let n={...e};delete n.version;let r=xe(),i={event:n.event,...n},o=te(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Sn,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Sn,event:o.event,output_truncated:!0})),wt.stderr.write(`${s}
4
+ `)}else wt.stderr.write(t)}var En="2",ie=null,v=null,oe=!1,_e=!1;function zi(){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=An.randomBytes(4).toString("hex");return Be.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var St=64*1024*1024,Ji=null;function kt(e={}){if(e.quiet&&(_e=!0),oe)return;let t=zi();if(!t)return;ie=null;let n=null;try{if((Ji??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=Be.dirname(t);if(w.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=w.statSync(r),d=l.mode&511;if(!l.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 i=w.constants.O_NOFOLLOW??0;n=w.openSync(t,w.constants.O_APPEND|w.constants.O_CREAT|w.constants.O_WRONLY|(w.constants.O_NONBLOCK??0)|i,384);let o=w.fstatSync(n),s=w.lstatSync(t);if(!o.isFile()||s.isSymbolicLink()||s.dev!==o.dev||s.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);w.fchmodSync(n,384)}catch(r){if(n!==null)try{w.closeSync(n)}catch{}_e||re({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,oe=!0}var Xi=[/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 Vi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Xi.some(n=>n.test(t))}function Ln(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=Zi(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Vi(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Zi(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Qi(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ln(e.url)}:e}function eo(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=te(i,xe()),s=JSON.stringify({version:En,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:En,timestamp:t,type:r,output_truncated:!0})),s}function _(e){if(!oe||!ie||v===null)return;let t=Qi(e),n=eo(t);try{if(w.fstatSync(v).size+Buffer.byteLength(n,"utf8")+1>St){oe=!1;try{w.closeSync(v)}catch{}v=null,_e||re({event:"sidecar_disabled",reason:"size_limit",...ie===null?{}:{path:I(ie)},max_bytes:St},`${I(`[allscale] sidecar exceeded ${St} 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}w.appendFileSync(v,`${n}
7
+ `)}catch(r){if(oe=!1,v!==null){try{w.closeSync(v)}catch{}v=null}try{_e||re({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=Ln;function Tn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function we(){if(_e=!1,oe=!1,v!==null){try{w.closeSync(v)}catch{}v=null}}function In(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Tn()||!t}var ye=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),to=new Set(Array.from(ye).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),no=Array.from(ye).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),ro=new Set(["--otp-stdin","--password-stdin"]);function Et(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(ye.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ye.has(r)){t.push(r),n+1<e.length&&(ye.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let o=r.slice(0,2);if(to.has(o)){t.push(`${o}<redacted>`);continue}}let i=ro.has(r)?void 0:no.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function Cn(e){_({type:"error",code:e.code,message:I(e.message)}),_({type:"command-end",ok:!1,exitCode:e.exitCode}),we()}var be=pe()??cn,ae={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 fn(e)?new URL(e).origin:null}function C(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function On(){let e=process.env[ae.TOKEN]?.trim();return e&&e.length>0?e:void 0}function At(){let e=process.env[ae.PROFILE]?.trim();return e&&e.length>0?e:void 0}function De(){let e=process.env[ae.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Rn(){let e=process.env[ae.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Nn(){let e=process.env[ae.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function vn(){let e=process.env[ae.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Pn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(pe()===void 0&&be!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${be} (production), but a saved profile wins over the default,
10
10
  so this session still uses staging. That pin was written before the default changed, so it may just be
11
11
  the old default rather than a deliberate choice.
12
- To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
- To move to production, run: ${jt} --api-base ${le}
14
- `}var te=A(require("fs")),gn=A(require("os")),ct=A(require("path")),ut=A(require("@iarna/toml"));var Li=".allscale",Ti="config.toml";function dt(){return ct.join(gn.homedir(),Li)}function Ci(){return ct.join(dt(),Ti)}function Ee(){let e=Ci();if(!te.existsSync(e))return{};let t=te.readFileSync(e,"utf-8");try{return ut.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function hn(e){return Object.keys(e.profile??{}).sort()}function _n(e,t){return e.profile?.[t]}function yn(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 F(e){if(!W(e))throw new a("input.invalid",`Refusing to send credentials to API base ${L(e)}. `+Ye)}function pt(e,t){F(e);let n=U(e),r=typeof t=="string"?U(t):null;if(n&&r===n)return;let i=typeof t=="string"?L(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${L(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function wn(e,t){let n=U(e),r=U(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${L(t)} because it is outside the configured API origin ${L(e)}.`)}function Ae(e){let t=ie();if(t===void 0||$(e))return;let n=U(e),r=se();if(r.length>0){let o=r.map(c=>U(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>L(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${L(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 i=U(t);if(!(n!==null&&n===i))throw new a("input.invalid",`Refusing to send to ${L(e)} \u2014 this build only signs for ${L(t)}. Re-login against this build's environment, or use a build for that one.`)}var Ii=require("@noble/hashes/sha3");var Oi={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},kn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Le=["USDT","USDC"];function bn(e){return Oi[e.toLowerCase()]??null}function Sn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var va=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function En(e){return e===1?"USDT":"USDC"}var T=require("@oclif/core"),ce=class e extends v.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:v.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:v.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:oe()==="public"}),"api-base":v.Flags.string({description:Ke,helpGroup:"GLOBAL",hidden:oe()==="public"}),"insecure-storage":v.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()),sn(),_({type:"session-start",command:this.id??"",argv:Ni(this.argv)});let t=this.constructor;if(oe()==="public"){if(this.argv.some(o=>o==="--token"||o.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(o=>o==="--api-base"||o.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&&Se()!==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.")}if(t.requiresEscapeHatch&&!fn())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. The real access boundary is enforced server-side by the key's scope regardless.");let n=cn(this.jsonEnabled()),r=this.argv.length===0&&!n&&Fi(t)?this.config.findCommand(this.id??""):void 0;if(r){be();let o=await(0,v.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return _({type:"command-end",ok:!0}),be(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Vt(i),{data:i})}catch(t){let n=Xt(t);_({type:"error",code:n.code,message:N(n.message)}),_({type:"command-end",ok:!1,exitCode:n.exitCode}),be(),this.emitError(n),process.exitCode=n.exitCode;return}finally{st(!1)}}resolveSessionApiBaseChain(t){let n=Ee(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||lt()!==void 0,s=yn(n,r,lt()),c=_n(n,s),l=i??Se(),d=l??c?.api_base??le,f=mn({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,X({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||F(n),n}resolveContext(t){if(oe()==="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&&Se()!==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:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(F(i),Ae(i)),{apiBase:i,profile:s,token:n??un(),insecureStorage:r||dn(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${$i(t)}
15
- `)}},Ce=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"]),Ri=new Set(Array.from(Ce).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Ni(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(Ce.has(o)){t.push(`${o}=<redacted>`);continue}}}if(Ce.has(r)){t.push(r),n+1<e.length&&(Ce.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(Ri.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var xi=/(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 Pi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xi.test(t)}var vi=/_(removed|cleared|count|total)$/i;function Bi(e,t){return typeof t=="number"&&vi.test(e)}var Di=new Set(Le);function Ui(e,t){return e==="token_symbol"&&typeof t=="string"&&Di.has(t)}var Te=100;function ft(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Te),r=n.map(i=>ft(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,Te))n[i]=Pi(i)&&!Bi(i,o)&&!Ui(i,o)?"<redacted>":ft(o,t+1);if(r.length>Te){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Te} more keys`}return n}return typeof e=="string"?N(e):e}function $i(e){let t=nn()?void 0:2,n=ft(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:N(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Fi(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 Ie=/^0x[0-9a-fA-F]{64}$/,Mi=["wallet.bridge_timeout","wallet.bridge_invalid_response","wallet.headless_sign_failed"];function An(e){return typeof e=="string"&&Mi.includes(e)}var dr=require("crypto"),E=require("process");var Un=A(require("path"));var ht=require("crypto"),u=A(require("fs")),b=A(require("path"));var Oe=1024*1024,Gi=5e3,Hi=20,Ki=3e4,mt=4096,Yi=new Int32Array(new SharedArrayBuffer(4)),ue=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Re(e){return e instanceof ue}var C=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},qi=null;function G(){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 Ne(){return(qi??process.platform)!=="win32"}function xn(){if(!Ne())throw G()}function Pn(e){try{return u.default.lstatSync(e),!1}catch(t){if(!k(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(b.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(k(t,"ENOENT"))return!0;throw t}}function k(e,t){return typeof e=="object"&&e!==null&&e.code===t}function de(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function pe(e,t){return e.dev===t.dev&&e.ino===t.ino}function ji(e){Atomics.wait(Yi,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!k(t,"ESRCH")}}function Wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(e,t){let n=b.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&k(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),s=u.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!pe(o,s))throw new Error("credential-store parent changed while it was being inspected");de(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&b.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 B(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&&k(o,"ENOENT")?new C:o}if(!pe(n,i))throw r.retryOnPathChange?new C: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 ue;if(de(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 zi(e,t){if(t.size>Oe)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Oe+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>Oe)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Tn(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(k(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(k(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=B(e,t,n);return zi(t,r)}finally{t!==null&&u.default.closeSync(t)}}function Cn(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(k(i,"ENOENT")&&Pn(e))return;throw i}let n=u.default.fstatSync(t),r=B(e,t,n);H(e,r)}finally{t!==null&&u.default.closeSync(t)}Dn(b.dirname(e))}function Ji(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(k(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 ue;de(t,"credential-store replacement target")}function Xi(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),i=b.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(k(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Bn(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 Dn(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 Vi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Oe)throw new Error("credential-store file exceeds the maximum supported size");let r=b.dirname(e),i=b.basename(e),o=null,s=null,c=!1;try{let l=Xi(r,i);o=l.fd,s=l.tempPath;let d=u.default.fstatSync(o);if((B(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Bn(o,n),u.default.fsyncSync(o),B(s,o,u.default.fstatSync(o));let p=o;o=null,u.default.closeSync(p),Ji(e),u.default.renameSync(s,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&s!==null)try{u.default.unlinkSync(s)}catch{}}Dn(r)}function Zi(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function Qi(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function eo(e,t){if(t.size>mt)return null;let n=Buffer.alloc(mt+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>mt)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 H(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!pe(n,t))throw new Error("credential-store lock changed while it was being inspected");de(n,"credential-store lock"),u.default.unlinkSync(e)}function In(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(k(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 C}catch(d){if(k(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=B(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=eo(n,i);return{state:(o?.target===t&&o?!vn(o.pid):Date.now()-i.mtimeMs>=Ki)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function to(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=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(s),l=B(i,s,c,{allowMultipleLinks:!0});return Bn(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(c){if(k(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function no(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 k(r,"ENOENT")?new C:r}try{let r=u.default.fstatSync(n),i=B(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!pe(i,t))throw new C;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function On(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(k(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 C}catch(r){if(k(r,"ENOENT"))return!1;throw r}throw n}return B(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function ro(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(k(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=B(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{H(e,n)}catch{}throw u.default.closeSync(t),r}}function M(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");ji(Hi)}function Rn(e){let t=b.dirname(e),n=b.basename(e),r=Zi(e),i=Qi(e),o=to(t,n),s=Date.now()+Gi,c=!1,l=!1,d=null,f;try{for(;d===null;)try{if(On(i)){M(s,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=no(r,o.stats),c=!0}catch(p){if(l&&!c){try{H(r,o.stats)}catch{}l=!1}if(p instanceof C){M(s,!1);continue}if(!k(p,"EEXIST"))throw p;let m;try{m=In(r,n)}catch(S){if(S instanceof C){M(s,!1);continue}throw S}if(m.state==="absent")continue;if(m.state==="stale"){let S;try{S=ro(i)}catch(g){if(g instanceof C){M(s,!1);continue}throw g}if(S!==null){try{let g;try{g=In(r,n)}catch(w){if(w instanceof C){M(s,!1);continue}throw w}g.state==="stale"&&H(r,g.stats)}finally{gt(S)}continue}}let h;try{h=On(i)}catch(S){if(S instanceof C){M(s,!1);continue}throw S}M(s,h)}}catch(p){f=p}try{H(o.claimPath,o.stats)}catch(p){!k(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function gt(e){try{H(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function io(e,t){let n=Wi(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 Nn(e){let t=b.dirname(e),n=b.basename(e);for(let r of u.default.readdirSync(t)){let i=io(r,n);if(i===null||vn(i))continue;let o=b.join(t,r),s=null;try{try{s=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(k(d,"ENOENT")||k(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(s),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!pe(c,l))continue;try{de(c,"credential-store orphan")}catch{continue}H(o,c)}catch(c){if(!k(c,"ENOENT"))throw c}finally{s!==null&&u.default.closeSync(s)}}}function fe(e,t,n){if(!Ne()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw G();if(!Ln(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw G()}});let s=Rn(e);try{return Nn(e),n({read:()=>Tn(e),remove:()=>Cn(e),write:()=>{throw G()}})}finally{gt(s)}}if(!t.createParent){let o=!1;try{o=Pn(e)}catch{throw G()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw G()}})}throw G()}if(!Ln(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Rn(e);try{return Nn(e),n({read:()=>Tn(e),remove:()=>Cn(e),write:o=>Vi(e,o)})}finally{gt(i)}}var _t="allscale-cli";function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $n(e){return bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function Y(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 yt(){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 xe(){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 K,wt=!1;function oo(){return pn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function so(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 ao(){if(K!==void 0)return K;if(oo())return wt=!1,K=null,K;try{K=require("keytar"),wt=!1}catch(e){wt=!so(e),K=null}return K}function Fn(){let e=Ne()?"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 kt(e){try{return await e()}catch{throw Fn()}}var St=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await kt(()=>this.keytar.getPassword(_t,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw Y("OS keychain")}if(!$n(r))throw Y("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await kt(()=>this.keytar.setPassword(_t,t,JSON.stringify(n)))}async delete(t){await this.read(t),await kt(()=>this.keytar.deletePassword(_t,t))}},lo="credentials.json",Et=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Un.join(dt(),lo)}read(t){let n;try{n=t.read()}catch(i){throw Re(i)?yt():Y("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw Y("plaintext file")}if(!bt(r)||!bt(r.profiles))throw Y("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Re(r)?yt():xe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!$n(r))throw Y("plaintext file");return r}}async get(t){try{return fe(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:Y("plaintext file")}}async set(t,n){try{fe(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 a?r:xe()}}async delete(t){try{fe(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:xe()}}async clearProfile(t){try{return fe(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:Re(n)?yt():xe()}}};function Mn(e){if(e.insecureStorage)return xn(),new Et(e.insecureFilePath);let t=ao();if(t)return new St(t);throw Fn()}var At=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 Pe(){return new At}var ve="allscale_access_token",Lt="allscale_refresh_token";function Gn(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 Tt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Ct(e,t){return e.find(n=>n.name===t)?.value??null}var Hn=A(require("crypto")),Kn=A(require("fs")),Yn=A(require("path"));var co="key-id",uo="x-allscale-cli-version",It="cli-1",po="aScaLe_cli_obf_v1",fo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function mo(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 go=mo(fo,po),qn=`Bearer ${go}`;function jn(e,t){let n=We(e);if(n!==null)return t.find(r=>We(r.base)===n)}function ho(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=se();if(t.length>0){let r=jn(e,t);if(r)return r.key;if($(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:$(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 _o(e){{let r="cli-1".trim();if(r.length>0)return r}let t=se();if(t.length>0){let r=e!==void 0?jn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&$(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():It}if(!$(t[0].base))return It}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():It}function yo(){return"0.1.0"}function wo(){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 Ot(e,t){let n=ho(t);if(!n)throw wo();let r=_o(t),i=Math.floor(Date.now()/1e3).toString(),o=Hn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[uo]:yo()};return r.length>0&&(s[co]=r),s}function Wn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ko(e,t={}){let n;try{n=hn(Ee())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",Jt(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function zn(e){if(e.profileExplicit){let t=ko(e.profile);if(t)return t}return new a("auth.no_token",zt(e.profile,e.flow))}var Rt=256*1024,Be=class extends a{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"}},De=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 Nt(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 Be(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,m)=>{l=setTimeout(()=>{m(new De(e.status,d))},d),l.unref?.()});try{for(;;){let p=o.read(),{done:m,value:h}=f?await Promise.race([p,f]):await p;if(m)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(p){throw p instanceof De&&o.cancel(p).catch(()=>{}),p}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var bo="X-AllScale-Api-Key",So=3e4,Eo=32*1024*1024,Ao=4*1024*1024;function Lo(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 To(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 Co(e,t){if(!(e<300||e>=400))throw new a("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 Qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Co(e.status,e.url)}}var Jn="--dns-result-order=ipv4first";async function Ue(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"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),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(s);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new 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=${Jn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${Jn}`})}var q=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??So;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");F(this.opts.apiBase),Ae(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=Lo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${D(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 ${D(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();wn(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=er(t.path),l=s==="required"?!0:s==="none"?!1:Ro(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw zn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Wn(t.body),f=!!o||!!r?.access_token;l&&f&&!this.opts.override&&pt(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:l&&f,bodyForSig:d,tokens:r,extra:t.headers}),m=Date.now();_({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(g){throw new a("transport.network",`Network error contacting ${D(i)}: ${g instanceof Error?g.message:String(g)}`)}if(_({type:"response",status:h.status,durationMs:Date.now()-m}),l&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let g=await To(this.refreshSingleFlight(),t.signal),w=this.buildHeaders({attachAuth:l&&!!g.access_token,bodyForSig:d,tokens:g,extra:t.headers}),I=Date.now();_({type:"request",method:t.method??"GET",url:i});let O;try{O=await fetch(i,{method:t.method??"GET",headers:w,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(P){throw new a("transport.network",`Network error contacting ${D(i)} on refresh-retry: ${P instanceof Error?P.message:String(P)}`)}return _({type:"response",status:O.status,durationMs:Date.now()-I}),Xn(O,{withMetadata:n.withMetadata,authBearing:l,responseKind:Vn(t)})}return Xn(h,{withMetadata:n.withMetadata,authBearing:l&&f,agentKeyAuth:l&&!!o,responseKind:Vn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ot(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=qn;let i=t.tokens;if(i?.agent_key)return r[bo]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=Tt([{name:ve,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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${Xe()}.`);if(pt(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=Tt([{name:ve,value:t.access_token},{name:Lt,value:t.refresh_token}]),i=Ot("",this.opts.apiBase);_({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!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 _({type:"refresh",ok:!1}),new a("transport.network",s&&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)}_({type:"response",status:l.status,durationMs:0});try{await Qn(l)}catch(h){throw _({type:"refresh",ok:!1}),h}if(l.status!==200){_({type:"refresh",ok:!1}),await Ue(l);let h=await Po(l);throw await Ue(l,h),tr(l.status,h),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Xe()}.`,{status:l.status})}let d=Gn(l.headers),f=Ct(d,ve),p=Ct(d,Lt);if(!f||!p)throw _({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,m),_({type:"refresh",ok:!0}),m}},Io=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function er(e){let t=e.split(/[?#]/,1)[0];return Io.some(n=>t===n||t.startsWith(`${n}/`))}var Oo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function xt(e){let t=e.split(/[?#]/,1)[0];return Oo.some(n=>n.test(t))}function Ro(e){return er(e)||xt(e)}async function Xn(e,t={}){await Qn(e);let n=e.status>=200&&e.status<300;n||await Ue(e);let r=t.responseKind??"mutation",o=await Nt(e,n?r==="query"?Eo:Ao:Rt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ue(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,f)=>{l[f]=d}),{status:e.status,headers:l,body:s}}return s}let c=vo(s)??`HTTP ${e.status}`;if(tr(e.status,s),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 l=t.authBearing?"auth.token_expired":"input.invalid";throw new a(l,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 Vn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Zn=2014;function No(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===Zn||n===String(Zn)}var xo=1e4;async function Po(e,t=xo){if(e.status>=200&&e.status<300)return"";try{return await Nt(e,Rt,{timeoutMs:t})}catch{return""}}function tr(e,t){if(!(e>=200&&e<300)&&No(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"?t.slice(0,500):t})}function vo(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 Bo=/^\/(api\/)?(v1\/)?public\//;function $e(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Bo.test(n),i=n&&xt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new q({apiBase:e.apiBase,tokenStore:Mn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var ne={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_TOKEN_CONSUMED:7411},Do=new Set(Object.values(ne));async function nr(e,t,n){return rr(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init")}async function Pt(e,t){return rr(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function rr(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Uo(o,r);if(s!==null)throw s}throw o}return $o(i,r)}function Uo(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||!Do.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return ir(i,o,t)}function $o(e,t){if(e.code!==void 0&&e.code!==0)throw ir(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 ir(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case ne.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case ne.CLI_OP_EXPIRED:return new a("wallet.bridge_timeout",r,{broker_code:e});case ne.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case ne.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case ne.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var sr=require("child_process");async function ar(e,t={}){if(!qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${L(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.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.");if(r==="linux"&&!n.DISPLAY&&!i)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 o=Fo(r,i);await Mo(o.command,[...o.args,e])}function Fo(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 Mo(e,t){return new Promise((n,r)=>{let i;try{i=(0,sr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(or(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(or(e,s)))}),setImmediate(()=>{o||(o=!0,i.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 lr=A(require("http"));var Go=9e4,Ho=16*1024;function cr(e){let t=e.timeoutMs??Go;return new Promise((n,r)=>{let i=!1,o=!1,s=null,c,l,d=new Promise((p,m)=>{c=p,l=m}),f=lr.createServer((p,m)=>{Ko(p,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:h=>{s&&clearTimeout(s),c(h),f.close()}})});f.on("error",p=>{let m=new a("transport.network",`Loopback listener error: ${p.message}`);o?l(m):r(m),s&&clearTimeout(s)}),f.listen({host:"127.0.0.1",port:e.port??0},()=>{let p=f.address();if(!p||typeof p=="string"){f.close(),r(new a("transport.network","Failed to read loopback listener port"));return}s=setTimeout(()=>{l(new a("wallet.bridge_timeout",`Bridge timed out after ${t}ms waiting for browser callback.`)),f.close()},t),s.unref?.(),o=!0,n({port:p.port,awaitResult:d,close:()=>{s&&clearTimeout(s),f.close()}})})})}function Ko(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=[],s=!1;e.on("data",c=>{if(!s){if(i+=c.length,i>Ho){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(s)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,f=typeof d.state=="string"?d.state:"",p=typeof d.result_token=="string"?d.result_token:void 0,m=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(!Yo(f,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(p===void 0&&m===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:p,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function Yo(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 vt(e){try{return JSON.parse(e),!0}catch{return!1}}function ur(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},c=()=>{s(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,s(),e.off("data",d),e.off("end",f),e.off("error",p),e.pause()},d=h=>{if(n)return;s(),t+=h.toString();let S=t.trim(),g=t.length-t.trimStart().length,w=t.indexOf(`
17
- `,g),I=w===-1?"":t.slice(g,w).trim();if(S.startsWith("{")){if(vt(S)){l(),r(S);return}if(w===-1){c();return}if(!vt(I)&&!I.endsWith("}")){let O=t.slice(w+1),P=O.split(`
18
- `).find(ge=>ge.trim()!=="")??"";if(I==="{"&&(!/\S/.test(O)||/^\s*"[^"]*"\s*:/.test(O)||/^\s*"[^"]*$/.test(P))){c();return}}l(),r(vt(I)?I:t.slice(g).trim());return}if(w!==-1){l(),r(I);return}else!S&&t.includes(`
19
- `)&&(l(),r(""))},f=()=>{if(n)return;let h=t.trim();if(!h){l();return}l(),r(h)},p=()=>{n||l()},m=new Promise(h=>{r=h});return e.resume(),e.on("data",d),e.on("end",f),e.on("error",p),{promise:m,cancel:()=>{n||l()}}}function qo(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 pr(e){let t=$e(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Zo(n),i=e._openBrowser??ar,o=e._startListener??cr,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,dr.randomBytes)(32).toString("hex"),d=await nr(t,e.op,e.payload);_({type:"bridge_init",op_id:d.op_id,expires_at:d.expires_at});let f=d.expires_at-Math.floor(Date.now()/1e3),p=Number.isFinite(f)?Math.max(0,f):0,m=Math.min(Math.max(6e4,p*1e3),2147483647),h=e.timeoutMs!=null&&e.timeoutMs>0&&e.timeoutMs<=2147483647?e.timeoutMs:m;E.stderr.write(`Bridge op registered (op_id=${d.op_id}, op TTL ~${p}s, waiting up to ${Math.round(h/1e3)}s for confirmation).
20
- `);let S=await o({state:l,expectedOrigin:r,timeoutMs:h}),g=S.awaitResult.then(R=>({source:"loopback",...R}),R=>({source:"listener_error",error:R})),w=Date.now(),I=setInterval(()=>{let R=Math.floor((Date.now()-w)/1e3);E.stderr.write(`Still waiting for confirmation\u2026 (${R}s elapsed)
21
- `)},15e3);I.unref?.();let O,P=e.signal===void 0?void 0:qo(e.signal);try{let R=Jo(n,{op_id:d.op_id,port:S.port,state:l});_({type:"bridge_browser_open",url:R});let ge=s==="ack"?"confirmation token":"result";if(E.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 ${be}
14
+ `}var Y=T(require("fs")),xn=T(require("os")),Lt=T(require("path")),Tt=T(require("@iarna/toml"));var so=".allscale",ao="config.toml";function It(){return Lt.join(xn.homedir(),so)}function lo(){return Lt.join(It(),ao)}function Ue(){let e=lo();if(!Y.existsSync(e))return{};let t=Y.readFileSync(e,"utf-8");try{return Tt.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function Bn(e){return Object.keys(e.profile??{}).sort()}function Dn(e,t){return e.profile?.[t]}function Un(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(!ee(e))throw new a("input.invalid",`Refusing to send credentials to API base ${C(e)}. `+fe)}function $e(e,t){q(e);let n=G(e),r=typeof t=="string"?G(t):null;if(n&&r===n)return;let i=typeof t=="string"?C(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${C(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function $n(e,t){let n=G(e),r=G(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${C(t)} because it is outside the configured API origin ${C(e)}.`)}function Fe(e){let t=pe();if(t===void 0||H(e))return;let n=G(e),r=ge();if(r.length>0){let o=r.map(c=>G(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>C(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${C(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 i=G(t);if(!(n!==null&&n===i))throw new a("input.invalid",`Refusing to send to ${C(e)} \u2014 this build only signs for ${C(t)}. Re-login against this build's environment, or use a build for that one.`)}var co=require("@noble/hashes/sha3");var uo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},Fn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Me=["USDT","USDC"];function Mn(e){return uo[e.toLowerCase()]??null}function Gn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var Ol=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function Kn(e){return e===1?"USDT":"USDC"}var O=require("@oclif/core"),Se=class e extends U.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:U.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:U.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:me()==="public"}),"api-base":U.Flags.string({description:ot,helpGroup:"GLOBAL",hidden:me()==="public"}),"insecure-storage":U.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{bt(this.jsonEnabled()),kt(),_({type:"session-start",command:this.id??"",argv:Et(this.argv)});let t=this.constructor;if(me()==="public"){if(this.argv.some(o=>o==="--token"||o.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(o=>o==="--api-base"||o.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&&De()!==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=In(this.jsonEnabled()),r=this.argv.length===0&&!n&&wo(t)?this.config.findCommand(this.id??""):void 0;if(r){we();let o=await(0,U.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}if(t.requiresEscapeHatch&&!vn())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 i=await this.runCommand();return _({type:"command-end",ok:!0}),we(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||_n(i),{data:i})}catch(t){let n=hn(t);Cn({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{bt(!1)}}resolveSessionApiBaseChain(t){let n=Ue(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||At()!==void 0,s=Un(n,r,At()),c=Dn(n,s),l=i??De(),d=l??c?.api_base??be,f=Pn({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,re({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||q(n),n}resolveContext(t){if(me()==="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&&De()!==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:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(q(i),Fe(i)),{apiBase:i,profile:s,token:n??On(),insecureStorage:r||Rn(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${_o(t)}
15
+ `)}};var fo=/_(removed|cleared|count|total)$/i;function po(e,t){return typeof t=="number"&&fo.test(e)}var mo=new Set(Me);function go(e,t){return e==="token_symbol"&&typeof t=="string"&&mo.has(t)}var Ge=100;function Ke(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ge),r=n.map(i=>Ke(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,Ge))n[i]=ve(i)&&!po(i,o)&&!go(i,o)?"<redacted>":Ke(o,t+1);if(r.length>Ge){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ge} more keys`}return n}if(typeof e=="string"){let n=ho(e);return n!==void 0?I(JSON.stringify(Ke(n,t+1))):I(e)}return e}function ho(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 _o(e){let t=kn()?void 0:2,n=Ke(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 wo(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 le=/^0x[0-9a-fA-F]{64}$/,yo=["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"&&yo.includes(e)}var Br=require("crypto"),A=require("process");var nr=T(require("path"));var Rt=require("crypto"),u=T(require("fs")),k=T(require("path"));var He=1024*1024,bo=5e3,So=20,ko=3e4,Ct=4096,Eo=new Int32Array(new SharedArrayBuffer(4)),ke=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ye(e){return e instanceof ke}var R=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ao=null;function W(){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 qe(){return(Ao??process.platform)!=="win32"}function Vn(){if(!qe())throw W()}function Zn(e){try{return u.default.lstatSync(e),!1}catch(t){if(!S(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(k.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 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 Ae(e,t){return e.dev===t.dev&&e.ino===t.ino}function Lo(e){Atomics.wait(Eo,0,0,e)}function Qn(e){try{return process.kill(e,0),!0}catch(t){return!S(t,"ESRCH")}}function To(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yn(e,t){let n=k.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),s=u.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Ae(o,s))throw new Error("credential-store parent changed while it was being inspected");Ee(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&k.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(!Ae(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 ke;if(Ee(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 Io(e,t){if(t.size>He)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(He+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>He)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function qn(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 Io(t,r)}finally{t!==null&&u.default.closeSync(t)}}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")&&Zn(e))return;throw i}let n=u.default.fstatSync(t),r=$(e,t,n);z(e,r)}finally{t!==null&&u.default.closeSync(t)}tr(k.dirname(e))}function Co(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 ke;Ee(t,"credential-store replacement target")}function Oo(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=k.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 er(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 tr(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>He)throw new Error("credential-store file exceeds the maximum supported size");let r=k.dirname(e),i=k.basename(e),o=null,s=null,c=!1;try{let l=Oo(r,i);o=l.fd,s=l.tempPath;let d=u.default.fstatSync(o);if(($(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");er(o,n),u.default.fsyncSync(o),$(s,o,u.default.fstatSync(o));let p=o;o=null,u.default.closeSync(p),Co(e),u.default.renameSync(s,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&s!==null)try{u.default.unlinkSync(s)}catch{}}tr(r)}function No(e){return k.join(k.dirname(e),`.${k.basename(e)}.lock`)}function vo(e){return k.join(k.dirname(e),`.${k.basename(e)}.lock-recovery`)}function Po(e,t){if(t.size>Ct)return null;let n=Buffer.alloc(Ct+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>Ct)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 z(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!Ae(n,t))throw new Error("credential-store lock changed while it was being inspected");Ee(n,"credential-store lock"),u.default.unlinkSync(e)}function Wn(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=Po(n,i);return{state:(o?.target===t&&o?!Qn(o.pid):Date.now()-i.mtimeMs>=ko)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function xo(e,t){for(let n=0;n<8;n+=1){let r=(0,Rt.randomBytes)(12).toString("hex"),i=k.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=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(s),l=$(i,s,c,{allowMultipleLinks:!0});return er(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(c){if(S(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Bo(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(!Ae(i,t))throw new R;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function zn(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 Do(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{z(e,n)}catch{}throw u.default.closeSync(t),r}}function j(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");Lo(So)}function Jn(e){let t=k.dirname(e),n=k.basename(e),r=No(e),i=vo(e),o=xo(t,n),s=Date.now()+bo,c=!1,l=!1,d=null,f;try{for(;d===null;)try{if(zn(i)){j(s,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=Bo(r,o.stats),c=!0}catch(p){if(l&&!c){try{z(r,o.stats)}catch{}l=!1}if(p instanceof R){j(s,!1);continue}if(!S(p,"EEXIST"))throw p;let m;try{m=Wn(r,n)}catch(y){if(y instanceof R){j(s,!1);continue}throw y}if(m.state==="absent")continue;if(m.state==="stale"){let y;try{y=Do(i)}catch(h){if(h instanceof R){j(s,!1);continue}throw h}if(y!==null){try{let h;try{h=Wn(r,n)}catch(b){if(b instanceof R){j(s,!1);continue}throw b}h.state==="stale"&&z(r,h.stats)}finally{Ot(y)}continue}}let g;try{g=zn(i)}catch(y){if(y instanceof R){j(s,!1);continue}throw y}j(s,g)}}catch(p){f=p}try{z(o.claimPath,o.stats)}catch(p){!S(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function Ot(e){try{z(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function Uo(e,t){let n=To(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 Xn(e){let t=k.dirname(e),n=k.basename(e);for(let r of u.default.readdirSync(t)){let i=Uo(r,n);if(i===null||Qn(i))continue;let o=k.join(t,r),s=null;try{try{s=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(s),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!Ae(c,l))continue;try{Ee(c,"credential-store orphan")}catch{continue}z(o,c)}catch(c){if(!S(c,"ENOENT"))throw c}finally{s!==null&&u.default.closeSync(s)}}}function Le(e,t,n){if(!qe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw W();if(!Yn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw W()}});let s=Jn(e);try{return Xn(e),n({read:()=>qn(e),remove:()=>jn(e),write:()=>{throw W()}})}finally{Ot(s)}}if(!t.createParent){let o=!1;try{o=Zn(e)}catch{throw W()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw W()}})}throw W()}if(!Yn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Jn(e);try{return Xn(e),n({read:()=>qn(e),remove:()=>jn(e),write:o=>Ro(e,o)})}finally{Ot(i)}}var Nt="allscale-cli";function Bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rr(e){return Bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function X(e){return new a("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function vt(){return new a("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function je(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var J,Pt=!1;function $o(){return Nn()?"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(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function Mo(){if(J!==void 0)return J;if($o())return Pt=!1,J=null,J;try{J=require("keytar"),Pt=!1}catch(e){Pt=!Fo(e),J=null}return J}function ir(){let e=qe()?"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 xt(e){try{return await e()}catch{throw ir()}}var Dt=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await xt(()=>this.keytar.getPassword(Nt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw X("OS keychain")}if(!rr(r))throw X("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await xt(()=>this.keytar.setPassword(Nt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await xt(()=>this.keytar.deletePassword(Nt,t))}},Go="credentials.json",Ut=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??nr.join(It(),Go)}read(t){let n;try{n=t.read()}catch(i){throw Ye(i)?vt():X("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw X("plaintext file")}if(!Bt(r)||!Bt(r.profiles))throw X("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ye(r)?vt():je()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!rr(r))throw X("plaintext file");return r}}async get(t){try{return Le(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:X("plaintext file")}}async set(t,n){try{Le(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof a?r:je()}}async delete(t){try{Le(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof a?n:je()}}async clearProfile(t){try{return Le(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof a?n:Ye(n)?vt():je()}}};function or(e){if(e.insecureStorage)return Vn(),new Ut(e.insecureFilePath);let t=Mo();if(t)return new Dt(t);throw ir()}var $t=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 We(){return new $t}var ze="allscale_access_token",Ft="allscale_refresh_token";function sr(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 Mt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Gt(e,t){return e.find(n=>n.name===t)?.value??null}var ar=T(require("crypto")),lr=T(require("fs")),cr=T(require("path"));var Ko="key-id",Ho="x-allscale-cli-version",Kt="cli-1",Yo="aScaLe_cli_obf_v1",qo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function jo(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 Wo=jo(qo,Yo),ur=`Bearer ${Wo}`;function dr(e,t){let n=lt(e);if(n!==null)return t.find(r=>lt(r.base)===n)}function zo(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=ge();if(t.length>0){let r=dr(e,t);if(r)return r.key;if(H(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:H(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function Jo(e){{let r="cli-1".trim();if(r.length>0)return r}let t=ge();if(t.length>0){let r=e!==void 0?dr(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&H(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():Kt}if(!H(t[0].base))return Kt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():Kt}function Xo(){return"1.0.1"}function Vo(){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 Ht(e,t){let n=zo(t);if(!n)throw Vo();let r=Jo(t),i=Math.floor(Date.now()/1e3).toString(),o=ar.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Ho]:Xo()};return r.length>0&&(s[Ko]=r),s}function fr(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Zo(e,t={}){let n;try{n=Bn(Ue())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",gn(e)+(t.messageSuffix??""),{profile:e})}function pr(e){if(e.profileExplicit){let t=Zo(e.profile);if(t)return t}return new a("auth.no_token",mn(e.profile))}var Qo=500,es=8,mr=100;function Yt(e,t=0){if(t>es)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,mr),r=n.map(i=>Yt(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);for(let[r,i]of Object.entries(e).slice(0,mr))n[r]=ve(r)?"<redacted>":Yt(i,t+1);return n}return e}function ts(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 gr(e,t=Qo){let n=ts(e),r=n===void 0?Ne(e):JSON.stringify(Yt(n));return Pe(r,t)}var qt=256*1024,Je=class extends a{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"}},Xe=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 jt(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 Je(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,m)=>{l=setTimeout(()=>{m(new Xe(e.status,d))},d),l.unref?.()});try{for(;;){let p=o.read(),{done:m,value:g}=f?await Promise.race([p,f]):await p;if(m)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new Je(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Xe&&o.cancel(p).catch(()=>{}),p}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var ns="X-AllScale-Api-Key",rs=3e4,is=32*1024*1024,os=4*1024*1024;function ss(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 as(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 ls(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 br(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}ls(e.status,e.url)}}var hr="--dns-result-order=ipv4first";async function Ve(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),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(s);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new 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=${hr} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${hr}`})}var V=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??rs;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),Fe(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=ss(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.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{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();$n(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Sr(t.path),l=s==="required"?!0:s==="none"?!1:ds(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw pr({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=fr(t.body),f=!!o||!!r?.access_token;l&&f&&!this.opts.override&&$e(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:l&&f,bodyForSig:d,tokens:r,extra:t.headers}),m=Date.now();_({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let g;try{g=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(h){throw new a("transport.network",`Network error contacting ${M(i)}: ${h instanceof Error?h.message:String(h)}`)}if(_({type:"response",status:g.status,durationMs:Date.now()-m}),l&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let h=await as(this.refreshSingleFlight(),t.signal),b=this.buildHeaders({attachAuth:l&&!!h.access_token,bodyForSig:d,tokens:h,extra:t.headers}),P=Date.now();_({type:"request",method:t.method??"GET",url:i});let L;try{L=await fetch(i,{method:t.method??"GET",headers:b,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(K){throw new a("transport.network",`Network error contacting ${M(i)} on refresh-retry: ${K instanceof Error?K.message:String(K)}`)}return _({type:"response",status:L.status,durationMs:Date.now()-P}),_r(L,{withMetadata:n.withMetadata,authBearing:l,responseKind:wr(t)})}return _r(g,{withMetadata:n.withMetadata,authBearing:l&&f,agentKeyAuth:l&&!!o,responseKind:wr(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ht(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=ur;let i=t.tokens;if(i?.agent_key)return r[ns]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=Mt([{name:ze,value:o}]))}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($e(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 ${Re()}.`);if($e(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=Mt([{name:ze,value:t.access_token},{name:Ft,value:t.refresh_token}]),i=Ht("",this.opts.apiBase);_({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!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(g){throw _({type:"refresh",ok:!1}),new a("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${M(n)} timed out after 10s with no response.`:`Network error during token refresh against ${M(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}_({type:"response",status:l.status,durationMs:0});try{await br(l)}catch(g){throw _({type:"refresh",ok:!1}),g}if(l.status!==200){let g=null;try{await Ve(l);let y=await hs(l);await Ve(l,y),Er(l.status,y),l.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(y){throw _({type:"refresh",ok:!1}),y}if(g)return _({type:"refresh",ok:!0,adopted:!0}),g;throw _({type:"refresh",ok:!1}),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Re()}.`,{status:l.status})}let d=sr(l.headers),f=Gt(d,ze),p=Gt(d,Ft);if(!f||!p)throw _({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,m),_({type:"refresh",ok:!0}),m}},cs=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Sr(e){let t=e.split(/[?#]/,1)[0];return cs.some(n=>t===n||t.startsWith(`${n}/`))}var us=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Wt(e){let t=e.split(/[?#]/,1)[0];return us.some(n=>n.test(t))}function ds(e){return Sr(e)||Wt(e)}async function _r(e,t={}){await br(e);let n=e.status>=200&&e.status<300;n||await Ve(e);let r=t.responseKind??"mutation",o=await jt(e,n?r==="query"?is:os:qt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ve(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,f)=>{l[f]=d}),{status:e.status,headers:l,body:s}}return s}let c=_s(s)??`HTTP ${e.status}`;if(Er(e.status,s),ms(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 l=t.authBearing?"auth.token_expired":"input.invalid";throw new a(l,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 wr(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var fs=2014,yr=2004;function kr(e,t){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let r=n.code;return r===t||r===String(t)}function ps(e){return kr(e,fs)}function ms(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&kr(t,yr))throw new a("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Re()} 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:yr})}var gs=1e4;async function hs(e,t=gs){if(e.status>=200&&e.status<300)return"";try{return await jt(e,qt,{timeoutMs:t})}catch{return""}}function Er(e,t){if(!(e>=200&&e<300)&&ps(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"?gr(t):t})}function _s(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 ws=/^\/(api\/)?(v1\/)?public\//;function Ze(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&ws.test(n),i=n&&Wt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new V({apiBase:e.apiBase,tokenStore:or({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new V({apiBase:e.apiBase,tokenStore:We(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var x={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},ys=new Set(Object.values(x));async function Ar(e,t,n){let{body:r,headers:i}=await ks(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init");return{...r,server_now_ms:bs(i)}}function bs(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 zt(e,t){return Ss(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function Ss(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Lr(o,r);if(s!==null)throw s}throw o}return Tr(i,r)}async function ks(e,t,n,r){let i;try{i=await e.requestWithMetadata({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Lr(o,r);if(s!==null)throw s}throw o}return{body:Tr(i.body,r),headers:i.headers??{}}}function Lr(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||!ys.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return Ir(i,o,t)}function Tr(e,t){if(e.code!==void 0&&e.code!==0)throw Ir(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 Ir(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case x.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case x.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 x.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case x.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case x.CLI_OP_INVALID_PAYLOAD:case x.CLI_OP_SELF_TRANSFER:case x.CLI_OP_INSUFFICIENT_BALANCE:case x.CLI_OP_WALLET_STATE_CONFLICT:return new a("input.invalid",r,{broker_code:e});case x.CLI_OP_PREFLIGHT_UNAVAILABLE:return new a("backend.internal",r,{broker_code:e});case x.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 Cr(e){let t=e?.trim();return t?t!=="0"&&t.toLowerCase()!=="false":!1}var Es=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function As(e,t,n,r){if(Cr(e.CI)||Es.some(s=>Cr(e[s])))return"ci";let o=t!=="darwin"&&t!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":n===!0||r===!0?null:"no-tty"}function Ls(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 Nr(e,t={}){if(!st(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${C(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.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 o=i?null:As(n,r,t._stdinIsTTY??process.stdin.isTTY,t._stderrIsTTY??process.stderr.isTTY);if(o)throw new a("wallet.requires_browser_auth",Ls(o));if(r==="linux"&&!n.DISPLAY&&!i)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=Ts(r,i);await Is(s.command,[...s.args,e])}function Ts(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 Is(e,t){return new Promise((n,r)=>{let i;try{i=(0,Rr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(Or(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(Or(e,s)))}),setImmediate(()=>{o||(o=!0,i.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 Cs=9e4,Os=16*1024;function Pr(e){let t=e.timeoutMs??Cs;return new Promise((n,r)=>{let i=!1,o=!1,s=null,c,l,d=new Promise((p,m)=>{c=p,l=m}),f=vr.createServer((p,m)=>{Rs(p,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:g=>{s&&clearTimeout(s),c(g),f.close()}})});f.on("error",p=>{let m=new a("transport.network",`Loopback listener error: ${p.message}`);o?l(m):r(m),s&&clearTimeout(s)}),f.listen({host:"127.0.0.1",port:e.port??0},()=>{let p=f.address();if(!p||typeof p=="string"){f.close(),r(new a("transport.network","Failed to read loopback listener port"));return}let m=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,g=m!=null?Math.max(1,Math.min(t,m)):t,y=m!=null&&m<=t;s=setTimeout(()=>{l(new a("wallet.bridge_timeout",`Bridge timed out after ${g}ms waiting for browser callback.`,{bridge_deadline:y?"op_ttl":"duration"})),f.close()},g),s.unref?.(),o=!0,n({port:p.port,awaitResult:d,close:()=>{s&&clearTimeout(s),f.close()}})})})}function Rs(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=[],s=!1;e.on("data",c=>{if(!s){if(i+=c.length,i>Os){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(s)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,f=typeof d.state=="string"?d.state:"",p=typeof d.result_token=="string"?d.result_token:void 0,m=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(!Ns(f,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(p===void 0&&m===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:p,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function Ns(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=()=>{},i=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},c=()=>{s(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,s(),e.off("data",d),e.off("end",f),e.off("error",p),e.pause()},d=g=>{if(n)return;s(),t+=g.toString();let y=t.trim(),h=t.length-t.trimStart().length,b=t.indexOf(`
17
+ `,h),P=b===-1?"":t.slice(h,b).trim();if(y.startsWith("{")){if(Jt(y)){l(),r(y);return}if(b===-1){c();return}if(!Jt(P)&&!P.endsWith("}")){let L=t.slice(b+1),K=L.split(`
18
+ `).find(F=>F.trim()!=="")??"";if(P==="{"&&(!/\S/.test(L)||/^\s*"[^"]*"\s*:/.test(L)||/^\s*"[^"]*$/.test(K))){c();return}}l(),r(Jt(P)?P:t.slice(h).trim());return}if(b!==-1){l(),r(P);return}else!y&&t.includes(`
19
+ `)&&(l(),r(""))},f=()=>{if(n)return;let g=t.trim();if(!g){l();return}l(),r(g)},p=()=>{n||l()},m=new Promise(g=>{r=g});return e.resume(),e.on("data",d),e.on("end",f),e.on("error",p),{promise:m,cancel:()=>{n||l()}}}function vs(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 Dr(e){let t=Ze(e.ctx),n=e.browserBase??e.ctx.apiBase,r=$s(n),i=e._openBrowser??Nr,o=e._startListener??Pr,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,Br.randomBytes)(32).toString("hex"),d=Date.now(),f=await Ar(t,e.op,e.payload);_({type:"bridge_init",op_id:f.op_id,expires_at:f.expires_at});let m=f.server_now_ms!=null?f.expires_at*1e3-f.server_now_ms-1e3:null,g=2147483647,h=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,b=9e5,P=6e4,L=m!=null&&Number.isFinite(m)&&m>0?m:null,K=Math.max(0,Math.round((L??0)/1e3)),N=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,F=N!=null&&N<=g?N:null,B,ue,nn=!1,rn=!1,on=!1;if(L!=null){let E=Math.min(L,g),D=L>g;F!=null&&F<E?(B=F,ue="caller"):(B=E,ue=D?"timer_ceiling":"op_ttl",nn=!D&&N!=null&&N>E)}else{let E=f.expires_at*1e3-d,D=Number.isFinite(E)?Math.min(Math.max(E,P),b):b,Z=F??h;Z>D?(B=D,ue="op_ttl_unverified",rn=N!=null&&N>D):(B=Z,ue=F!=null?"caller":"unknown_ttl"),on=N!=null&&F==null}let pi=ue==="op_ttl",mi=L!=null?`~${K}s`:"unknown";A.stderr.write(`Bridge op registered (op_id=${f.op_id}, op TTL ${mi}, waiting up to ${Math.round(B/1e3)}s for confirmation).
20
+ `),nn&&A.stderr.write(`Note: the confirmation wait of ${N}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
+ `),rn&&A.stderr.write(`Note: the confirmation wait of ${N}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
+ `),on&&A.stderr.write(`Note: the requested confirmation wait of ${N}ms is outside the usable range (1ms-${g}ms), so it was ignored and the wait fell back to ~${Math.round(B/1e3)}s.
23
+ `);let rt=await o({state:l,...L!=null?{deadlineAtMs:d+L}:{},expectedOrigin:r,timeoutMs:B}),gi=rt.awaitResult.then(E=>({source:"loopback",...E}),E=>({source:"listener_error",error:E})),hi=Date.now(),sn=setInterval(()=>{let E=Math.floor((Date.now()-hi)/1e3);A.stderr.write(`Still waiting for confirmation\u2026 (${E}s elapsed)
24
+ `)},15e3);sn.unref?.();let Ie,it=e.signal===void 0?void 0:vs(e.signal);try{let E=Ds(n,{op_id:f.op_id,port:rt.port,state:l});_({type:"bridge_browser_open",url:E});let D=s==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(A.stderr.write(c?e.autoOpen===!1?`
22
25
  Confirm this in your browser. Open the URL below on any device where
23
26
  you're signed in to AllScale (local auto-open is disabled):
24
27
 
25
- ${R}
28
+ ${E}
26
29
 
27
30
  `:`
28
31
  Confirm this in your browser. The URL is below \u2014 it auto-opens if a
29
32
  browser is available on this machine; otherwise open it on any device
30
33
  where you're signed in to AllScale:
31
34
 
32
- ${R}
35
+ ${E}
33
36
 
34
37
  `:`
35
38
  Confirm this in a browser on this machine. The callback must reach the
36
39
  local listener; non-interactive stdin cannot accept a result pasted
37
40
  back from another device:
38
41
 
39
- ${R}
42
+ ${E}
40
43
 
41
- `),e.autoOpen===!1)E.stderr.write(`(browser auto-open skipped \u2014 use the link above)
42
- `);else try{await i(R),E.stderr.write(`(opened in your default browser)
43
- `)}catch{E.stderr.write(`(no local browser to open \u2014 use the link above)
44
- `)}c?E.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 i(E),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
45
48
  reach this machine (e.g. you opened the link elsewhere over SSH), copy
46
- the ${ge} the page shows, paste it here, and press Enter:
49
+ the ${D} the page shows, paste it here, and press Enter:
47
50
 
48
- `):E.stderr.write(`stdin is non-interactive; waiting for the browser callback.
51
+ `):A.stderr.write(`stdin is non-interactive; waiting for the browser callback.
49
52
 
50
- `),c&&(O=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:ur());let He=[g];O!==void 0&&He.push(O.promise.then(Kr=>({source:"paste",line:Kr}))),P!==void 0&&He.push(P.promise);let j=await Promise.race(He);if(j.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(j.source==="listener_error")throw jo(j.error);if(j.source==="loopback")return E.stderr.write(`Browser returned result; processing\u2026
51
- `),await Wo(t,s,j);let he=j.line.trim();if(!he)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"&&he.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(he))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 E.stderr.write(`Received pasted ${ge}; processing\u2026
52
- `),await zo(t,s,he)}finally{clearInterval(I),P?.cleanup(),O?.cancel(),S.close()}}function jo(e){return e instanceof a&&(e.code==="wallet.bridge_timeout"||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 Wo(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.");_({type:"bridge_result_received",source:"loopback"});let r=await Pt(e,n.result_token);return _({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),E.stderr.write(`Verified by broker.
53
- `),{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 _({type:"bridge_result_received",source:"loopback"}),_({type:"bridge_data_received",source:"loopback"}),E.stderr.write(`Result received from browser.
54
- `),{result_data:n.result_data}}async function zo(e,t,n){if(t==="ack"){_({type:"bridge_result_received",source:"paste"});let i=await Pt(e,n);return _({type:"bridge_verified",op_id:i.op_id,source:"paste"}),E.stderr.write(`Verified by broker.
55
- `),{ack:i}}let r;try{r=Vo(n)}catch(i){throw i instanceof a&&i.code==="input.invalid"?new a("wallet.bridge_invalid_response",i.message):i}return _({type:"bridge_result_received",source:"paste"}),_({type:"bridge_data_received",source:"paste"}),E.stderr.write(`Result accepted.
56
- `),{result_data:r}}function Jo(e,t){let n=new URL("/cli",fr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}var Xo=/^0x[0-9a-fA-F]{64}$/;function Vo(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(Xo.test(e))return{tx_hash:e};throw new a("input.invalid",`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function Zo(e){return fr(e).origin}function fr(e){if(!W(e))throw new a("input.invalid",`Refusing browser base ${L(e)}: bridge state and operation identifiers may only be sent to an exact trusted AllScale origin (${ye.join(", ")}) or an explicit loopback development origin. It must not contain embedded URL userinfo.`);return new URL(e)}var mr=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:all"]),gr=new Set(["payroll","admin:user","admin:org","admin:audit"]);function hr(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function _r(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Qo={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",create_store:"store:all",auto_payout_session_status:"claim_link:read_only",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},es={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},ts=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,ns=/is not available to API keys/i,yr=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function wr(e){if(typeof e!="string")return;let t=ts.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=ns.test(n),o=!i&&yr.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(l=>l.trim()).filter(l=>yr.test(l));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function kr(e){let t=es[e];if(t!==void 0)return{ungrantableReason:t};let n=Qo[e];if(n!==void 0)return{scope:n}}function br(e){if(gr.has(hr(e)))return{kind:"ungrantable"};for(let t of mr)if(_r(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Sr(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Er(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}function Lr(e,t){let n=Tr(e),r={graphql_error_count:rs(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw is(e,t,r);if(n===3400)throw new a("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Sr(e))throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Er(e)}`,r);if(n!==void 0)throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function Tr(e){let t=Ar(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=Ar(r.code);if(i!==void 0)return i}}function Ar(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function rs(e){return Array.isArray(e)?e.length:e==null?0:1}function is(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=wr(os(e,Tr(e))),s=kr(t.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,f=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||s?.ungrantableReason!==void 0){let p=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("auth.permission_denied",`${r} is not available to agent keys${p}. Re-authorizing will NOT help \u2014 no scope grants it.${f} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let p=br(l),m=p.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:p.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${ae()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${ae()}\` with \`--scopes ${l}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${f} ${m}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...p.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${f} Re-run \`allscale device-login\` (or \`${ae()}\`) and grant the required scope.`,i)}function os(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var ss="/api/secure/graphql";async function Cr(e,t){t.showDoc&&process.stderr.write(`${t.document}
57
- `);let r=await $e(e).request({method:"POST",path:ss,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});Lr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var as=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,ls=/^0(?:\.0+)?$/,Bt=128;function Ir(e,t,n={}){if(t.length>Bt)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Bt} characters.`);let r=t.trim();if(!as.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 Or(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("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}function re(e,t){let n=l=>{if(typeof l!="string"||l.length>Bt||!/^\d+(?:\.\d+)?$/.test(l))return null;let[d,f=""]=l.split(".");return{whole:d.replace(/^0+(?=\d)/,""),fraction:f.replace(/0+$/,"")}},r=n(e),i=n(t);if(!r||!i)return null;if(r.whole.length!==i.whole.length)return r.whole.length<i.whole.length?-1:1;if(r.whole!==i.whole)return r.whole<i.whole?-1:1;let o=Math.max(r.fraction.length,i.fraction.length),s=r.fraction.padEnd(o,"0"),c=i.fraction.padEnd(o,"0");return s===c?0:s<c?-1:1}function me(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new a("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}var cs=`query claim_link_funding_by_idempotency_key($idempotency_key: String!) {
53
+ `),c&&(Ie=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:xr());let Z=[gi];Ie!==void 0&&Z.push(Ie.promise.then(_i=>({source:"paste",line:_i}))),it!==void 0&&Z.push(it.promise);let Q=await Promise.race(Z);if(Q.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(Q.source==="listener_error")throw Ps(Q.error,pi);if(Q.source==="loopback")return A.stderr.write(`Browser returned result; processing\u2026
54
+ `),await xs(t,s,Q);let Ce=Q.line.trim();if(!Ce)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"&&Ce.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(Ce))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 Bs(t,s,Ce,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(sn),it?.cleanup(),Ie?.cancel(),rt.close()}}function Ps(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 xs(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.");_({type:"bridge_result_received",source:"loopback"});let r=await zt(e,n.result_token);return _({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 _({type:"bridge_result_received",source:"loopback"}),_({type:"bridge_data_received",source:"loopback"}),A.stderr.write(`Result received from browser.
57
+ `),{result_data:n.result_data}}async function Bs(e,t,n,r){if(t==="ack"){_({type:"bridge_result_received",source:"paste"});let o=await zt(e,n);return _({type:"bridge_verified",op_id:o.op_id,source:"paste"}),A.stderr.write(`Verified by broker.
58
+ `),{ack:o}}let i;try{i=Us(n,{acceptBareTxHashPaste:r})}catch(o){throw o instanceof a&&o.code==="input.invalid"?new a("wallet.bridge_invalid_response",o.message):o}return _({type:"bridge_result_received",source:"paste"}),_({type:"bridge_data_received",source:"paste"}),A.stderr.write(`Result accepted.
59
+ `),{result_data:i}}function Ds(e,t){let n=new URL("/cli",Ur(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 Us(e,t={}){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(t.acceptBareTxHashPaste!==!1&&le.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 $s(e){return Ur(e).origin}function Ur(e){if(!ee(e))throw new a("input.invalid",`Refusing browser base ${C(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${fe}`);return new URL(e)}var Fs=new Set;var Ms=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"]),Xt=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"]),Vt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Qe(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function $r(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Gs=new Set(["cli_op:all"]),Ks=new Set([...Gs].map(Qe));var Kc=new Set([...[...Ms,...Xt,...Fs].map(Qe),...Vt,...Ks]);var Hs={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},Ys={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},qs=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,js=/is not available to API keys/i,Fr=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Mr(e){if(typeof e!="string")return;let t=qs.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=js.test(n),o=!i&&Fr.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(l=>l.trim()).filter(l=>Fr.test(l));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function Gr(e){let t=Ys[e];if(t!==void 0)return{ungrantableReason:t};let n=Hs[e];if(n!==void 0)return{scope:n}}function Kr(e){if(Vt.has(Qe(e)))return{kind:"ungrantable"};for(let t of Xt)if($r(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Hr(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Yr(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}var Ws=new Set([3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5100,5150,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function jr(e,t){let n=Wr(e),r={graphql_error_count:zs(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw Js(e,t,r);if(n===429)throw new a("rate_limited",`GraphQL ${t.kind} '${t.operationName}' was rate limited. Retry after a backoff.`,r);if(n===1002)throw new a("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${t.kind} '${t.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,r);if(n!==void 0&&Ws.has(n))throw new a("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Hr(e))throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Yr(e)}`,r);if(n!==void 0)throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function Wr(e){let t=qr(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=qr(r.code);if(i!==void 0)return i}}function qr(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function zs(e){return Array.isArray(e)?e.length:e==null?0:1}function Js(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=Mr(Xs(e,Wr(e))),s=Gr(t.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,f=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||s?.ungrantableReason!==void 0){let p=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("auth.permission_denied",`${r} is not available to agent keys${p}. Re-authorizing will NOT help \u2014 no scope grants it.${f} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let p=Kr(l),m=p.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:p.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${he()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${he()}\` with \`--scopes ${l}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${f} ${m}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...p.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${f} Re-run \`allscale device-login\` (or \`${he()}\`) and grant the required scope.`,i)}function Xs(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var Vs="/api/secure/graphql";async function zr(e,t){t.showDoc&&process.stderr.write(`${t.document}
60
+ `);let r=await Ze(e).request({method:"POST",path:Vs,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});jr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var Zs=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Qs=/^0(?:\.0+)?$/,Zt=128;function Jr(e,t,n={}){if(t.length>Zt)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Zt} characters.`);let r=t.trim();if(!Zs.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&Qs.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Xr(e,t,n,r="for the selected token and chain"){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places ${r}; got '${t}'. The CLI will not round a funds amount.`);return t}function ce(e,t){let n=l=>{if(typeof l!="string"||l.length>Zt||!/^\d+(?:\.\d+)?$/.test(l))return null;let[d,f=""]=l.split(".");return{whole:d.replace(/^0+(?=\d)/,""),fraction:f.replace(/0+$/,"")}},r=n(e),i=n(t);if(!r||!i)return null;if(r.whole.length!==i.whole.length)return r.whole.length<i.whole.length?-1:1;if(r.whole!==i.whole)return r.whole<i.whole?-1:1;let o=Math.max(r.fraction.length,i.fraction.length),s=r.fraction.padEnd(o,"0"),c=i.fraction.padEnd(o,"0");return s===c?0:s<c?-1:1}function Te(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new a("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}var ea=`query claim_link_funding_by_idempotency_key($idempotency_key: String!) {
58
61
  claim_link_funding_by_idempotency_key(idempotency_key: $idempotency_key) {
59
62
  claim_link {
60
63
  id
@@ -71,5 +74,5 @@ the ${ge} the page shows, paste it here, and press Enter:
71
74
  claim_url
72
75
  claim_window_seconds
73
76
  }
74
- }`,Rr={1:"PENDING_DEPOSIT",2:"LINK_SENT",3:"CLAIMING",4:"CLAIMED",5:"EXPIRED",6:"CANCELLED"},us=new Set(Object.values(Rr)),ds=new Set(["EXPIRED","CANCELLED"]),ps=new Set(["outcome","phase","claim_link_id","funding_tx_hash"]),fs=new Set(["completed","cancelled","ambiguous"]),ms=new Set(["pre_create","creating","created","signed","broadcast","settling","funded"]),gs=new Set(["creating","created","signed","broadcast","settling"]),hs=new Set(["created","signed","broadcast","settling","funded"]),Nr=/^[A-Za-z0-9_-]{1,128}$/,_s=/^[A-Za-z0-9_-]{16,256}$/,ys=2048,ws=16,ks=/^\/(?:claim\/[A-Za-z0-9_-]{16,256}|s\/[A-Za-z0-9_-]{1,128})$/,bs=2e3,Ss=500;function Ut(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Es(e,t){if(typeof e!="string"||!Nr.test(e))throw new a("backend.internal",`${t} returned a malformed Claim Link id.`);return e}function As(e,t){if(typeof e!="string"||!_s.test(e))throw new a("backend.internal",`${t} returned a malformed claim token.`);return e}function Ls(e){if(typeof e=="number"&&Number.isInteger(e)){let t=Rr[e];if(t!==void 0)return t}if(typeof e=="string"){let t=e.trim().toUpperCase().replace(/-/g,"_");if(us.has(t))return t}throw new a("backend.internal","Claim Link funding lookup returned an unknown lifecycle status.")}function Ts(e,t){if(e==null)return null;if(typeof e!="string"||!Ie.test(e))throw new a("backend.internal",`${t} returned a malformed funding transaction hash.`);return e}function Cs(e,t){if(e==null)return null;if(typeof e!="string"||e.length===0||e.length>ys||e.trim()!==e)throw new a("backend.internal",`${t} returned a malformed Claim Link URL.`);return e}function Is(e){if(typeof e!="string"||e.trim()!==e||re(e,e)===null)throw new a("backend.internal","Claim Link funding lookup returned a malformed amount.");return e}function Os(e){if(typeof e!="string"||e.length===0||e.length>ws||!/^[A-Za-z0-9]+$/.test(e))throw new a("backend.internal","Claim Link funding lookup returned a malformed token symbol.");return e}function Rs(e){if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed chain.");return e}function Dt(e,t,n){if(e===null)return null;if(typeof e!="string"||e.length>n)throw new a("backend.internal",`Claim Link funding lookup returned a malformed ${t}.`);return e}function Ns(e){if(e===null)return null;if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed claim window.");return e}function xs(e,t,n){let r;try{r=new URL(e)}catch{throw new a("backend.internal",`${n} returned a malformed Claim Link URL.`)}let i=new URL(t).origin;if(r.origin!==i||r.username.length>0||r.password.length>0||r.search.length>0||r.hash.length>0||!ks.test(r.pathname))throw new a("backend.internal",`${n} returned a Claim Link URL outside the configured API origin or supported claim routes.`);return r.toString()}function Ps(e){if(e==null)return null;if(!Ut(e)||!Ut(e.claim_link))throw new a("backend.internal","Claim Link funding lookup returned a malformed result.");return{claimLinkId:Es(e.claim_link.id,"Claim Link funding lookup"),status:Ls(e.claim_link.status),amount:Is(e.claim_link.amount),tokenSymbol:Os(e.claim_link.token_symbol),chain:Rs(e.claim_link.chain),receiverEmail:Dt(e.claim_link.receiver_email,"receiver email",254),senderDisplayName:Dt(e.claim_link.sender_display_name,"sender display name",100),senderMessage:Dt(e.claim_link.sender_message,"sender message",200),claimWindowSeconds:Ns(e.claim_window_seconds),claimToken:As(e.claim_token,"Claim Link funding lookup"),claimUrl:Cs(e.claim_url,"Claim Link funding lookup"),fundingTxHash:Ts(e.claim_link.funded_tx_hash,"Claim Link funding lookup")}}function vs(e,t){let n=[];re(e.amount,t.amount)!==0&&n.push("amount"),e.tokenSymbol.toUpperCase()!==En(t.stable_coin).toUpperCase()&&n.push("stable_coin"),e.chain!==t.chain&&n.push("chain");let r=i=>{let o=i?.trim()??"";return o.length===0?null:o};return r(e.receiverEmail)?.toLowerCase()!==r(t.receiver_email)?.toLowerCase()&&n.push("receiver_email"),r(e.senderDisplayName)!==r(t.sender_display_name)&&n.push("sender_display_name"),r(e.senderMessage)!==r(t.sender_message)&&n.push("sender_message"),e.claimWindowSeconds!==t.claim_window_seconds&&n.push("claim_window_seconds"),n}function Fe(e,t,n){let r=vs(e,t);if(r.length===0)return;let i={idempotency_key:t.idempotency_key,claim_link_id:e.claimLinkId,status:e.status,intent_conflict:!0,mismatched_fields:r,retry_with_same_idempotency_key:!1};throw n?new a("claim_link.funding_ambiguous","The authoritative Claim Link bound to this idempotency key does not match the requested intent after browser authorization may have started. Do not retry automatically, fund the returned link, or use a new key; inspect the existing operation manually.",{outcome_ambiguous:!0,...i}):new a("claim_link.intent_conflict","This idempotency key is already bound to different Claim Link terms. The browser was not opened and the existing link was not funded by this command. Re-run with the original terms or choose a new key only for an intentional new link.",i)}async function Bs(e,t){let n=await Cr(e,{kind:"query",operationName:"claim_link_funding_by_idempotency_key",document:cs,variables:{idempotency_key:t}});return Ps(n)}function Ds(e){if(e==null)return null;if(typeof e!="string"||!Nr.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Us(e){if(e==null)return null;if(typeof e!="string"||!Ie.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function $s(e){if(!Ut(e)||Object.keys(e).some(s=>!ps.has(s))||typeof e.outcome!="string"||!fs.has(e.outcome)||typeof e.phase!="string"||!ms.has(e.phase))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");let t=e.outcome,n=e.phase,r=Ds(e.claim_link_id),i=Us(e.funding_tx_hash);if(!(t==="completed"&&n==="funded"&&r!==null||t==="cancelled"&&n==="pre_create"&&r===null&&i===null||t==="ambiguous"&&gs.has(n)&&(!hs.has(n)||r!==null)))throw new a("wallet.bridge_invalid_response","Browser returned an inconsistent Claim Link receipt.");return{outcome:t,phase:n,claimLinkId:r,fundingTxHash:i}}function Me(e,t,n){if(e.status==="PENDING_DEPOSIT")throw new Error("PENDING_DEPOSIT cannot be rendered as a success");if(xr(e))throw $t(n,e,null);let r;try{let i=e.claimUrl??new URL(`/claim/${encodeURIComponent(e.claimToken)}`,t).toString();r=xs(i,t,"Claim Link funding lookup")}catch{throw new a("backend.internal","Claim Link funding is authoritative, but the lookup returned an untrusted or malformed claim URL. Do not create another link or use a new idempotency key; re-run only with exactly the same --idempotency-key after the service recovers.",{funding_authoritative:!0,idempotency_key:n,claim_link_id:e.claimLinkId,funding_tx_hash:e.fundingTxHash,status:e.status,retry_with_same_idempotency_key:!0})}return{claim_link_id:e.claimLinkId,claim_url:r,status:e.status,...e.fundingTxHash===null?{}:{funding_tx_hash:e.fundingTxHash}}}function xr(e){return ds.has(e.status)&&(e.fundingTxHash===null||!Ie.test(e.fundingTxHash))}function Fs(e,t,n){let i=!(t!==null&&xr(t))&&(t===null||n?.claimLinkId===t.claimLinkId)?n:null;return{outcome_ambiguous:!0,idempotency_key:e,claim_link_id:t?.claimLinkId??i?.claimLinkId??null,funding_tx_hash:t===null?i?.fundingTxHash??null:t.fundingTxHash,phase:i?.phase??(t===null?"unknown":"created"),status:t?.status??null,retry_with_same_idempotency_key:!0}}function $t(e,t,n){return new a("claim_link.funding_ambiguous","Claim Link funding is not authoritatively proven complete. Funds may have been signed or broadcast, or a terminal state may lack a validated funding transaction hash. Re-run this command only with exactly the same --idempotency-key so it reconciles the existing operation; do not use a new key or create another link.",Fs(e,t,n))}function Ms(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener("abort",i),n(!0)},e);r.unref?.();let i=()=>{clearTimeout(r),n(!1)};t.addEventListener("abort",i,{once:!0})})}function Gs(e){return new Promise(t=>setTimeout(t,e))}async function Hs(e,t,n){let r=Math.max(1,e._pollIntervalMs??bs);for(;await Ms(r,n)&&!n.aborted;)try{let i=await t(e.ctx,e.intent.idempotency_key);if(i!==null&&i.status!=="PENDING_DEPOSIT")return i}catch{}return null}async function Pr(e){let t=e._fetchFunding??Bs,n=e._runBridge??pr,r=e.intent.idempotency_key,i=await t(e.ctx,r);if(i!==null&&Fe(i,e.intent,!1),i!==null&&i.status!=="PENDING_DEPOSIT")return Me(i,e.ctx.apiBase,r);let o,s=new AbortController,c=!1,l=new AbortController,d=n({ctx:e.ctx,op:"create_claim_link",mode:"data",payload:{...e.intent},timeoutMs:e.timeoutMs,browserBase:e.browserBase,autoOpen:e.autoOpen,signal:s.signal}).then(g=>(c=!0,{kind:"bridge",result:g}),g=>(c=!0,{kind:"bridge_error",error:g})),f=Hs(e,t,l.signal).then(g=>({kind:"funding",record:g}));try{let g=await Promise.race([d,f]);if(g.kind==="funding"){if(g.record===null)throw new Error("Authoritative funding poll stopped unexpectedly.");Fe(g.record,e.intent,!0);let w=Math.max(0,e._bridgeCallbackGraceMs??Ss);return await Promise.race([d.then(()=>!0),Gs(w).then(()=>!1)])||s.abort(),Me(g.record,e.ctx.apiBase,r)}if(l.abort(),g.kind==="bridge_error")throw g.error;o=g.result}catch(g){if(l.abort(),!(g instanceof a)||!An(g.code))throw g;let w=null;try{w=await t(e.ctx,r)}catch{}if(w!==null&&Fe(w,e.intent,!0),w!==null&&w.status!=="PENDING_DEPOSIT")return Me(w,e.ctx.apiBase,r);throw $t(r,w,null)}finally{l.abort(),c||s.abort()}let p=null;try{p=$s(o.result_data)}catch{}let m=null,h=!1;try{m=await t(e.ctx,r),h=!0}catch{}if(m!==null&&Fe(m,e.intent,!0),m!==null&&m.status!=="PENDING_DEPOSIT")return Me(m,e.ctx.apiBase,r);throw p?.outcome==="cancelled"&&p.phase==="pre_create"&&h&&m===null?new a("claim_link.browser_cancelled","Claim Link creation was cancelled in the browser before a link was created.",{idempotency_key:r,claim_link_id:null,phase:"pre_create",status:null,retry_with_same_idempotency_key:!0}):$t(r,m,p)}var vr="0.1",Br="10000",Ks=6,Ys=60n,qs=30n*24n*60n*60n,Dr=336*60*60,Ur="14d",js="between 1m and 30d (inclusive)",Ws=/^(\d+)\s*([dhm])$/i,zs=32,Js=/^[a-zA-Z0-9_'^&+%-]+(?:\.[a-zA-Z0-9_'^&+%-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/i;function $r(e){if(e.length>zs)throw new a("input.invalid","--expires is too long; expected a duration like 14d, 24h, or 90m.");let t=Ws.exec(e.trim());if(!t)throw new a("input.invalid",`--expires must be a duration like 14d, 24h, or 90m (units: d/h/m); got '${e}'.`);let n=BigInt(t[1]),r=t[2].toLowerCase(),o=n*(r==="d"?86400n:r==="h"?3600n:60n);if(o<Ys||o>qs)throw new a("input.invalid",`--expires must be ${js}; got '${e}'.`);return{seconds:Number(o),label:`${n}${r}`}}function Fr(e){let t=Or("--amount",Ir("--amount",e),Ks),n=re(t,vr),r=re(t,Br);if(n===null||r===null)throw new a("input.invalid",`--amount is not a supported decimal value: '${e}'.`);if(n<0)throw new a("input.invalid",`--amount must be at least ${vr}; got '${t}'.`);if(r>0)throw new a("input.invalid",`--amount must not exceed ${Br}; got '${t}'.`);let[i,o]=t.split("."),s=o?.replace(/0+$/,"")??"";return s.length===0?i:`${i}.${s}`}function Mr(e){let t=me("--receiver-email",e,254);if(t===void 0)return null;if(!Js.test(t))throw new a("input.invalid","--receiver-email is not a valid email address.");return t}var Xs=require("crypto");var Gr=128;function Hr(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Gr)throw new a("input.invalid",`--idempotency-key must contain 1-${Gr} characters after trimming.`);return t}var Ge=class e extends ce{static description="Create and fund a fixed-intent Claim Link in one browser authorization ceremony, then confirm the authoritative lifecycle state. Requires claim_link:all for an agent-key session.";static examples=["$ allscale claim-link create --idempotency-key order-1042 --amount 10 --chain base","$ allscale claim-link create --idempotency-key order-1043 --amount 25.50 --stable-coin USDC --chain polygon --expires 7d --message 'Invoice 1043'","$ allscale claim-link create --idempotency-key order-1044 --amount 5 --chain base --receiver-email client@example.com --sender-display-name 'Acme' --no-browser"];static flags={amount:T.Flags.string({helpGroup:"REQUIRED",description:"Exact amount the receiver can claim, as a decimal string. Range 0.1-10000; at most 6 effective decimal places. The CLI never rounds it.",required:!0}),chain:T.Flags.string({helpGroup:"REQUIRED",description:"EVM chain for the Claim Link.",options:[...kn],required:!0}),"idempotency-key":T.Flags.string({helpGroup:"REQUIRED",description:"Required stable key for this logical Claim Link create/fund operation (1-128 characters). Reuse it after an ambiguous result; use a new key only for an intentional second link.",required:!0}),"stable-coin":T.Flags.string({description:"Stablecoin for the Claim Link.",options:[...Le],default:"USDT"}),"receiver-email":T.Flags.string({description:"Optional sender-only receiver label. AllScale does not email the receiver; you still share the resulting link yourself."}),"sender-display-name":T.Flags.string({description:"Optional sender name shown to the receiver. Max 100 characters."}),message:T.Flags.string({description:"Optional purpose/message shown on the Claim Link page. Max 200 characters."}),expires:T.Flags.string({description:"Claim window as a duration using m/h/d (1m-30d). The window starts after funding confirms.",default:Ur}),"bridge-timeout":T.Flags.integer({description:"Shorten the browser confirmation deadline, in milliseconds. By default the CLI waits for the broker op TTL.",min:1e3}),"browser-base":T.Flags.string({description:"Override the trusted base URL of the printed /cli bridge link (defaults to the session API base)."}),"no-browser":T.Flags.boolean({description:"Do not auto-open a local browser. The command still prints the bridge URL and waits for its callback or a pasted receipt.",default:!1}),...ce.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=Hr(t["idempotency-key"]);if(n===void 0)throw new a("input.invalid","--idempotency-key is required for Claim Link reconciliation.");let r=bn(t.chain);if(r===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let i=Sn(t["stable-coin"]);if(i===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);let o=$r(t.expires),s={idempotency_key:n,amount:Fr(t.amount),chain:r,stable_coin:i,receiver_email:Mr(t["receiver-email"]),sender_display_name:me("--sender-display-name",t["sender-display-name"],100)??null,sender_message:me("--message",t.message,200)??null,claim_window_seconds:o.seconds===Dr?null:o.seconds},c=this.resolveContext(t);return Pr({ctx:c,intent:s,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],autoOpen:!t["no-browser"]})}};
77
+ }`,Vr={1:"PENDING_DEPOSIT",2:"LINK_SENT",3:"CLAIMING",4:"CLAIMED",5:"EXPIRED",6:"CANCELLED"},ta=new Set(Object.values(Vr)),na=new Set(["EXPIRED","CANCELLED"]),ra=new Set(["outcome","phase","claim_link_id","funding_tx_hash"]),ia=new Set(["completed","cancelled","ambiguous"]),oa=new Set(["pre_create","creating","created","signed","broadcast","settling","funded"]),sa=new Set(["creating","created","signed","broadcast","settling"]),aa=new Set(["created","signed","broadcast","settling","funded"]),Zr=/^[A-Za-z0-9_-]{1,128}$/,la=/^[A-Za-z0-9_-]{16,256}$/,ca=2048,ua=16,da=/^\/(?:claim\/[A-Za-z0-9_-]{16,256}|s\/[A-Za-z0-9_-]{1,128})$/,fa=2e3,pa=500;function en(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ma(e,t){if(typeof e!="string"||!Zr.test(e))throw new a("backend.internal",`${t} returned a malformed Claim Link id.`);return e}function ga(e,t){if(typeof e!="string"||!la.test(e))throw new a("backend.internal",`${t} returned a malformed claim token.`);return e}function ha(e){if(typeof e=="number"&&Number.isInteger(e)){let t=Vr[e];if(t!==void 0)return t}if(typeof e=="string"){let t=e.trim().toUpperCase().replace(/-/g,"_");if(ta.has(t))return t}throw new a("backend.internal","Claim Link funding lookup returned an unknown lifecycle status.")}function _a(e,t){if(e==null)return null;if(typeof e!="string"||!le.test(e))throw new a("backend.internal",`${t} returned a malformed funding transaction hash.`);return e}function wa(e,t){if(e==null)return null;if(typeof e!="string"||e.length===0||e.length>ca||e.trim()!==e)throw new a("backend.internal",`${t} returned a malformed Claim Link URL.`);return e}function ya(e){if(typeof e!="string"||e.trim()!==e||ce(e,e)===null)throw new a("backend.internal","Claim Link funding lookup returned a malformed amount.");return e}function ba(e){if(typeof e!="string"||e.length===0||e.length>ua||!/^[A-Za-z0-9]+$/.test(e))throw new a("backend.internal","Claim Link funding lookup returned a malformed token symbol.");return e}function Sa(e){if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed chain.");return e}function Qt(e,t,n){if(e===null)return null;if(typeof e!="string"||e.length>n)throw new a("backend.internal",`Claim Link funding lookup returned a malformed ${t}.`);return e}function ka(e){if(e===null)return null;if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed claim window.");return e}function Ea(e,t,n){let r;try{r=new URL(e)}catch{throw new a("backend.internal",`${n} returned a malformed Claim Link URL.`)}let i=new URL(t).origin;if(r.origin!==i||r.username.length>0||r.password.length>0||r.search.length>0||r.hash.length>0||!da.test(r.pathname))throw new a("backend.internal",`${n} returned a Claim Link URL outside the configured API origin or supported claim routes.`);return r.toString()}function Aa(e){if(e==null)return null;if(!en(e)||!en(e.claim_link))throw new a("backend.internal","Claim Link funding lookup returned a malformed result.");return{claimLinkId:ma(e.claim_link.id,"Claim Link funding lookup"),status:ha(e.claim_link.status),amount:ya(e.claim_link.amount),tokenSymbol:ba(e.claim_link.token_symbol),chain:Sa(e.claim_link.chain),receiverEmail:Qt(e.claim_link.receiver_email,"receiver email",254),senderDisplayName:Qt(e.claim_link.sender_display_name,"sender display name",100),senderMessage:Qt(e.claim_link.sender_message,"sender message",200),claimWindowSeconds:ka(e.claim_window_seconds),claimToken:ga(e.claim_token,"Claim Link funding lookup"),claimUrl:wa(e.claim_url,"Claim Link funding lookup"),fundingTxHash:_a(e.claim_link.funded_tx_hash,"Claim Link funding lookup")}}function La(e,t){let n=[];ce(e.amount,t.amount)!==0&&n.push("amount"),e.tokenSymbol.toUpperCase()!==Kn(t.stable_coin).toUpperCase()&&n.push("stable_coin"),e.chain!==t.chain&&n.push("chain");let r=i=>{let o=i?.trim()??"";return o.length===0?null:o};return r(e.receiverEmail)?.toLowerCase()!==r(t.receiver_email)?.toLowerCase()&&n.push("receiver_email"),r(e.senderDisplayName)!==r(t.sender_display_name)&&n.push("sender_display_name"),r(e.senderMessage)!==r(t.sender_message)&&n.push("sender_message"),e.claimWindowSeconds!==t.claim_window_seconds&&n.push("claim_window_seconds"),n}function et(e,t,n){let r=La(e,t);if(r.length===0)return;let i={idempotency_key:t.idempotency_key,claim_link_id:e.claimLinkId,status:e.status,intent_conflict:!0,mismatched_fields:r,retry_with_same_idempotency_key:!1};throw n?new a("claim_link.funding_ambiguous","The authoritative Claim Link bound to this idempotency key does not match the requested intent after browser authorization may have started. Do not retry automatically, fund the returned link, or use a new key; inspect the existing operation manually.",{outcome_ambiguous:!0,...i}):new a("claim_link.intent_conflict","This idempotency key is already bound to different Claim Link terms. The browser was not opened and the existing link was not funded by this command. Re-run with the original terms or choose a new key only for an intentional new link.",i)}async function Ta(e,t){let n=await zr(e,{kind:"query",operationName:"claim_link_funding_by_idempotency_key",document:ea,variables:{idempotency_key:t}});return Aa(n)}function Ia(e){if(e==null)return null;if(typeof e!="string"||!Zr.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Ca(e){if(e==null)return null;if(typeof e!="string"||!le.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Oa(e){if(!en(e)||Object.keys(e).some(s=>!ra.has(s))||typeof e.outcome!="string"||!ia.has(e.outcome)||typeof e.phase!="string"||!oa.has(e.phase))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");let t=e.outcome,n=e.phase,r=Ia(e.claim_link_id),i=Ca(e.funding_tx_hash);if(!(t==="completed"&&n==="funded"&&r!==null||t==="cancelled"&&n==="pre_create"&&r===null&&i===null||t==="ambiguous"&&sa.has(n)&&(!aa.has(n)||r!==null)))throw new a("wallet.bridge_invalid_response","Browser returned an inconsistent Claim Link receipt.");return{outcome:t,phase:n,claimLinkId:r,fundingTxHash:i}}function tt(e,t,n){if(e.status==="PENDING_DEPOSIT")throw new Error("PENDING_DEPOSIT cannot be rendered as a success");if(Qr(e))throw tn(n,e,null);let r;try{let i=e.claimUrl??new URL(`/claim/${encodeURIComponent(e.claimToken)}`,t).toString();r=Ea(i,t,"Claim Link funding lookup")}catch{throw new a("backend.internal","Claim Link funding is authoritative, but the lookup returned an untrusted or malformed claim URL. Do not create another link or use a new idempotency key; re-run only with exactly the same --idempotency-key after the service recovers.",{funding_authoritative:!0,idempotency_key:n,claim_link_id:e.claimLinkId,funding_tx_hash:e.fundingTxHash,status:e.status,retry_with_same_idempotency_key:!0})}return{claim_link_id:e.claimLinkId,claim_url:r,status:e.status,...e.fundingTxHash===null?{}:{funding_tx_hash:e.fundingTxHash}}}function Qr(e){return na.has(e.status)&&(e.fundingTxHash===null||!le.test(e.fundingTxHash))}function Ra(e,t,n){let i=!(t!==null&&Qr(t))&&(t===null||n?.claimLinkId===t.claimLinkId)?n:null;return{outcome_ambiguous:!0,idempotency_key:e,claim_link_id:t?.claimLinkId??i?.claimLinkId??null,funding_tx_hash:t===null?i?.fundingTxHash??null:t.fundingTxHash,phase:i?.phase??(t===null?"unknown":"created"),status:t?.status??null,retry_with_same_idempotency_key:!0}}function tn(e,t,n){return new a("claim_link.funding_ambiguous","Claim Link funding is not authoritatively proven complete. Funds may have been signed or broadcast, or a terminal state may lack a validated funding transaction hash. Re-run this command only with exactly the same --idempotency-key so it reconciles the existing operation; do not use a new key or create another link.",Ra(e,t,n))}function Na(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener("abort",i),n(!0)},e);r.unref?.();let i=()=>{clearTimeout(r),n(!1)};t.addEventListener("abort",i,{once:!0})})}function va(e){return new Promise(t=>setTimeout(t,e))}async function Pa(e,t,n){let r=Math.max(1,e._pollIntervalMs??fa);for(;await Na(r,n)&&!n.aborted;)try{let i=await t(e.ctx,e.intent.idempotency_key);if(i!==null&&i.status!=="PENDING_DEPOSIT")return i}catch{}return null}async function ei(e){let t=e._fetchFunding??Ta,n=e._runBridge??Dr,r=e.intent.idempotency_key,i=await t(e.ctx,r);if(i!==null&&et(i,e.intent,!1),i!==null&&i.status!=="PENDING_DEPOSIT")return tt(i,e.ctx.apiBase,r);let o,s=new AbortController,c=!1,l=new AbortController,d=n({ctx:e.ctx,op:"create_claim_link",mode:"data",payload:{...e.intent},timeoutMs:e.timeoutMs,browserBase:e.browserBase,autoOpen:e.autoOpen,signal:s.signal}).then(h=>(c=!0,{kind:"bridge",result:h}),h=>(c=!0,{kind:"bridge_error",error:h})),f=Pa(e,t,l.signal).then(h=>({kind:"funding",record:h}));try{let h=await Promise.race([d,f]);if(h.kind==="funding"){if(h.record===null)throw new Error("Authoritative funding poll stopped unexpectedly.");et(h.record,e.intent,!0);let b=Math.max(0,e._bridgeCallbackGraceMs??pa);return await Promise.race([d.then(()=>!0),va(b).then(()=>!1)])||s.abort(),tt(h.record,e.ctx.apiBase,r)}if(l.abort(),h.kind==="bridge_error")throw h.error;o=h.result}catch(h){if(l.abort(),!(h instanceof a)||!Hn(h.code))throw h;let b=null;try{b=await t(e.ctx,r)}catch{}if(b!==null&&et(b,e.intent,!0),b!==null&&b.status!=="PENDING_DEPOSIT")return tt(b,e.ctx.apiBase,r);throw tn(r,b,null)}finally{l.abort(),c||s.abort()}let p=null;try{p=Oa(o.result_data)}catch{}let m=null,g=!1;try{m=await t(e.ctx,r),g=!0}catch{}if(m!==null&&et(m,e.intent,!0),m!==null&&m.status!=="PENDING_DEPOSIT")return tt(m,e.ctx.apiBase,r);throw p?.outcome==="cancelled"&&p.phase==="pre_create"&&g&&m===null?new a("claim_link.browser_cancelled","Claim Link creation was cancelled in the browser before a link was created.",{idempotency_key:r,claim_link_id:null,phase:"pre_create",status:null,retry_with_same_idempotency_key:!0}):tn(r,m,p)}var ti="0.1",ni="10000",xa=6,Ba=60n,Da=30n*24n*60n*60n,ri=336*60*60,ii="14d",Ua="between 1m and 30d (inclusive)",$a=/^(\d+)\s*([dhm])$/i,Fa=32,Ma=/^[a-zA-Z0-9_'^&+%-]+(?:\.[a-zA-Z0-9_'^&+%-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/i;function oi(e){if(e.length>Fa)throw new a("input.invalid","--expires is too long; expected a duration like 14d, 24h, or 90m.");let t=$a.exec(e.trim());if(!t)throw new a("input.invalid",`--expires must be a duration like 14d, 24h, or 90m (units: d/h/m); got '${e}'.`);let n=BigInt(t[1]),r=t[2].toLowerCase(),o=n*(r==="d"?86400n:r==="h"?3600n:60n);if(o<Ba||o>Da)throw new a("input.invalid",`--expires must be ${Ua}; got '${e}'.`);return{seconds:Number(o),label:`${n}${r}`}}function si(e){let t=Xr("--amount",Jr("--amount",e),xa),n=ce(t,ti),r=ce(t,ni);if(n===null||r===null)throw new a("input.invalid",`--amount is not a supported decimal value: '${e}'.`);if(n<0)throw new a("input.invalid",`--amount must be at least ${ti}; got '${t}'.`);if(r>0)throw new a("input.invalid",`--amount must not exceed ${ni}; got '${t}'.`);let[i,o]=t.split("."),s=o?.replace(/0+$/,"")??"";return s.length===0?i:`${i}.${s}`}function ai(e){let t=Te("--receiver-email",e,254);if(t===void 0)return null;if(!Ma.test(t))throw new a("input.invalid","--receiver-email is not a valid email address.");return t}var Ga=11,li=[...Fn,...de],Ka=de.length>0,ci=Ka?"EVM chain for the Claim Link. sepolia is a testnet (Ethereum Sepolia); the browser ceremony accepts it only on environments with testnets enabled.":"EVM chain for the Claim Link.";function ui(e){let t=e.toLowerCase();return t==="sepolia"&&de.includes(t)?Ga:Mn(t)}var Ha=require("crypto");var di=128;function fi(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>di)throw new a("input.invalid",`--idempotency-key must contain 1-${di} characters after trimming.`);return t}var nt=class e extends Se{static description="Create and fund a fixed-intent Claim Link in one browser authorization ceremony, then confirm the authoritative lifecycle state. Requires claim_link:all for an agent-key session.";static examples=["$ allscale claim-link create --idempotency-key order-1042 --amount 10 --chain base","$ allscale claim-link create --idempotency-key order-1043 --amount 25.50 --stable-coin USDC --chain polygon --expires 7d --message 'Invoice 1043'","$ allscale claim-link create --idempotency-key order-1044 --amount 5 --chain base --receiver-email client@example.com --sender-display-name 'Acme' --no-browser"];static flags={amount:O.Flags.string({helpGroup:"REQUIRED",description:"Exact amount the receiver can claim, as a decimal string. Range 0.1-10000; at most 6 effective decimal places. The CLI never rounds it.",required:!0}),chain:O.Flags.string({helpGroup:"REQUIRED",description:ci,options:[...li],required:!0}),"idempotency-key":O.Flags.string({helpGroup:"REQUIRED",description:"Required stable key for this logical Claim Link create/fund operation (1-128 characters). Reuse it after an ambiguous result; use a new key only for an intentional second link.",required:!0}),"stable-coin":O.Flags.string({description:"Stablecoin for the Claim Link.",options:[...Me],default:"USDT"}),"receiver-email":O.Flags.string({description:"Optional sender-only receiver label. AllScale does not email the receiver; you still share the resulting link yourself."}),"sender-display-name":O.Flags.string({description:"Optional sender name shown to the receiver. Max 100 characters."}),message:O.Flags.string({description:"Optional purpose/message shown on the Claim Link page. Max 200 characters."}),expires:O.Flags.string({description:"Claim window as a duration using m/h/d (1m-30d). The window starts after funding confirms.",default:ii}),"bridge-timeout":O.Flags.integer({description:"Shorten the browser confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life. It can only shorten the wait \u2014 a value above that 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 this receipt-aware flow waits up to 240s 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":O.Flags.string({description:"Override the trusted base URL of the printed /cli bridge link (defaults to the session API base)."}),"no-browser":O.Flags.boolean({description:"Do not auto-open a local browser. The command still prints the bridge URL and waits for its callback or a pasted receipt.",default:!1}),...Se.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=fi(t["idempotency-key"]);if(n===void 0)throw new a("input.invalid","--idempotency-key is required for Claim Link reconciliation.");let r=ui(t.chain);if(r===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let i=Gn(t["stable-coin"]);if(i===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);let o=oi(t.expires),s={idempotency_key:n,amount:si(t.amount),chain:r,stable_coin:i,receiver_email:ai(t["receiver-email"]),sender_display_name:Te("--sender-display-name",t["sender-display-name"],100)??null,sender_message:Te("--message",t.message,200)??null,claim_window_seconds:o.seconds===ri?null:o.seconds},c=this.resolveContext(t);return ei({ctx:c,intent:s,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],autoOpen:!t["no-browser"]})}};
75
78
  //# sourceMappingURL=create.js.map