@allscale/cli 0.1.0

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 (38) hide show
  1. package/README.md +482 -0
  2. package/bin/dev.js +11 -0
  3. package/bin/run-oclif.js +69 -0
  4. package/bin/run.js +6 -0
  5. package/dist/commands/build-info.js +16 -0
  6. package/dist/commands/claim-link/claim.js +17 -0
  7. package/dist/commands/claim-link/create.js +75 -0
  8. package/dist/commands/claim-link/get.js +18 -0
  9. package/dist/commands/claim-link/list.js +18 -0
  10. package/dist/commands/claim-link/preview.js +18 -0
  11. package/dist/commands/claim-link/status.js +17 -0
  12. package/dist/commands/describe.js +16 -0
  13. package/dist/commands/device-login.js +40 -0
  14. package/dist/commands/invoice/get.js +18 -0
  15. package/dist/commands/invoice/list.js +19 -0
  16. package/dist/commands/invoice/pay.js +66 -0
  17. package/dist/commands/invoice/received.js +19 -0
  18. package/dist/commands/invoice/send.js +167 -0
  19. package/dist/commands/invoice/sent.js +18 -0
  20. package/dist/commands/invoice/update.js +18 -0
  21. package/dist/commands/logout.js +17 -0
  22. package/dist/commands/operations.js +16 -0
  23. package/dist/commands/otp-login.js +23 -0
  24. package/dist/commands/otp-send.js +17 -0
  25. package/dist/commands/payout/send.js +23 -0
  26. package/dist/commands/payout/status.js +18 -0
  27. package/dist/commands/scope.js +22 -0
  28. package/dist/commands/store/create.js +28 -0
  29. package/dist/commands/transaction/get.js +18 -0
  30. package/dist/commands/transaction/list.js +18 -0
  31. package/dist/commands/wallet/list.js +18 -0
  32. package/dist/commands/wallet/send.js +63 -0
  33. package/dist/commands/whoami.js +18 -0
  34. package/dist/hooks/version-suffix.js +2 -0
  35. package/dist/index.js +17 -0
  36. package/dist/lib/help.js +3 -0
  37. package/oclif.manifest.json +3329 -0
  38. package/package.json +135 -0
