@allscale/cli 0.1.0 → 1.0.2

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 +144 -45
  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 +14 -14
  11. package/dist/commands/describe.js +13 -13
  12. package/dist/commands/device-login.js +29 -29
  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 +46 -43
  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 +19 -13
  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 +19 -18
  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 +17 -15
  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 +140 -296
  38. package/package.json +4 -6
  39. package/dist/commands/claim-link/preview.js +0 -18
@@ -1,17 +1,17 @@
1
- "use strict";var zn=Object.create;var ie=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Jn=Object.getOwnPropertyNames;var Vn=Object.getPrototypeOf,Xn=Object.prototype.hasOwnProperty;var Zn=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jn(t))!Xn.call(e,i)&&i!==n&&ie(e,i,{get:()=>t[i],enumerable:!(r=Wn(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?zn(Vn(e)):{},yt(t||!e||!e.__esModule?ie(n,"default",{value:e,enumerable:!0}):n,e)),Qn=e=>yt(ie({},"__esModule",{value:!0}),e);var qi={};Zn(qi,{default:()=>be,requireSuccessfulClaim:()=>qn});module.exports=Qn(qi);var I=require("@oclif/core");var wt="public",Et="https://app.allscale.io";var St=["https://app.allscale.io"];var Te="Override the API base URL (public builds accept only https://app.allscale.io)";var Ie="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function At(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 bt(e){return At(e)!==null}function Oe(e){let t=At(e);return t!==null&&St.includes(t.origin)}function V(){return"".trim()||void 0}function x(){return"public"}function P(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function Re(e){try{return new URL(e).origin}catch{return null}}function X(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return Ce()}function Ce(){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:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.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 kt="`allscale device-login` (or `allscale otp-login` for headless automation)";var Lt="drop `--headless` and use the browser-bridge flow with an agent-key session.",Tt="allscale device-login";var tr="device-login";function Ot(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function xe(){return kt}function Ct(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 `+Lt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${Ot()}\` for headless automation`+"."}function Rt(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 ${tr} --profile ${e}\`.`}var nr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_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},rr=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Pe(e){return(typeof e=="string"?e:String(e??"")).replace(rr,"")}var ir=64;function ve(e,t=new Map,n=0){if(typeof e=="string")return Pe(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ir)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ve(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:ve(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super(Pe(n)),this.code=t,this.details=r&&ve(r),this.name="AllscaleError"}get exitCode(){return nr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function vt(e){if(e instanceof l)return e;if(e instanceof Error){if(ar(e)){let t=cr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var or=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),sr=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function ar(e){if(lr(e))return!0;let t=e.name??"";return or.has(t)?t==="CLIError"?Ne(e,"parse")||It(e.message):!0:It(e.message)}function lr(e){if(!Ne(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Ne(e,"parse")}function It(e){return e?Pe(e).split(`
2
- `).some(t=>sr.some(n=>n.test(t.trim()))):!1}function Ne(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function cr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Nt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
- `)}var g=A(require("fs")),se=A(require("path")),Ft=A(require("crypto"));var ur="...<truncated>",dr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,fr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Me=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Be=String.raw`(?:proxy[_-]?)?authorization`,pr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Be}"|'${Be}'|${Be})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Me}`,"gi"),gr=/\b(https?:\/\/)[^\s/?#]+@/gi,Ue=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)`,hr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ue}"|'${Ue}'|${Ue})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Me}`,"gi"),De=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)`,mr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${De}"|'${De}'|${De})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Me}`,"g");function xt(e){return e.replace(gr,"$1<redacted>@").replace(dr,"<redacted-jwt>").replace(pr,"$1$2$3<redacted>").replace(hr,"$1$2<redacted>").replace(mr,"$1$2<redacted>").replace(fr,"Bearer <redacted>")}function Pt(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 Bt(e,t,n=ur){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function k(e,t=16384){return Bt(Pt(xt(e)),t)}var $e=100,_r=8,yr=8*1024;function oe(){return{remaining:yr}}function Fe(e,t){let n=Math.min(16384,t.remaining),r=Bt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function K(e,t,n=0,r={}){if(n>_r)return Fe("<truncated>",t);if(typeof e=="string"){let i=xt(e);return Fe(r.escapeControls?Pt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,$e),o=i.map(s=>K(s,t,n+1,r));return e.length>i.length&&o.push(Fe(`<${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,$e))i[s]=K(c,t,n+1,r);return o.length>$e&&(i.output_truncated=!0),i}return e}var Ge=require("process");var Ke=!1;function He(e){Ke=e}function Dt(){return Ke}var Ut="1";function Y(e,t){if(Ke){let n={...e};delete n.version;let r=oe(),i={event:n.event,...n},o=K(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Ut,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Ut,event:o.event,output_truncated:!0})),Ge.stderr.write(`${s}
4
- `)}else Ge.stderr.write(t)}var $t="2",q=null,L=null,j=!1;function wr(){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=Ft.randomBytes(4).toString("hex");return se.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Ye=64*1024*1024,Er=null;function Mt(){if(j)return;let e=wr();if(!e)return;q=null;let t=null;try{if((Er??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=se.dirname(e);if(g.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=g.statSync(n),u=c.mode&511;if(!c.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let r=g.constants.O_NOFOLLOW??0;t=g.openSync(e,g.constants.O_APPEND|g.constants.O_CREAT|g.constants.O_WRONLY|(g.constants.O_NONBLOCK??0)|r,384);let i=g.fstatSync(t),o=g.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`);g.fchmodSync(t,384)}catch(n){if(t!==null)try{g.closeSync(t)}catch{}Y({event:"sidecar_disabled",reason:"open_failed",detail:k(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${k(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
- `);return}q=e,L=t,j=!0}var Sr=[/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 Ar(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Sr.some(n=>n.test(t))}function Gt(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=br(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Ar(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function br(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function kr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Gt(e.url)}:e}function Lr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=K(i,oe()),s=JSON.stringify({version:$t,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:$t,timestamp:t,type:r,output_truncated:!0})),s}function E(e){if(!j||!q||L===null)return;let t=kr(e),n=Lr(t);try{if(g.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Ye){j=!1;try{g.closeSync(L)}catch{}L=null,Y({event:"sidecar_disabled",reason:"size_limit",...q===null?{}:{path:k(q)},max_bytes:Ye},`${k(`[allscale] sidecar exceeded ${Ye} bytes; disabling it for the rest of this run. Rotate or remove ${q}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
- `);return}g.appendFileSync(L,`${n}
7
- `)}catch(r){if(j=!1,L!==null){try{g.closeSync(L)}catch{}L=null}try{Y({event:"sidecar_disabled",reason:"write_failed",detail:k(r.message)},`${k(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
- `)}catch{}}}var C=Gt;function Kt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function ae(){if(j=!1,L!==null){try{g.closeSync(L)}catch{}L=null}}function Ht(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Kt()||!t}var Z=V()??Et,W={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function R(e){return bt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Yt(){let e=process.env[W.TOKEN]?.trim();return e&&e.length>0?e:void 0}function qe(){let e=process.env[W.PROFILE]?.trim();return e&&e.length>0?e:void 0}function le(){let e=process.env[W.API_BASE]?.trim();return e&&e.length>0?e:void 0}function qt(){let e=process.env[W.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function jt(){let e=process.env[W.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function zt(){let e=process.env[W.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Wt(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(V()===void 0&&Z!==""&&"".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 ${Z} (production), but a saved profile wins over the default,
1
+ "use strict";var ar=Object.create;var le=Object.defineProperty;var lr=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var fr=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},It=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of cr(t))!dr.call(e,i)&&i!==n&&le(e,i,{get:()=>t[i],enumerable:!(r=lr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?ar(ur(e)):{},It(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e)),pr=e=>It(le({},"__esModule",{value:!0}),e);var vo={};fr(vo,{default:()=>ve,requireSuccessfulClaim:()=>or});module.exports=pr(vo);var I=require("@oclif/core");var Ot="public",Ct="https://app.allscale.io";var vt=["https://app.allscale.io"];var xe="Override the API base URL (public builds accept only https://app.allscale.io)";var Pe="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Rt(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 Nt(e){return Rt(e)!==null}function Be(e){let t=Rt(e);return t!==null&&vt.includes(t.origin)}function V(){return"".trim()||void 0}function C(){return"public"}function x(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function De(e){try{return new URL(e).origin}catch{return null}}function X(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return $e()}function $e(){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:u}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof u=="string"?u.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 hr="device-login",gr=/^[A-Za-z0-9._-]{1,64}$/;function Me(e){return gr.test(e)?e:"<profile>"}function Pt(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Me(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function ce(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Bt(e){let t=Me(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${t}\` (recommended), or use \`${Pt(e)}\` for headless automation.`}function $t(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${hr} --profile ${Me(e)}\`.`}var mr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_invalid":5,"auth.token_expired":5,"auth.device_pairing_timeout":3,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},_r=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 Ge(e){return(typeof e=="string"?e:String(e??"")).replace(_r,"")}var yr=64;function Ue(e,t=new Map,n=0){if(typeof e=="string")return Ge(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=yr)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(Ue(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:Ue(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var l=class extends Error{code;details;constructor(t,n,r){super(Ge(n)),this.code=t,this.details=r&&Ue(r),this.name="AllscaleError"}get exitCode(){return mr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Dt(e){if(e instanceof l)return e;if(e instanceof Error){if(Sr(e)){let t=Ar(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new l("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new l("internal",e.message,{name:e.name})}return new l("internal","Unknown error",{value:String(e)})}var wr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Er=[/^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 Sr(e){if(br(e))return!0;let t=e.name??"";return wr.has(t)?t==="CLIError"?Fe(e,"parse")||xt(e.message):!0:xt(e.message)}function br(e){if(!Fe(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Fe(e,"parse")}function xt(e){return e?Ge(e).split(`
2
+ `).some(t=>Er.some(n=>n.test(t.trim()))):!1}function Fe(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function Ar(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ut(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var h=A(require("fs")),he=A(require("path")),jt=A(require("crypto"));var kr="...<truncated>",Lr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Tr=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,He=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ke=String.raw`(?:proxy[_-]?)?authorization`,Ir=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ke}"|'${Ke}'|${Ke})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${He}`,"gi"),Or=/\b(https?:\/\/)[^\s/?#]+@/gi,Cr=String.raw`(?:[A-Za-z0-9]+[_-])*`,vr=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,Mt=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)`,Ft=Mt(Cr),Rr=Mt(vr),Nr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ft}"|'${Ft}'|${Rr})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${He}`,"gi"),qe=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)`,xr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${qe}"|'${qe}'|${qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${He}`,"g");function ue(e){return e.replace(Or,"$1<redacted>@").replace(Lr,"<redacted-jwt>").replace(Ir,"$1$2$3<redacted>").replace(Nr,"$1$2<redacted>").replace(xr,"$1$2<redacted>").replace(Tr,"Bearer <redacted>")}var Pr=/(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 de(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Pr.test(t)}function Gt(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 fe(e,t,n=kr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",u=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(u+f>t)break;c+=d,u+=f}return c}let i=t-r,o="",s=0;for(let c of e){let u=Buffer.byteLength(c,"utf8");if(s+u>i)break;o+=c,s+=u}return`${o}${n}`}function b(e,t=16384){return fe(Gt(ue(e)),t)}var Ye=100,Br=8,$r=8*1024;function pe(){return{remaining:$r}}function je(e,t){let n=Math.min(16384,t.remaining),r=fe(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function q(e,t,n=0,r={}){if(n>Br)return je("<truncated>",t);if(typeof e=="string"){let i=ue(e);return je(r.escapeControls?Gt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ye),o=i.map(s=>q(s,t,n+1,r));return e.length>i.length&&o.push(je(`<${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,Ye))i[s]=q(c,t,n+1,r);return o.length>Ye&&(i.output_truncated=!0),i}return e}var We=require("process");var ze=!1;function Je(e){ze=e}function qt(){return ze}var Kt="1";function j(e,t){if(ze){let n={...e};delete n.version;let r=pe(),i={event:n.event,...n},o=q(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Kt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Kt,event:o.event,output_truncated:!0})),We.stderr.write(`${s}
4
+ `)}else We.stderr.write(t)}var Yt="2",H=null,L=null,W=!1,Z=!1;function Dr(){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=jt.randomBytes(4).toString("hex");return he.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var Ve=64*1024*1024,Ur=null;function Xe(e={}){if(e.quiet&&(Z=!0),W)return;let t=Dr();if(!t)return;H=null;let n=null;try{if((Ur??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let r=he.dirname(t);if(h.mkdirSync(r,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let u=h.statSync(r),d=u.mode&511;if(!u.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=h.constants.O_NOFOLLOW??0;n=h.openSync(t,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|i,384);let o=h.fstatSync(n),s=h.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`);h.fchmodSync(n,384)}catch(r){if(n!==null)try{h.closeSync(n)}catch{}Z||j({event:"sidecar_disabled",reason:"open_failed",detail:b(`sidecar path '${t}' could not be opened safely (${r.message})`)},`${b(`[allscale] sidecar path '${t}' could not be opened safely (${r.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}H=t,L=n,W=!0}var Fr=[/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 Mr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fr.some(n=>n.test(t))}function Ht(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=Gr(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Mr(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Gr(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Kr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ht(e.url)}:e}function qr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=q(i,pe()),s=JSON.stringify({version:Yt,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Yt,timestamp:t,type:r,output_truncated:!0})),s}function w(e){if(!W||!H||L===null)return;let t=Kr(e),n=qr(t);try{if(h.fstatSync(L).size+Buffer.byteLength(n,"utf8")+1>Ve){W=!1;try{h.closeSync(L)}catch{}L=null,Z||j({event:"sidecar_disabled",reason:"size_limit",...H===null?{}:{path:b(H)},max_bytes:Ve},`${b(`[allscale] sidecar exceeded ${Ve} bytes; disabling it for the rest of this run. Rotate or remove ${H}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}h.appendFileSync(L,`${n}
7
+ `)}catch(r){if(W=!1,L!==null){try{h.closeSync(L)}catch{}L=null}try{Z||j({event:"sidecar_disabled",reason:"write_failed",detail:b(r.message)},`${b(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var v=Ht;function Wt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Q(){if(Z=!1,W=!1,L!==null){try{h.closeSync(L)}catch{}L=null}}function zt(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Wt()||!t}var ee=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"]),Yr=new Set(Array.from(ee).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),jr=Array.from(ee).filter(e=>e.startsWith("--")).sort((e,t)=>t.length-e.length),Hr=new Set(["--otp-stdin","--password-stdin"]);function Ze(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let o=r.indexOf("=");if(o!==-1){let s=r.slice(0,o);if(ee.has(s)){t.push(`${s}=<redacted>`);continue}}}if(ee.has(r)){t.push(r),n+1<e.length&&(ee.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(Yr.has(o)){t.push(`${o}<redacted>`);continue}}let i=Hr.has(r)?void 0:jr.find(o=>r.length>o.length&&r.startsWith(o));if(i){t.push(`${i}<redacted>`);continue}t.push(r)}return t}function Jt(e){w({type:"error",code:e.code,message:b(e.message)}),w({type:"command-end",ok:!1,exitCode:e.exitCode}),Q()}var te=V()??Ct,J={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function P(e){return Nt(e)?new URL(e).origin:null}function T(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Vt(){let e=process.env[J.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Qe(){let e=process.env[J.PROFILE]?.trim();return e&&e.length>0?e:void 0}function ne(){let e=process.env[J.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Xt(){let e=process.env[J.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Zt(){let e=process.env[J.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Qt(){let e=process.env[J.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(V()===void 0&&te!==""&&"".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 ${te} (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: ${Tt} --api-base ${Z}
14
- `}var J=A(require("fs")),Jt=A(require("os")),je=A(require("path")),ze=A(require("@iarna/toml"));var Or=".allscale",Cr="config.toml";function We(){return je.join(Jt.homedir(),Or)}function Rr(){return je.join(We(),Cr)}function ce(){let e=Rr();if(!J.existsSync(e))return{};let t=J.readFileSync(e,"utf-8");try{return ze.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function Vt(e){return Object.keys(e.profile??{}).sort()}function Xt(e,t){return e.profile?.[t]}function Zt(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function v(e){if(!Oe(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Ie)}function Je(e,t){v(e);let n=R(e),r=typeof t=="string"?R(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function Qt(e,t){let n=R(e),r=R(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function ue(e){let t=V();if(t===void 0||P(e))return;let n=R(e),r=X();if(r.length>0){let o=r.map(c=>R(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>T(c.base)).join(", ");throw new l("input.invalid",`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=R(t);if(!(n!==null&&n===i))throw new l("input.invalid",`Refusing to send to ${T(e)} \u2014 this build only signs for ${T(t)}. Re-login against this build's environment, or use a build for that one.`)}var en=require("@noble/hashes/sha3");var tn=["USDT","USDC"];function nn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,en.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let i=0;i<t.length;i+=1){let o=t[i];if(!/[a-fA-F]/.test(o))continue;let s=Number.parseInt(r[i],16)>=8;if(s&&o!==o.toUpperCase()||!s&&o!==o.toLowerCase())return!1}return!0}var vr=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function rn(e){return vr.has(e.toLowerCase())}var B=require("@oclif/core"),Q=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:x()==="public"}),"api-base":I.Flags.string({description:Te,helpGroup:"GLOBAL",hidden:x()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{He(this.jsonEnabled()),Mt(),E({type:"session-start",command:this.id??"",argv:xr(this.argv)});let t=this.constructor;if(x()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&le()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!zt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=Ht(this.jsonEnabled()),r=this.argv.length===0&&!n&&Gr(t)?this.config.findCommand(this.id??""):void 0;if(r){ae();let o=await(0,I.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 E({type:"command-end",ok:!0}),ae(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Nt(i),{data:i})}catch(t){let n=vt(t);E({type:"error",code:n.code,message:k(n.message)}),E({type:"command-end",ok:!1,exitCode:n.exitCode}),ae(),this.emitError(n),process.exitCode=n.exitCode;return}finally{He(!1)}}resolveSessionApiBaseChain(t){let n=ce(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||qe()!==void 0,s=Zt(n,r,qe()),c=Xt(n,s),u=i??le(),d=u??c?.api_base??Z,f=Wt({resolvedApiBase:d,fromExplicitOverride:u!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,Y({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||v(n),n}resolveContext(t){if(x()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&le()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:u}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(v(i),ue(i)),{apiBase:i,profile:s,token:n??Yt(),insecureStorage:r||qt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:u}}emitError(t){process.stderr.write(`${Mr(t)}
15
- `)}},fe=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"]),Nr=new Set(Array.from(fe).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function xr(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(fe.has(o)){t.push(`${o}=<redacted>`);continue}}}if(fe.has(r)){t.push(r),n+1<e.length&&(fe.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(Nr.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var Pr=/(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 Br(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Pr.test(t)}var Ur=/_(removed|cleared|count|total)$/i;function Dr(e,t){return typeof t=="number"&&Ur.test(e)}var $r=new Set(tn);function Fr(e,t){return e==="token_symbol"&&typeof t=="string"&&$r.has(t)}var de=100;function Ve(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,de),r=n.map(i=>Ve(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,de))n[i]=Br(i)&&!Dr(i,o)&&!Fr(i,o)?"<redacted>":Ve(o,t+1);if(r.length>de){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-de} more keys`}return n}return typeof e=="string"?k(e):e}function Mr(e){let t=Dt()?void 0:2,n=Ve(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:k(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Gr(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 on=/^0x[0-9a-fA-F]{64}$/;var yn=A(require("path"));var Qe=require("crypto"),a=A(require("fs")),_=A(require("path"));var pe=1024*1024,Kr=5e3,Hr=20,Yr=3e4,Xe=4096,qr=new Int32Array(new SharedArrayBuffer(4)),ee=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function ge(e){return e instanceof ee}var b=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},jr=null;function D(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function he(){return(jr??process.platform)!=="win32"}function pn(){if(!he())throw D()}function gn(e){try{return a.default.lstatSync(e),!1}catch(t){if(!m(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(_.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(m(t,"ENOENT"))return!0;throw t}}function m(e,t){return typeof e=="object"&&e!==null&&e.code===t}function te(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function ne(e,t){return e.dev===t.dev&&e.ino===t.ino}function zr(e){Atomics.wait(qr,0,0,e)}function hn(e){try{return process.kill(e,0),!0}catch(t){return!m(t,"ESRCH")}}function Wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sn(e,t){let n=_.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&m(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=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!ne(o,s))throw new Error("credential-store parent changed while it was being inspected");te(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&_.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&m(o,"ENOENT")?new b:o}if(!ne(n,i))throw r.retryOnPathChange?new b: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 ee;if(te(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.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 Jr(e,t){if(t.size>pe)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(pe+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>pe)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function an(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(m(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Jr(t,r)}finally{t!==null&&a.default.closeSync(t)}}function ln(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(m(i,"ENOENT")&&gn(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);$(e,r)}finally{t!==null&&a.default.closeSync(t)}_n(_.dirname(e))}function Vr(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(m(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ee;te(t,"credential-store replacement target")}function Xr(e,t){for(let n=0;n<8;n+=1){let r=(0,Qe.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(m(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function mn(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function _n(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Zr(e,t){let n=Buffer.from(t,"utf8");if(n.length>pe)throw new Error("credential-store file exceeds the maximum supported size");let r=_.dirname(e),i=_.basename(e),o=null,s=null,c=!1;try{let u=Xr(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");mn(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),Vr(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}_n(r)}function Qr(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function ei(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function ti(e,t){if(t.size>Xe)return null;let n=Buffer.alloc(Xe+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>Xe)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 $(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!ne(n,t))throw new Error("credential-store lock changed while it was being inspected");te(n,"credential-store lock"),a.default.unlinkSync(e)}function cn(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(m(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new b}catch(d){if(m(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ti(n,i);return{state:(o?.target===t&&o?!hn(o.pid):Date.now()-i.mtimeMs>=Yr)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function ni(e,t){for(let n=0;n<8;n+=1){let r=(0,Qe.randomBytes)(12).toString("hex"),i=_.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(i,s,c,{allowMultipleLinks:!0});return mn(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(m(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function ri(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw m(r,"ENOENT")?new b:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ne(i,t))throw new b;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function un(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(m(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new b}catch(r){if(m(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function ii(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(m(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{$(e,n)}catch{}throw a.default.closeSync(t),r}}function U(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");zr(Hr)}function dn(e){let t=_.dirname(e),n=_.basename(e),r=Qr(e),i=ei(e),o=ni(t,n),s=Date.now()+Kr,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(un(i)){U(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=ri(r,o.stats),c=!0}catch(p){if(u&&!c){try{$(r,o.stats)}catch{}u=!1}if(p instanceof b){U(s,!1);continue}if(!m(p,"EEXIST"))throw p;let y;try{y=cn(r,n)}catch(w){if(w instanceof b){U(s,!1);continue}throw w}if(y.state==="absent")continue;if(y.state==="stale"){let w;try{w=ii(i)}catch(S){if(S instanceof b){U(s,!1);continue}throw S}if(w!==null){try{let S;try{S=cn(r,n)}catch(N){if(N instanceof b){U(s,!1);continue}throw N}S.state==="stale"&&$(r,S.stats)}finally{Ze(w)}continue}}let h;try{h=un(i)}catch(w){if(w instanceof b){U(s,!1);continue}throw w}U(s,h)}}catch(p){f=p}try{$(o.claimPath,o.stats)}catch(p){!m(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function Ze(e){try{$(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function oi(e,t){let n=Wr(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 fn(e){let t=_.dirname(e),n=_.basename(e);for(let r of a.default.readdirSync(t)){let i=oi(r,n);if(i===null||hn(i))continue;let o=_.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(m(d,"ENOENT")||m(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!ne(c,u))continue;try{te(c,"credential-store orphan")}catch{continue}$(o,c)}catch(c){if(!m(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function re(e,t,n){if(!he()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!sn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let s=dn(e);try{return fn(e),n({read:()=>an(e),remove:()=>ln(e),write:()=>{throw D()}})}finally{Ze(s)}}if(!t.createParent){let o=!1;try{o=gn(e)}catch{throw D()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!sn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=dn(e);try{return fn(e),n({read:()=>an(e),remove:()=>ln(e),write:o=>Zr(e,o)})}finally{Ze(i)}}var et="allscale-cli";function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e){return it(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function M(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function tt(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function me(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var F,nt=!1;function si(){return jt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function ai(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 li(){if(F!==void 0)return F;if(si())return nt=!1,F=null,F;try{F=require("keytar"),nt=!1}catch(e){nt=!ai(e),F=null}return F}function En(){let e=he()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function rt(e){try{return await e()}catch{throw En()}}var ot=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await rt(()=>this.keytar.getPassword(et,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw M("OS keychain")}if(!wn(r))throw M("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await rt(()=>this.keytar.setPassword(et,t,JSON.stringify(n)))}async delete(t){await this.read(t),await rt(()=>this.keytar.deletePassword(et,t))}},ci="credentials.json",st=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??yn.join(We(),ci)}read(t){let n;try{n=t.read()}catch(i){throw ge(i)?tt():M("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw M("plaintext file")}if(!it(r)||!it(r.profiles))throw M("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw ge(r)?tt():me()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!wn(r))throw M("plaintext file");return r}}async get(t){try{return re(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:M("plaintext file")}}async set(t,n){try{re(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 l?r:me()}}async delete(t){try{re(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:me()}}async clearProfile(t){try{return re(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:ge(n)?tt():me()}}};function Sn(e){if(e.insecureStorage)return pn(),new st(e.insecureFilePath);let t=li();if(t)return new ot(t);throw En()}var at=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function _e(){return new at}var ye="allscale_access_token",lt="allscale_refresh_token";function An(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 ct(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function ut(e,t){return e.find(n=>n.name===t)?.value??null}var bn=A(require("crypto")),kn=A(require("fs")),Ln=A(require("path"));var ui="key-id",di="x-allscale-cli-version",dt="cli-1",fi="aScaLe_cli_obf_v1",pi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function gi(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 hi=gi(pi,fi),Tn=`Bearer ${hi}`;function In(e,t){let n=Re(e);if(n!==null)return t.find(r=>Re(r.base)===n)}function mi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=In(e,t);if(r)return r.key;if(P(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:P(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 _i(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?In(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&P(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():dt}if(!P(t[0].base))return dt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():dt}function yi(){return"0.1.0"}function wi(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function ft(e,t){let n=mi(t);if(!n)throw wi();let r=_i(t),i=Math.floor(Date.now()/1e3).toString(),o=bn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[di]:yi()};return r.length>0&&(s[ui]=r),s}function On(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function Ei(e,t={}){let n;try{n=Vt(ce())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",Rt(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function Cn(e){if(e.profileExplicit){let t=Ei(e.profile);if(t)return t}return new l("auth.no_token",Ct(e.profile,e.flow))}var pt=256*1024,we=class extends l{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"}},Ee=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function gt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new we(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,y)=>{u=setTimeout(()=>{y(new Ee(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:y,value:h}=f?await Promise.race([p,f]):await p;if(y)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new we(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(p){throw p instanceof Ee&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Si="X-AllScale-Api-Key",Ai=3e4,bi=32*1024*1024,ki=4*1024*1024;function Li(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 Ti(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 Ii(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${C(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Pn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Ii(e.status,e.url)}}var Rn="--dns-result-order=ipv4first";async function Se(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),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Rn} 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=${Rn}`})}var G=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??Ai;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");v(this.opts.apiBase),ue(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=Li(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${C(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();Qt(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Bn(t.path),u=s==="required"?!0:s==="none"?!1:Ri(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw Cn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=On(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&Je(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),y=Date.now();E({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(S){throw new l("transport.network",`Network error contacting ${C(i)}: ${S instanceof Error?S.message:String(S)}`)}if(E({type:"response",status:h.status,durationMs:Date.now()-y}),u&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let S=await Ti(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),jn=Date.now();E({type:"request",method:t.method??"GET",url:i});let ke;try{ke=await fetch(i,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Le){throw new l("transport.network",`Network error contacting ${C(i)} on refresh-retry: ${Le instanceof Error?Le.message:String(Le)}`)}return E({type:"response",status:ke.status,durationMs:Date.now()-jn}),vn(ke,{withMetadata:n.withMetadata,authBearing:u,responseKind:Nn(t)})}return vn(h,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:Nn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...ft(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Tn;let i=t.tokens;if(i?.agent_key)return r[Si]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=ct([{name:ye,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 l("auth.token_expired",`No refresh token available; log in again \u2014 ${xe()}.`);if(Je(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=ct([{name:ye,value:t.access_token},{name:lt,value:t.refresh_token}]),i=ft("",this.opts.apiBase);E({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw E({type:"refresh",ok:!1}),new l("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${C(n)} timed out after 10s with no response.`:`Network error during token refresh against ${C(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}E({type:"response",status:u.status,durationMs:0});try{await Pn(u)}catch(h){throw E({type:"refresh",ok:!1}),h}if(u.status!==200){E({type:"refresh",ok:!1}),await Se(u);let h=await xi(u);throw await Se(u,h),Un(u.status,h),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${xe()}.`,{status:u.status})}let d=An(u.headers),f=ut(d,ye),p=ut(d,lt);if(!f||!p)throw E({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let y={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,y),E({type:"refresh",ok:!0}),y}},Oi=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Bn(e){let t=e.split(/[?#]/,1)[0];return Oi.some(n=>t===n||t.startsWith(`${n}/`))}var Ci=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function ht(e){let t=e.split(/[?#]/,1)[0];return Ci.some(n=>n.test(t))}function Ri(e){return Bn(e)||ht(e)}async function vn(e,t={}){await Pn(e);let n=e.status>=200&&e.status<300;n||await Se(e);let r=t.responseKind??"mutation",o=await gt(e,n?r==="query"?bi:ki:pt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Se(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 u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=Pi(s)??`HTTP ${e.status}`;if(Un(e.status,s),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function Nn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var xn=2014;function vi(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===xn||n===String(xn)}var Ni=1e4;async function xi(e,t=Ni){if(e.status>=200&&e.status<300)return"";try{return await gt(e,pt,{timeoutMs:t})}catch{return""}}function Un(e,t){if(!(e>=200&&e<300)&&vi(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}function Pi(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 Bi=/^\/(api\/)?(v1\/)?public\//;function mt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Bi.test(n),i=n&&ht(n),o=r&&!i&&!t.forceAuth;if(e.token)return new G({apiBase:e.apiBase,tokenStore:_e(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new G({apiBase:e.apiBase,tokenStore:_e(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new G({apiBase:e.apiBase,tokenStore:Sn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new G({apiBase:e.apiBase,tokenStore:_e(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var Dn="/api/v1/public/claim-links";var Ui=1e4;function $n(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Dn}/${n}:claim`:`${Dn}/${n}`}function Ae(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let i=t.trim();if(!i)throw new l("input.invalid","--claim-token is empty.");return _t(i,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return _t(Di(r),"--claim-url")}async function Fn(e,t,n=Ui){let r=e["claim-url"]?.trim();if(!r)return Ae(e);let i;try{i=new URL(r)}catch{return Ae(e)}let o=/^\/s\/([^/]+)\/?$/.exec(i.pathname);if(!o||e["claim-token"]!==void 0)return Ae(e);v(t);let s=new URL(t).origin;if(i.origin!==s||i.username||i.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(o[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let y;try{y=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let h=y.headers.get("location");try{y.body?.cancel().catch(()=>{})}catch{}if(y.status!==302||!h)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:y.status});let w;try{w=new URL(h,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(w.origin!==s||w.username||w.password||w.search||w.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let S=/^\/claim\/([^/]+)\/?$/.exec(w.pathname);if(!S)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(S[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return _t(N,"--claim-url")}function _t(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"Claim token must be a URL-safe token string, not empty or malformed.");return e}function Di(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),i=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],o=i.endsWith(":claim")?i.slice(0,-6):i;try{return decodeURIComponent(o)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function Mn(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function Gn(e,t=""){let n=x()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var $i=["claimed","not_claimable","expired","payout_pending","payout_failed"],Fi=64,Mi=128,Gi=/^[a-z][a-z0-9_]*$/,Ki=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function Kn(e){return typeof e=="string"&&e.length>0&&e.length<=Fi&&Gi.test(e)}function Hn(e){return typeof e=="string"&&e.length>0&&e.length<=Mi&&Ki.test(e)}function Yn(e){return typeof e=="string"&&on.test(e)}function Hi(e){let t={outcome_ambiguous:!0};if(typeof e!="object"||e===null)return t;let n=e;return Kn(n.outcome)&&(t.outcome=n.outcome),Hn(n.claim_link_id)&&(t.claim_link_id=n.claim_link_id),n.claim_tx_hash===null?t.claim_tx_hash=null:Yn(n.claim_tx_hash)&&(t.claim_tx_hash=n.claim_tx_hash),t}function Yi(e){if(typeof e!="object"||e===null)return!1;let t=e;return Kn(t.outcome)&&$i.includes(t.outcome)&&Hn(t.claim_link_id)&&(t.claim_tx_hash===void 0||t.claim_tx_hash===null||Yn(t.claim_tx_hash))}function qn(e){if(!Yi(e))throw new l("backend.internal","Claim endpoint returned an invalid result; the claim outcome is unknown. Inspect the Claim Link before retrying.",Hi(e));if(e.outcome==="claimed")return e;let t={outcome:e.outcome,claim_link_id:e.claim_link_id,claim_tx_hash:e.claim_tx_hash??null};throw e.outcome==="payout_pending"||e.outcome==="payout_failed"?new l("claim.payout_ambiguous",`Claim payout is ${e.outcome==="payout_pending"?"still pending":"not proven successful"}. Do not submit another claim; reconcile this Claim Link first.`,{...t,outcome_ambiguous:!0}):new l(e.outcome==="expired"?"claim.expired":"claim.not_claimable",e.outcome==="expired"?"Claim did not complete because this Claim Link has expired.":"Claim did not complete because this Claim Link is not claimable in its current state. Inspect its status before deciding whether to retry.",t)}var be=class e extends Q{static description="Claim a Claim Link. Anonymous claims require --to; authenticated business receivers can use --to-wallet. Only an on-chain-proven claimed outcome exits 0.";static examples=["$ allscale claim-link claim --claim-token <token> --to 0xabc...","$ allscale claim-link claim --claim-url https://app.allscale.io/claim/<token> --to-wallet"];static usage=Gn("claim"," [--to <value> | --to-wallet]");static requiresInput=!0;static flags={"claim-token":B.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":B.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),to:B.Flags.string({helpGroup:"REQUIRED (ONE OF)",description:"Receiver EVM address for anonymous Path-A claims.",exclusive:["to-wallet"]}),"to-wallet":B.Flags.boolean({helpGroup:"REQUIRED (ONE OF)",description:"Claim into the authenticated receiver business's AllScale wallet for the link's chain. Requires login/token.",default:!1,exclusive:["to"]}),...Q.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Fn(t,n.apiBase),i=$n(r,"claim"),o,s;if(t["to-wallet"])o={},s="required";else{let d=t.to?.trim();if(!d)throw new l("input.invalid","Pass --to <0x address> or --to-wallet.");if(!nn(d))throw new l("input.invalid",`--to is not a valid EVM address: '${d}' (expected 0x followed by 40 hex characters).`);if(rn(d))throw new l("input.invalid","--to must not be the zero or burn address; funds claimed to it cannot be recovered.");o={receiver_address:d},s="none"}let u=await mt(n,{pathHint:i,forceAuth:s==="required"}).request({method:"POST",path:i,body:o,auth:s});return qn(Mn(u))}};0&&(module.exports={requireSuccessfulClaim});
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 ${te}
14
+ `}var B=A(require("fs")),tn=A(require("os")),et=A(require("path")),tt=A(require("@iarna/toml"));var Jr=".allscale",Vr="config.toml";function nt(){return et.join(tn.homedir(),Jr)}function Xr(){return et.join(nt(),Vr)}function ge(){let e=Xr();if(!B.existsSync(e))return{};let t=B.readFileSync(e,"utf-8");try{return tt.parse(t)}catch(n){throw new l("internal",`Failed to parse ${e}: ${n.message}`)}}function nn(e){return Object.keys(e.profile??{}).sort()}function rn(e,t){return e.profile?.[t]}function on(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new l("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function R(e){if(!Be(e))throw new l("input.invalid",`Refusing to send credentials to API base ${T(e)}. `+Pe)}function me(e,t){R(e);let n=P(e),r=typeof t=="string"?P(t):null;if(n&&r===n)return;let i=typeof t=="string"?T(t):"<missing origin binding>";throw new l("input.invalid",`Refusing to send stored credentials: API base ${T(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function sn(e,t){let n=P(e),r=P(t);if(!(n&&r===n))throw new l("input.invalid",`Refusing API request to ${T(t)} because it is outside the configured API origin ${T(e)}.`)}function _e(e){let t=Qr(e);if(t)throw new l("input.invalid",t.message)}function Zr(){let e=V();if(e===void 0)return;let t=X();return t.length>0?{endpoints:t.map(n=>n.base),fromPairs:!0}:{endpoints:[e],fromPairs:!1}}function Qr(e){let t=Zr();if(t===void 0||x(e))return;let{endpoints:n,fromPairs:r}=t,i=P(e),o=n.map(c=>P(c)).filter(c=>c!==null);if(i!==null&&o.includes(i))return;let s=n.map(c=>T(c)).join(", ");return{message:r?`Refusing to send to ${T(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`:`Refusing to send to ${T(e)} \u2014 this build only signs for ${s}. Re-login against this build's environment, or use a build for that one.`}}var an=require("@noble/hashes/sha3");var ln=["USDT","USDC"];function cn(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let t=e.slice(2);if(t===t.toLowerCase()||t===t.toUpperCase())return!0;let n=t.toLowerCase(),r=Buffer.from((0,an.keccak_256)(Buffer.from(n,"ascii"))).toString("hex");for(let i=0;i<t.length;i+=1){let o=t[i];if(!/[a-fA-F]/.test(o))continue;let s=Number.parseInt(r[i],16)>=8;if(s&&o!==o.toUpperCase()||!s&&o!==o.toLowerCase())return!1}return!0}var rt="0x1234567890abcdef1234567890abcdef12345678";function ei(e){return e.toLowerCase()===rt}function un(e,t="--to"){if(ei(e))throw new l("input.invalid",`${t} is the documentation example address; pass a destination address you control.`)}var ti=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function dn(e){return ti.has(e.toLowerCase())}var ni="unknown_otp_id",ri="invalid_code",ii="expired_code";function oi(e){return`'${e.replace(/'/g,"'\\''")}'`}function fn(e){return`Run \`allscale otp-send --email ${oi(e)}\` first \u2014 that command does report a missing account \u2014 then retry with the otp_id it returns and a fresh code.`}var si=new Map([[ni,(e,t)=>`${e}: this environment never issued the --otp-id you passed for '${t}', so the verification code was never the problem. The backend decides this by comparing the otp_id against that address alone, so it says nothing about whether the account exists. ${fn(t)}`],[ri,e=>`${e}: the --otp-id is one this environment issued and a live code stands behind it \u2014 the verification code you passed is what does not match. Check for a typo \u2014 the backend invalidates the code after a few wrong answers, so if you are unsure, request a fresh code instead of guessing.`],[ii,(e,t,n)=>n?`${e}: this run's send request was accepted moments ago, but this attempt could not claim a live code for the --otp-id. Delivery is asynchronous and the code is stored only after the email goes out, so it may still be in flight \u2014 or the send may have failed outright, in which case no code is coming. The code you submitted may also have expired, been used, run out of attempts, or been replaced by a newer send. Check the inbox, including spam, and retry with whatever code arrived. If nothing arrives, confirm the address and wait at least three minutes before requesting one fresh code \u2014 sends are rate-limited per address, and retrying in a tight loop spends that budget even when the send is rejected.`:`${e}: this attempt could not claim a live code for the --otp-id. The code you submitted may have expired, been used, run out of attempts, been replaced by a later send, or never have been requested for this address; the backend does not distinguish those. If a newer code was delivered after the one you entered, use that one. ${fn(t)}`]]);var pn=[...si.keys()];var $=require("@oclif/core"),re=class e extends I.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:I.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:I.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:C()==="public"}),"api-base":I.Flags.string({description:xe,helpGroup:"GLOBAL",hidden:C()==="public"}),"insecure-storage":I.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{Je(this.jsonEnabled()),Xe(),w({type:"session-start",command:this.id??"",argv:Ze(this.argv)});let t=this.constructor;if(C()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&ne()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=zt(this.jsonEnabled()),r=this.argv.length===0&&!n&&gi(t)?this.config.findCommand(this.id??""):void 0;if(r){Q();let o=await(0,I.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&&!Qt())throw this.argv.length>0&&await this.parse(),new l("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let i=await this.runCommand();return w({type:"command-end",ok:!0}),Q(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ut(i),{data:i})}catch(t){let n=Dt(t);Jt({code:n.code,message:n.message,exitCode:n.exitCode}),this.emitError(n),process.exitCode=n.exitCode;return}finally{Je(!1)}}resolveSessionApiBaseChain(t){let n=ge(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||Qe()!==void 0,s=on(n,r,Qe()),c=rn(n,s),u=C()==="public"&&ne()!==void 0,d=i??(u?void 0:ne()),f=d??c?.api_base??te,p=en({resolvedApiBase:f,fromExplicitOverride:d!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,j({event:"legacy_staging_profile",api_base:f,profile:s},p)),{apiBase:f,explicitApiBase:d,envApiBaseIgnored:u,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||R(n),n}resolveContext(t){if(C()==="public"){if(t.token!==void 0)throw new l("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new l("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&ne()!==void 0)throw new l("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,envApiBaseIgnored:s,profile:c,profileApiBase:u,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(R(i),_e(i)),{apiBase:i,profile:c,token:n??Vt(),insecureStorage:r||Xt(),apiBaseSource:o!==void 0?"explicit":u!==void 0?"profile":"default",profileExplicit:d,envApiBaseIgnored:s}}emitError(t){process.stderr.write(`${hi(t)}
15
+ `)}};var ai=/_(removed|cleared|count|total)$/i;function li(e,t){return typeof t=="number"&&ai.test(e)}var ci=new Set(ln);function ui(e,t){return e==="token_symbol"&&typeof t=="string"&&ci.has(t)}var di=new Set(pn);function fi(e,t){return e==="otp_reason"&&typeof t=="string"&&di.has(t)}var ye=100;function we(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,ye),r=n.map(i=>we(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,ye))n[i]=de(i)&&!li(i,o)&&!ui(i,o)&&!fi(i,o)?"<redacted>":we(o,t+1);if(r.length>ye){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-ye} more keys`}return n}if(typeof e=="string"){let n=pi(e);return n!==void 0?b(JSON.stringify(we(n,t+1))):b(e)}return e}function pi(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return;let n;try{n=JSON.parse(t)}catch{return}return n!==null&&typeof n=="object"?n:void 0}function hi(e){let t=qt()?void 0:2,n=we(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:b(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function gi(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 hn=/^0x[0-9a-fA-F]{64}$/;var In=A(require("path"));var st=require("crypto"),a=A(require("fs")),y=A(require("path"));var Ee=1024*1024,mi=5e3,_i=20,yi=3e4,it=4096,wi=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Se(e){return e instanceof ie}var k=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ei=null;function U(){return new l("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function be(){return(Ei??process.platform)!=="win32"}function bn(){if(!be())throw U()}function An(e){try{return a.default.lstatSync(e),!1}catch(t){if(!_(t,"ENOENT"))throw t}try{let t=a.default.lstatSync(y.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(_(t,"ENOENT"))return!0;throw t}}function _(e,t){return typeof e=="object"&&e!==null&&e.code===t}function oe(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function se(e,t){return e.dev===t.dev&&e.ino===t.ino}function Si(e){Atomics.wait(wi,0,0,e)}function kn(e){try{return process.kill(e,0),!0}catch(t){return!_(t,"ESRCH")}}function bi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gn(e,t){let n=y.dirname(e);t&&a.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=a.default.lstatSync(n)}catch(o){if(!t&&_(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=a.default.openSync(n,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0));let o=a.default.fstatSync(i),s=a.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!se(o,s))throw new Error("credential-store parent changed while it was being inspected");oe(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&y.basename(n)===".allscale"&&(a.default.fchmodSync(i,448),c=a.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&a.default.closeSync(i)}return!0}function O(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=a.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&_(o,"ENOENT")?new k:o}if(!se(n,i))throw r.retryOnPathChange?new k: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 ie;if(oe(n,"credential-store file"),process.platform!=="win32"){a.default.fchmodSync(t,384);let o=a.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 Ai(e,t){if(t.size>Ee)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Ee+1),r=0;for(;r<n.length;){let i=a.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Ee)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function mn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(_(i,"ENOENT"))try{if(a.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(_(o,"ENOENT"))return null;throw o}throw i}let n=a.default.fstatSync(t),r=O(e,t,n);return Ai(t,r)}finally{t!==null&&a.default.closeSync(t)}}function _n(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(i){if(_(i,"ENOENT")&&An(e))return;throw i}let n=a.default.fstatSync(t),r=O(e,t,n);F(e,r)}finally{t!==null&&a.default.closeSync(t)}Tn(y.dirname(e))}function ki(e){let t;try{t=a.default.lstatSync(e)}catch(n){if(_(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 ie;oe(t,"credential-store replacement target")}function Li(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),i=y.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(_(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Ln(e,t){let n=0;for(;n<t.length;){let r=a.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Tn(e){if(process.platform==="win32")return;let t=null;try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_DIRECTORY??0)|(a.default.constants.O_NOFOLLOW??0)),a.default.fsyncSync(t)}catch{}finally{if(t!==null)try{a.default.closeSync(t)}catch{}}}function Ti(e,t){let n=Buffer.from(t,"utf8");if(n.length>Ee)throw new Error("credential-store file exceeds the maximum supported size");let r=y.dirname(e),i=y.basename(e),o=null,s=null,c=!1;try{let u=Li(r,i);o=u.fd,s=u.tempPath;let d=a.default.fstatSync(o);if((O(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Ln(o,n),a.default.fsyncSync(o),O(s,o,a.default.fstatSync(o));let p=o;o=null,a.default.closeSync(p),ki(e),a.default.renameSync(s,e),c=!0}finally{if(o!==null)try{a.default.closeSync(o)}catch{}if(!c&&s!==null)try{a.default.unlinkSync(s)}catch{}}Tn(r)}function Ii(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock`)}function Oi(e){return y.join(y.dirname(e),`.${y.basename(e)}.lock-recovery`)}function Ci(e,t){if(t.size>it)return null;let n=Buffer.alloc(it+1),r=0;for(;r<n.length;){let o=a.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>it)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function F(e,t){let n=a.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!se(n,t))throw new Error("credential-store lock changed while it was being inspected");oe(n,"credential-store lock"),a.default.unlinkSync(e)}function yn(e,t){let n=null;try{try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(u){if(_(u,"ENOENT"))try{let d=a.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new k}catch(d){if(_(d,"ENOENT"))return{state:"absent"};throw d}throw u}let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Ci(n,i);return{state:(o?.target===t&&o?!kn(o.pid):Date.now()-i.mtimeMs>=yi)?"stale":"active",stats:i}}finally{n!==null&&a.default.closeSync(n)}}function vi(e,t){for(let n=0;n<8;n+=1){let r=(0,st.randomBytes)(12).toString("hex"),i=y.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=a.default.openSync(i,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_WRONLY|(a.default.constants.O_NOFOLLOW??0),384);let c=a.default.fstatSync(s),u=O(i,s,c,{allowMultipleLinks:!0});return Ln(s,Buffer.from(JSON.stringify(o),"utf8")),a.default.fsyncSync(s),{claimPath:i,metadata:o,stats:u}}catch(c){if(_(c,"EEXIST"))continue;try{a.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&a.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function Ri(e,t){let n;try{n=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(r){throw _(r,"ENOENT")?new k:r}try{let r=a.default.fstatSync(n),i=O(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!se(i,t))throw new k;return{fd:n,lockPath:e,stats:i}}catch(r){throw a.default.closeSync(n),r}}function wn(e){let t=null;try{try{t=a.default.openSync(e,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(n){if(_(n,"ENOENT"))try{let r=a.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new k}catch(r){if(_(r,"ENOENT"))return!1;throw r}throw n}return O(e,t,a.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&a.default.closeSync(t)}}function Ni(e){let t;try{t=a.default.openSync(e,a.default.constants.O_CREAT|a.default.constants.O_EXCL|a.default.constants.O_RDWR|(a.default.constants.O_NOFOLLOW??0),384)}catch(r){if(_(r,"EEXIST"))return null;throw r}let n=null;try{n=a.default.fstatSync(t);let r=O(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{F(e,n)}catch{}throw a.default.closeSync(t),r}}function D(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");Si(_i)}function En(e){let t=y.dirname(e),n=y.basename(e),r=Ii(e),i=Oi(e),o=vi(t,n),s=Date.now()+mi,c=!1,u=!1,d=null,f;try{for(;d===null;)try{if(wn(i)){D(s,!0);continue}a.default.linkSync(o.claimPath,r),u=!0,d=Ri(r,o.stats),c=!0}catch(p){if(u&&!c){try{F(r,o.stats)}catch{}u=!1}if(p instanceof k){D(s,!1);continue}if(!_(p,"EEXIST"))throw p;let E;try{E=yn(r,n)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}if(E.state==="absent")continue;if(E.state==="stale"){let m;try{m=Ni(i)}catch(S){if(S instanceof k){D(s,!1);continue}throw S}if(m!==null){try{let S;try{S=yn(r,n)}catch(N){if(N instanceof k){D(s,!1);continue}throw N}S.state==="stale"&&F(r,S.stats)}finally{ot(m)}continue}}let g;try{g=wn(i)}catch(m){if(m instanceof k){D(s,!1);continue}throw m}D(s,g)}}catch(p){f=p}try{F(o.claimPath,o.stats)}catch(p){!_(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{F(e.lockPath,e.stats)}finally{a.default.closeSync(e.fd)}}function xi(e,t){let n=bi(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 Sn(e){let t=y.dirname(e),n=y.basename(e);for(let r of a.default.readdirSync(t)){let i=xi(r,n);if(i===null||kn(i))continue;let o=y.join(t,r),s=null;try{try{s=a.default.openSync(o,a.default.constants.O_RDONLY|(a.default.constants.O_NOFOLLOW??0)|(a.default.constants.O_NONBLOCK??0))}catch(d){if(_(d,"ENOENT")||_(d,"ELOOP"))continue;throw d}let c=a.default.fstatSync(s),u=a.default.lstatSync(o);if(!c.isFile()||u.isSymbolicLink()||!u.isFile()||!se(c,u))continue;try{oe(c,"credential-store orphan")}catch{continue}F(o,c)}catch(c){if(!_(c,"ENOENT"))throw c}finally{s!==null&&a.default.closeSync(s)}}}function ae(e,t,n){if(!be()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw U();if(!gn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw U()}});let s=En(e);try{return Sn(e),n({read:()=>mn(e),remove:()=>_n(e),write:()=>{throw U()}})}finally{ot(s)}}if(!t.createParent){let o=!1;try{o=An(e)}catch{throw U()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw U()}})}throw U()}if(!gn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=En(e);try{return Sn(e),n({read:()=>mn(e),remove:()=>_n(e),write:o=>Ti(e,o)})}finally{ot(i)}}var at="allscale-cli";function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function On(e){return dt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function G(e){return new l("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function lt(){return new l("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Ae(){return new l("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var M,ct=!1;function Pi(){return Zt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Bi(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function $i(){if(M!==void 0)return M;if(Pi())return ct=!1,M=null,M;try{M=require("keytar"),ct=!1}catch(e){ct=!Bi(e),M=null}return M}function Cn(){let e=be()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new l("storage.unavailable","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 ut(e){try{return await e()}catch{throw Cn()}}var ft=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await ut(()=>this.keytar.getPassword(at,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw G("OS keychain")}if(!On(r))throw G("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await ut(()=>this.keytar.setPassword(at,t,JSON.stringify(n)))}async delete(t){await this.read(t),await ut(()=>this.keytar.deletePassword(at,t))}},Di="credentials.json",pt=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??In.join(nt(),Di)}read(t){let n;try{n=t.read()}catch(i){throw Se(i)?lt():G("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw G("plaintext file")}if(!dt(r)||!dt(r.profiles))throw G("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Se(r)?lt():Ae()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!On(r))throw G("plaintext file");return r}}async get(t){try{return ae(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof l?n:G("plaintext file")}}async set(t,n){try{ae(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 l?r:Ae()}}async delete(t){try{ae(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof l?n:Ae()}}async clearProfile(t){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof l?n:Se(n)?lt():Ae()}}};function vn(e){if(e.insecureStorage)return bn(),new pt(e.insecureFilePath);let t=$i();if(t)return new ft(t);throw Cn()}var ht=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new l("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function ke(){return new ht}var Le="allscale_access_token",gt="allscale_refresh_token";function Rn(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 _t(e,t){return e.find(n=>n.name===t)?.value??null}var Nn=A(require("crypto")),xn=A(require("fs")),Pn=A(require("path"));var Ui="key-id",Fi="x-allscale-cli-version",yt="cli-1",Mi="aScaLe_cli_obf_v1",Gi="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Ki(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 qi=Ki(Gi,Mi),Bn=`Bearer ${qi}`;function $n(e,t){let n=De(e);if(n!==null)return t.find(r=>De(r.base)===n)}function Yi(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=X();if(t.length>0){let r=$n(e,t);if(r)return r.key;if(x(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:x(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 ji(e){{let r="cli-1".trim();if(r.length>0)return r}let t=X();if(t.length>0){let r=e!==void 0?$n(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&x(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():yt}if(!x(t[0].base))return yt}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():yt}function Hi(){return"1.0.2"}function Wi(){return new l("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function wt(e,t){let n=Yi(t);if(!n)throw Wi();let r=ji(t),i=Math.floor(Date.now()/1e3).toString(),o=Nn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[Fi]:Hi()};return r.length>0&&(s[Ui]=r),s}function Dn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function zi(e,t={}){let n;try{n=nn(ge())}catch{return}if(!(n.length===0||n.includes(e)))return new l("auth.unknown_profile",$t(e)+(t.messageSuffix??""),{profile:e})}function Un(e){if(e.profileExplicit){let t=zi(e.profile);if(t)return t}return new l("auth.no_token",Bt(e.profile))}var Ji=500,Vi=8,Fn=100;function Et(e,t=0){if(t>Vi)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Fn),r=n.map(i=>Et(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,Fn))n[r]=de(r)?"<redacted>":Et(i,t+1);return n}return e}function Xi(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 Mn(e,t=Ji){let n=Xi(e),r=n===void 0?ue(e):JSON.stringify(Et(n));return fe(r,t)}var St=256*1024,Te=class extends l{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"}},Ie=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 bt(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 Te(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,u,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,E)=>{u=setTimeout(()=>{E(new Ie(e.status,d))},d),u.unref?.()});try{for(;;){let p=o.read(),{done:E,value:g}=f?await Promise.race([p,f]):await p;if(E)break;if(c+=g.byteLength,c>t)throw o.cancel().catch(()=>{}),new Te(e.status,t,n.oversizeKind);s.push(Buffer.from(g))}}catch(p){throw p instanceof Ie&&o.cancel(p).catch(()=>{}),p}finally{u!==void 0&&clearTimeout(u);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var Zi="X-AllScale-Api-Key",Qi=3e4,eo=32*1024*1024,to=4*1024*1024;function no(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 ro(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 io(e,t){if(!(e<300||e>=400))throw new l("transport.network",`API returned HTTP ${e} (a redirect) for ${v(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function jn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}io(e.status,e.url)}}var Gn="--dns-result-order=ipv4first";async function Oe(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),u=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&u)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new l("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Gn} 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=${Gn}`})}var K=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??Qi;if(!Number.isFinite(r)||r<1)throw new l("input.invalid","HTTP request timeout must be a positive number of milliseconds.");R(this.opts.apiBase),_e(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=no(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new l("transport.timeout",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof l)?new l("transport.network",`Request to ${v(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();sn(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=Hn(t.path),u=s==="required"?!0:s==="none"?!1:ao(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw Un({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Dn(t.body),f=!!o||!!r?.access_token;u&&f&&!this.opts.override&&me(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:u&&f,bodyForSig:d,tokens:r,extra:t.headers}),E=Date.now();w({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(S){throw new l("transport.network",`Network error contacting ${v(i)}: ${S instanceof Error?S.message:String(S)}`)}if(w({type:"response",status:g.status,durationMs:Date.now()-E}),u&&!!r?.access_token&&!o&&g.status===401&&!t._isRefresh&&!this.opts.override){let S=await ro(this.refreshSingleFlight(),t.signal),N=this.buildHeaders({attachAuth:u&&!!S.access_token,bodyForSig:d,tokens:S,extra:t.headers}),sr=Date.now();w({type:"request",method:t.method??"GET",url:i});let Re;try{Re=await fetch(i,{method:t.method??"GET",headers:N,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(Ne){throw new l("transport.network",`Network error contacting ${v(i)} on refresh-retry: ${Ne instanceof Error?Ne.message:String(Ne)}`)}return w({type:"response",status:Re.status,durationMs:Date.now()-sr}),Kn(Re,{withMetadata:n.withMetadata,authBearing:u,responseKind:qn(t)})}return Kn(g,{withMetadata:n.withMetadata,authBearing:u&&f,agentKeyAuth:u&&!!o,responseKind:qn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...wt(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=Bn;let i=t.tokens;if(i?.agent_key)return r[Zi]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=mt([{name:Le,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(me(this.opts.apiBase,n.api_base),n.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return n}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new l("auth.token_expired",`No refresh token available; log in again \u2014 ${ce()}.`);if(me(this.opts.apiBase,t.api_base),t.agent_key)throw new l("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=mt([{name:Le,value:t.access_token},{name:gt,value:t.refresh_token}]),i=wt("",this.opts.apiBase);w({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),u;try{u=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(g){throw w({type:"refresh",ok:!1}),new l("transport.network",s&&g instanceof Error&&g.name==="AbortError"?`Token refresh against ${v(n)} timed out after 10s with no response.`:`Network error during token refresh against ${v(n)}: ${g instanceof Error?g.message:String(g)}`)}finally{clearTimeout(c)}w({type:"response",status:u.status,durationMs:0});try{await jn(u)}catch(g){throw w({type:"refresh",ok:!1}),g}if(u.status!==200){let g=null;try{await Oe(u);let m=await po(u);await Oe(u,m),zn(u.status,m),u.status===401&&(g=await this.adoptConcurrentlyRotatedTokens(t))}catch(m){throw w({type:"refresh",ok:!1}),m}if(g)return w({type:"refresh",ok:!0,adopted:!0}),g;throw w({type:"refresh",ok:!1}),new l("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${ce()}.`,{status:u.status})}let d=Rn(u.headers),f=_t(d,Le),p=_t(d,gt);if(!f||!p)throw w({type:"refresh",ok:!1}),new l("auth.token_expired","Refresh response did not include new access/refresh cookies.");let E={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,E),w({type:"refresh",ok:!0}),E}},oo=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Hn(e){let t=e.split(/[?#]/,1)[0];return oo.some(n=>t===n||t.startsWith(`${n}/`))}var so=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function At(e){let t=e.split(/[?#]/,1)[0];return so.some(n=>n.test(t))}function ao(e){return Hn(e)||At(e)}async function Kn(e,t={}){await jn(e);let n=e.status>=200&&e.status<300;n||await Oe(e);let r=t.responseKind??"mutation",o=await bt(e,n?r==="query"?eo:to:St,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Oe(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 u={};return e.headers.forEach((d,f)=>{u[f]=d}),{status:e.status,headers:u,body:s}}return s}let c=ho(s)??`HTTP ${e.status}`;if(zn(e.status,s),uo(e.status,s,t),e.status===401){if(t.agentKeyAuth)throw new l("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let u=t.authBearing?"auth.token_expired":"input.invalid";throw new l(u,c,{status:401,body:s})}throw e.status===403?new l("auth.permission_denied",c,{status:403,body:s}):e.status===404?new l("not_found",c,{status:404,body:s}):e.status===429?new l("rate_limited",c,{status:429,body:s}):e.status>=500?new l("backend.internal",c,{status:e.status,body:s}):new l("input.invalid",c,{status:e.status,body:s})}function qn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var lo=2014,Yn=2004;function Wn(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 co(e){return Wn(e,lo)}function uo(e,t,n){if(!(e>=200&&e<300)&&n.authBearing&&!(e===401&&n.agentKeyAuth)&&Wn(t,Yn))throw new l("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${ce()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Yn})}var fo=1e4;async function po(e,t=fo){if(e.status>=200&&e.status<300)return"";try{return await bt(e,St,{timeoutMs:t})}catch{return""}}function zn(e,t){if(!(e>=200&&e<300)&&co(t))throw new l("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?Mn(t):t})}function ho(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 go=/^\/(api\/)?(v1\/)?public\//;function kt(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&go.test(n),i=n&&At(n),o=r&&!i&&!t.forceAuth;if(e.token)return new K({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new K({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new K({apiBase:e.apiBase,tokenStore:vn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new K({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var mo=new Set;var _o=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"]),Jn=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","wallet:all","claim_link:read_only","claim_link:all","store:read_only","store:all"]),Vn=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Lt(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}var yo=new Set(["cli_op:all"]),wo=new Set([...yo].map(Lt));var ha=new Set([...[..._o,...Jn,...mo].map(Lt),...Vn,...wo]);var Eo=new Set([8100]),Oa=new Set([...Eo,3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);var Xn="/api/v1/public/claim-links";var So=1e4;function Zn(e,t){let n=encodeURIComponent(e);return t==="claim"?`${Xn}/${n}:claim`:`${Xn}/${n}`}function Ce(e){let t=e["claim-token"],n=e["claim-url"];if((t===void 0?0:1)+(n===void 0?0:1)!=1)throw new l("input.invalid","Pass exactly one of --claim-token or --claim-url.");if(t!==void 0){let i=t.trim();if(!i)throw new l("input.invalid","--claim-token is empty.");return Tt(i,"--claim-token")}let r=n.trim();if(!r)throw new l("input.invalid","--claim-url is empty.");return Tt(bo(r),"--claim-url")}async function Qn(e,t,n=So){let r=e["claim-url"]?.trim();if(!r)return Ce(e);let i;try{i=new URL(r)}catch{return Ce(e)}let o=/^\/s\/([^/]+)\/?$/.exec(i.pathname);if(!o||e["claim-token"]!==void 0)return Ce(e);R(t);let s=new URL(t).origin;if(i.origin!==s||i.username||i.password)throw new l("input.invalid","--claim-url short links must use the configured API origin and must not contain credentials.");let c;try{c=decodeURIComponent(o[1])}catch{throw new l("input.invalid","--claim-url contains a malformed short-link code.")}if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw new l("input.invalid","--claim-url contains a malformed short-link code.");let u=new URL(`/s/${encodeURIComponent(c)}`,s),d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},n);p.unref?.();let E;try{E=await fetch(u,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},credentials:"omit",redirect:"manual",referrerPolicy:"no-referrer",signal:d.signal})}catch{throw new l(f?"transport.timeout":"transport.network",f?`Claim short-link resolution timed out after ${n}ms.`:"Network error while resolving the claim short link.",f?{timeout_ms:n}:void 0)}finally{clearTimeout(p)}let g=E.headers.get("location");try{E.body?.cancel().catch(()=>{})}catch{}if(E.status!==302||!g)throw new l("transport.network","Claim short-link resolution expected one HTTP 302 redirect to the canonical claim URL.",{status:E.status});let m;try{m=new URL(g,u)}catch{throw new l("transport.network","Claim short-link redirect was malformed.")}if(m.origin!==s||m.username||m.password||m.search||m.hash)throw new l("transport.network","Claim short-link redirect did not stay on the configured API origin.");let S=/^\/claim\/([^/]+)\/?$/.exec(m.pathname);if(!S)throw new l("transport.network","Claim short-link redirect did not target the canonical claim route.");let N;try{N=decodeURIComponent(S[1])}catch{throw new l("transport.network","Claim short-link redirect contained a malformed token.")}return Tt(N,"--claim-url")}function Tt(e,t){if(!/^[A-Za-z0-9_-]{16,256}$/.test(e))throw new l("input.invalid",t==="--claim-url"?"--claim-url does not contain a usable claim token. Paste the full claim link exactly as you received it, without truncating or re-typing it.":"--claim-token must be 16-256 characters, using only letters, digits, `-` and `_`.");return e}function bo(e){let t;try{t=new URL(e)}catch(s){throw new l("input.invalid",`--claim-url is not a valid URL: ${s.message}`)}let n=t.pathname.split("/").filter(Boolean);if(n.length===0)throw new l("input.invalid","--claim-url does not contain a token path segment.");let r=n.lastIndexOf("claim-links"),i=r!==-1&&r+1<n.length?n[r+1]:n[n.length-1],o=i.endsWith(":claim")?i.slice(0,-6):i;try{return decodeURIComponent(o)}catch{throw new l("input.invalid","--claim-url contains a malformed percent-encoded token segment. Paste the full claim link exactly as you received it.")}}function er(e){if(!e||typeof e!="object")return e;let t=e;if("code"in t&&t.code!==0)throw new l("input.invalid","Backend returned a non-success API envelope.",{code:t.code,errors:t.errors});return"data"in t?t.data:e}function tr(e,t=""){let n=C()==="public"?"":" [--token <value>] [--api-base <value>]";return`claim-link ${e} (--claim-token <value> | --claim-url <value>) [--json] [--profile <value>]${n} [--insecure-storage]`+t}var Ao=["claimed","not_claimable","expired","payout_pending","payout_failed"],ko=64,Lo=128,To=/^[a-z][a-z0-9_]*$/,Io=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function nr(e){return typeof e=="string"&&e.length>0&&e.length<=ko&&To.test(e)}function rr(e){return typeof e=="string"&&e.length>0&&e.length<=Lo&&Io.test(e)}function ir(e){return typeof e=="string"&&hn.test(e)}function Oo(e){let t={outcome_ambiguous:!0};if(typeof e!="object"||e===null)return t;let n=e;return nr(n.outcome)&&(t.outcome=n.outcome),rr(n.claim_link_id)&&(t.claim_link_id=n.claim_link_id),n.claim_tx_hash===null?t.claim_tx_hash=null:ir(n.claim_tx_hash)&&(t.claim_tx_hash=n.claim_tx_hash),t}function Co(e){if(typeof e!="object"||e===null)return!1;let t=e;return nr(t.outcome)&&Ao.includes(t.outcome)&&rr(t.claim_link_id)&&(t.claim_tx_hash===void 0||t.claim_tx_hash===null||ir(t.claim_tx_hash))}function or(e){if(!Co(e))throw new l("backend.internal","Claim endpoint returned an invalid result; the claim outcome is unknown. Inspect the Claim Link before retrying.",Oo(e));if(e.outcome==="claimed")return e;let t={outcome:e.outcome,claim_link_id:e.claim_link_id,claim_tx_hash:e.claim_tx_hash??null};throw e.outcome==="payout_pending"||e.outcome==="payout_failed"?new l("claim.payout_ambiguous",`Claim payout is ${e.outcome==="payout_pending"?"still pending":"not proven successful"}. Do not submit another claim; reconcile this Claim Link first.`,{...t,outcome_ambiguous:!0}):new l(e.outcome==="expired"?"claim.expired":"claim.not_claimable",e.outcome==="expired"?"Claim did not complete because this Claim Link has expired.":"Claim did not complete because this Claim Link is not claimable in its current state. Inspect its status before deciding whether to retry.",t)}var ve=class e extends re{static description="Claim a Claim Link. Path-A claims (no AllScale account sign-in) require --to; authenticated business receivers can use --to-wallet. Only an on-chain-proven claimed outcome exits 0.";static examples=[`$ allscale claim-link claim --claim-token claim-token-from-share-link --to ${rt}`,"$ allscale claim-link claim --claim-url https://app.allscale.io/claim/claim-token-from-share-link --to-wallet"];static usage=tr("claim"," (--to <value> | --to-wallet)");static requiresInput=!0;static flags={"claim-token":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Raw bearer claim token. Secret: prefer env/history-safe invocation."}),"claim-url":$.Flags.string({helpGroup:"REQUIRED SOURCE (ONE OF)",description:"Canonical claim URL, or a same-origin /s/ short URL resolved with one unauthenticated 302."}),to:$.Flags.string({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Receiver EVM address for Path-A claims (no AllScale account sign-in). This does not make the transaction anonymous: network, request, compliance, and public blockchain data may still be processed or observable.",exclusive:["to-wallet"]}),"to-wallet":$.Flags.boolean({helpGroup:"REQUIRED DESTINATION (ONE OF)",description:"Claim into the authenticated receiver business's AllScale wallet for the link's chain. Requires login/token.",default:!1,exclusive:["to"]}),...re.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=await Qn(t,n.apiBase),i=Zn(r,"claim"),o,s;if(t["to-wallet"])o={},s="required";else{let d=t.to?.trim();if(!d)throw new l("input.invalid","Pass --to <0x address> or --to-wallet.");if(!cn(d))throw new l("input.invalid",`--to is not a valid EVM address: '${d}' (expected 0x followed by 40 hex characters).`);if(dn(d))throw new l("input.invalid","--to must not be the zero or burn address; funds claimed to it cannot be recovered.");un(d),o={receiver_address:d},s="none"}let u=await kt(n,{pathHint:i,forceAuth:s==="required"}).request({method:"POST",path:i,body:o,auth:s});return or(er(u))}};0&&(module.exports={requireSuccessfulClaim});
17
17
  //# sourceMappingURL=claim.js.map