@@ -0,0 +1,16 @@
1
+ "use strict";var ze=Object.create;var k=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Ze=(e,n)=>{for(var t in n)k(e,t,{get:n[t],enumerable:!0})},pe=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of qe(n))!Ve.call(e,i)&&i!==t&&k(e,i,{get:()=>n[i],enumerable:!(r=Je(n,i))||r.enumerable});return e};var g=(e,n,t)=>(t=e!=null?ze(We(e)):{},pe(n||!e||!e.__esModule?k(t,"default",{value:e,enumerable:!0}):t,e)),Xe=e=>pe(k({},"__esModule",{value:!0}),e);var Wn={};Ze(Wn,{default:()=>Y});module.exports=Xe(Wn);var A=require("@oclif/core");var fe="public",ge="https://app.allscale.io";var _e=["https://app.allscale.io"];var M="Override the API base URL (public builds accept only https://app.allscale.io)";var K="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Ae(e){try{let n=new URL(e);return n.username.length>0||n.password.length>0?null:n.protocol==="https:"?n:null}catch{return null}}function he(e){return Ae(e)!==null}function H(e){let n=Ae(e);return n!==null&&_e.includes(n.origin)}function h(){return"".trim()||void 0}function E(){return"public"}function S(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function z(e){try{return new URL(e).origin}catch{return null}}function m(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return j()}function j(){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:a,keyId:u}=o;if(typeof s!="string"||s.trim().length===0||typeof a!="string"||a.trim().length===0)continue;let f=typeof u=="string"?u.trim():"";i.push({base:s.trim(),key:a,keyId:f.length>0?f:"cli-1"})}return i}catch{return[]}let n=process.env.ALLSCALE_SIGNING_KEY??"",t=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(n.trim().length>0&&t.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:t,key:n,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Ee="allscale device-login";var Qe={"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},en=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 W(e){return(typeof e=="string"?e:String(e??"")).replace(en,"")}var nn=64;function J(e,n=new Map,t=0){if(typeof e=="string")return W(e);if(e===null||typeof e!="object")return e;let r=n.get(e);if(r!==void 0)return r;if(t>=nn)return e;if(Array.isArray(e)){let s=[];n.set(e,s);for(let a of e)s.push(J(a,n,t+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};n.set(e,o);for(let[s,a]of Object.entries(e))Object.defineProperty(o,s,{value:J(a,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(n,t,r){super(W(t)),this.code=n,this.details=r&&J(r),this.name="AllscaleError"}get exitCode(){return Qe[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function me(e){if(e instanceof c)return e;if(e instanceof Error){if(on(e)){let n=an(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new c("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var tn=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),rn=[/^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 on(e){if(sn(e))return!0;let n=e.name??"";return tn.has(n)?n==="CLIError"?q(e,"parse")||Se(e.message):!0:Se(e.message)}function sn(e){if(!q(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&q(e,"parse")}function Se(e){return e?W(e).split(`
2
+ `).some(n=>rn.some(t=>t.test(n.trim()))):!1}function q(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function an(e){let n=e,t={};for(let r of["code","exitCode","suggestions","ref"])n[r]!==void 0&&(t[r]=n[r]);return t}function Le(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var l=g(require("fs")),v=g(require("path")),Oe=g(require("crypto"));var ln="...<truncated>",cn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,un=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,ne=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,V=String.raw`(?:proxy[_-]?)?authorization`,dn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${V}"|'${V}'|${V})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${ne}`,"gi"),pn=/\b(https?:\/\/)[^\s/?#]+@/gi,Z=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)`,fn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Z}"|'${Z}'|${Z})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ne}`,"gi"),X=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)`,gn=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${X}"|'${X}'|${X})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${ne}`,"g");function Ie(e){return e.replace(pn,"$1<redacted>@").replace(cn,"<redacted-jwt>").replace(dn,"$1$2$3<redacted>").replace(fn,"$1$2<redacted>").replace(gn,"$1$2<redacted>").replace(un,"Bearer <redacted>")}function be(e){let n="";for(let t of e){let r=t.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;n+=i?`\\u${r.toString(16).padStart(4,"0")}`:t}return n}function ye(e,n,t=ln){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let r=Buffer.byteLength(t,"utf8");if(r>=n){let a="",u=0;for(let f of t){let L=Buffer.byteLength(f,"utf8");if(u+L>n)break;a+=f,u+=L}return a}let i=n-r,o="",s=0;for(let a of e){let u=Buffer.byteLength(a,"utf8");if(s+u>i)break;o+=a,s+=u}return`${o}${t}`}function p(e,n=16384){return ye(be(Ie(e)),n)}var Q=100,_n=8,An=8*1024;function x(){return{remaining:An}}function ee(e,n){let t=Math.min(16384,n.remaining),r=ye(e,t);return n.remaining-=Buffer.byteLength(r,"utf8"),r}function I(e,n,t=0,r={}){if(t>_n)return ee("<truncated>",n);if(typeof e=="string"){let i=Ie(e);return ee(r.escapeControls?be(i):i,n)}if(Array.isArray(e)){let i=e.slice(0,Q),o=i.map(s=>I(s,n,t+1,r));return e.length>i.length&&o.push(ee(`<${e.length-i.length} more items truncated>`,n)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,a]of o.slice(0,Q))i[s]=I(a,n,t+1,r);return o.length>Q&&(i.output_truncated=!0),i}return e}var te=require("process");var re=!1;function ie(e){re=e}function we(){return re}var Te="1";function y(e,n){if(re){let t={...e};delete t.version;let r=x(),i={event:t.event,...t},o=I(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:Te,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Te,event:o.event,output_truncated:!0})),te.stderr.write(`${s}
4
+ `)}else te.stderr.write(n)}var Ce="2",T=null,d=null,w=!1;function hn(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let n=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(n){let t=new Date().toISOString().replace(/[:.]/g,"-"),r=Oe.randomBytes(4).toString("hex");return v.join(n,`allscale-output-${t}-${r}.ndjson`)}return null}var oe=64*1024*1024,En=null;function Re(){if(w)return;let e=hn();if(!e)return;T=null;let n=null;try{if((En??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let t=v.dirname(e);if(l.mkdirSync(t,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let a=l.statSync(t),u=a.mode&511;if(!a.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=l.constants.O_NOFOLLOW??0;n=l.openSync(e,l.constants.O_APPEND|l.constants.O_CREAT|l.constants.O_WRONLY|(l.constants.O_NONBLOCK??0)|r,384);let i=l.fstatSync(n),o=l.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`);l.fchmodSync(n,384)}catch(t){if(n!==null)try{l.closeSync(n)}catch{}y({event:"sidecar_disabled",reason:"open_failed",detail:p(`sidecar path '${e}' could not be opened safely (${t.message})`)},`${p(`[allscale] sidecar path '${e}' could not be opened safely (${t.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}T=e,d=n,w=!0}var Sn=[/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 mn(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Sn.some(t=>t.test(n))}function Ln(e){try{let n=new URL(e),t=n.username.length>0||n.password.length>0;t&&(n.username="",n.password="");let r=n.pathname;n.pathname=In(n.pathname);let i=t;n.pathname!==r&&(i=!0);for(let[o]of n.searchParams)mn(o)&&(n.searchParams.set(o,"<redacted>"),i=!0);return i?n.toString():e}catch{return e}}function In(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function bn(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ln(e.url)}:e}function yn(e){let n=new Date().toISOString(),t=e,{type:r,...i}=t,o=I(i,x()),s=JSON.stringify({version:Ce,timestamp:n,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Ce,timestamp:n,type:r,output_truncated:!0})),s}function R(e){if(!w||!T||d===null)return;let n=bn(e),t=yn(n);try{if(l.fstatSync(d).size+Buffer.byteLength(t,"utf8")+1>oe){w=!1;try{l.closeSync(d)}catch{}d=null,y({event:"sidecar_disabled",reason:"size_limit",...T===null?{}:{path:p(T)},max_bytes:oe},`${p(`[allscale] sidecar exceeded ${oe} bytes; disabling it for the rest of this run. Rotate or remove ${T}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}l.appendFileSync(d,`${t}
7
+ `)}catch(r){if(w=!1,d!==null){try{l.closeSync(d)}catch{}d=null}try{y({event:"sidecar_disabled",reason:"write_failed",detail:p(r.message)},`${p(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}function Ne(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function U(){if(w=!1,d!==null){try{l.closeSync(d)}catch{}d=null}}function Pe(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Ne()||!n}var N=h()??ge,P={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 D(e){return he(e)?new URL(e).origin:null}function _(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Be(){let e=process.env[P.TOKEN]?.trim();return e&&e.length>0?e:void 0}function se(){let e=process.env[P.PROFILE]?.trim();return e&&e.length>0?e:void 0}function $(){let e=process.env[P.API_BASE]?.trim();return e&&e.length>0?e:void 0}function ke(){let e=process.env[P.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function xe(){let e=process.env[P.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ve(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:r,profileApiBaseSource:i}=e;if(h()===void 0&&N!==""&&"".length!==0&&!t&&i!=="explicit"&&r===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${N} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
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: ${Ee} --api-base ${N}
14
+ `}var O=g(require("fs")),Ue=g(require("os")),ae=g(require("path")),le=g(require("@iarna/toml"));var Cn=".allscale",On="config.toml";function Rn(){return ae.join(Ue.homedir(),Cn)}function Nn(){return ae.join(Rn(),On)}function De(){let e=Nn();if(!O.existsSync(e))return{};let n=O.readFileSync(e,"utf-8");try{return le.parse(n)}catch(t){throw new c("internal",`Failed to parse ${e}: ${t.message}`)}}function $e(e,n){return e.profile?.[n]}function Ge(e,n,t){let r=n??t??e.default??"default";if(r.includes(":"))throw new c("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function ce(e){if(!H(e))throw new c("input.invalid",`Refusing to send credentials to API base ${_(e)}. `+K)}function Fe(e){let n=h();if(n===void 0||S(e))return;let t=D(e),r=m();if(r.length>0){let o=r.map(a=>D(a.base)).filter(a=>a!==null);if(t!==null&&o.includes(t))return;let s=r.map(a=>_(a.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${_(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=D(n);if(!(t!==null&&t===i))throw new c("input.invalid",`Refusing to send to ${_(e)} \u2014 this build only signs for ${_(n)}. Re-login against this build's environment, or use a build for that one.`)}var Pn=require("@noble/hashes/sha3");var Ye=["USDT","USDC"];var Ut=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var Me=require("@oclif/core"),B=class e extends A.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:A.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:A.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:E()==="public"}),"api-base":A.Flags.string({description:M,helpGroup:"GLOBAL",hidden:E()==="public"}),"insecure-storage":A.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{ie(this.jsonEnabled()),Re(),R({type:"session-start",command:this.id??"",argv:kn(this.argv)});let n=this.constructor;if(E()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new c("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 c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!n.isLocalOnly&&$()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(n.requiresEscapeHatch&&!xe())throw this.argv.length>0&&await this.parse(),new c("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 t=Pe(this.jsonEnabled()),r=this.argv.length===0&&!t&&Yn(n)?this.config.findCommand(this.id??""):void 0;if(r){U();let o=await(0,A.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 R({type:"command-end",ok:!0}),U(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||Le(i),{data:i})}catch(n){let t=me(n);R({type:"error",code:t.code,message:p(t.message)}),R({type:"command-end",ok:!1,exitCode:t.exitCode}),U(),this.emitError(t),process.exitCode=t.exitCode;return}finally{ie(!1)}}resolveSessionApiBaseChain(n){let t=De(),r=n.profile??void 0,i=n["api-base"]??void 0,o=r!==void 0||se()!==void 0,s=Ge(t,r,se()),a=$e(t,s),u=i??$(),f=u??a?.api_base??N,L=ve({resolvedApiBase:f,fromExplicitOverride:u!==void 0,profileApiBase:a?.api_base,profileApiBaseSource:a?.api_base_source});return L&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,y({event:"legacy_staging_profile",api_base:f,profile:s},L)),{apiBase:f,explicitApiBase:u,profileApiBase:a?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||ce(t),t}resolveContext(n){if(E()==="public"){if(n.token!==void 0)throw new c("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(n["api-base"]!==void 0)throw new c("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&$()!==void 0)throw new c("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let t=n.token??void 0,r=!!n["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:a,profileExplicit:u}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(ce(i),Fe(i)),{apiBase:i,profile:s,token:t??Be(),insecureStorage:r||ke(),apiBaseSource:o!==void 0?"explicit":a!==void 0?"profile":"default",profileExplicit:u}}emitError(n){process.stderr.write(`${Fn(n)}
15
+ `)}},F=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"]),Bn=new Set(Array.from(F).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function kn(e){let n=[];for(let t=0;t<e.length;t+=1){let r=e[t];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(F.has(o)){n.push(`${o}=<redacted>`);continue}}}if(F.has(r)){n.push(r),t+1<e.length&&(F.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Bn.has(i)){n.push(`${i}<redacted>`);continue}}n.push(r)}return n}var xn=/(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 vn(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xn.test(n)}var Un=/_(removed|cleared|count|total)$/i;function Dn(e,n){return typeof n=="number"&&Un.test(e)}var $n=new Set(Ye);function Gn(e,n){return e==="token_symbol"&&typeof n=="string"&&$n.has(n)}var G=100;function ue(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,G),r=t.map(i=>ue(i,n+1));return e.length>t.length&&r.push(`<${e.length-t.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let t=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,G))t[i]=vn(i)&&!Dn(i,o)&&!Gn(i,o)?"<redacted>":ue(o,n+1);if(r.length>G){let i="<truncated>";for(;i in t;)i=`<${i}>`;t[i]=`${r.length-G} more keys`}return t}return typeof e=="string"?p(e):e}function Fn(e){let n=we()?void 0:2,t=ue(e.toJSON()),r=JSON.stringify(t,null,n);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:p(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function Yn(e){if(e.requiresInput===!0)return!0;let n=i=>typeof i=="object"&&i!==null&&i.required===!0,t=e.flags??{},r=e.args??{};return Object.values(t).some(i=>n(i))||Object.values(r).some(i=>n(i))}var Mn=g(require("crypto")),Kn=g(require("fs")),Hn=g(require("path"));var de="cli-1",jn="aScaLe_cli_obf_v1",zn="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Jn(e,n){let t=Buffer.from(e,"base64"),r=Buffer.from(n,"utf8"),i=Buffer.alloc(t.length);for(let o=0;o<t.length;o++)i[o]=t[o]^r[o%r.length];return i.toString("utf8")}var qn=Jn(zn,jn),Xt=`Bearer ${qn}`;function Ke(e,n){let t=z(e);if(t!==null)return n.find(r=>z(r.base)===t)}function He(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return!0;let n=m();if(n.length>0){if(e===void 0||Ke(e,n))return!0;if(S(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?!0:S(n[0].base)}return!1}let t=process.env.ALLSCALE_SIGNING_KEY;return!!(t&&t.trim().length>0)}function je(e){{let r="cli-1".trim();if(r.length>0)return r}let n=m();if(n.length>0){let r=e!==void 0?Ke(e,n):void 0;if(r)return r.keyId;if(e!==void 0&&S(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():de}if(!S(n[0].base))return de}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():de}var Y=class e extends B{static isLocalOnly=!0;static description="Show which API base (if any) this build is bound to, and its signing-key id. Never prints the signing key itself \u2014 only its (non-secret, already-forgeable) id.";static examples=["$ allscale build-info"];static flags={...B.baseFlags};async runCommand(){await this.parse(e);let n=h();return{target:E(),api_base:n===void 0?null:_(n),bound:n!==void 0,signing_key_id:He()?je():null,endpoints:m().map(t=>({base:_(t.base),key_id:t.keyId}))}}};
16
+ //# sourceMappingURL=build-info.js.map
@@ -0,0 +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,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
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});
17
+ //# sourceMappingURL=claim.js.map
@@ -0,0 +1,75 @@
1
+ "use strict";var Yr=Object.create;var _e=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var jr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var Jr=(e,t)=>{for(var n in t)_e(e,n,{get:t[n],enumerable:!0})},Ft=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jr(t))!zr.call(e,i)&&i!==n&&_e(e,i,{get:()=>t[i],enumerable:!(r=qr(t,i))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Yr(Wr(e)):{},Ft(t||!e||!e.__esModule?_e(n,"default",{value:e,enumerable:!0}):n,e)),Xr=e=>Ft(_e({},"__esModule",{value:!0}),e);var Vs={};Jr(Vs,{default:()=>Ge});module.exports=Xr(Vs);var v=require("@oclif/core");var Mt="public",Gt="https://app.allscale.io";var ye=["https://app.allscale.io"];var Ke="Override the API base URL (public builds accept only https://app.allscale.io)";var Ye="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function Ht(e){try{let t=new URL(e);return t.username.length>0||t.password.length>0?null:t.protocol==="https:"?t:null}catch{return null}}function Kt(e){return Ht(e)!==null}function W(e){let t=Ht(e);return t!==null&&ye.includes(t.origin)}function qe(e){return W(e)}function ie(){return"".trim()||void 0}function oe(){return"public"}function $(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function We(e){try{return new URL(e).origin}catch{return null}}function se(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return je()}function je(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:s,key:c,keyId:l}=o;if(typeof s!="string"||s.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let d=typeof l=="string"?l.trim():"";i.push({base:s.trim(),key:c,keyId:d.length>0?d:"cli-1"})}return i}catch{return[]}let t=process.env.ALLSCALE_SIGNING_KEY??"",n=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(t.trim().length>0&&n.length>0){let r=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:n,key:t,keyId:r&&r.length>0?r:"cli-1"}]}return[]}var Yt="`allscale device-login` (or `allscale otp-login` for headless automation)";var qt="drop `--headless` and use the browser-bridge flow with an agent-key session.",jt="allscale device-login";var Zr="device-login";function ae(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Xe(){return Yt}function zt(e,t="default"){return t==="headless"?`No tokens stored for profile '${e}'. Headless signing needs the user token of a legacy JWT session, which agent keys do not carry \u2014 `+qt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${ae()}\` for headless automation`+"."}function Jt(e,t){let n=t.length>0?`Saved profiles: ${t.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${n} Check the spelling first; to deliberately create '${e}', run \`allscale ${Zr} --profile ${e}\`.`}var Qr={"input.invalid":2,"storage.unavailable":2,"transport.network":3,"transport.timeout":3,"transport.response_too_large":2,"auth.no_token":4,"auth.unknown_profile":2,"auth.token_expired":5,"auth.credential_changed":3,"auth.permission_denied":6,"auth.signature_rejected":11,"claim.not_claimable":12,"claim.expired":12,"claim.payout_ambiguous":9,"claim_link.funding_ambiguous":9,"claim_link.intent_conflict":2,"claim_link.browser_cancelled":12,"user.cancelled":12,"signing.key_unavailable":2,not_found:7,rate_limited:8,"backend.internal":9,"wallet.requires_browser_auth":6,"wallet.bridge_timeout":3,"wallet.bridge_invalid_response":9,"wallet.headless_not_supported":6,"wallet.headless_setup_required":6,"wallet.headless_config_missing":6,"wallet.headless_sign_failed":9,"raw.disabled":10,internal:1},ei=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Ve(e){return(typeof e=="string"?e:String(e??"")).replace(ei,"")}var ti=64;function ze(e,t=new Map,n=0){if(typeof e=="string")return Ve(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=ti)return e;if(Array.isArray(e)){let s=[];t.set(e,s);for(let c of e)s.push(ze(c,t,n+1));return s}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[s,c]of Object.entries(e))Object.defineProperty(o,s,{value:ze(c,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(t,n,r){super(Ve(n)),this.code=t,this.details=r&&ze(r),this.name="AllscaleError"}get exitCode(){return Qr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Xt(e){if(e instanceof a)return e;if(e instanceof Error){if(ii(e)){let t=si(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new a("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var ni=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),ri=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function ii(e){if(oi(e))return!0;let t=e.name??"";return ni.has(t)?t==="CLIError"?Je(e,"parse")||Wt(e.message):!0:Wt(e.message)}function oi(e){if(!Je(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&Je(e,"parse")}function Wt(e){return e?Ve(e).split(`
2
+ `).some(t=>ri.some(n=>n.test(t.trim()))):!1}function Je(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function si(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Vt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var y=A(require("fs")),ke=A(require("path")),on=A(require("crypto"));var ai="...<truncated>",li=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,ci=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,rt=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ze=String.raw`(?:proxy[_-]?)?authorization`,ui=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ze}"|'${Ze}'|${Ze})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${rt}`,"gi"),di=/\b(https?:\/\/)[^\s/?#]+@/gi,Qe=String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|(?:[A-Za-z0-9]+[_-])*(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,pi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Qe}"|'${Qe}'|${Qe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"gi"),et=String.raw`(?:[A-Za-z0-9]+(?:Token|Secret)|[Oo][Tt][Pp]Code|[Ss]essionId|(?:api|API|access|Access|private|Private|signing|Signing)Key|[Cc]laimUrl)`,fi=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${et}"|'${et}'|${et})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${rt}`,"g");function Zt(e){return e.replace(di,"$1<redacted>@").replace(li,"<redacted-jwt>").replace(ui,"$1$2$3<redacted>").replace(pi,"$1$2<redacted>").replace(fi,"$1$2<redacted>").replace(ci,"Bearer <redacted>")}function Qt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function en(e,t,n=ai){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let c="",l=0;for(let d of n){let f=Buffer.byteLength(d,"utf8");if(l+f>t)break;c+=d,l+=f}return c}let i=t-r,o="",s=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(s+l>i)break;o+=c,s+=l}return`${o}${n}`}function N(e,t=16384){return en(Qt(Zt(e)),t)}var tt=100,mi=8,gi=8*1024;function we(){return{remaining:gi}}function nt(e,t){let n=Math.min(16384,t.remaining),r=en(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function z(e,t,n=0,r={}){if(n>mi)return nt("<truncated>",t);if(typeof e=="string"){let i=Zt(e);return nt(r.escapeControls?Qt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,tt),o=i.map(s=>z(s,t,n+1,r));return e.length>i.length&&o.push(nt(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[s,c]of o.slice(0,tt))i[s]=z(c,t,n+1,r);return o.length>tt&&(i.output_truncated=!0),i}return e}var it=require("process");var ot=!1;function st(e){ot=e}function nn(){return ot}var tn="1";function X(e,t){if(ot){let n={...e};delete n.version;let r=we(),i={event:n.event,...n},o=z(i,r,0,{escapeControls:!0}),s=JSON.stringify({version:tn,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:tn,event:o.event,output_truncated:!0})),it.stderr.write(`${s}
4
+ `)}else it.stderr.write(t)}var rn="2",V=null,x=null,Z=!1;function hi(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=on.randomBytes(4).toString("hex");return ke.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var at=64*1024*1024,_i=null;function sn(){if(Z)return;let e=hi();if(!e)return;V=null;let t=null;try{if((_i??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=ke.dirname(e);if(y.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let c=y.statSync(n),l=c.mode&511;if(!c.isDirectory()||(l&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${l.toString(8).padStart(3,"0")}`)}let r=y.constants.O_NOFOLLOW??0;t=y.openSync(e,y.constants.O_APPEND|y.constants.O_CREAT|y.constants.O_WRONLY|(y.constants.O_NONBLOCK??0)|r,384);let i=y.fstatSync(t),o=y.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let s=i.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);y.fchmodSync(t,384)}catch(n){if(t!==null)try{y.closeSync(t)}catch{}X({event:"sidecar_disabled",reason:"open_failed",detail:N(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${N(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}V=e,x=t,Z=!0}var yi=[/password/i,/secret/i,/token/i,/api[_-]?key/i,/signing[_-]?key/i,/private[_-]?key/i,/credential/i,/otp/i,/signature/i,/(?:^|[_-])sig(?:[_-]|$)/i,/hmac/i,/session[_-]?id/i,/nonce/i,/bearer/i,/authorization/i,/^code$/i,/^auth$/i,/^state$/i];function wi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return yi.some(n=>n.test(t))}function an(e){try{let t=new URL(e),n=t.username.length>0||t.password.length>0;n&&(t.username="",t.password="");let r=t.pathname;t.pathname=ki(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)wi(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function ki(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function bi(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:an(e.url)}:e}function Si(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=z(i,we()),s=JSON.stringify({version:rn,timestamp:t,type:r,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:rn,timestamp:t,type:r,output_truncated:!0})),s}function _(e){if(!Z||!V||x===null)return;let t=bi(e),n=Si(t);try{if(y.fstatSync(x).size+Buffer.byteLength(n,"utf8")+1>at){Z=!1;try{y.closeSync(x)}catch{}x=null,X({event:"sidecar_disabled",reason:"size_limit",...V===null?{}:{path:N(V)},max_bytes:at},`${N(`[allscale] sidecar exceeded ${at} bytes; disabling it for the rest of this run. Rotate or remove ${V}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}y.appendFileSync(x,`${n}
7
+ `)}catch(r){if(Z=!1,x!==null){try{y.closeSync(x)}catch{}x=null}try{X({event:"sidecar_disabled",reason:"write_failed",detail:N(r.message)},`${N(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var D=an;function ln(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function be(){if(Z=!1,x!==null){try{y.closeSync(x)}catch{}x=null}}function cn(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||ln()||!t}var le=ie()??Gt,ee={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function U(e){return Kt(e)?new URL(e).origin:null}function L(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function un(){let e=process.env[ee.TOKEN]?.trim();return e&&e.length>0?e:void 0}function lt(){let e=process.env[ee.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Se(){let e=process.env[ee.API_BASE]?.trim();return e&&e.length>0?e:void 0}function dn(){let e=process.env[ee.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function pn(){let e=process.env[ee.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function fn(){let e=process.env[ee.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function mn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(ie()===void 0&&le!==""&&"".length!==0&&!n&&i!=="explicit"&&r===""&&t==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${le} (production), but a saved profile wins over the default,
10
+ so this session still uses staging. That pin was written before the default changed, so it may just be
11
+ the old default rather than a deliberate choice.
12
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
13
+ To move to production, run: ${jt} --api-base ${le}
14
+ `}var te=A(require("fs")),gn=A(require("os")),ct=A(require("path")),ut=A(require("@iarna/toml"));var Li=".allscale",Ti="config.toml";function dt(){return ct.join(gn.homedir(),Li)}function Ci(){return ct.join(dt(),Ti)}function Ee(){let e=Ci();if(!te.existsSync(e))return{};let t=te.readFileSync(e,"utf-8");try{return ut.parse(t)}catch(n){throw new a("internal",`Failed to parse ${e}: ${n.message}`)}}function hn(e){return Object.keys(e.profile??{}).sort()}function _n(e,t){return e.profile?.[t]}function yn(e,t,n){let r=t??n??e.default??"default";if(r.includes(":"))throw new a("input.invalid",`Invalid profile name '${r}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return r}function F(e){if(!W(e))throw new a("input.invalid",`Refusing to send credentials to API base ${L(e)}. `+Ye)}function pt(e,t){F(e);let n=U(e),r=typeof t=="string"?U(t):null;if(n&&r===n)return;let i=typeof t=="string"?L(t):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${L(e)} does not match their bound origin ${i}. Re-login against the intended API base before retrying.`)}function wn(e,t){let n=U(e),r=U(t);if(!(n&&r===n))throw new a("input.invalid",`Refusing API request to ${L(t)} because it is outside the configured API origin ${L(e)}.`)}function Ae(e){let t=ie();if(t===void 0||$(e))return;let n=U(e),r=se();if(r.length>0){let o=r.map(c=>U(c.base)).filter(c=>c!==null);if(n!==null&&o.includes(n))return;let s=r.map(c=>L(c.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${L(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=U(t);if(!(n!==null&&n===i))throw new a("input.invalid",`Refusing to send to ${L(e)} \u2014 this build only signs for ${L(t)}. Re-login against this build's environment, or use a build for that one.`)}var Ii=require("@noble/hashes/sha3");var Oi={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},kn=["ethereum","bsc","base","polygon","arbitrum","optimism"],Le=["USDT","USDC"];function bn(e){return Oi[e.toLowerCase()]??null}function Sn(e){let t=e.toUpperCase();return t==="USDT"?1:t==="USDC"?2:null}var va=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function En(e){return e===1?"USDT":"USDC"}var T=require("@oclif/core"),ce=class e extends v.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:v.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:v.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:oe()==="public"}),"api-base":v.Flags.string({description:Ke,helpGroup:"GLOBAL",hidden:oe()==="public"}),"insecure-storage":v.Flags.boolean({description:"Force POSIX plaintext token storage at ~/.allscale/credentials.json (mode 0600) instead of the OS keychain \u2014 for headless / CI / agent use. Unavailable on Windows because Node cannot verify owner-only ACL/link safety. Also via ALLSCALE_INSECURE_STORAGE=1.",default:!1,helpGroup:"GLOBAL"})};async run(){try{st(this.jsonEnabled()),sn(),_({type:"session-start",command:this.id??"",argv:Ni(this.argv)});let t=this.constructor;if(oe()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!t.isLocalOnly&&Se()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(t.requiresEscapeHatch&&!fn())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let n=cn(this.jsonEnabled()),r=this.argv.length===0&&!n&&Fi(t)?this.config.findCommand(this.id??""):void 0;if(r){be();let o=await(0,v.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return _({type:"command-end",ok:!0}),be(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Vt(i),{data:i})}catch(t){let n=Xt(t);_({type:"error",code:n.code,message:N(n.message)}),_({type:"command-end",ok:!1,exitCode:n.exitCode}),be(),this.emitError(n),process.exitCode=n.exitCode;return}finally{st(!1)}}resolveSessionApiBaseChain(t){let n=Ee(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||lt()!==void 0,s=yn(n,r,lt()),c=_n(n,s),l=i??Se(),d=l??c?.api_base??le,f=mn({resolvedApiBase:d,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,X({event:"legacy_staging_profile",api_base:d,profile:s},f)),{apiBase:d,explicitApiBase:l,profileApiBase:c?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||F(n),n}resolveContext(t){if(oe()==="public"){if(t.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(t["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Se()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:s,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(F(i),Ae(i)),{apiBase:i,profile:s,token:n??un(),insecureStorage:r||dn(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(t){process.stderr.write(`${$i(t)}
15
+ `)}},Ce=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Ri=new Set(Array.from(Ce).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Ni(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(Ce.has(o)){t.push(`${o}=<redacted>`);continue}}}if(Ce.has(r)){t.push(r),n+1<e.length&&(Ce.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Ri.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var xi=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Pi(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return xi.test(t)}var vi=/_(removed|cleared|count|total)$/i;function Bi(e,t){return typeof t=="number"&&vi.test(e)}var Di=new Set(Le);function Ui(e,t){return e==="token_symbol"&&typeof t=="string"&&Di.has(t)}var Te=100;function ft(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Te),r=n.map(i=>ft(i,t+1));return e.length>n.length&&r.push(`<${e.length-n.length} more items truncated>`),r}if(e!==null&&typeof e=="object"){let n=Object.create(null),r=Object.entries(e);for(let[i,o]of r.slice(0,Te))n[i]=Pi(i)&&!Bi(i,o)&&!Ui(i,o)?"<redacted>":ft(o,t+1);if(r.length>Te){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Te} more keys`}return n}return typeof e=="string"?N(e):e}function $i(e){let t=nn()?void 0:2,n=ft(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:N(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function Fi(e){if(e.requiresInput===!0)return!0;let t=i=>typeof i=="object"&&i!==null&&i.required===!0,n=e.flags??{},r=e.args??{};return Object.values(n).some(i=>t(i))||Object.values(r).some(i=>t(i))}var Ie=/^0x[0-9a-fA-F]{64}$/,Mi=["wallet.bridge_timeout","wallet.bridge_invalid_response","wallet.headless_sign_failed"];function An(e){return typeof e=="string"&&Mi.includes(e)}var dr=require("crypto"),E=require("process");var Un=A(require("path"));var ht=require("crypto"),u=A(require("fs")),b=A(require("path"));var Oe=1024*1024,Gi=5e3,Hi=20,Ki=3e4,mt=4096,Yi=new Int32Array(new SharedArrayBuffer(4)),ue=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Re(e){return e instanceof ue}var C=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},qi=null;function G(){return new a("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function Ne(){return(qi??process.platform)!=="win32"}function xn(){if(!Ne())throw G()}function Pn(e){try{return u.default.lstatSync(e),!1}catch(t){if(!k(t,"ENOENT"))throw t}try{let t=u.default.lstatSync(b.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(k(t,"ENOENT"))return!0;throw t}}function k(e,t){return typeof e=="object"&&e!==null&&e.code===t}function de(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function pe(e,t){return e.dev===t.dev&&e.ino===t.ino}function ji(e){Atomics.wait(Yi,0,0,e)}function vn(e){try{return process.kill(e,0),!0}catch(t){return!k(t,"ESRCH")}}function Wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ln(e,t){let n=b.dirname(e);t&&u.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=u.default.lstatSync(n)}catch(o){if(!t&&k(o,"ENOENT"))return!1;throw o}if(r.isSymbolicLink()||!r.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let i=null;try{i=u.default.openSync(n,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0));let o=u.default.fstatSync(i),s=u.default.lstatSync(n);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!pe(o,s))throw new Error("credential-store parent changed while it was being inspected");de(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&b.basename(n)===".allscale"&&(u.default.fchmodSync(i,448),c=u.default.fstatSync(i)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&u.default.closeSync(i)}return!0}function B(e,t,n,r={}){if(!n.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let i;try{i=u.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&k(o,"ENOENT")?new C:o}if(!pe(n,i))throw r.retryOnPathChange?new C:new Error("credential-store target changed while it was being opened or is not a regular file");if(i.isSymbolicLink()||!i.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!r.allowMultipleLinks&&(n.nlink!==1||i.nlink!==1))throw new ue;if(de(n,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(t,384);let o=u.default.fstatSync(t);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return n}function zi(e,t){if(t.size>Oe)throw new Error("credential-store file exceeds the maximum supported size");let n=Buffer.alloc(Oe+1),r=0;for(;r<n.length;){let i=u.default.readSync(e,n,r,n.length-r,null);if(i===0)break;r+=i}if(r>Oe)throw new Error("credential-store file exceeds the maximum supported size");return n.subarray(0,r).toString("utf8")}function Tn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(k(i,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(k(o,"ENOENT"))return null;throw o}throw i}let n=u.default.fstatSync(t),r=B(e,t,n);return zi(t,r)}finally{t!==null&&u.default.closeSync(t)}}function Cn(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){if(k(i,"ENOENT")&&Pn(e))return;throw i}let n=u.default.fstatSync(t),r=B(e,t,n);H(e,r)}finally{t!==null&&u.default.closeSync(t)}Dn(b.dirname(e))}function Ji(e){let t;try{t=u.default.lstatSync(e)}catch(n){if(k(n,"ENOENT"))return;throw n}if(t.isSymbolicLink()||!t.isFile())throw new Error("credential-store replacement target must be a regular file");if(t.nlink!==1)throw new ue;de(t,"credential-store replacement target")}function Xi(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(k(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Bn(e,t){let n=0;for(;n<t.length;){let r=u.default.writeSync(e,t,n,t.length-n,null);if(!Number.isSafeInteger(r)||r<=0)throw new Error("credential-store temp file write made no progress");n+=r}}function Dn(e){if(process.platform==="win32")return;let t=null;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(t)}catch{}finally{if(t!==null)try{u.default.closeSync(t)}catch{}}}function Vi(e,t){let n=Buffer.from(t,"utf8");if(n.length>Oe)throw new Error("credential-store file exceeds the maximum supported size");let r=b.dirname(e),i=b.basename(e),o=null,s=null,c=!1;try{let l=Xi(r,i);o=l.fd,s=l.tempPath;let d=u.default.fstatSync(o);if((B(s,o,d).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Bn(o,n),u.default.fsyncSync(o),B(s,o,u.default.fstatSync(o));let p=o;o=null,u.default.closeSync(p),Ji(e),u.default.renameSync(s,e),c=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!c&&s!==null)try{u.default.unlinkSync(s)}catch{}}Dn(r)}function Zi(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock`)}function Qi(e){return b.join(b.dirname(e),`.${b.basename(e)}.lock-recovery`)}function eo(e,t){if(t.size>mt)return null;let n=Buffer.alloc(mt+1),r=0;for(;r<n.length;){let o=u.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>mt)return null;let i;try{i=JSON.parse(n.subarray(0,r).toString("utf8"))}catch{return null}return typeof i!="object"||i===null||!Number.isSafeInteger(i.pid)||(i.pid??0)<=0||typeof i.nonce!="string"||!/^[a-f0-9]{24}$/.test(i.nonce??"")||typeof i.target!="string"?null:i}function H(e,t){let n=u.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!pe(n,t))throw new Error("credential-store lock changed while it was being inspected");de(n,"credential-store lock"),u.default.unlinkSync(e)}function In(e,t){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(l){if(k(l,"ENOENT"))try{let d=u.default.lstatSync(e);throw d.isSymbolicLink()||!d.isFile()?new Error("credential-store lock must be a real regular file"):new C}catch(d){if(k(d,"ENOENT"))return{state:"absent"};throw d}throw l}let r=u.default.fstatSync(n),i=B(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=eo(n,i);return{state:(o?.target===t&&o?!vn(o.pid):Date.now()-i.mtimeMs>=Ki)?"stale":"active",stats:i}}finally{n!==null&&u.default.closeSync(n)}}function to(e,t){for(let n=0;n<8;n+=1){let r=(0,ht.randomBytes)(12).toString("hex"),i=b.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},s=null;try{s=u.default.openSync(i,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384);let c=u.default.fstatSync(s),l=B(i,s,c,{allowMultipleLinks:!0});return Bn(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:i,metadata:o,stats:l}}catch(c){if(k(c,"EEXIST"))continue;try{u.default.unlinkSync(i)}catch{}throw c}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function no(e,t){let n;try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){throw k(r,"ENOENT")?new C:r}try{let r=u.default.fstatSync(n),i=B(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!pe(i,t))throw new C;return{fd:n,lockPath:e,stats:i}}catch(r){throw u.default.closeSync(n),r}}function On(e){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(n){if(k(n,"ENOENT"))try{let r=u.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new C}catch(r){if(k(r,"ENOENT"))return!1;throw r}throw n}return B(e,t,u.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&u.default.closeSync(t)}}function ro(e){let t;try{t=u.default.openSync(e,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_RDWR|(u.default.constants.O_NOFOLLOW??0),384)}catch(r){if(k(r,"EEXIST"))return null;throw r}let n=null;try{n=u.default.fstatSync(t);let r=B(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{H(e,n)}catch{}throw u.default.closeSync(t),r}}function M(e,t){if(Date.now()>=e)throw t?new Error("credential-store recovery gate remained present past the bounded wait; a previous lock reclaimer may have crashed, so automatic recovery is intentionally disabled and manual inspection/removal is required"):new Error("credential-store lock remained busy past the bounded wait");ji(Hi)}function Rn(e){let t=b.dirname(e),n=b.basename(e),r=Zi(e),i=Qi(e),o=to(t,n),s=Date.now()+Gi,c=!1,l=!1,d=null,f;try{for(;d===null;)try{if(On(i)){M(s,!0);continue}u.default.linkSync(o.claimPath,r),l=!0,d=no(r,o.stats),c=!0}catch(p){if(l&&!c){try{H(r,o.stats)}catch{}l=!1}if(p instanceof C){M(s,!1);continue}if(!k(p,"EEXIST"))throw p;let m;try{m=In(r,n)}catch(S){if(S instanceof C){M(s,!1);continue}throw S}if(m.state==="absent")continue;if(m.state==="stale"){let S;try{S=ro(i)}catch(g){if(g instanceof C){M(s,!1);continue}throw g}if(S!==null){try{let g;try{g=In(r,n)}catch(w){if(w instanceof C){M(s,!1);continue}throw w}g.state==="stale"&&H(r,g.stats)}finally{gt(S)}continue}}let h;try{h=On(i)}catch(S){if(S instanceof C){M(s,!1);continue}throw S}M(s,h)}}catch(p){f=p}try{H(o.claimPath,o.stats)}catch(p){!k(p,"ENOENT")&&!c&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(d===null)throw new Error("credential-store lock acquisition failed");return d}function gt(e){try{H(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function io(e,t){let n=Wi(t),r=new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${n}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!r)return null;let i=Number(r[1]);return Number.isSafeInteger(i)&&i>0?i:null}function Nn(e){let t=b.dirname(e),n=b.basename(e);for(let r of u.default.readdirSync(t)){let i=io(r,n);if(i===null||vn(i))continue;let o=b.join(t,r),s=null;try{try{s=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(k(d,"ENOENT")||k(d,"ELOOP"))continue;throw d}let c=u.default.fstatSync(s),l=u.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!pe(c,l))continue;try{de(c,"credential-store orphan")}catch{continue}H(o,c)}catch(c){if(!k(c,"ENOENT"))throw c}finally{s!==null&&u.default.closeSync(s)}}}function fe(e,t,n){if(!Ne()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw G();if(!Ln(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw G()}});let s=Rn(e);try{return Nn(e),n({read:()=>Tn(e),remove:()=>Cn(e),write:()=>{throw G()}})}finally{gt(s)}}if(!t.createParent){let o=!1;try{o=Pn(e)}catch{throw G()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw G()}})}throw G()}if(!Ln(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Rn(e);try{return Nn(e),n({read:()=>Tn(e),remove:()=>Cn(e),write:o=>Vi(e,o)})}finally{gt(i)}}var _t="allscale-cli";function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $n(e){return bt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function Y(e){return new a("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function yt(){return new a("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function xe(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var K,wt=!1;function oo(){return pn()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function so(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function ao(){if(K!==void 0)return K;if(oo())return wt=!1,K=null,K;try{K=require("keytar"),wt=!1}catch(e){wt=!so(e),K=null}return K}function Fn(){let e=Ne()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new a("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function kt(e){try{return await e()}catch{throw Fn()}}var St=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await kt(()=>this.keytar.getPassword(_t,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw Y("OS keychain")}if(!$n(r))throw Y("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await kt(()=>this.keytar.setPassword(_t,t,JSON.stringify(n)))}async delete(t){await this.read(t),await kt(()=>this.keytar.deletePassword(_t,t))}},lo="credentials.json",Et=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??Un.join(dt(),lo)}read(t){let n;try{n=t.read()}catch(i){throw Re(i)?yt():Y("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw Y("plaintext file")}if(!bt(r)||!bt(r.profiles))throw Y("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Re(r)?yt():xe()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!$n(r))throw Y("plaintext file");return r}}async get(t){try{return fe(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof a?n:Y("plaintext file")}}async set(t,n){try{fe(this.filePath,{createParent:!0},r=>{let i=this.read(r);this.profileTokens(i,t),i.profiles[t]=n,this.write(r,i)})}catch(r){throw r instanceof a?r:xe()}}async delete(t){try{fe(this.filePath,{createParent:!1},n=>{let r=this.read(n);this.profileTokens(r,t)!==void 0&&(delete r.profiles[t],this.write(n,r))})}catch(n){throw n instanceof a?n:xe()}}async clearProfile(t){try{return fe(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},n=>{let r=this.read(n);return this.profileTokens(r,t)===void 0?!1:(delete r.profiles[t],Object.keys(r.profiles).length===0?n.remove():this.write(n,r),!0)})}catch(n){throw n instanceof a?n:Re(n)?yt():xe()}}};function Mn(e){if(e.insecureStorage)return xn(),new Et(e.insecureFilePath);let t=ao();if(t)return new St(t);throw Fn()}var At=class{kind="insecure-file";async get(t){return null}async set(t,n){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(t){}};function Pe(){return new At}var ve="allscale_access_token",Lt="allscale_refresh_token";function Gn(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(n=>{let r=n.indexOf(";"),i=r===-1?n:n.slice(0,r),o=i.indexOf("=");return o===-1?null:{name:i.slice(0,o).trim(),value:i.slice(o+1).trim()}}).filter(n=>n!==null)}function Tt(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}function Ct(e,t){return e.find(n=>n.name===t)?.value??null}var Hn=A(require("crypto")),Kn=A(require("fs")),Yn=A(require("path"));var co="key-id",uo="x-allscale-cli-version",It="cli-1",po="aScaLe_cli_obf_v1",fo="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function mo(e,t){let n=Buffer.from(e,"base64"),r=Buffer.from(t,"utf8"),i=Buffer.alloc(n.length);for(let o=0;o<n.length;o++)i[o]=n[o]^r[o%r.length];return i.toString("utf8")}var go=mo(fo,po),qn=`Bearer ${go}`;function jn(e,t){let n=We(e);if(n!==null)return t.find(r=>We(r.base)===n)}function ho(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=se();if(t.length>0){let r=jn(e,t);if(r)return r.key;if($(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:$(t[0].base)?t[0].key:void 0}return}let n=process.env.ALLSCALE_SIGNING_KEY;return n&&n.trim().length>0?n:void 0}function _o(e){{let r="cli-1".trim();if(r.length>0)return r}let t=se();if(t.length>0){let r=e!==void 0?jn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&$(e)){let i=process.env.ALLSCALE_SIGNING_KEY;if(i&&i.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():It}if(!$(t[0].base))return It}return t[0].keyId}let n=process.env.ALLSCALE_SIGNING_KEY_ID;return n!==void 0?n.trim():It}function yo(){return"0.1.0"}function wo(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function Ot(e,t){let n=ho(t);if(!n)throw wo();let r=_o(t),i=Math.floor(Date.now()/1e3).toString(),o=Hn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),s={timestamp:i,"secret-key":o,[uo]:yo()};return r.length>0&&(s[co]=r),s}function Wn(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function ko(e,t={}){let n;try{n=hn(Ee())}catch{return}if(!(n.length===0||n.includes(e)))return new a("auth.unknown_profile",Jt(e,n)+(t.messageSuffix??""),{profile:e,known_profiles:n})}function zn(e){if(e.profileExplicit){let t=ko(e.profile);if(t)return t}return new a("auth.no_token",zt(e.profile,e.flow))}var Rt=256*1024,Be=class extends a{constructor(t,n,r="backend-envelope"){let i=r==="successful-query",o=r==="successful-mutation";super(i?"transport.response_too_large":"backend.internal",i?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so it was not parsed. For list commands, request fewer rows by removing --all or using --input/--limit pagination, and reduce --select when possible; for other commands, contact support.`:o?`The API returned an HTTP-success response larger than the CLI's ${n}-byte safety limit, so its result was not parsed. The operation may already have completed; inspect authoritative state before retrying.`:`API response body exceeded the ${n}-byte safety limit and was not parsed.`,{status:t,max_body_bytes:n,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},De=class extends Error{status;timeoutMs;constructor(t,n){super(`API response body read exceeded its ${n}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=t,this.timeoutMs=n}};async function Nt(e,t,n={}){if(!Number.isSafeInteger(t)||t<=0)throw new RangeError("maxBytes must be a positive safe integer");if(n.timeoutMs!==void 0&&(!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let r=e.headers.get("content-length"),i=r!==null&&/^\d+$/.test(r.trim())?Number(r):void 0;if(i!==void 0&&i>t)throw e.body?.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],c=0,l,d=n.timeoutMs,f=d===void 0?void 0:new Promise((p,m)=>{l=setTimeout(()=>{m(new De(e.status,d))},d),l.unref?.()});try{for(;;){let p=o.read(),{done:m,value:h}=f?await Promise.race([p,f]):await p;if(m)break;if(c+=h.byteLength,c>t)throw o.cancel().catch(()=>{}),new Be(e.status,t,n.oversizeKind);s.push(Buffer.from(h))}}catch(p){throw p instanceof De&&o.cancel(p).catch(()=>{}),p}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(s,c).toString("utf8")}var bo="X-AllScale-Api-Key",So=3e4,Eo=32*1024*1024,Ao=4*1024*1024;function Lo(e,t){let n=new AbortController,r=!1,i=()=>{n.abort(e?.reason)};e?.aborted?i():e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",i)}}}function To(e,t){return t?t.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((n,r)=>{let i=()=>{r(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>{t.removeEventListener("abort",i)})}):e}function Co(e,t){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${D(t||"the request")}. The CLI does NOT follow redirects on credential-bearing requests \u2014 a cross-origin hop could re-send credentials and the request body to the new host. Check that --api-base / ALLSCALE_API_BASE points at the API origin directly and that no proxy is rewriting it.`,{status:e})}async function Qn(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Co(e.status,e.url)}}var Jn="--dns-result-order=ipv4first";async function Ue(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),s=t?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),l=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(s);if(!((o||c)&&(i||t!==void 0&&l)))return;if(t===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let f=/^[A-Za-z0-9-]{1,128}$/.test(r)?r:void 0;throw new a("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Jn} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...f?{cf_ray:f}:{},ipv4_workaround:`NODE_OPTIONS=${Jn}`})}var q=class{constructor(t){this.opts=t}opts;refreshInFlight=null;async requestWithMetadata(t){return this.requestInternal(t,{withMetadata:!0})}async request(t){return this.requestInternal(t,{withMetadata:!1})}async requestInternal(t,n){let r=t.timeoutMs??this.opts.requestTimeoutMs??So;if(!Number.isFinite(r)||r<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");F(this.opts.apiBase),Ae(this.opts.apiBase);let i=this.opts.override?{access_token:this.opts.override.access_token,refresh_token:this.opts.override.refresh_token??""}:await this.opts.tokenStore.get(this.opts.profile),o=Lo(t.signal,r);try{return await this.requestWithinDeadline({...t,signal:o.signal},n,i)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} timed out after ${r}ms.`,{timeout_ms:r}):t.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${D(new URL(t.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(t,n,r){let i=new URL(t.path,this.opts.apiBase).toString();wn(this.opts.apiBase,i);let o=r?.agent_key,s=t.auth??"auto",c=er(t.path),l=s==="required"?!0:s==="none"?!1:Ro(t.path);if((c||s==="required")&&!t._isRefresh&&!this.opts.override&&!r?.access_token&&!o)throw zn({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let d=Wn(t.body),f=!!o||!!r?.access_token;l&&f&&!this.opts.override&&pt(this.opts.apiBase,r?.api_base);let p=this.buildHeaders({attachAuth:l&&f,bodyForSig:d,tokens:r,extra:t.headers}),m=Date.now();_({type:"request",method:t.method??"GET",url:i,...t._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(i,{method:t.method??"GET",headers:p,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(g){throw new a("transport.network",`Network error contacting ${D(i)}: ${g instanceof Error?g.message:String(g)}`)}if(_({type:"response",status:h.status,durationMs:Date.now()-m}),l&&!!r?.access_token&&!o&&h.status===401&&!t._isRefresh&&!this.opts.override){let g=await To(this.refreshSingleFlight(),t.signal),w=this.buildHeaders({attachAuth:l&&!!g.access_token,bodyForSig:d,tokens:g,extra:t.headers}),I=Date.now();_({type:"request",method:t.method??"GET",url:i});let O;try{O=await fetch(i,{method:t.method??"GET",headers:w,body:t.body!==void 0?d:void 0,signal:t.signal,redirect:"manual"})}catch(P){throw new a("transport.network",`Network error contacting ${D(i)} on refresh-retry: ${P instanceof Error?P.message:String(P)}`)}return _({type:"response",status:O.status,durationMs:Date.now()-I}),Xn(O,{withMetadata:n.withMetadata,authBearing:l,responseKind:Vn(t)})}return Xn(h,{withMetadata:n.withMetadata,authBearing:l&&f,agentKeyAuth:l&&!!o,responseKind:Vn(t)})}buildHeaders(t){let r={Accept:"application/json","Content-Type":"application/json",...Ot(t.bodyForSig,this.opts.apiBase),...t.extra};if(t.attachAuth){r.Authorization=qn;let i=t.tokens;if(i?.agent_key)return r[bo]=i.agent_key,r;let o=i?.access_token;o&&(r.Cookie=Tt([{name:ve,value:o}]))}return r}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async doRefresh(){let t=await this.opts.tokenStore.get(this.opts.profile);if(!t?.access_token||!t?.refresh_token)throw new a("auth.token_expired",`No refresh token available; log in again \u2014 ${Xe()}.`);if(pt(this.opts.apiBase,t.api_base),t.agent_key)throw new a("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than overwrite it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");let n=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),r=Tt([{name:ve,value:t.access_token},{name:Lt,value:t.refresh_token}]),i=Ot("",this.opts.apiBase);_({type:"request",method:"POST",url:n,refresh:!0});let o=new AbortController,s=!1,c=setTimeout(()=>{s=!0,o.abort()},1e4),l;try{l=await fetch(n,{method:"POST",headers:{Accept:"application/json",Cookie:r,...i},signal:o.signal,redirect:"manual"})}catch(h){throw _({type:"refresh",ok:!1}),new a("transport.network",s&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${D(n)} timed out after 10s with no response.`:`Network error during token refresh against ${D(n)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(c)}_({type:"response",status:l.status,durationMs:0});try{await Qn(l)}catch(h){throw _({type:"refresh",ok:!1}),h}if(l.status!==200){_({type:"refresh",ok:!1}),await Ue(l);let h=await Po(l);throw await Ue(l,h),tr(l.status,h),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Xe()}.`,{status:l.status})}let d=Gn(l.headers),f=Ct(d,ve),p=Ct(d,Lt);if(!f||!p)throw _({type:"refresh",ok:!1}),new a("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...t,access_token:f,refresh_token:p};return await this.opts.tokenStore.set(this.opts.profile,m),_({type:"refresh",ok:!0}),m}},Io=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function er(e){let t=e.split(/[?#]/,1)[0];return Io.some(n=>t===n||t.startsWith(`${n}/`))}var Oo=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function xt(e){let t=e.split(/[?#]/,1)[0];return Oo.some(n=>n.test(t))}function Ro(e){return er(e)||xt(e)}async function Xn(e,t={}){await Qn(e);let n=e.status>=200&&e.status<300;n||await Ue(e);let r=t.responseKind??"mutation",o=await Nt(e,n?r==="query"?Eo:Ao:Rt,{oversizeKind:n?r==="query"?"successful-query":"successful-mutation":"backend-envelope"});n||await Ue(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(t.withMetadata){let l={};return e.headers.forEach((d,f)=>{l[f]=d}),{status:e.status,headers:l,body:s}}return s}let c=vo(s)??`HTTP ${e.status}`;if(tr(e.status,s),e.status===401){if(t.agentKeyAuth)throw new a("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let l=t.authBearing?"auth.token_expired":"input.invalid";throw new a(l,c,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",c,{status:403,body:s}):e.status===404?new a("not_found",c,{status:404,body:s}):e.status===429?new a("rate_limited",c,{status:429,body:s}):e.status>=500?new a("backend.internal",c,{status:e.status,body:s}):new a("input.invalid",c,{status:e.status,body:s})}function Vn(e){if(e.responseKind)return e.responseKind;let t=(e.method??"GET").toUpperCase();return t==="GET"||t==="HEAD"?"query":"mutation"}var Zn=2014;function No(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let n=t.code;return n===Zn||n===String(Zn)}var xo=1e4;async function Po(e,t=xo){if(e.status>=200&&e.status<300)return"";try{return await Nt(e,Rt,{timeoutMs:t})}catch{return""}}function tr(e,t){if(!(e>=200&&e<300)&&No(t))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof t=="string"?t.slice(0,500):t})}function vo(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.message=="string")return t.message;if(typeof t.detail=="string")return t.detail;if(Array.isArray(t.detail))return JSON.stringify(t.detail)}var Bo=/^\/(api\/)?(v1\/)?public\//;function $e(e,t={}){let n=typeof t.pathHint=="string"?t.pathHint:"",r=n&&Bo.test(n),i=n&&xt(n),o=r&&!i&&!t.forceAuth;if(e.token)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new q({apiBase:e.apiBase,tokenStore:Mn({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(i)return new q({apiBase:e.apiBase,tokenStore:Pe(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var ne={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_TOKEN_CONSUMED:7411},Do=new Set(Object.values(ne));async function nr(e,t,n){return rr(e,"/api/secure/wallet/cli_op_init",{op:t,payload:n},"cli_op_init")}async function Pt(e,t){return rr(e,"/api/secure/wallet/cli_op_result",{result_token:t},"cli_op_result")}async function rr(e,t,n,r){let i;try{i=await e.request({method:"POST",path:t,body:n})}catch(o){if(o instanceof a){let s=Uo(o,r);if(s!==null)throw s}throw o}return $o(i,r)}function Uo(e,t){let n=e.details?.body;if(!n||typeof n!="object")return null;let r=n,i=typeof r.code=="number"?r.code:void 0;if(i===void 0||i===0||!Do.has(i))return null;let o=typeof r.errors=="string"?r.errors:typeof r.message=="string"?r.message:e.message;return ir(i,o,t)}function $o(e,t){if(e.code!==void 0&&e.code!==0)throw ir(e.code,e.message,t);if(e.data===void 0)throw new a("backend.internal",`Broker ${t} returned no data envelope`,{envelope:e});return e.data}function ir(e,t,n){let r=t??`Broker ${n} returned code ${e}`;switch(e){case ne.CLI_OP_NOT_FOUND:return new a("not_found",r,{broker_code:e});case ne.CLI_OP_EXPIRED:return new a("wallet.bridge_timeout",r,{broker_code:e});case ne.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",r,{broker_code:e});case ne.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",r,{broker_code:e});case ne.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",r,{broker_code:e});default:return new a("backend.internal",r,{broker_code:e})}}var sr=require("child_process");async function ar(e,t={}){if(!qe(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${L(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(r==="linux"&&!n.DISPLAY&&!i)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(t._execOverride){await t._execOverride(e);return}let o=Fo(r,i);await Mo(o.command,[...o.args,e])}function Fo(e,t){return t&&t.length>0?{command:t,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function Mo(e,t){return new Promise((n,r)=>{let i;try{i=(0,sr.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(s){r(or(e,s));return}let o=!1;i.once("error",s=>{o||(o=!0,r(or(e,s)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function or(e,t){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var lr=A(require("http"));var Go=9e4,Ho=16*1024;function cr(e){let t=e.timeoutMs??Go;return new Promise((n,r)=>{let i=!1,o=!1,s=null,c,l,d=new Promise((p,m)=>{c=p,l=m}),f=lr.createServer((p,m)=>{Ko(p,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>i,tryConsume:()=>i?!1:(i=!0,!0),onSuccess:h=>{s&&clearTimeout(s),c(h),f.close()}})});f.on("error",p=>{let m=new a("transport.network",`Loopback listener error: ${p.message}`);o?l(m):r(m),s&&clearTimeout(s)}),f.listen({host:"127.0.0.1",port:e.port??0},()=>{let p=f.address();if(!p||typeof p=="string"){f.close(),r(new a("transport.network","Failed to read loopback listener port"));return}s=setTimeout(()=>{l(new a("wallet.bridge_timeout",`Bridge timed out after ${t}ms waiting for browser callback.`)),f.close()},t),s.unref?.(),o=!0,n({port:p.port,awaitResult:d,close:()=>{s&&clearTimeout(s),f.close()}})})})}function Ko(e,t,n){let r=e.headers.origin??"";if(e.method==="OPTIONS"){if(r===n.expectedOrigin){let c={"Access-Control-Allow-Origin":n.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(c["Access-Control-Allow-Private-Network"]="true"),t.writeHead(204,c)}else t.writeHead(403);t.end();return}if(e.method!=="POST"||e.url!=="/result"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"not_found"}));return}if(n.isConsumed()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}if(r!==n.expectedOrigin){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"origin_mismatch"}));return}let i=0,o=[],s=!1;e.on("data",c=>{if(!s){if(i+=c.length,i>Ho){s=!0,t.writeHead(413,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(s)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"invalid_body"}));return}let d=l,f=typeof d.state=="string"?d.state:"",p=typeof d.result_token=="string"?d.result_token:void 0,m=d.result_data!==void 0&&d.result_data!==null&&typeof d.result_data=="object"&&!Array.isArray(d.result_data)?d.result_data:void 0;if(!Yo(f,n.state)){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"state_mismatch"}));return}if(p===void 0&&m===void 0){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"missing_result"}));return}if(!n.tryConsume()){t.writeHead(410,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"already_consumed"}));return}t.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":n.expectedOrigin}),t.end(JSON.stringify({ok:!0})),n.onSuccess({result_token:p,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function Yo(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function vt(e){try{return JSON.parse(e),!0}catch{return!1}}function ur(){let e=process.stdin,t="",n=!1,r=()=>{},i=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},c=()=>{s(),o=setTimeout(()=>{n||(l(),r(t.trim()))},i),o.unref?.()},l=()=>{n=!0,s(),e.off("data",d),e.off("end",f),e.off("error",p),e.pause()},d=h=>{if(n)return;s(),t+=h.toString();let S=t.trim(),g=t.length-t.trimStart().length,w=t.indexOf(`
17
+ `,g),I=w===-1?"":t.slice(g,w).trim();if(S.startsWith("{")){if(vt(S)){l(),r(S);return}if(w===-1){c();return}if(!vt(I)&&!I.endsWith("}")){let O=t.slice(w+1),P=O.split(`
18
+ `).find(ge=>ge.trim()!=="")??"";if(I==="{"&&(!/\S/.test(O)||/^\s*"[^"]*"\s*:/.test(O)||/^\s*"[^"]*$/.test(P))){c();return}}l(),r(vt(I)?I:t.slice(g).trim());return}if(w!==-1){l(),r(I);return}else!S&&t.includes(`
19
+ `)&&(l(),r(""))},f=()=>{if(n)return;let h=t.trim();if(!h){l();return}l(),r(h)},p=()=>{n||l()},m=new Promise(h=>{r=h});return e.resume(),e.on("data",d),e.on("end",f),e.on("error",p),{promise:m,cancel:()=>{n||l()}}}function qo(e){let t;return{promise:new Promise(r=>{if(e.aborted){r({source:"aborted"});return}t=()=>r({source:"aborted"}),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>{t!==void 0&&e.removeEventListener("abort",t)}}}async function pr(e){let t=$e(e.ctx),n=e.browserBase??e.ctx.apiBase,r=Zo(n),i=e._openBrowser??ar,o=e._startListener??cr,s=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,dr.randomBytes)(32).toString("hex"),d=await nr(t,e.op,e.payload);_({type:"bridge_init",op_id:d.op_id,expires_at:d.expires_at});let f=d.expires_at-Math.floor(Date.now()/1e3),p=Number.isFinite(f)?Math.max(0,f):0,m=Math.min(Math.max(6e4,p*1e3),2147483647),h=e.timeoutMs!=null&&e.timeoutMs>0&&e.timeoutMs<=2147483647?e.timeoutMs:m;E.stderr.write(`Bridge op registered (op_id=${d.op_id}, op TTL ~${p}s, waiting up to ${Math.round(h/1e3)}s for confirmation).
20
+ `);let S=await o({state:l,expectedOrigin:r,timeoutMs:h}),g=S.awaitResult.then(R=>({source:"loopback",...R}),R=>({source:"listener_error",error:R})),w=Date.now(),I=setInterval(()=>{let R=Math.floor((Date.now()-w)/1e3);E.stderr.write(`Still waiting for confirmation\u2026 (${R}s elapsed)
21
+ `)},15e3);I.unref?.();let O,P=e.signal===void 0?void 0:qo(e.signal);try{let R=Jo(n,{op_id:d.op_id,port:S.port,state:l});_({type:"bridge_browser_open",url:R});let ge=s==="ack"?"confirmation token":"result";if(E.stderr.write(c?e.autoOpen===!1?`
22
+ Confirm this in your browser. Open the URL below on any device where
23
+ you're signed in to AllScale (local auto-open is disabled):
24
+
25
+ ${R}
26
+
27
+ `:`
28
+ Confirm this in your browser. The URL is below \u2014 it auto-opens if a
29
+ browser is available on this machine; otherwise open it on any device
30
+ where you're signed in to AllScale:
31
+
32
+ ${R}
33
+
34
+ `:`
35
+ Confirm this in a browser on this machine. The callback must reach the
36
+ local listener; non-interactive stdin cannot accept a result pasted
37
+ back from another device:
38
+
39
+ ${R}
40
+
41
+ `),e.autoOpen===!1)E.stderr.write(`(browser auto-open skipped \u2014 use the link above)
42
+ `);else try{await i(R),E.stderr.write(`(opened in your default browser)
43
+ `)}catch{E.stderr.write(`(no local browser to open \u2014 use the link above)
44
+ `)}c?E.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
45
+ reach this machine (e.g. you opened the link elsewhere over SSH), copy
46
+ the ${ge} the page shows, paste it here, and press Enter:
47
+
48
+ `):E.stderr.write(`stdin is non-interactive; waiting for the browser callback.
49
+
50
+ `),c&&(O=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:ur());let He=[g];O!==void 0&&He.push(O.promise.then(Kr=>({source:"paste",line:Kr}))),P!==void 0&&He.push(P.promise);let j=await Promise.race(He);if(j.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(j.source==="listener_error")throw jo(j.error);if(j.source==="loopback")return E.stderr.write(`Browser returned result; processing\u2026
51
+ `),await Wo(t,s,j);let he=j.line.trim();if(!he)throw new a("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(s==="ack"&&he.startsWith("{"))throw new a("wallet.bridge_invalid_response","Pasted value looks like JSON, not a confirmation token. Copy the single-line token the /cli page shows, not the result JSON.");if(s==="ack"&&/\s/.test(he))throw new a("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return E.stderr.write(`Received pasted ${ge}; processing\u2026
52
+ `),await zo(t,s,he)}finally{clearInterval(I),P?.cleanup(),O?.cancel(),S.close()}}function jo(e){return e instanceof a&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_invalid_response")?e:new a("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function Wo(e,t,n){if(t==="ack"){if(!n.result_token)throw new a("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");_({type:"bridge_result_received",source:"loopback"});let r=await Pt(e,n.result_token);return _({type:"bridge_verified",op_id:r.op_id,source:"loopback"}),E.stderr.write(`Verified by broker.
53
+ `),{ack:r,result_data:n.result_data}}if(!n.result_data)throw new a("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return _({type:"bridge_result_received",source:"loopback"}),_({type:"bridge_data_received",source:"loopback"}),E.stderr.write(`Result received from browser.
54
+ `),{result_data:n.result_data}}async function zo(e,t,n){if(t==="ack"){_({type:"bridge_result_received",source:"paste"});let i=await Pt(e,n);return _({type:"bridge_verified",op_id:i.op_id,source:"paste"}),E.stderr.write(`Verified by broker.
55
+ `),{ack:i}}let r;try{r=Vo(n)}catch(i){throw i instanceof a&&i.code==="input.invalid"?new a("wallet.bridge_invalid_response",i.message):i}return _({type:"bridge_result_received",source:"paste"}),_({type:"bridge_data_received",source:"paste"}),E.stderr.write(`Result accepted.
56
+ `),{result_data:r}}function Jo(e,t){let n=new URL("/cli",fr(e));return n.searchParams.set("op_id",t.op_id),n.searchParams.set("port",String(t.port)),n.searchParams.set("state",t.state),n.toString()}var Xo=/^0x[0-9a-fA-F]{64}$/;function Vo(e){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(Xo.test(e))return{tx_hash:e};throw new a("input.invalid",`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function Zo(e){return fr(e).origin}function fr(e){if(!W(e))throw new a("input.invalid",`Refusing browser base ${L(e)}: bridge state and operation identifiers may only be sent to an exact trusted AllScale origin (${ye.join(", ")}) or an explicit loopback development origin. It must not contain embedded URL userinfo.`);return new URL(e)}var mr=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:all"]),gr=new Set(["payroll","admin:user","admin:org","admin:audit"]);function hr(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function _r(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}var Qo={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",create_store:"store:all",auto_payout_session_status:"claim_link:read_only",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},es={business:"the broad `business` query is default-denied for agent keys by design \u2014 no scope grants it, because allowing the entry point would expose every nested field of the Business type"},ts=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,ns=/is not available to API keys/i,yr=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function wr(e){if(typeof e!="string")return;let t=ts.exec(e);if(!t)return;let n=t[1].trim(),r=t[2].trim(),i=ns.test(n),o=!i&&yr.test(n)?n:void 0,s;if(r.toLowerCase()==="none")s=[];else{let c=r.split(",").map(l=>l.trim()).filter(l=>yr.test(l));s=c.length>0?c:void 0}if(!(o===void 0&&!i))return{required:o,granted:s,notAvailableToKeys:i}}function kr(e){let t=es[e];if(t!==void 0)return{ungrantableReason:t};let n=Qo[e];if(n!==void 0)return{scope:n}}function br(e){if(gr.has(hr(e)))return{kind:"ungrantable"};for(let t of mr)if(_r(t,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function Sr(e){if(!e||typeof e!="object")return!1;let t=e.errors;return Array.isArray(t)&&t.length>0}function Er(e,t=3){let n=e.errors;return!Array.isArray(n)||n.length===0?"":n.slice(0,t).map(r=>typeof r=="object"&&r!==null&&typeof r.message=="string"?r.message:JSON.stringify(r)).join("; ")}function Lr(e,t){let n=Tr(e),r={graphql_error_count:rs(e.errors),...n===void 0?{}:{backend_code:n}};if(n===2102)throw is(e,t,r);if(n===3400)throw new a("not_found",`GraphQL ${t.kind} '${t.operationName}' could not find the requested resource.`,r);if(Sr(e))throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' returned errors: ${Er(e)}`,r);if(n!==void 0)throw new a("input.invalid",`GraphQL ${t.kind} '${t.operationName}' failed with backend code ${n}.`,r)}function Tr(e){let t=Ar(e.code);if(t!==void 0)return t;if(Array.isArray(e.errors))for(let n of e.errors){if(!n||typeof n!="object")continue;let r=n.extensions;if(!r||typeof r!="object")continue;let i=Ar(r.code);if(i!==void 0)return i}}function Ar(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let t=Number(e);if(Number.isSafeInteger(t)&&t>0)return t}}function rs(e){return Array.isArray(e)?e.length:e==null?0:1}function is(e,t,n){let r=`GraphQL ${t.kind} '${t.operationName}'`,i={...n,operation:t.operationName},o=wr(os(e,Tr(e))),s=kr(t.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??s?.scope,d=o?.granted,f=d===void 0?"":` This key holds ${d.length>0?d.join(", "):"no scopes"}.`;if(c||s?.ungrantableReason!==void 0){let p=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("auth.permission_denied",`${r} is not available to agent keys${p}. Re-authorizing will NOT help \u2014 no scope grants it.${f} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...i,missing_scopes:[],...d===void 0?{}:{granted_scopes:d},ungrantable:!0})}if(l!==void 0){let p=br(l),m=p.kind==="ungrantable"?`\`${l}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:p.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${ae()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${ae()}\` with \`--scopes ${l}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${r}.${f} ${m}`,{...i,missing_scopes:[l],...d===void 0?{}:{granted_scopes:d},...p.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${r}.${f} Re-run \`allscale device-login\` (or \`${ae()}\`) and grant the required scope.`,i)}function os(e,t){let n=e.errors;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=i=>{if(i===null||typeof i!="object")return;let o=i.message;return typeof o=="string"?o:void 0};if(t!==void 0)for(let i of n){if(i===null||typeof i!="object")continue;let o=i.extensions;if(!o||typeof o!="object")continue;let s=o.code;if(s===t||typeof s=="string"&&Number(s)===t){let l=r(i);if(l!==void 0)return l}}for(let i of n){let o=r(i);if(o!==void 0)return o}return""}var ss="/api/secure/graphql";async function Cr(e,t){t.showDoc&&process.stderr.write(`${t.document}
57
+ `);let r=await $e(e).request({method:"POST",path:ss,responseKind:t.kind,body:{query:t.document,variables:t.variables,operationName:t.operationName}});Lr(r,{kind:t.kind,operationName:t.operationName});let i=r.data?.[t.operationName];return i===void 0?null:i}var as=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,ls=/^0(?:\.0+)?$/,Bt=128;function Ir(e,t,n={}){if(t.length>Bt)throw new a("input.invalid",`${e} is too long; decimal values may contain at most ${Bt} characters.`);let r=t.trim();if(!as.test(r))throw new a("input.invalid",`${e} must be a decimal string without sign or exponent; got '${t}'.`);if(!n.allowZero&&ls.test(r))throw new a("input.invalid",`${e} must be greater than zero; got '${t}'.`);return r}function Or(e,t,n){if((t.split(".")[1]??"").replace(/0+$/,"").length>n)throw new a("input.invalid",`${e} supports at most ${n} effective decimal places for the selected token and chain; got '${t}'. The CLI will not round a funds amount.`);return t}function re(e,t){let n=l=>{if(typeof l!="string"||l.length>Bt||!/^\d+(?:\.\d+)?$/.test(l))return null;let[d,f=""]=l.split(".");return{whole:d.replace(/^0+(?=\d)/,""),fraction:f.replace(/0+$/,"")}},r=n(e),i=n(t);if(!r||!i)return null;if(r.whole.length!==i.whole.length)return r.whole.length<i.whole.length?-1:1;if(r.whole!==i.whole)return r.whole<i.whole?-1:1;let o=Math.max(r.fraction.length,i.fraction.length),s=r.fraction.padEnd(o,"0"),c=i.fraction.padEnd(o,"0");return s===c?0:s<c?-1:1}function me(e,t,n){if(t===void 0)return;let r=t.trim();if(r.length!==0){if(r.length>n)throw new a("input.invalid",`${e} must be ${n} characters or fewer.`);return r}}var cs=`query claim_link_funding_by_idempotency_key($idempotency_key: String!) {
58
+ claim_link_funding_by_idempotency_key(idempotency_key: $idempotency_key) {
59
+ claim_link {
60
+ id
61
+ status
62
+ amount
63
+ token_symbol
64
+ chain
65
+ receiver_email
66
+ sender_display_name
67
+ sender_message
68
+ funded_tx_hash
69
+ }
70
+ claim_token
71
+ claim_url
72
+ claim_window_seconds
73
+ }
74
+ }`,Rr={1:"PENDING_DEPOSIT",2:"LINK_SENT",3:"CLAIMING",4:"CLAIMED",5:"EXPIRED",6:"CANCELLED"},us=new Set(Object.values(Rr)),ds=new Set(["EXPIRED","CANCELLED"]),ps=new Set(["outcome","phase","claim_link_id","funding_tx_hash"]),fs=new Set(["completed","cancelled","ambiguous"]),ms=new Set(["pre_create","creating","created","signed","broadcast","settling","funded"]),gs=new Set(["creating","created","signed","broadcast","settling"]),hs=new Set(["created","signed","broadcast","settling","funded"]),Nr=/^[A-Za-z0-9_-]{1,128}$/,_s=/^[A-Za-z0-9_-]{16,256}$/,ys=2048,ws=16,ks=/^\/(?:claim\/[A-Za-z0-9_-]{16,256}|s\/[A-Za-z0-9_-]{1,128})$/,bs=2e3,Ss=500;function Ut(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Es(e,t){if(typeof e!="string"||!Nr.test(e))throw new a("backend.internal",`${t} returned a malformed Claim Link id.`);return e}function As(e,t){if(typeof e!="string"||!_s.test(e))throw new a("backend.internal",`${t} returned a malformed claim token.`);return e}function Ls(e){if(typeof e=="number"&&Number.isInteger(e)){let t=Rr[e];if(t!==void 0)return t}if(typeof e=="string"){let t=e.trim().toUpperCase().replace(/-/g,"_");if(us.has(t))return t}throw new a("backend.internal","Claim Link funding lookup returned an unknown lifecycle status.")}function Ts(e,t){if(e==null)return null;if(typeof e!="string"||!Ie.test(e))throw new a("backend.internal",`${t} returned a malformed funding transaction hash.`);return e}function Cs(e,t){if(e==null)return null;if(typeof e!="string"||e.length===0||e.length>ys||e.trim()!==e)throw new a("backend.internal",`${t} returned a malformed Claim Link URL.`);return e}function Is(e){if(typeof e!="string"||e.trim()!==e||re(e,e)===null)throw new a("backend.internal","Claim Link funding lookup returned a malformed amount.");return e}function Os(e){if(typeof e!="string"||e.length===0||e.length>ws||!/^[A-Za-z0-9]+$/.test(e))throw new a("backend.internal","Claim Link funding lookup returned a malformed token symbol.");return e}function Rs(e){if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed chain.");return e}function Dt(e,t,n){if(e===null)return null;if(typeof e!="string"||e.length>n)throw new a("backend.internal",`Claim Link funding lookup returned a malformed ${t}.`);return e}function Ns(e){if(e===null)return null;if(!Number.isSafeInteger(e)||e<=0)throw new a("backend.internal","Claim Link funding lookup returned a malformed claim window.");return e}function xs(e,t,n){let r;try{r=new URL(e)}catch{throw new a("backend.internal",`${n} returned a malformed Claim Link URL.`)}let i=new URL(t).origin;if(r.origin!==i||r.username.length>0||r.password.length>0||r.search.length>0||r.hash.length>0||!ks.test(r.pathname))throw new a("backend.internal",`${n} returned a Claim Link URL outside the configured API origin or supported claim routes.`);return r.toString()}function Ps(e){if(e==null)return null;if(!Ut(e)||!Ut(e.claim_link))throw new a("backend.internal","Claim Link funding lookup returned a malformed result.");return{claimLinkId:Es(e.claim_link.id,"Claim Link funding lookup"),status:Ls(e.claim_link.status),amount:Is(e.claim_link.amount),tokenSymbol:Os(e.claim_link.token_symbol),chain:Rs(e.claim_link.chain),receiverEmail:Dt(e.claim_link.receiver_email,"receiver email",254),senderDisplayName:Dt(e.claim_link.sender_display_name,"sender display name",100),senderMessage:Dt(e.claim_link.sender_message,"sender message",200),claimWindowSeconds:Ns(e.claim_window_seconds),claimToken:As(e.claim_token,"Claim Link funding lookup"),claimUrl:Cs(e.claim_url,"Claim Link funding lookup"),fundingTxHash:Ts(e.claim_link.funded_tx_hash,"Claim Link funding lookup")}}function vs(e,t){let n=[];re(e.amount,t.amount)!==0&&n.push("amount"),e.tokenSymbol.toUpperCase()!==En(t.stable_coin).toUpperCase()&&n.push("stable_coin"),e.chain!==t.chain&&n.push("chain");let r=i=>{let o=i?.trim()??"";return o.length===0?null:o};return r(e.receiverEmail)?.toLowerCase()!==r(t.receiver_email)?.toLowerCase()&&n.push("receiver_email"),r(e.senderDisplayName)!==r(t.sender_display_name)&&n.push("sender_display_name"),r(e.senderMessage)!==r(t.sender_message)&&n.push("sender_message"),e.claimWindowSeconds!==t.claim_window_seconds&&n.push("claim_window_seconds"),n}function Fe(e,t,n){let r=vs(e,t);if(r.length===0)return;let i={idempotency_key:t.idempotency_key,claim_link_id:e.claimLinkId,status:e.status,intent_conflict:!0,mismatched_fields:r,retry_with_same_idempotency_key:!1};throw n?new a("claim_link.funding_ambiguous","The authoritative Claim Link bound to this idempotency key does not match the requested intent after browser authorization may have started. Do not retry automatically, fund the returned link, or use a new key; inspect the existing operation manually.",{outcome_ambiguous:!0,...i}):new a("claim_link.intent_conflict","This idempotency key is already bound to different Claim Link terms. The browser was not opened and the existing link was not funded by this command. Re-run with the original terms or choose a new key only for an intentional new link.",i)}async function Bs(e,t){let n=await Cr(e,{kind:"query",operationName:"claim_link_funding_by_idempotency_key",document:cs,variables:{idempotency_key:t}});return Ps(n)}function Ds(e){if(e==null)return null;if(typeof e!="string"||!Nr.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function Us(e){if(e==null)return null;if(typeof e!="string"||!Ie.test(e))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");return e}function $s(e){if(!Ut(e)||Object.keys(e).some(s=>!ps.has(s))||typeof e.outcome!="string"||!fs.has(e.outcome)||typeof e.phase!="string"||!ms.has(e.phase))throw new a("wallet.bridge_invalid_response","Browser returned a malformed Claim Link receipt.");let t=e.outcome,n=e.phase,r=Ds(e.claim_link_id),i=Us(e.funding_tx_hash);if(!(t==="completed"&&n==="funded"&&r!==null||t==="cancelled"&&n==="pre_create"&&r===null&&i===null||t==="ambiguous"&&gs.has(n)&&(!hs.has(n)||r!==null)))throw new a("wallet.bridge_invalid_response","Browser returned an inconsistent Claim Link receipt.");return{outcome:t,phase:n,claimLinkId:r,fundingTxHash:i}}function Me(e,t,n){if(e.status==="PENDING_DEPOSIT")throw new Error("PENDING_DEPOSIT cannot be rendered as a success");if(xr(e))throw $t(n,e,null);let r;try{let i=e.claimUrl??new URL(`/claim/${encodeURIComponent(e.claimToken)}`,t).toString();r=xs(i,t,"Claim Link funding lookup")}catch{throw new a("backend.internal","Claim Link funding is authoritative, but the lookup returned an untrusted or malformed claim URL. Do not create another link or use a new idempotency key; re-run only with exactly the same --idempotency-key after the service recovers.",{funding_authoritative:!0,idempotency_key:n,claim_link_id:e.claimLinkId,funding_tx_hash:e.fundingTxHash,status:e.status,retry_with_same_idempotency_key:!0})}return{claim_link_id:e.claimLinkId,claim_url:r,status:e.status,...e.fundingTxHash===null?{}:{funding_tx_hash:e.fundingTxHash}}}function xr(e){return ds.has(e.status)&&(e.fundingTxHash===null||!Ie.test(e.fundingTxHash))}function Fs(e,t,n){let i=!(t!==null&&xr(t))&&(t===null||n?.claimLinkId===t.claimLinkId)?n:null;return{outcome_ambiguous:!0,idempotency_key:e,claim_link_id:t?.claimLinkId??i?.claimLinkId??null,funding_tx_hash:t===null?i?.fundingTxHash??null:t.fundingTxHash,phase:i?.phase??(t===null?"unknown":"created"),status:t?.status??null,retry_with_same_idempotency_key:!0}}function $t(e,t,n){return new a("claim_link.funding_ambiguous","Claim Link funding is not authoritatively proven complete. Funds may have been signed or broadcast, or a terminal state may lack a validated funding transaction hash. Re-run this command only with exactly the same --idempotency-key so it reconciles the existing operation; do not use a new key or create another link.",Fs(e,t,n))}function Ms(e,t){return t.aborted?Promise.resolve(!1):new Promise(n=>{let r=setTimeout(()=>{t.removeEventListener("abort",i),n(!0)},e);r.unref?.();let i=()=>{clearTimeout(r),n(!1)};t.addEventListener("abort",i,{once:!0})})}function Gs(e){return new Promise(t=>setTimeout(t,e))}async function Hs(e,t,n){let r=Math.max(1,e._pollIntervalMs??bs);for(;await Ms(r,n)&&!n.aborted;)try{let i=await t(e.ctx,e.intent.idempotency_key);if(i!==null&&i.status!=="PENDING_DEPOSIT")return i}catch{}return null}async function Pr(e){let t=e._fetchFunding??Bs,n=e._runBridge??pr,r=e.intent.idempotency_key,i=await t(e.ctx,r);if(i!==null&&Fe(i,e.intent,!1),i!==null&&i.status!=="PENDING_DEPOSIT")return Me(i,e.ctx.apiBase,r);let o,s=new AbortController,c=!1,l=new AbortController,d=n({ctx:e.ctx,op:"create_claim_link",mode:"data",payload:{...e.intent},timeoutMs:e.timeoutMs,browserBase:e.browserBase,autoOpen:e.autoOpen,signal:s.signal}).then(g=>(c=!0,{kind:"bridge",result:g}),g=>(c=!0,{kind:"bridge_error",error:g})),f=Hs(e,t,l.signal).then(g=>({kind:"funding",record:g}));try{let g=await Promise.race([d,f]);if(g.kind==="funding"){if(g.record===null)throw new Error("Authoritative funding poll stopped unexpectedly.");Fe(g.record,e.intent,!0);let w=Math.max(0,e._bridgeCallbackGraceMs??Ss);return await Promise.race([d.then(()=>!0),Gs(w).then(()=>!1)])||s.abort(),Me(g.record,e.ctx.apiBase,r)}if(l.abort(),g.kind==="bridge_error")throw g.error;o=g.result}catch(g){if(l.abort(),!(g instanceof a)||!An(g.code))throw g;let w=null;try{w=await t(e.ctx,r)}catch{}if(w!==null&&Fe(w,e.intent,!0),w!==null&&w.status!=="PENDING_DEPOSIT")return Me(w,e.ctx.apiBase,r);throw $t(r,w,null)}finally{l.abort(),c||s.abort()}let p=null;try{p=$s(o.result_data)}catch{}let m=null,h=!1;try{m=await t(e.ctx,r),h=!0}catch{}if(m!==null&&Fe(m,e.intent,!0),m!==null&&m.status!=="PENDING_DEPOSIT")return Me(m,e.ctx.apiBase,r);throw p?.outcome==="cancelled"&&p.phase==="pre_create"&&h&&m===null?new a("claim_link.browser_cancelled","Claim Link creation was cancelled in the browser before a link was created.",{idempotency_key:r,claim_link_id:null,phase:"pre_create",status:null,retry_with_same_idempotency_key:!0}):$t(r,m,p)}var vr="0.1",Br="10000",Ks=6,Ys=60n,qs=30n*24n*60n*60n,Dr=336*60*60,Ur="14d",js="between 1m and 30d (inclusive)",Ws=/^(\d+)\s*([dhm])$/i,zs=32,Js=/^[a-zA-Z0-9_'^&+%-]+(?:\.[a-zA-Z0-9_'^&+%-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/i;function $r(e){if(e.length>zs)throw new a("input.invalid","--expires is too long; expected a duration like 14d, 24h, or 90m.");let t=Ws.exec(e.trim());if(!t)throw new a("input.invalid",`--expires must be a duration like 14d, 24h, or 90m (units: d/h/m); got '${e}'.`);let n=BigInt(t[1]),r=t[2].toLowerCase(),o=n*(r==="d"?86400n:r==="h"?3600n:60n);if(o<Ys||o>qs)throw new a("input.invalid",`--expires must be ${js}; got '${e}'.`);return{seconds:Number(o),label:`${n}${r}`}}function Fr(e){let t=Or("--amount",Ir("--amount",e),Ks),n=re(t,vr),r=re(t,Br);if(n===null||r===null)throw new a("input.invalid",`--amount is not a supported decimal value: '${e}'.`);if(n<0)throw new a("input.invalid",`--amount must be at least ${vr}; got '${t}'.`);if(r>0)throw new a("input.invalid",`--amount must not exceed ${Br}; got '${t}'.`);let[i,o]=t.split("."),s=o?.replace(/0+$/,"")??"";return s.length===0?i:`${i}.${s}`}function Mr(e){let t=me("--receiver-email",e,254);if(t===void 0)return null;if(!Js.test(t))throw new a("input.invalid","--receiver-email is not a valid email address.");return t}var Xs=require("crypto");var Gr=128;function Hr(e){if(e===void 0)return;let t=e.trim();if(!t||t.length>Gr)throw new a("input.invalid",`--idempotency-key must contain 1-${Gr} characters after trimming.`);return t}var Ge=class e extends ce{static description="Create and fund a fixed-intent Claim Link in one browser authorization ceremony, then confirm the authoritative lifecycle state. Requires claim_link:all for an agent-key session.";static examples=["$ allscale claim-link create --idempotency-key order-1042 --amount 10 --chain base","$ allscale claim-link create --idempotency-key order-1043 --amount 25.50 --stable-coin USDC --chain polygon --expires 7d --message 'Invoice 1043'","$ allscale claim-link create --idempotency-key order-1044 --amount 5 --chain base --receiver-email client@example.com --sender-display-name 'Acme' --no-browser"];static flags={amount:T.Flags.string({helpGroup:"REQUIRED",description:"Exact amount the receiver can claim, as a decimal string. Range 0.1-10000; at most 6 effective decimal places. The CLI never rounds it.",required:!0}),chain:T.Flags.string({helpGroup:"REQUIRED",description:"EVM chain for the Claim Link.",options:[...kn],required:!0}),"idempotency-key":T.Flags.string({helpGroup:"REQUIRED",description:"Required stable key for this logical Claim Link create/fund operation (1-128 characters). Reuse it after an ambiguous result; use a new key only for an intentional second link.",required:!0}),"stable-coin":T.Flags.string({description:"Stablecoin for the Claim Link.",options:[...Le],default:"USDT"}),"receiver-email":T.Flags.string({description:"Optional sender-only receiver label. AllScale does not email the receiver; you still share the resulting link yourself."}),"sender-display-name":T.Flags.string({description:"Optional sender name shown to the receiver. Max 100 characters."}),message:T.Flags.string({description:"Optional purpose/message shown on the Claim Link page. Max 200 characters."}),expires:T.Flags.string({description:"Claim window as a duration using m/h/d (1m-30d). The window starts after funding confirms.",default:Ur}),"bridge-timeout":T.Flags.integer({description:"Shorten the browser confirmation deadline, in milliseconds. By default the CLI waits for the broker op TTL.",min:1e3}),"browser-base":T.Flags.string({description:"Override the trusted base URL of the printed /cli bridge link (defaults to the session API base)."}),"no-browser":T.Flags.boolean({description:"Do not auto-open a local browser. The command still prints the bridge URL and waits for its callback or a pasted receipt.",default:!1}),...ce.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=Hr(t["idempotency-key"]);if(n===void 0)throw new a("input.invalid","--idempotency-key is required for Claim Link reconciliation.");let r=bn(t.chain);if(r===null)throw new a("input.invalid",`--chain '${t.chain}' is not a supported EVM chain.`);let i=Sn(t["stable-coin"]);if(i===null)throw new a("input.invalid",`--stable-coin '${t["stable-coin"]}' is not supported (USDT or USDC).`);let o=$r(t.expires),s={idempotency_key:n,amount:Fr(t.amount),chain:r,stable_coin:i,receiver_email:Mr(t["receiver-email"]),sender_display_name:me("--sender-display-name",t["sender-display-name"],100)??null,sender_message:me("--message",t.message,200)??null,claim_window_seconds:o.seconds===Dr?null:o.seconds},c=this.resolveContext(t);return Pr({ctx:c,intent:s,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],autoOpen:!t["no-browser"]})}};
75
+ //# sourceMappingURL=create.js.map