@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,40 @@
1
+ "use strict";var er=Object.create;var ae=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var or=(e,t)=>{for(var n in t)ae(e,n,{get:t[n],enumerable:!0})},Ct=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of nr(t))!ir.call(e,i)&&i!==n&&ae(e,i,{get:()=>t[i],enumerable:!(r=tr(t,i))||r.enumerable});return e};var b=(e,t,n)=>(n=e!=null?er(rr(e)):{},Ct(t||!e||!e.__esModule?ae(n,"default",{value:e,enumerable:!0}):n,e)),sr=e=>Ct(ae({},"__esModule",{value:!0}),e);var qi={};or(qi,{APPROVAL_SCREEN_SCOPES:()=>Ae,UNGRANTABLE_CATEGORIES:()=>Le,approvalScreenCanGrant:()=>ct,default:()=>De,isWellFormedScope:()=>Ie,scopeCategory:()=>ke,scopeSatisfies:()=>Te});module.exports=sr(qi);var C=require("@oclif/core");var Rt="public",Pt="https://app.allscale.io";var Nt=["https://app.allscale.io"];var Ge="Override the API base URL (public builds accept only https://app.allscale.io)";var Ke="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function xt(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 xt(e)!==null}function le(e){let t=xt(e);return t!==null&&Nt.includes(t.origin)}function Ye(e){return le(e)}function J(){return"".trim()||void 0}function z(){return"public"}function N(e){try{let{hostname:t}=new URL(e);return t==="127.0.0.1"||t==="localhost"||t==="[::1]"}catch{return!1}}function qe(e){try{return new URL(e).origin}catch{return null}}function V(){{let e="[]".trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return He()}function He(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let r=JSON.parse(e);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(typeof o!="object"||o===null)continue;let{base:a,key:l,keyId:d}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let u=typeof d=="string"?d.trim():"";i.push({base:a.trim(),key:l,keyId:u.length>0?u:"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 Dt="allscale device-login";var ar={"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},lr=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 Je(e){return(typeof e=="string"?e:String(e??"")).replace(lr,"")}var cr=64;function je(e,t=new Map,n=0){if(typeof e=="string")return Je(e);if(e===null||typeof e!="object")return e;let r=t.get(e);if(r!==void 0)return r;if(n>=cr)return e;if(Array.isArray(e)){let a=[];t.set(e,a);for(let l of e)a.push(je(l,t,n+1));return a}let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)return e;let o={};t.set(e,o);for(let[a,l]of Object.entries(e))Object.defineProperty(o,a,{value:je(l,t,n+1),writable:!0,enumerable:!0,configurable:!0});return o}var c=class extends Error{code;details;constructor(t,n,r){super(Je(n)),this.code=t,this.details=r&&je(r),this.name="AllscaleError"}get exitCode(){return ar[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function $t(e){if(e instanceof c)return e;if(e instanceof Error){if(pr(e)){let t=gr(e),n={};return e.name&&e.name!=="Error"&&(n.name=e.name),Object.keys(t).length>0&&(n.oclif=t),new c("input.invalid",e.message,Object.keys(n).length>0?n:void 0)}return new c("internal",e.message,{name:e.name})}return new c("internal","Unknown error",{value:String(e)})}var ur=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),dr=[/^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 pr(e){if(fr(e))return!0;let t=e.name??"";return ur.has(t)?t==="CLIError"?We(e,"parse")||Ut(e.message):!0:Ut(e.message)}function fr(e){if(!We(e,"oclif"))return!1;let t=e.oclif;return typeof t=="object"&&t!==null&&t.exit===2&&We(e,"parse")}function Ut(e){return e?Je(e).split(`
2
+ `).some(t=>dr.some(n=>n.test(t.trim()))):!1}function We(e,t){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,t)}function gr(e){let t=e,n={};for(let r of["code","exitCode","suggestions","ref"])t[r]!==void 0&&(n[r]=t[r]);return n}function Ft(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var h=b(require("fs")),pe=b(require("path")),jt=b(require("crypto"));var hr="...<truncated>",mr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,_r=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,et=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,ze=String.raw`(?:proxy[_-]?)?authorization`,yr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${ze}"|'${ze}'|${ze})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${et}`,"gi"),wr=/\b(https?:\/\/)[^\s/?#]+@/gi,Ve=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)`,Sr=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ve}"|'${Ve}'|${Ve})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${et}`,"gi"),Xe=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)`,Er=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Xe}"|'${Xe}'|${Xe})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${et}`,"g");function Mt(e){return e.replace(wr,"$1<redacted>@").replace(mr,"<redacted-jwt>").replace(yr,"$1$2$3<redacted>").replace(Sr,"$1$2<redacted>").replace(Er,"$1$2<redacted>").replace(_r,"Bearer <redacted>")}function Gt(e){let t="";for(let n of e){let r=n.codePointAt(0),i=r<=8||r>=11&&r<=12||r>=14&&r<=31||r>=127&&r<=159;t+=i?`\\u${r.toString(16).padStart(4,"0")}`:n}return t}function Kt(e,t,n=hr){if(t<=0)return"";if(Buffer.byteLength(e,"utf8")<=t)return e;let r=Buffer.byteLength(n,"utf8");if(r>=t){let l="",d=0;for(let u of n){let f=Buffer.byteLength(u,"utf8");if(d+f>t)break;l+=u,d+=f}return l}let i=t-r,o="",a=0;for(let l of e){let d=Buffer.byteLength(l,"utf8");if(a+d>i)break;o+=l,a+=d}return`${o}${n}`}function A(e,t=16384){return Kt(Gt(Mt(e)),t)}var Ze=100,br=8,Ar=8*1024;function ce(){return{remaining:Ar}}function Qe(e,t){let n=Math.min(16384,t.remaining),r=Kt(e,n);return t.remaining-=Buffer.byteLength(r,"utf8"),r}function M(e,t,n=0,r={}){if(n>br)return Qe("<truncated>",t);if(typeof e=="string"){let i=Mt(e);return Qe(r.escapeControls?Gt(i):i,t)}if(Array.isArray(e)){let i=e.slice(0,Ze),o=i.map(a=>M(a,t,n+1,r));return e.length>i.length&&o.push(Qe(`<${e.length-i.length} more items truncated>`,t)),o}if(e!==null&&typeof e=="object"){let i=Object.create(null),o=Object.entries(e);for(let[a,l]of o.slice(0,Ze))i[a]=M(l,t,n+1,r);return o.length>Ze&&(i.output_truncated=!0),i}return e}var ue=require("process");var de=!1;function tt(e){de=e}function Ht(){return de}function X(e){de||ue.stderr.write(e)}var Yt="1";function O(e,t){if(de){let n={...e};delete n.version;let r=ce(),i={event:n.event,...n},o=M(i,r,0,{escapeControls:!0}),a=JSON.stringify({version:Yt,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Yt,event:o.event,output_truncated:!0})),ue.stderr.write(`${a}
4
+ `)}else ue.stderr.write(t)}var qt="2",K=null,k=null,Y=!1;function Lr(){let e=process.env.ALLSCALE_OUTPUT_FILE_PATH;if(e)return e;let t=process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY;if(t){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=jt.randomBytes(4).toString("hex");return pe.join(t,`allscale-output-${n}-${r}.ndjson`)}return null}var nt=64*1024*1024,kr=null;function Wt(){if(Y)return;let e=Lr();if(!e)return;K=null;let t=null;try{if((kr??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let n=pe.dirname(e);if(h.mkdirSync(n,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=h.statSync(n),d=l.mode&511;if(!l.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let r=h.constants.O_NOFOLLOW??0;t=h.openSync(e,h.constants.O_APPEND|h.constants.O_CREAT|h.constants.O_WRONLY|(h.constants.O_NONBLOCK??0)|r,384);let i=h.fstatSync(t),o=h.lstatSync(e);if(!i.isFile()||o.isSymbolicLink()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&i.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let a=i.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);h.fchmodSync(t,384)}catch(n){if(t!==null)try{h.closeSync(t)}catch{}O({event:"sidecar_disabled",reason:"open_failed",detail:A(`sidecar path '${e}' could not be opened safely (${n.message})`)},`${A(`[allscale] sidecar path '${e}' could not be opened safely (${n.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}K=e,k=t,Y=!0}var Tr=[/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 Ir(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Tr.some(n=>n.test(t))}function Jt(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=Or(t.pathname);let i=n;t.pathname!==r&&(i=!0);for(let[o]of t.searchParams)Ir(o)&&(t.searchParams.set(o,"<redacted>"),i=!0);return i?t.toString():e}catch{return e}}function Or(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function vr(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Jt(e.url)}:e}function Cr(e){let t=new Date().toISOString(),n=e,{type:r,...i}=n,o=M(i,ce()),a=JSON.stringify({version:qt,timestamp:t,type:r,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:qt,timestamp:t,type:r,output_truncated:!0})),a}function H(e){if(!Y||!K||k===null)return;let t=vr(e),n=Cr(t);try{if(h.fstatSync(k).size+Buffer.byteLength(n,"utf8")+1>nt){Y=!1;try{h.closeSync(k)}catch{}k=null,O({event:"sidecar_disabled",reason:"size_limit",...K===null?{}:{path:A(K)},max_bytes:nt},`${A(`[allscale] sidecar exceeded ${nt} bytes; disabling it for the rest of this run. Rotate or remove ${K}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}h.appendFileSync(k,`${n}
7
+ `)}catch(r){if(Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}try{O({event:"sidecar_disabled",reason:"write_failed",detail:A(r.message)},`${A(`[allscale] sidecar write failed (${r.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var zt=Jt;function Vt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function fe(){if(Y=!1,k!==null){try{h.closeSync(k)}catch{}k=null}}function ge(e=!1){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Vt()||!t}var Z=J()??Pt,j={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function he(e){return Bt(e)?new URL(e).origin:null}function P(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"<unparseable URL>"}}function Xt(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function rt(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function me(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Zt(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Qt(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function en(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function tn(e){let{resolvedApiBase:t,fromExplicitOverride:n,profileApiBase:r,profileApiBaseSource:i}=e;if(J()===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: ${Dt} --api-base ${Z}
14
+ `}var v=b(require("fs")),nn=b(require("os")),it=b(require("path")),_e=b(require("@iarna/toml"));var Nr=".allscale",xr="config.toml";function ye(){return it.join(nn.homedir(),Nr)}function we(){return it.join(ye(),xr)}function Q(){let e=we();if(!v.existsSync(e))return{};let t=v.readFileSync(e,"utf-8");try{return _e.parse(t)}catch(n){throw new c("internal",`Failed to parse ${e}: ${n.message}`)}}function rn(e){let t=ye();v.existsSync(t)||v.mkdirSync(t,{recursive:!0,mode:448});let n=_e.stringify(e);v.writeFileSync(we(),n,{mode:384})}function on(e,t){return e.profile?.[t]}function sn(e,t,n){return{...e,profile:{...e.profile??{},[t]:n}}}function an(e,t,n){let r=t??n??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 Se(e){if(!le(e))throw new c("input.invalid",`Refusing to send credentials to API base ${P(e)}. `+Ke)}function ot(e){let t=J();if(t===void 0||N(e))return;let n=he(e),r=V();if(r.length>0){let o=r.map(l=>he(l.base)).filter(l=>l!==null);if(n!==null&&o.includes(n))return;let a=r.map(l=>P(l.base)).join(", ");throw new c("input.invalid",`Refusing to send to ${P(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let i=he(t);if(!(n!==null&&n===i))throw new c("input.invalid",`Refusing to send to ${P(e)} \u2014 this build only signs for ${P(t)}. Re-login against this build's environment, or use a build for that one.`)}var Br=require("@noble/hashes/sha3");var ln=["USDT","USDC"];var Po=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var x=require("@oclif/core"),ee=class e extends C.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:C.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:C.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:z()==="public"}),"api-base":C.Flags.string({description:Ge,helpGroup:"GLOBAL",hidden:z()==="public"}),"insecure-storage":C.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{tt(this.jsonEnabled()),Wt(),H({type:"session-start",command:this.id??"",argv:Ur(this.argv)});let t=this.constructor;if(z()==="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(!t.isLocalOnly&&me()!==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(t.requiresEscapeHatch&&!en())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 n=ge(this.jsonEnabled()),r=this.argv.length===0&&!n&&qr(t)?this.config.findCommand(this.id??""):void 0;if(r){fe();let o=await(0,C.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(r,this.config.topics);return}let i=await this.runCommand();return H({type:"command-end",ok:!0}),fe(),t.emitsOwnOutput?void 0:(this.jsonEnabled()||Ft(i),{data:i})}catch(t){let n=$t(t);H({type:"error",code:n.code,message:A(n.message)}),H({type:"command-end",ok:!1,exitCode:n.exitCode}),fe(),this.emitError(n),process.exitCode=n.exitCode;return}finally{tt(!1)}}resolveSessionApiBaseChain(t){let n=Q(),r=t.profile??void 0,i=t["api-base"]??void 0,o=r!==void 0||rt()!==void 0,a=an(n,r,rt()),l=on(n,a),d=i??me(),u=d??l?.api_base??Z,f=tn({resolvedApiBase:u,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return f&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,O({event:"legacy_staging_profile",api_base:u,profile:a},f)),{apiBase:u,explicitApiBase:d,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(t){let{apiBase:n}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||Se(n),n}resolveContext(t){if(z()==="public"){if(t.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(t["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&&me()!==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 n=t.token??void 0,r=!!t["insecure-storage"],{apiBase:i,explicitApiBase:o,profile:a,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(t);return this.constructor.isLocalOnly||(Se(i),ot(i)),{apiBase:i,profile:a,token:n??Xt(),insecureStorage:r||Zt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d}}emitError(t){process.stderr.write(`${Hr(t)}
15
+ `)}},be=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),Dr=new Set(Array.from(be).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Ur(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r.startsWith("-")){let i=r.indexOf("=");if(i!==-1){let o=r.slice(0,i);if(be.has(o)){t.push(`${o}=<redacted>`);continue}}}if(be.has(r)){t.push(r),n+1<e.length&&(be.has(e[n+1])||(t.push("<redacted>"),n+=1));continue}if(r.startsWith("-")&&!r.startsWith("--")&&r.length>2&&r[1]!=="="){let i=r.slice(0,2);if(Dr.has(i)){t.push(`${i}<redacted>`);continue}}t.push(r)}return t}var $r=/(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 Fr(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return $r.test(t)}var Mr=/_(removed|cleared|count|total)$/i;function Gr(e,t){return typeof t=="number"&&Mr.test(e)}var Kr=new Set(ln);function Yr(e,t){return e==="token_symbol"&&typeof t=="string"&&Kr.has(t)}var Ee=100;function st(e,t=0){if(t>8)return"<truncated>";if(Array.isArray(e)){let n=e.slice(0,Ee),r=n.map(i=>st(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,Ee))n[i]=Fr(i)&&!Gr(i,o)&&!Yr(i,o)?"<redacted>":st(o,t+1);if(r.length>Ee){let i="<truncated>";for(;i in n;)i=`<${i}>`;n[i]=`${r.length-Ee} more keys`}return n}return typeof e=="string"?A(e):e}function Hr(e){let t=Ht()?void 0:2,n=st(e.toJSON()),r=JSON.stringify(n,null,t);return Buffer.byteLength(r,"utf8")+1<=65536?r:JSON.stringify({error:{code:e.code,message:A(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,t)}function qr(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))}function cn(e){let t=new Map;for(let n of e){let r=n.lastIndexOf(":");if(r===-1){t.set(n,t.get(n)??new Set);continue}let i=n.slice(0,r),o=n.slice(r+1),a=t.get(i)??new Set;a.add(o),t.set(i,a)}return[...t].map(([n,r])=>{if(r.size===0)return n;if(r.size===1)return`${n}:${[...r][0]}`;let i=["read_only","all"].filter(o=>r.has(o));for(let o of r)i.includes(o)||i.push(o);return`${n}:{${i.join(",")}}`}).join(", ")}var at=new Set(["transaction:all","store:read_only","wallet:all"]),lt=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","store:all","wallet:read_only"]),Ae=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"]),Le=new Set(["payroll","admin:user","admin:org","admin:audit"]);function ke(e){let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function Te(e,t){if(e===t)return!0;let n=":read_only";return t.endsWith(n)&&e===`${t.slice(0,-n.length)}:all`}function ct(e){return[...Ae].some(t=>Te(t,e))}function Ie(e){let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return!1;let n=e.slice(t+1);return n==="read_only"||n==="all"}var dn=require("child_process");async function pn(e,t={}){if(!Ye(e))throw new c("input.invalid",`Refusing to launch browser for untrusted origin: ${P(e)}`);let n=t._env??process.env,r=t._platform??process.platform,i=n.BROWSER?.trim();if(i&&i.toLowerCase()==="none")throw new c("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 c("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=jr(r,i);await Wr(o.command,[...o.args,e])}function jr(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 Wr(e,t){return new Promise((n,r)=>{let i;try{i=(0,dn.spawn)(e,t,{detached:!0,stdio:"ignore"})}catch(a){r(un(e,a));return}let o=!1;i.once("error",a=>{o||(o=!0,r(un(e,a)))}),setImmediate(()=>{o||(o=!0,i.unref(),n())})})}function un(e,t){return new c("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${t.message}. Re-run on a host with a graphical environment.`)}var ut=require("process"),fn=require("readline");async function gn(e){let t=(0,fn.createInterface)({input:process.stdin,output:ut.stderr}),n;try{let r=await new Promise(o=>{let a=!1,l=d=>{a||(a=!0,o(d))};t.on("SIGINT",()=>l(void 0)),t.on("close",()=>l(void 0)),n=()=>l(void 0),process.on("SIGINT",n),t.question(`${e} [Y/n] `,l)});if(r===void 0)return ut.stderr.write(`
16
+ `),!1;let i=r.trim().toLowerCase();return i===""||i==="y"||i==="yes"}finally{n&&process.removeListener("SIGINT",n),t.close()}}var hn=b(require("crypto")),mn=b(require("fs")),_n=b(require("path"));var Jr="key-id",zr="x-allscale-cli-version",dt="cli-1",Vr="aScaLe_cli_obf_v1",Xr="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Zr(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 Qr=Zr(Xr,Vr),ei=`Bearer ${Qr}`;function yn(e,t){let n=qe(e);if(n!==null)return t.find(r=>qe(r.base)===n)}function ti(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let t=V();if(t.length>0){let r=yn(e,t);if(r)return r.key;if(N(e)){let i=process.env.ALLSCALE_SIGNING_KEY;return i&&i.trim().length>0?i:N(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 ni(e){{let r="cli-1".trim();if(r.length>0)return r}let t=V();if(t.length>0){let r=e!==void 0?yn(e,t):void 0;if(r)return r.keyId;if(e!==void 0&&N(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(!N(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 ri(){return"0.1.0"}function ii(){return new c("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 Oe(e,t){let n=ti(t);if(!n)throw ii();let r=ni(t),i=Math.floor(Date.now()/1e3).toString(),o=hn.createHash("sha256").update(`${n}${i}${e}`).digest("hex"),a={timestamp:i,"secret-key":o,[zr]:ri()};return r.length>0&&(a[Jr]=r),a}function ve(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var pt=256*1024,Ce=class extends c{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"}},W=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 ft(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 Ce(e.status,t,n.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],l=0,d,u=n.timeoutMs,f=u===void 0?void 0:new Promise((p,g)=>{d=setTimeout(()=>{g(new W(e.status,u))},u),d.unref?.()});try{for(;;){let p=o.read(),{done:g,value:m}=f?await Promise.race([p,f]):await p;if(g)break;if(l+=m.byteLength,l>t)throw o.cancel().catch(()=>{}),new Ce(e.status,t,n.oversizeKind);a.push(Buffer.from(m))}}catch(p){throw p instanceof W&&o.cancel(p).catch(()=>{}),p}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(a,l).toString("utf8")}var ks=32*1024*1024,Ts=4*1024*1024;function oi(e,t){if(!(e<300||e>=400))throw new c("transport.network",`API returned HTTP ${e} (a redirect) for ${zt(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 gt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}oi(e.status,e.url)}}var wn="--dns-result-order=ipv4first";async function te(e,t){if(e.status!==403)return;let n=e.headers.get("content-type")?.toLowerCase()??"",r=e.headers.get("cf-ray")??"",i=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=n.includes("text/html"),a=t?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),d=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||l)&&(i||t!==void 0&&d)))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 c("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=${wn} 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=${wn}`})}var Sn=2014;function si(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===Sn||n===String(Sn)}function Re(e,t){if(!(e>=200&&e<300)&&si(t))throw new c("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})}var ai={1:"admin",2:"business",3:"employee",10:"third_party_customer"};function En(e){if(typeof e=="string")return e;if(typeof e=="number")return ai[e]??`user_type_${e}`}function bn(e){if(typeof e!="string")return;let t=e.trim();if(t.length===0||t.length>254||/\s/.test(t))return;let n=t.indexOf("@");if(!(n<=0)&&t.indexOf("@",n+1)===-1&&n!==t.length-1)return t.toLowerCase()}var li="/api/public/auth/cli_authorize_init",ci="/api/public/auth/cli_authorize_poll",ht=1e4,mt=1e4,ui=1e3,di=3,pi=3e4,Ln=900,kn="empty_response",Tn="invalid_response",In="poll_fetch_failure",On="poll_request_timeout",vn="poll_body_failure",Cn="poll_body_timeout",fi="approved_credential_mismatch";async function gi(e,t={}){let n=new URL(li,e).toString(),r={credential_mode:"agent_key"};t.scopes!==void 0&&(r.scopes=t.scopes),t.device_label!==void 0&&(r.device_label=t.device_label);let i=JSON.stringify(r),o=Oe(ve(r),e),a=Date.now()+ht,l;try{l=await Nn(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...o},body:i},ht)}catch(p){throw Pn(n,p,"init",ht)}if(await te(l),l.status===429)throw new c("rate_limited","Device-pairing init was rate-limited.",{status:429});if(await gt(l),l.status!==200){let p=await ne(l,a,n,"init");throw await te(l,p),Re(l.status,p),new c(l.status>=500?"backend.internal":"input.invalid",`Device-pairing init failed: HTTP ${l.status}`,{status:l.status,body:p.slice(0,500)})}let u=_i(await ne(l,a,n,"init")).data??{};for(let p of["polling_token","verification_code","verification_url"])if(typeof u[p]!="string"||u[p].length===0)throw new c("backend.internal",`Device-pairing init response missing required field: ${p}`);if(typeof u.expires_at!="number"||u.expires_at<=0)throw new c("backend.internal","Device-pairing init response missing or invalid expires_at");let f=typeof u.poll_interval=="number"&&u.poll_interval>0?u.poll_interval:2;return{polling_token:u.polling_token,verification_code:u.verification_code,verification_url:u.verification_url,expires_at:u.expires_at,poll_interval:f}}async function hi(e,t,n=mt){let r=new URL(ci,e).toString(),i={polling_token:t},o=JSON.stringify(i),a=Oe(ve(i),e),l=Number.isFinite(n)&&n>0?Math.max(1,Math.min(mt,Math.floor(n))):mt,d=Date.now()+l,u;try{u=await Nn(r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...a},body:o},l)}catch(I){throw Pn(r,I,"poll",l)}if(await te(u),u.status===429)throw new c("rate_limited","Device-pairing poll was rate-limited.",{status:429});if(u.status>=500){let I=await ne(u,d,r,"poll");Re(u.status,I);let Me=yi(I);throw Me===7510?new c("auth.token_expired","Device-pairing window expired. Re-run `allscale device-login`."):Me===7511?new c("auth.no_token","Polling token is invalid or already consumed. Re-run `allscale device-login`."):Me===7530?new c("input.invalid","None of the approved scopes can be granted to this account, so no key was issued. Re-run `allscale device-login` and approve different scopes."):new c("backend.internal",`Device-pairing poll failed: HTTP ${u.status}`,{status:u.status,body:I.slice(0,500)})}if(await gt(u),u.status!==200){let I=await ne(u,d,r,"poll");throw await te(u,I),Re(u.status,I),new c("input.invalid",`Device-pairing poll failed: HTTP ${u.status}`,{status:u.status,body:I.slice(0,500)})}let f=await ne(u,d,r,"poll");if(f.trim().length===0)throw new c("backend.internal","Device-pairing poll returned an empty HTTP 200 response.",{status:200,reason:kn});let p;try{p=JSON.parse(f)}catch{throw _t()}if(p===null||typeof p!="object"||Array.isArray(p))throw _t();let g=p,m=g.data?.status;if(m==="pending")return{status:"pending"};if(m!=="approved")throw _t();let S=En(g.data?.user_type)??"business",_=g.data?.scopes,T=Array.isArray(_)&&_.every(I=>typeof I=="string")?_:void 0,E=T&&T.length>0?{scopes:T}:{},Ue=g.data?.agent_key;if(typeof Ue!="string"||Ue.length===0)throw new c("backend.internal","Requested a scoped agent key, but the backend approved a legacy full-permission cookie session \u2014 it may not support scoped keys yet, or a rolling deploy may be in progress. Refusing to store the broader credential. The one-shot approval was consumed, so do not start a new pairing blindly; review your active CLI keys in the AllScale web dashboard first, before re-running `allscale device-login`.",{status:200,outcome_ambiguous:!0,reason:fi,expected_credential:"agent_key"});let $e=g.data?.agent_key_expires_at,Fe=g.data?.business_id,Zn=typeof Fe=="string"&&Fe.length>0?{business_id:Fe}:{},vt=bn(g.data?.user_email),Qn=vt===void 0?{}:{user_email:vt};return{status:"approved",user_type:S,credential:"agent_key",tokens:{access_token:"",refresh_token:"",agent_key:Ue,...typeof $e=="number"&&$e>0?{agent_key_expires_at:$e}:{},user_type:S,api_base:e,...E,...Zn,...Qn}}}async function Rn(e,t){let n=await gi(e,{scopes:t.scopes,device_label:t.device_label}),r=t._now??(()=>Math.floor(Date.now()/1e3)),i=typeof t._maxWallSeconds=="number"&&t._maxWallSeconds>0?t._maxWallSeconds:Ln,o=Math.min(n.expires_at,r()+i);await t.onInit(n,{pollingDeadlineAt:o});let a=t._sleep??(g=>new Promise(m=>{setTimeout(m,g)})),l=Math.max(ui,n.poll_interval*1e3),d=0,u=l,f=0,p;for(;;){let g=(o-r())*1e3;if(g<=0)throw An(p,f);await a(Math.min(u,g));let m=(o-r())*1e3;if(m<=0)throw An(p,f);d+=1;let S;try{S=await hi(e,n.polling_token,m)}catch(_){if(p!==void 0&&_ instanceof c&&_.code==="auth.no_token")throw yt(p,f,"invalid_polling_token_after_transient_failure");if(!mi(_))throw _;if(f+=1,p=_,f>di)throw yt(_,f,"transient_retry_budget_exhausted");u=Math.min(pi,l*2**f);continue}if(S.status==="approved")return{...S,verification_code:n.verification_code};f=0,p=void 0,u=l,t.onPending?.(d)}}function Pn(e,t,n,r){return t instanceof Error&&t.name==="AbortError"?new c("transport.timeout",`Device-pairing ${n} against ${e} timed out after ${r}ms.`,{timeout_ms:r,stage:n,reason:n==="poll"?On:"init_request_timeout"}):new c("transport.network",`Network error during device-pairing ${n} against ${e}.`,{stage:n,reason:n==="poll"?In:"init_fetch_failure"})}function mi(e){if(!(e instanceof c))return!1;if(e.code==="transport.network")return e.details?.stage==="poll"&&(e.details.reason===In||e.details.reason===vn);if(e.code==="transport.timeout")return e.details?.stage==="poll"&&(e.details.reason===On||e.details.reason===Cn);if(e.code!=="backend.internal")return!1;let t=e.details?.status;return typeof t=="number"&&t>=500&&t<=599||e.details?.reason===kn||e.details?.reason===Tn}function _t(){return new c("backend.internal","Device-pairing poll returned a malformed or unexpected HTTP 200 response.",{status:200,reason:Tn})}function An(e,t){return e!==void 0?yt(e,t,"pairing_deadline_elapsed_after_transient_failure"):new c("auth.token_expired",`Device-pairing timed out before the browser confirmed \u2014 the pairing window closed, or the CLI reached its ${Ln/60}-minute polling ceiling. Nothing was stored locally. If you approved in the browser after seeing this, the pairing may still have minted a key that never reached this CLI \u2014 review and revoke it in the AllScale web dashboard. Then re-run \`allscale device-login\`.`)}function yt(e,t,n){let r=e.details?.status;return new c("backend.internal","Device-pairing result is ambiguous: a poll response was lost after the browser may have approved the one-shot exchange. A credential may have been issued without reaching this CLI. Do not assume a blind retry is safe; check the browser result, and review your active CLI keys in the AllScale web dashboard, before starting a new pairing.",{outcome_ambiguous:!0,reason:n,transient_failures:t,last_transient_error_code:e.code,...typeof r=="number"?{last_http_status:r}:{}})}async function ne(e,t,n,r){let i=Math.max(1,t-Date.now());try{return await ft(e,pt,{timeoutMs:i})}catch(o){throw o instanceof c?o:o instanceof W?new c("transport.timeout",`Device-pairing ${r} response body timed out after ${o.timeoutMs}ms.`,{status:o.status,timeout_ms:o.timeoutMs,stage:r,reason:r==="poll"?Cn:"init_body_timeout"}):new c("transport.network",`Network error while reading the device-pairing ${r} response body from ${n}.`,{status:e.status,stage:r,reason:r==="poll"?vn:"init_body_failure"})}}async function Nn(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n);i.unref?.();try{return await fetch(e,{...t,redirect:"manual",signal:r.signal})}finally{clearTimeout(i)}}function _i(e){if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function yi(e){if(e)try{let t=JSON.parse(e);if(typeof t.code=="number")return t.code}catch{}}var jn=b(require("path"));var Et=require("crypto"),s=b(require("fs")),w=b(require("path"));var Pe=1024*1024,wi=5e3,Si=20,Ei=3e4,wt=4096,bi=new Int32Array(new SharedArrayBuffer(4)),re=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ne(e){return e instanceof re}var L=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Ai=null;function D(){return new c("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 xe(){return(Ai??process.platform)!=="win32"}function Gn(){if(!xe())throw D()}function Kn(e){try{return s.default.lstatSync(e),!1}catch(t){if(!y(t,"ENOENT"))throw t}try{let t=s.default.lstatSync(w.dirname(e));return!t.isSymbolicLink()&&t.isDirectory()}catch(t){if(y(t,"ENOENT"))return!0;throw t}}function y(e,t){return typeof e=="object"&&e!==null&&e.code===t}function ie(e,t){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${t} is not owned by the current effective user`)}function oe(e,t){return e.dev===t.dev&&e.ino===t.ino}function Li(e){Atomics.wait(bi,0,0,e)}function Yn(e){try{return process.kill(e,0),!0}catch(t){return!y(t,"ESRCH")}}function ki(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xn(e,t){let n=w.dirname(e);t&&s.default.mkdirSync(n,{recursive:!0,mode:448});let r;try{r=s.default.lstatSync(n)}catch(o){if(!t&&y(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=s.default.openSync(n,s.default.constants.O_RDONLY|(s.default.constants.O_DIRECTORY??0)|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0));let o=s.default.fstatSync(i),a=s.default.lstatSync(n);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!oe(o,a))throw new Error("credential-store parent changed while it was being inspected");ie(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&w.basename(n)===".allscale"&&(s.default.fchmodSync(i,448),l=s.default.fstatSync(i)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{i!==null&&s.default.closeSync(i)}return!0}function R(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=s.default.lstatSync(e)}catch(o){throw r.retryOnPathChange&&y(o,"ENOENT")?new L:o}if(!oe(n,i))throw r.retryOnPathChange?new L: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 re;if(ie(n,"credential-store file"),process.platform!=="win32"){s.default.fchmodSync(t,384);let o=s.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 Ti(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=s.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 Bn(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(i){if(y(i,"ENOENT"))try{if(s.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(y(o,"ENOENT"))return null;throw o}throw i}let n=s.default.fstatSync(t),r=R(e,t,n);return Ti(t,r)}finally{t!==null&&s.default.closeSync(t)}}function Dn(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(i){if(y(i,"ENOENT")&&Kn(e))return;throw i}let n=s.default.fstatSync(t),r=R(e,t,n);U(e,r)}finally{t!==null&&s.default.closeSync(t)}qn(w.dirname(e))}function Ii(e){let t;try{t=s.default.lstatSync(e)}catch(n){if(y(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 re;ie(t,"credential-store replacement target")}function Oi(e,t){for(let n=0;n<8;n+=1){let r=(0,Et.randomBytes)(12).toString("hex"),i=w.join(e,`.${t}.${process.pid}.${r}.tmp`);try{return{fd:s.default.openSync(i,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_WRONLY|(s.default.constants.O_NOFOLLOW??0),384),tempPath:i}}catch(o){if(y(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function Hn(e,t){let n=0;for(;n<t.length;){let r=s.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 qn(e){if(process.platform==="win32")return;let t=null;try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_DIRECTORY??0)|(s.default.constants.O_NOFOLLOW??0)),s.default.fsyncSync(t)}catch{}finally{if(t!==null)try{s.default.closeSync(t)}catch{}}}function vi(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=w.dirname(e),i=w.basename(e),o=null,a=null,l=!1;try{let d=Oi(r,i);o=d.fd,a=d.tempPath;let u=s.default.fstatSync(o);if((R(a,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");Hn(o,n),s.default.fsyncSync(o),R(a,o,s.default.fstatSync(o));let p=o;o=null,s.default.closeSync(p),Ii(e),s.default.renameSync(a,e),l=!0}finally{if(o!==null)try{s.default.closeSync(o)}catch{}if(!l&&a!==null)try{s.default.unlinkSync(a)}catch{}}qn(r)}function Ci(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock`)}function Ri(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock-recovery`)}function Pi(e,t){if(t.size>wt)return null;let n=Buffer.alloc(wt+1),r=0;for(;r<n.length;){let o=s.default.readSync(e,n,r,n.length-r,null);if(o===0)break;r+=o}if(r>wt)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 U(e,t){let n=s.default.lstatSync(e);if(n.isSymbolicLink()||!n.isFile()||!oe(n,t))throw new Error("credential-store lock changed while it was being inspected");ie(n,"credential-store lock"),s.default.unlinkSync(e)}function Un(e,t){let n=null;try{try{n=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(d){if(y(d,"ENOENT"))try{let u=s.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new L}catch(u){if(y(u,"ENOENT"))return{state:"absent"};throw u}throw d}let r=s.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Pi(n,i);return{state:(o?.target===t&&o?!Yn(o.pid):Date.now()-i.mtimeMs>=Ei)?"stale":"active",stats:i}}finally{n!==null&&s.default.closeSync(n)}}function Ni(e,t){for(let n=0;n<8;n+=1){let r=(0,Et.randomBytes)(12).toString("hex"),i=w.join(e,`.${t}.${process.pid}.${r}.lock-claim`),o={pid:process.pid,nonce:r,target:t},a=null;try{a=s.default.openSync(i,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_WRONLY|(s.default.constants.O_NOFOLLOW??0),384);let l=s.default.fstatSync(a),d=R(i,a,l,{allowMultipleLinks:!0});return Hn(a,Buffer.from(JSON.stringify(o),"utf8")),s.default.fsyncSync(a),{claimPath:i,metadata:o,stats:d}}catch(l){if(y(l,"EEXIST"))continue;try{s.default.unlinkSync(i)}catch{}throw l}finally{a!==null&&s.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function xi(e,t){let n;try{n=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(r){throw y(r,"ENOENT")?new L:r}try{let r=s.default.fstatSync(n),i=R(e,n,r,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!oe(i,t))throw new L;return{fd:n,lockPath:e,stats:i}}catch(r){throw s.default.closeSync(n),r}}function $n(e){let t=null;try{try{t=s.default.openSync(e,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(n){if(y(n,"ENOENT"))try{let r=s.default.lstatSync(e);throw r.isSymbolicLink()||!r.isFile()?new Error("credential-store recovery gate must be a real regular file"):new L}catch(r){if(y(r,"ENOENT"))return!1;throw r}throw n}return R(e,t,s.default.fstatSync(t),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{t!==null&&s.default.closeSync(t)}}function Bi(e){let t;try{t=s.default.openSync(e,s.default.constants.O_CREAT|s.default.constants.O_EXCL|s.default.constants.O_RDWR|(s.default.constants.O_NOFOLLOW??0),384)}catch(r){if(y(r,"EEXIST"))return null;throw r}let n=null;try{n=s.default.fstatSync(t);let r=R(e,t,n,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:t,lockPath:e,stats:r}}catch(r){if(n!==null)try{U(e,n)}catch{}throw s.default.closeSync(t),r}}function B(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");Li(Si)}function Fn(e){let t=w.dirname(e),n=w.basename(e),r=Ci(e),i=Ri(e),o=Ni(t,n),a=Date.now()+wi,l=!1,d=!1,u=null,f;try{for(;u===null;)try{if($n(i)){B(a,!0);continue}s.default.linkSync(o.claimPath,r),d=!0,u=xi(r,o.stats),l=!0}catch(p){if(d&&!l){try{U(r,o.stats)}catch{}d=!1}if(p instanceof L){B(a,!1);continue}if(!y(p,"EEXIST"))throw p;let g;try{g=Un(r,n)}catch(S){if(S instanceof L){B(a,!1);continue}throw S}if(g.state==="absent")continue;if(g.state==="stale"){let S;try{S=Bi(i)}catch(_){if(_ instanceof L){B(a,!1);continue}throw _}if(S!==null){try{let _;try{_=Un(r,n)}catch(T){if(T instanceof L){B(a,!1);continue}throw T}_.state==="stale"&&U(r,_.stats)}finally{St(S)}continue}}let m;try{m=$n(i)}catch(S){if(S instanceof L){B(a,!1);continue}throw S}B(a,m)}}catch(p){f=p}try{U(o.claimPath,o.stats)}catch(p){!y(p,"ENOENT")&&!l&&f===void 0&&(f=p)}if(f!==void 0)throw f;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function St(e){try{U(e.lockPath,e.stats)}finally{s.default.closeSync(e.fd)}}function Di(e,t){let n=ki(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 Mn(e){let t=w.dirname(e),n=w.basename(e);for(let r of s.default.readdirSync(t)){let i=Di(r,n);if(i===null||Yn(i))continue;let o=w.join(t,r),a=null;try{try{a=s.default.openSync(o,s.default.constants.O_RDONLY|(s.default.constants.O_NOFOLLOW??0)|(s.default.constants.O_NONBLOCK??0))}catch(u){if(y(u,"ENOENT")||y(u,"ELOOP"))continue;throw u}let l=s.default.fstatSync(a),d=s.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!oe(l,d))continue;try{ie(l,"credential-store orphan")}catch{continue}U(o,l)}catch(l){if(!y(l,"ENOENT"))throw l}finally{a!==null&&s.default.closeSync(a)}}}function se(e,t,n){if(!xe()){if(t.allowUnsupportedPlatformCleanup){if(t.createParent)throw D();if(!xn(e,!1))return n({read:()=>null,remove:()=>{},write:()=>{throw D()}});let a=Fn(e);try{return Mn(e),n({read:()=>Bn(e),remove:()=>Dn(e),write:()=>{throw D()}})}finally{St(a)}}if(!t.createParent){let o=!1;try{o=Kn(e)}catch{throw D()}if(o)return n({read:()=>null,remove:()=>{},write:()=>{throw D()}})}throw D()}if(!xn(e,t.createParent))return n({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let i=Fn(e);try{return Mn(e),n({read:()=>Bn(e),remove:()=>Dn(e),write:o=>vi(e,o)})}finally{St(i)}}var bt="allscale-cli";function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wn(e){return Tt(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new c("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 At(){return new c("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 Be(){return new c("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var $,Lt=!1;function Ui(){return Qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function $i(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let t=e.message;return typeof t=="string"&&t.split(`
17
+ `,1)[0]==="Cannot find module 'keytar'"}function Fi(){if($!==void 0)return $;if(Ui())return Lt=!1,$=null,$;try{$=require("keytar"),Lt=!1}catch(e){Lt=!$i(e),$=null}return $}function Jn(){let e=xe()?"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 c("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 Jn()}}var It=class{constructor(t){this.keytar=t}keytar;kind="keychain";async read(t){let n=await kt(()=>this.keytar.getPassword(bt,t));if(n===null)return null;let r;try{r=JSON.parse(n)}catch{throw F("OS keychain")}if(!Wn(r))throw F("OS keychain");return r}async get(t){return this.read(t)}async set(t,n){await this.read(t),await kt(()=>this.keytar.setPassword(bt,t,JSON.stringify(n)))}async delete(t){await this.read(t),await kt(()=>this.keytar.deletePassword(bt,t))}},Mi="credentials.json",Ot=class{kind="insecure-file";filePath;constructor(t){this.filePath=t??jn.join(ye(),Mi)}read(t){let n;try{n=t.read()}catch(i){throw Ne(i)?At():F("plaintext file")}if(n===null)return{profiles:{}};let r;try{r=JSON.parse(n)}catch{throw F("plaintext file")}if(!Tt(r)||!Tt(r.profiles))throw F("plaintext file");return r}write(t,n){try{t.write(JSON.stringify(n,null,2))}catch(r){throw Ne(r)?At():Be()}}profileTokens(t,n){let r=t.profiles[n];if(r!==void 0){if(!Wn(r))throw F("plaintext file");return r}}async get(t){try{return se(this.filePath,{createParent:!1},n=>this.profileTokens(this.read(n),t)??null)}catch(n){throw n instanceof c?n:F("plaintext file")}}async set(t,n){try{se(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 c?r:Be()}}async delete(t){try{se(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 c?n:Be()}}async clearProfile(t){try{return se(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 c?n:Ne(n)?At():Be()}}};function zn(e){if(e.insecureStorage)return Gn(),new Ot(e.insecureFilePath);let t=Fi();if(t)return new It(t);throw Jn()}async function Vn(e,t){await e.get(t)}async function Xn(e,t,n){try{await e.set(t,n)}catch(r){let i=r instanceof c?r.message:A(String(r)),o=n.agent_key?"An agent key was already minted for this account but could not be stored, so it is now orphaned: it cannot be listed or revoked from the CLI (key management is control-plane and rejects agent-key sessions). Remove it from the web dashboard.":"The session credential could not be stored, so nothing was persisted \u2014 no key record was created on the account. Re-run the command to authenticate again once storage is available.";throw new c(r instanceof c?r.code:"storage.unavailable",`${i} ${o}`,r instanceof c?r.details:void 0)}}var De=class e extends ee{static description="Log in via browser-confirmed device pairing. Use an existing web session or sign in there with Passkey or Email (enter the Email OTP on the webpage), then approve the CLI. The backend mints a scoped agent key \u2014 the only credential this CLI issues; no web sign-in secret is entered in the terminal.";static examples=["$ allscale device-login","$ allscale device-login --device-label tom-mbp-2026","$ allscale device-login --device-label CI-runner --scopes invoice:read_only --scopes claim_link:all"];static flags={"device-label":x.Flags.string({description:"Human-readable label shown in the browser approval UI so the user can confirm they're authorizing the right device."}),scopes:x.Flags.string({description:"Requested scopes for the eventual agent key, repeatable. Scope strings use `<category>:<tier>`; `:all` implies `:read_only` for the same category. Pairs the approval screen can grant: "+cn(Ae)+". The final set is chosen \u2014 and can be overridden \u2014 on that screen, and is ENFORCED server-side on every request. The Wallets toggle is on by default and grants `wallet:read_only`, which `invoice pay` and `wallet list` both need.",multiple:!0}),"no-browser":x.Flags.boolean({description:"Skip launching the browser; print the verification URL only. Open it in a browser to sign in with Passkey or Email and approve (the Email OTP stays on the webpage). Useful for CI or ssh sessions.",default:!1}),yes:x.Flags.boolean({char:"y",description:"Skip the interactive confirmation and start the pairing immediately. Only a BARE invocation is ever prompted, so passing any flag already skips it; use this to say so explicitly. Automation that allocates a pty for stdin/stdout/stderr and runs the command bare is indistinguishable from a human \u2014 that is the case this flag exists for.",default:!1}),...ee.baseFlags};async runCommand(){let{flags:t}=await this.parse(e),n=this.resolveContext(t),r=zn({insecureStorage:n.insecureStorage});if(this.argv.length===0&&!t.yes&&!ge(this.jsonEnabled())&&process.stderr.isTTY===!0&&(process.stderr.write(`\`allscale device-login\` will now:
18
+ - register a new pairing session with ${n.apiBase}
19
+ - open your browser at the approval page
20
+ - wait for your approval, then store a scoped agent key (profile: ${n.profile})
21
+ `),!await gn("Start device pairing?")))throw new c("user.cancelled","Device pairing cancelled \u2014 no pairing session was created.");await Vn(r,n.profile);let o=await Rn(n.apiBase,{scopes:t.scopes,device_label:t["device-label"],onInit:async(g,{pollingDeadlineAt:m})=>{await Gi(g,!!t["no-browser"],m)},onPending:g=>{(g===1||g%5===0)&&X(`Still waiting for approval (poll ${g})...
22
+ `)}});await Xn(r,n.profile,o.tokens);let a=Q(),l=sn(a,n.profile,{api_base:n.apiBase,user_type:Hi(o.user_type),api_base_source:n.apiBaseSource});l.default||(l.default=n.profile),rn(l),X(`Saved tokens to ${r.kind==="keychain"?"OS keychain":"~/.allscale/credentials.json"} (profile: ${n.profile}). Profile metadata: ${we()}
23
+ `);let d=o.tokens.scopes??[],u=typeof o.tokens.agent_key_expires_at=="number"?new Date(o.tokens.agent_key_expires_at*1e3).toISOString():void 0;X(`Credential: scoped agent key. Scopes${d.length>0?` (${d.join(", ")})`:""} are ENFORCED server-side.
24
+ ${u?`The key expires at ${u}`:"The key has no recorded expiry"} and does not refresh \u2014 re-run \`allscale device-login\` when it expires or is revoked.
25
+ `);let p=(t.scopes??[]).filter(g=>!d.some(m=>Te(m,g)));if(p.length>0){let g=p.filter(E=>!ct(E)),m=g.filter(E=>Ie(E)&&Le.has(ke(E))),S=g.filter(E=>at.has(E)),_=g.filter(E=>lt.has(E)),T=g.filter(E=>!lt.has(E)&&!at.has(E)&&!(Ie(E)&&Le.has(ke(E))));O({event:"scopes_not_granted",requested_not_granted:p,granted:d,..._.length>0?{otp_login_would_grant:_}:{},...S.length>0?{reaches_no_operation:S}:{},...T.length>0?{unrecognised:T}:{},...m.length>0?{ungrantable:m}:{}},`warning: requested scope(s) not granted: ${p.join(", ")}. The browser approval screen replaces the requested set with its own selection.
26
+ `+(_.length>0?`The screen cannot offer ${_.join(", ")} \u2014 use \`allscale otp-login --scopes <scope>\` for those.
27
+ `:"")+(S.length>0?`${S.join(", ")} reaches no operation today \u2014 a key can carry it, but nothing accepts it, so no login path makes it useful.
28
+ `:"")+(T.length>0?`${T.join(", ")} is not a recognised scope \u2014 check the spelling against \`--help\`; the catalog uses \`<category>:<tier>\`.
29
+ `:"")+(m.length>0?`${m.join(", ")} is not grantable to new keys at all \u2014 no login path can mint it.
30
+ `:""))}return{profile:n.profile,api_base:n.apiBase,user_type:o.user_type,storage:r.kind,verification_code:o.verification_code,device_label:t["device-label"]??void 0,credential:o.credential,...o.tokens.business_id===void 0?{}:{business_id:o.tokens.business_id},...o.tokens.user_email===void 0?{}:{user_email:o.tokens.user_email},scopes:d,...u?{agent_key_expires_at:u}:{}}}};async function Gi(e,t,n){if(O({event:"device_authorization",verification_url:e.verification_url,verification_code:e.verification_code,polling_deadline_at:new Date(n*1e3).toISOString()},`
31
+ Open this URL to authorize the CLI:
32
+ ${e.verification_url}
33
+
34
+ Or visit ${Yi(e.verification_url)} and enter:
35
+ ${e.verification_code}
36
+
37
+ Waiting for approval \u2014 the CLI stops polling at ${new Date(n*1e3).toISOString()} (about ${Ki(n)}).
38
+ `),!t)try{await pn(e.verification_url)}catch(r){let i=r instanceof c?r.message:String(r);X(`(couldn't open the browser automatically: ${i})
39
+ `)}}function Ki(e){let t=Math.max(0,Math.round(e-Date.now()/1e3));if(t<90)return`${t} second${t===1?"":"s"}`;let n=Math.round(t/60);return`${n} minute${n===1?"":"s"}`}function Yi(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Hi(e){return e==="business"||e==="employee"||e==="admin"?e:"business"}0&&(module.exports={APPROVAL_SCREEN_SCOPES,UNGRANTABLE_CATEGORIES,approvalScreenCanGrant,isWellFormedScope,scopeCategory,scopeSatisfies});
40
+ //# sourceMappingURL=device-login.js.map
@@ -0,0 +1,18 @@
1
+ "use strict";var di=Object.create;var le=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var hi=(e,n)=>{for(var t in n)le(e,t,{get:n[t],enumerable:!0})},Cn=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of fi(n))!yi.call(e,r)&&r!==t&&le(e,r,{get:()=>n[r],enumerable:!(i=pi(n,r))||i.enumerable});return e};var k=(e,n,t)=>(t=e!=null?di(mi(e)):{},Cn(n||!e||!e.__esModule?le(t,"default",{value:e,enumerable:!0}):t,e)),gi=e=>Cn(le({},"__esModule",{value:!0}),e);var Lo={};hi(Lo,{default:()=>Re});module.exports=gi(Lo);var ci=require("@oclif/core");var C=require("@oclif/core");var On="public",Rn="https://app.allscale.io";var In=["https://app.allscale.io"];var Pe="Override the API base URL (public builds accept only https://app.allscale.io)";var Ue="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function vn(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 Pn(e){return vn(e)!==null}function xe(e){let n=vn(e);return n!==null&&In.includes(n.origin)}function z(){return"".trim()||void 0}function X(){return"public"}function U(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function De(e){try{return new URL(e).origin}catch{return null}}function Q(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return Be()}function Be(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let i=JSON.parse(e);if(!Array.isArray(i))return[];let r=[];for(let o of i){if(typeof o!="object"||o===null)continue;let{base:a,key:l,keyId:s}=o;if(typeof a!="string"||a.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let u=typeof s=="string"?s.trim():"";r.push({base:a.trim(),key:l,keyId:u.length>0?u:"cli-1"})}return r}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 i=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:t,key:n,keyId:i&&i.length>0?i:"cli-1"}]}return[]}var Un="`allscale device-login` (or `allscale otp-login` for headless automation)";var xn="drop `--headless` and use the browser-bridge flow with an agent-key session.",Bn="allscale device-login";var Si="device-login";function Z(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Me(){return Un}function $n(e,n="default"){return n==="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 `+xn:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${Z()}\` for headless automation`+"."}function Fn(e,n){let t=n.length>0?`Saved profiles: ${n.join(", ")}.`:"No profiles are saved on this machine yet.";return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. ${t} Check the spelling first; to deliberately create '${e}', run \`allscale ${Si} --profile ${e}\`.`}var Ai={"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},ki=new RegExp(["\\u001b\\[[0-9;:<=>?]*[ -/]*[@-~]","\\u009b[0-9;:<=>?]*[ -/]*[@-~]","\\u001b\\][^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u009d[^\\u0007\\u001b\\u009c]*(?:\\u0007|\\u001b\\\\|\\u009c)","\\u001b[ -/]+[0-~]","\\u001b[0-Z\\x5c-~]","\\u001b\\[[0-9;:<=>?]*[ -/]*","\\u009b[0-9;:<=>?]*[ -/]*","[\\u0007\\u001b\\u0090\\u0098\\u009b\\u009c\\u009d\\u009e\\u009f]"].join("|"),"g");function Ge(e){return(typeof e=="string"?e:String(e??"")).replace(ki,"")}var Li=64;function $e(e,n=new Map,t=0){if(typeof e=="string")return Ge(e);if(e===null||typeof e!="object")return e;let i=n.get(e);if(i!==void 0)return i;if(t>=Li)return e;if(Array.isArray(e)){let a=[];n.set(e,a);for(let l of e)a.push($e(l,n,t+1));return a}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let o={};n.set(e,o);for(let[a,l]of Object.entries(e))Object.defineProperty(o,a,{value:$e(l,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var d=class extends Error{code;details;constructor(n,t,i){super(Ge(t)),this.code=n,this.details=i&&$e(i),this.name="AllscaleError"}get exitCode(){return Ai[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function Mn(e){if(e instanceof d)return e;if(e instanceof Error){if(Ei(e)){let n=wi(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new d("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new d("internal",e.message,{name:e.name})}return new d("internal","Unknown error",{value:String(e)})}var Ti=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),Ni=[/^Missing \d+ required arg/i,/^Missing required flag/i,/^Unexpected argument/i,/^Nonexistent flag/i,/^Unexpected arguments?/i,/^Failed parsing/i,/^Parsing --[A-Za-z0-9][A-Za-z0-9-]*(?:\s|$)/i,/^Expected (?:--|-).*/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* can only be specified once\.?$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects a value$/i,/^Flag --[A-Za-z0-9][A-Za-z0-9-]* expects one of these values: /i,/to be one of: /];function Ei(e){if(bi(e))return!0;let n=e.name??"";return Ti.has(n)?n==="CLIError"?Fe(e,"parse")||Dn(e.message):!0:Dn(e.message)}function bi(e){if(!Fe(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&Fe(e,"parse")}function Dn(e){return e?Ge(e).split(`
2
+ `).some(n=>Ni.some(t=>t.test(n.trim()))):!1}function Fe(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function wi(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function Gn(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var y=k(require("fs")),ue=k(require("path")),Jn=k(require("crypto"));var Ci="...<truncated>",Oi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,Ri=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,je=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ve=String.raw`(?:proxy[_-]?)?authorization`,Ii=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ve}"|'${Ve}'|${Ve})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${je}`,"gi"),vi=/\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)?>)${je}`,"gi"),Ke=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)`,Ui=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ke}"|'${Ke}'|${Ke})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${je}`,"g");function Vn(e){return e.replace(vi,"$1<redacted>@").replace(Oi,"<redacted-jwt>").replace(Ii,"$1$2$3<redacted>").replace(Pi,"$1$2<redacted>").replace(Ui,"$1$2<redacted>").replace(Ri,"Bearer <redacted>")}function qn(e){let n="";for(let t of e){let i=t.codePointAt(0),r=i<=8||i>=11&&i<=12||i>=14&&i<=31||i>=127&&i<=159;n+=r?`\\u${i.toString(16).padStart(4,"0")}`:t}return n}function Kn(e,n,t=Ci){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let l="",s=0;for(let u of t){let p=Buffer.byteLength(u,"utf8");if(s+p>n)break;l+=u,s+=p}return l}let r=n-i,o="",a=0;for(let l of e){let s=Buffer.byteLength(l,"utf8");if(a+s>r)break;o+=l,a+=s}return`${o}${t}`}function T(e,n=16384){return Kn(qn(Vn(e)),n)}var He=100,xi=8,Bi=8*1024;function ce(){return{remaining:Bi}}function Ye(e,n){let t=Math.min(16384,n.remaining),i=Kn(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function G(e,n,t=0,i={}){if(t>xi)return Ye("<truncated>",n);if(typeof e=="string"){let r=Vn(e);return Ye(i.escapeControls?qn(r):r,n)}if(Array.isArray(e)){let r=e.slice(0,He),o=r.map(a=>G(a,n,t+1,i));return e.length>r.length&&o.push(Ye(`<${e.length-r.length} more items truncated>`,n)),o}if(e!==null&&typeof e=="object"){let r=Object.create(null),o=Object.entries(e);for(let[a,l]of o.slice(0,He))r[a]=G(l,n,t+1,i);return o.length>He&&(r.output_truncated=!0),r}return e}var Je=require("process");var We=!1;function ze(e){We=e}function Yn(){return We}var Hn="1";function q(e,n){if(We){let t={...e};delete t.version;let i=ce(),r={event:t.event,...t},o=G(r,i,0,{escapeControls:!0}),a=JSON.stringify({version:Hn,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Hn,event:o.event,output_truncated:!0})),Je.stderr.write(`${a}
4
+ `)}else Je.stderr.write(n)}var jn="2",K=null,N=null,H=!1;function Di(){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,"-"),i=Jn.randomBytes(4).toString("hex");return ue.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var Xe=64*1024*1024,$i=null;function Wn(){if(H)return;let e=Di();if(!e)return;K=null;let n=null;try{if(($i??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let t=ue.dirname(e);if(y.mkdirSync(t,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=y.statSync(t),s=l.mode&511;if(!l.isDirectory()||(s&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${s.toString(8).padStart(3,"0")}`)}let i=y.constants.O_NOFOLLOW??0;n=y.openSync(e,y.constants.O_APPEND|y.constants.O_CREAT|y.constants.O_WRONLY|(y.constants.O_NONBLOCK??0)|i,384);let r=y.fstatSync(n),o=y.lstatSync(e);if(!r.isFile()||o.isSymbolicLink()||o.dev!==r.dev||o.ino!==r.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&r.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let a=r.mode&511;if((a&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${a.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);y.fchmodSync(n,384)}catch(t){if(n!==null)try{y.closeSync(n)}catch{}q({event:"sidecar_disabled",reason:"open_failed",detail:T(`sidecar path '${e}' could not be opened safely (${t.message})`)},`${T(`[allscale] sidecar path '${e}' could not be opened safely (${t.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}K=e,N=n,H=!0}var Fi=[/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 Mi(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Fi.some(t=>t.test(n))}function zn(e){try{let n=new URL(e),t=n.username.length>0||n.password.length>0;t&&(n.username="",n.password="");let i=n.pathname;n.pathname=Gi(n.pathname);let r=t;n.pathname!==i&&(r=!0);for(let[o]of n.searchParams)Mi(o)&&(n.searchParams.set(o,"<redacted>"),r=!0);return r?n.toString():e}catch{return e}}function Gi(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function Vi(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:zn(e.url)}:e}function qi(e){let n=new Date().toISOString(),t=e,{type:i,...r}=t,o=G(r,ce()),a=JSON.stringify({version:jn,timestamp:n,type:i,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:jn,timestamp:n,type:i,output_truncated:!0})),a}function S(e){if(!H||!K||N===null)return;let n=Vi(e),t=qi(n);try{if(y.fstatSync(N).size+Buffer.byteLength(t,"utf8")+1>Xe){H=!1;try{y.closeSync(N)}catch{}N=null,q({event:"sidecar_disabled",reason:"size_limit",...K===null?{}:{path:T(K)},max_bytes:Xe},`${T(`[allscale] sidecar exceeded ${Xe} bytes; disabling it for the rest of this run. Rotate or remove ${K}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}y.appendFileSync(N,`${t}
7
+ `)}catch(i){if(H=!1,N!==null){try{y.closeSync(N)}catch{}N=null}try{q({event:"sidecar_disabled",reason:"write_failed",detail:T(i.message)},`${T(`[allscale] sidecar write failed (${i.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var I=zn;function Xn(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function de(){if(H=!1,N!==null){try{y.closeSync(N)}catch{}N=null}}function Qn(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Xn()||!n}var ee=z()??Rn,j={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function v(e){return Pn(e)?new URL(e).origin:null}function w(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Zn(){let e=process.env[j.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Qe(){let e=process.env[j.PROFILE]?.trim();return e&&e.length>0?e:void 0}function pe(){let e=process.env[j.API_BASE]?.trim();return e&&e.length>0?e:void 0}function et(){let e=process.env[j.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function nt(){let e=process.env[j.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function tt(){let e=process.env[j.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function it(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:r}=e;if(z()===void 0&&ee!==""&&"".length!==0&&!t&&r!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
9
+ The CLI default is now ${ee} (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: ${Bn} --api-base ${ee}
14
+ `}var J=k(require("fs")),rt=k(require("os")),Ze=k(require("path")),en=k(require("@iarna/toml"));var Yi=".allscale",ji="config.toml";function nn(){return Ze.join(rt.homedir(),Yi)}function Ji(){return Ze.join(nn(),ji)}function fe(){let e=Ji();if(!J.existsSync(e))return{};let n=J.readFileSync(e,"utf-8");try{return en.parse(n)}catch(t){throw new d("internal",`Failed to parse ${e}: ${t.message}`)}}function ot(e){return Object.keys(e.profile??{}).sort()}function at(e,n){return e.profile?.[n]}function st(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new d("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function W(e){if(!xe(e))throw new d("input.invalid",`Refusing to send credentials to API base ${w(e)}. `+Ue)}function tn(e,n){W(e);let t=v(e),i=typeof n=="string"?v(n):null;if(t&&i===t)return;let r=typeof n=="string"?w(n):"<missing origin binding>";throw new d("input.invalid",`Refusing to send stored credentials: API base ${w(e)} does not match their bound origin ${r}. Re-login against the intended API base before retrying.`)}function lt(e,n){let t=v(e),i=v(n);if(!(t&&i===t))throw new d("input.invalid",`Refusing API request to ${w(n)} because it is outside the configured API origin ${w(e)}.`)}function me(e){let n=z();if(n===void 0||U(e))return;let t=v(e),i=Q();if(i.length>0){let o=i.map(l=>v(l.base)).filter(l=>l!==null);if(t!==null&&o.includes(t))return;let a=i.map(l=>w(l.base)).join(", ");throw new d("input.invalid",`Refusing to send to ${w(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let r=v(n);if(!(t!==null&&t===r))throw new d("input.invalid",`Refusing to send to ${w(e)} \u2014 this build only signs for ${w(n)}. Re-login against this build's environment, or use a build for that one.`)}var Wi=require("@noble/hashes/sha3");var ct=["USDT","USDC"];var aa=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);var te=require("@oclif/core"),ne=class e extends C.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:C.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:C.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:X()==="public"}),"api-base":C.Flags.string({description:Pe,helpGroup:"GLOBAL",hidden:X()==="public"}),"insecure-storage":C.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{ze(this.jsonEnabled()),Wn(),S({type:"session-start",command:this.id??"",argv:Xi(this.argv)});let n=this.constructor;if(X()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new d("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 d("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!n.isLocalOnly&&pe()!==void 0)throw new d("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&&!tt())throw this.argv.length>0&&await this.parse(),new d("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=Qn(this.jsonEnabled()),i=this.argv.length===0&&!t&&or(n)?this.config.findCommand(this.id??""):void 0;if(i){de();let o=await(0,C.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(i,this.config.topics);return}let r=await this.runCommand();return S({type:"command-end",ok:!0}),de(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||Gn(r),{data:r})}catch(n){let t=Mn(n);S({type:"error",code:t.code,message:T(t.message)}),S({type:"command-end",ok:!1,exitCode:t.exitCode}),de(),this.emitError(t),process.exitCode=t.exitCode;return}finally{ze(!1)}}resolveSessionApiBaseChain(n){let t=fe(),i=n.profile??void 0,r=n["api-base"]??void 0,o=i!==void 0||Qe()!==void 0,a=st(t,i,Qe()),l=at(t,a),s=r??pe(),u=s??l?.api_base??ee,p=it({resolvedApiBase:u,fromExplicitOverride:s!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,q({event:"legacy_staging_profile",api_base:u,profile:a},p)),{apiBase:u,explicitApiBase:s,profileApiBase:l?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||W(t),t}resolveContext(n){if(X()==="public"){if(n.token!==void 0)throw new d("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 d("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&pe()!==void 0)throw new d("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,i=!!n["insecure-storage"],{apiBase:r,explicitApiBase:o,profile:a,profileApiBase:l,profileExplicit:s}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(W(r),me(r)),{apiBase:r,profile:a,token:t??Zn(),insecureStorage:i||et(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:s}}emitError(n){process.stderr.write(`${rr(n)}
15
+ `)}},he=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"]),zi=new Set(Array.from(he).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Xi(e){let n=[];for(let t=0;t<e.length;t+=1){let i=e[t];if(i.startsWith("-")){let r=i.indexOf("=");if(r!==-1){let o=i.slice(0,r);if(he.has(o)){n.push(`${o}=<redacted>`);continue}}}if(he.has(i)){n.push(i),t+1<e.length&&(he.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2&&i[1]!=="="){let r=i.slice(0,2);if(zi.has(r)){n.push(`${r}<redacted>`);continue}}n.push(i)}return n}var Qi=/(token|secret|password|passwd|passphrase|cookie|authorization|bearer|credential|mnemonic|seed|api[_-]?key|apikey|private[_-]?key|privkey|otp|signature|hmac|(?:^|[_-])sig(?:[_-]|$)|session[_-]?id|^input$)/i;function Zi(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return Qi.test(n)}var er=/_(removed|cleared|count|total)$/i;function nr(e,n){return typeof n=="number"&&er.test(e)}var tr=new Set(ct);function ir(e,n){return e==="token_symbol"&&typeof n=="string"&&tr.has(n)}var ye=100;function rn(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,ye),i=t.map(r=>rn(r,n+1));return e.length>t.length&&i.push(`<${e.length-t.length} more items truncated>`),i}if(e!==null&&typeof e=="object"){let t=Object.create(null),i=Object.entries(e);for(let[r,o]of i.slice(0,ye))t[r]=Zi(r)&&!nr(r,o)&&!ir(r,o)?"<redacted>":rn(o,n+1);if(i.length>ye){let r="<truncated>";for(;r in t;)r=`<${r}>`;t[r]=`${i.length-ye} more keys`}return t}return typeof e=="string"?T(e):e}function rr(e){let n=Yn()?void 0:2,t=rn(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:T(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function or(e){if(e.requiresInput===!0)return!0;let n=r=>typeof r=="object"&&r!==null&&r.required===!0,t=e.flags??{},i=e.args??{};return Object.values(t).some(r=>n(r))||Object.values(i).some(r=>n(r))}var Lt=k(require("path"));var sn=require("crypto"),c=k(require("fs")),_=k(require("path"));var ge=1024*1024,ar=5e3,sr=20,lr=3e4,on=4096,cr=new Int32Array(new SharedArrayBuffer(4)),ie=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function _e(e){return e instanceof ie}var L=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},ur=null;function B(){return new d("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 Se(){return(ur??process.platform)!=="win32"}function gt(){if(!Se())throw B()}function _t(e){try{return c.default.lstatSync(e),!1}catch(n){if(!g(n,"ENOENT"))throw n}try{let n=c.default.lstatSync(_.dirname(e));return!n.isSymbolicLink()&&n.isDirectory()}catch(n){if(g(n,"ENOENT"))return!0;throw n}}function g(e,n){return typeof e=="object"&&e!==null&&e.code===n}function re(e,n){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${n} is not owned by the current effective user`)}function oe(e,n){return e.dev===n.dev&&e.ino===n.ino}function dr(e){Atomics.wait(cr,0,0,e)}function St(e){try{return process.kill(e,0),!0}catch(n){return!g(n,"ESRCH")}}function pr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ut(e,n){let t=_.dirname(e);n&&c.default.mkdirSync(t,{recursive:!0,mode:448});let i;try{i=c.default.lstatSync(t)}catch(o){if(!n&&g(o,"ENOENT"))return!1;throw o}if(i.isSymbolicLink()||!i.isDirectory())throw new Error("credential-store parent must be a real directory");if(process.platform==="win32")return!0;let r=null;try{r=c.default.openSync(t,c.default.constants.O_RDONLY|(c.default.constants.O_DIRECTORY??0)|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0));let o=c.default.fstatSync(r),a=c.default.lstatSync(t);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!oe(o,a))throw new Error("credential-store parent changed while it was being inspected");re(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&_.basename(t)===".allscale"&&(c.default.fchmodSync(r,448),l=c.default.fstatSync(r)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{r!==null&&c.default.closeSync(r)}return!0}function O(e,n,t,i={}){if(!t.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");let r;try{r=c.default.lstatSync(e)}catch(o){throw i.retryOnPathChange&&g(o,"ENOENT")?new L:o}if(!oe(t,r))throw i.retryOnPathChange?new L:new Error("credential-store target changed while it was being opened or is not a regular file");if(r.isSymbolicLink()||!r.isFile())throw new Error("credential-store target changed while it was being opened or is not a regular file");if(!i.allowMultipleLinks&&(t.nlink!==1||r.nlink!==1))throw new ie;if(re(t,"credential-store file"),process.platform!=="win32"){c.default.fchmodSync(n,384);let o=c.default.fstatSync(n);if((o.mode&63)!==0)throw new Error("credential-store file could not be made owner-only");return o}return t}function fr(e,n){if(n.size>ge)throw new Error("credential-store file exceeds the maximum supported size");let t=Buffer.alloc(ge+1),i=0;for(;i<t.length;){let r=c.default.readSync(e,t,i,t.length-i,null);if(r===0)break;i+=r}if(i>ge)throw new Error("credential-store file exceeds the maximum supported size");return t.subarray(0,i).toString("utf8")}function dt(e){let n=null;try{try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(r){if(g(r,"ENOENT"))try{if(c.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(g(o,"ENOENT"))return null;throw o}throw r}let t=c.default.fstatSync(n),i=O(e,n,t);return fr(n,i)}finally{n!==null&&c.default.closeSync(n)}}function pt(e){let n=null;try{try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(r){if(g(r,"ENOENT")&&_t(e))return;throw r}let t=c.default.fstatSync(n),i=O(e,n,t);D(e,i)}finally{n!==null&&c.default.closeSync(n)}kt(_.dirname(e))}function mr(e){let n;try{n=c.default.lstatSync(e)}catch(t){if(g(t,"ENOENT"))return;throw t}if(n.isSymbolicLink()||!n.isFile())throw new Error("credential-store replacement target must be a regular file");if(n.nlink!==1)throw new ie;re(n,"credential-store replacement target")}function yr(e,n){for(let t=0;t<8;t+=1){let i=(0,sn.randomBytes)(12).toString("hex"),r=_.join(e,`.${n}.${process.pid}.${i}.tmp`);try{return{fd:c.default.openSync(r,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_WRONLY|(c.default.constants.O_NOFOLLOW??0),384),tempPath:r}}catch(o){if(g(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function At(e,n){let t=0;for(;t<n.length;){let i=c.default.writeSync(e,n,t,n.length-t,null);if(!Number.isSafeInteger(i)||i<=0)throw new Error("credential-store temp file write made no progress");t+=i}}function kt(e){if(process.platform==="win32")return;let n=null;try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_DIRECTORY??0)|(c.default.constants.O_NOFOLLOW??0)),c.default.fsyncSync(n)}catch{}finally{if(n!==null)try{c.default.closeSync(n)}catch{}}}function hr(e,n){let t=Buffer.from(n,"utf8");if(t.length>ge)throw new Error("credential-store file exceeds the maximum supported size");let i=_.dirname(e),r=_.basename(e),o=null,a=null,l=!1;try{let s=yr(i,r);o=s.fd,a=s.tempPath;let u=c.default.fstatSync(o);if((O(a,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");At(o,t),c.default.fsyncSync(o),O(a,o,c.default.fstatSync(o));let f=o;o=null,c.default.closeSync(f),mr(e),c.default.renameSync(a,e),l=!0}finally{if(o!==null)try{c.default.closeSync(o)}catch{}if(!l&&a!==null)try{c.default.unlinkSync(a)}catch{}}kt(i)}function gr(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock`)}function _r(e){return _.join(_.dirname(e),`.${_.basename(e)}.lock-recovery`)}function Sr(e,n){if(n.size>on)return null;let t=Buffer.alloc(on+1),i=0;for(;i<t.length;){let o=c.default.readSync(e,t,i,t.length-i,null);if(o===0)break;i+=o}if(i>on)return null;let r;try{r=JSON.parse(t.subarray(0,i).toString("utf8"))}catch{return null}return typeof r!="object"||r===null||!Number.isSafeInteger(r.pid)||(r.pid??0)<=0||typeof r.nonce!="string"||!/^[a-f0-9]{24}$/.test(r.nonce??"")||typeof r.target!="string"?null:r}function D(e,n){let t=c.default.lstatSync(e);if(t.isSymbolicLink()||!t.isFile()||!oe(t,n))throw new Error("credential-store lock changed while it was being inspected");re(t,"credential-store lock"),c.default.unlinkSync(e)}function ft(e,n){let t=null;try{try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(s){if(g(s,"ENOENT"))try{let u=c.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new L}catch(u){if(g(u,"ENOENT"))return{state:"absent"};throw u}throw s}let i=c.default.fstatSync(t),r=O(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=Sr(t,r);return{state:(o?.target===n&&o?!St(o.pid):Date.now()-r.mtimeMs>=lr)?"stale":"active",stats:r}}finally{t!==null&&c.default.closeSync(t)}}function Ar(e,n){for(let t=0;t<8;t+=1){let i=(0,sn.randomBytes)(12).toString("hex"),r=_.join(e,`.${n}.${process.pid}.${i}.lock-claim`),o={pid:process.pid,nonce:i,target:n},a=null;try{a=c.default.openSync(r,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_WRONLY|(c.default.constants.O_NOFOLLOW??0),384);let l=c.default.fstatSync(a),s=O(r,a,l,{allowMultipleLinks:!0});return At(a,Buffer.from(JSON.stringify(o),"utf8")),c.default.fsyncSync(a),{claimPath:r,metadata:o,stats:s}}catch(l){if(g(l,"EEXIST"))continue;try{c.default.unlinkSync(r)}catch{}throw l}finally{a!==null&&c.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function kr(e,n){let t;try{t=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(i){throw g(i,"ENOENT")?new L:i}try{let i=c.default.fstatSync(t),r=O(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!oe(r,n))throw new L;return{fd:t,lockPath:e,stats:r}}catch(i){throw c.default.closeSync(t),i}}function mt(e){let n=null;try{try{n=c.default.openSync(e,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(t){if(g(t,"ENOENT"))try{let i=c.default.lstatSync(e);throw i.isSymbolicLink()||!i.isFile()?new Error("credential-store recovery gate must be a real regular file"):new L}catch(i){if(g(i,"ENOENT"))return!1;throw i}throw t}return O(e,n,c.default.fstatSync(n),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{n!==null&&c.default.closeSync(n)}}function Lr(e){let n;try{n=c.default.openSync(e,c.default.constants.O_CREAT|c.default.constants.O_EXCL|c.default.constants.O_RDWR|(c.default.constants.O_NOFOLLOW??0),384)}catch(i){if(g(i,"EEXIST"))return null;throw i}let t=null;try{t=c.default.fstatSync(n);let i=O(e,n,t,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:n,lockPath:e,stats:i}}catch(i){if(t!==null)try{D(e,t)}catch{}throw c.default.closeSync(n),i}}function x(e,n){if(Date.now()>=e)throw n?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");dr(sr)}function yt(e){let n=_.dirname(e),t=_.basename(e),i=gr(e),r=_r(e),o=Ar(n,t),a=Date.now()+ar,l=!1,s=!1,u=null,p;try{for(;u===null;)try{if(mt(r)){x(a,!0);continue}c.default.linkSync(o.claimPath,i),s=!0,u=kr(i,o.stats),l=!0}catch(f){if(s&&!l){try{D(i,o.stats)}catch{}s=!1}if(f instanceof L){x(a,!1);continue}if(!g(f,"EEXIST"))throw f;let m;try{m=ft(i,t)}catch(b){if(b instanceof L){x(a,!1);continue}throw b}if(m.state==="absent")continue;if(m.state==="stale"){let b;try{b=Lr(r)}catch(A){if(A instanceof L){x(a,!1);continue}throw A}if(b!==null){try{let A;try{A=ft(i,t)}catch(se){if(se instanceof L){x(a,!1);continue}throw se}A.state==="stale"&&D(i,A.stats)}finally{an(b)}continue}}let h;try{h=mt(r)}catch(b){if(b instanceof L){x(a,!1);continue}throw b}x(a,h)}}catch(f){p=f}try{D(o.claimPath,o.stats)}catch(f){!g(f,"ENOENT")&&!l&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function an(e){try{D(e.lockPath,e.stats)}finally{c.default.closeSync(e.fd)}}function Tr(e,n){let t=pr(n),i=new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.tmp$`).exec(e)??new RegExp(`^\\.${t}\\.(\\d+)\\.[a-f0-9]{24}\\.lock-claim$`).exec(e);if(!i)return null;let r=Number(i[1]);return Number.isSafeInteger(r)&&r>0?r:null}function ht(e){let n=_.dirname(e),t=_.basename(e);for(let i of c.default.readdirSync(n)){let r=Tr(i,t);if(r===null||St(r))continue;let o=_.join(n,i),a=null;try{try{a=c.default.openSync(o,c.default.constants.O_RDONLY|(c.default.constants.O_NOFOLLOW??0)|(c.default.constants.O_NONBLOCK??0))}catch(u){if(g(u,"ENOENT")||g(u,"ELOOP"))continue;throw u}let l=c.default.fstatSync(a),s=c.default.lstatSync(o);if(!l.isFile()||s.isSymbolicLink()||!s.isFile()||!oe(l,s))continue;try{re(l,"credential-store orphan")}catch{continue}D(o,l)}catch(l){if(!g(l,"ENOENT"))throw l}finally{a!==null&&c.default.closeSync(a)}}}function ae(e,n,t){if(!Se()){if(n.allowUnsupportedPlatformCleanup){if(n.createParent)throw B();if(!ut(e,!1))return t({read:()=>null,remove:()=>{},write:()=>{throw B()}});let a=yt(e);try{return ht(e),t({read:()=>dt(e),remove:()=>pt(e),write:()=>{throw B()}})}finally{an(a)}}if(!n.createParent){let o=!1;try{o=_t(e)}catch{throw B()}if(o)return t({read:()=>null,remove:()=>{},write:()=>{throw B()}})}throw B()}if(!ut(e,n.createParent))return t({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let r=yt(e);try{return ht(e),t({read:()=>dt(e),remove:()=>pt(e),write:o=>hr(e,o)})}finally{an(r)}}var ln="allscale-cli";function pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e){return pn(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function F(e){return new d("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 cn(){return new d("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function Ae(){return new d("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var $,un=!1;function Nr(){return nt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function Er(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let n=e.message;return typeof n=="string"&&n.split(`
16
+ `,1)[0]==="Cannot find module 'keytar'"}function br(){if($!==void 0)return $;if(Nr())return un=!1,$=null,$;try{$=require("keytar"),un=!1}catch(e){un=!Er(e),$=null}return $}function Nt(){let e=Se()?"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 d("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 dn(e){try{return await e()}catch{throw Nt()}}var fn=class{constructor(n){this.keytar=n}keytar;kind="keychain";async read(n){let t=await dn(()=>this.keytar.getPassword(ln,n));if(t===null)return null;let i;try{i=JSON.parse(t)}catch{throw F("OS keychain")}if(!Tt(i))throw F("OS keychain");return i}async get(n){return this.read(n)}async set(n,t){await this.read(n),await dn(()=>this.keytar.setPassword(ln,n,JSON.stringify(t)))}async delete(n){await this.read(n),await dn(()=>this.keytar.deletePassword(ln,n))}},wr="credentials.json",mn=class{kind="insecure-file";filePath;constructor(n){this.filePath=n??Lt.join(nn(),wr)}read(n){let t;try{t=n.read()}catch(r){throw _e(r)?cn():F("plaintext file")}if(t===null)return{profiles:{}};let i;try{i=JSON.parse(t)}catch{throw F("plaintext file")}if(!pn(i)||!pn(i.profiles))throw F("plaintext file");return i}write(n,t){try{n.write(JSON.stringify(t,null,2))}catch(i){throw _e(i)?cn():Ae()}}profileTokens(n,t){let i=n.profiles[t];if(i!==void 0){if(!Tt(i))throw F("plaintext file");return i}}async get(n){try{return ae(this.filePath,{createParent:!1},t=>this.profileTokens(this.read(t),n)??null)}catch(t){throw t instanceof d?t:F("plaintext file")}}async set(n,t){try{ae(this.filePath,{createParent:!0},i=>{let r=this.read(i);this.profileTokens(r,n),r.profiles[n]=t,this.write(i,r)})}catch(i){throw i instanceof d?i:Ae()}}async delete(n){try{ae(this.filePath,{createParent:!1},t=>{let i=this.read(t);this.profileTokens(i,n)!==void 0&&(delete i.profiles[n],this.write(t,i))})}catch(t){throw t instanceof d?t:Ae()}}async clearProfile(n){try{return ae(this.filePath,{createParent:!1,allowUnsupportedPlatformCleanup:!0},t=>{let i=this.read(t);return this.profileTokens(i,n)===void 0?!1:(delete i.profiles[n],Object.keys(i.profiles).length===0?t.remove():this.write(t,i),!0)})}catch(t){throw t instanceof d?t:_e(t)?cn():Ae()}}};function Et(e){if(e.insecureStorage)return gt(),new mn(e.insecureFilePath);let n=br();if(n)return new fn(n);throw Nt()}var yn=class{kind="insecure-file";async get(n){return null}async set(n,t){throw new d("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(n){}};function ke(){return new yn}var Le="allscale_access_token",hn="allscale_refresh_token";function bt(e){return(typeof e.getSetCookie=="function"?e.getSetCookie():e.get("set-cookie")?[e.get("set-cookie")]:[]).map(t=>{let i=t.indexOf(";"),r=i===-1?t:t.slice(0,i),o=r.indexOf("=");return o===-1?null:{name:r.slice(0,o).trim(),value:r.slice(o+1).trim()}}).filter(t=>t!==null)}function gn(e){return e.map(n=>`${n.name}=${n.value}`).join("; ")}function _n(e,n){return e.find(t=>t.name===n)?.value??null}var wt=k(require("crypto")),Ct=k(require("fs")),Ot=k(require("path"));var Cr="key-id",Or="x-allscale-cli-version",Sn="cli-1",Rr="aScaLe_cli_obf_v1",Ir="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function vr(e,n){let t=Buffer.from(e,"base64"),i=Buffer.from(n,"utf8"),r=Buffer.alloc(t.length);for(let o=0;o<t.length;o++)r[o]=t[o]^i[o%i.length];return r.toString("utf8")}var Pr=vr(Ir,Rr),Rt=`Bearer ${Pr}`;function It(e,n){let t=De(e);if(t!==null)return n.find(i=>De(i.base)===t)}function Ur(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let n=Q();if(n.length>0){let i=It(e,n);if(i)return i.key;if(U(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?r:U(n[0].base)?n[0].key:void 0}return}let t=process.env.ALLSCALE_SIGNING_KEY;return t&&t.trim().length>0?t:void 0}function xr(e){{let i="cli-1".trim();if(i.length>0)return i}let n=Q();if(n.length>0){let i=e!==void 0?It(e,n):void 0;if(i)return i.keyId;if(e!==void 0&&U(e)){let r=process.env.ALLSCALE_SIGNING_KEY;if(r&&r.trim().length>0){let o=process.env.ALLSCALE_SIGNING_KEY_ID;return o!==void 0?o.trim():Sn}if(!U(n[0].base))return Sn}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():Sn}function Br(){return"0.1.0"}function Dr(){return new d("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 An(e,n){let t=Ur(n);if(!t)throw Dr();let i=xr(n),r=Math.floor(Date.now()/1e3).toString(),o=wt.createHash("sha256").update(`${t}${r}${e}`).digest("hex"),a={timestamp:r,"secret-key":o,[Or]:Br()};return i.length>0&&(a[Cr]=i),a}function vt(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}function $r(e,n={}){let t;try{t=ot(fe())}catch{return}if(!(t.length===0||t.includes(e)))return new d("auth.unknown_profile",Fn(e,t)+(n.messageSuffix??""),{profile:e,known_profiles:t})}function Pt(e){if(e.profileExplicit){let n=$r(e.profile);if(n)return n}return new d("auth.no_token",$n(e.profile,e.flow))}var kn=256*1024,Te=class extends d{constructor(n,t,i="backend-envelope"){let r=i==="successful-query",o=i==="successful-mutation";super(r?"transport.response_too_large":"backend.internal",r?`The API returned an HTTP-success response larger than the CLI's ${t}-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 ${t}-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 ${t}-byte safety limit and was not parsed.`,{status:n,max_body_bytes:t,...o?{outcome_ambiguous:!0}:{}}),this.name="ResponseBodyTooLargeError"}},Ne=class extends Error{status;timeoutMs;constructor(n,t){super(`API response body read exceeded its ${t}ms deadline.`),this.name="ResponseBodyReadTimeoutError",this.status=n,this.timeoutMs=t}};async function Ln(e,n,t={}){if(!Number.isSafeInteger(n)||n<=0)throw new RangeError("maxBytes must be a positive safe integer");if(t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0))throw new RangeError("timeoutMs must be a positive safe integer");let i=e.headers.get("content-length"),r=i!==null&&/^\d+$/.test(i.trim())?Number(i):void 0;if(r!==void 0&&r>n)throw e.body?.cancel().catch(()=>{}),new Te(e.status,n,t.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],l=0,s,u=t.timeoutMs,p=u===void 0?void 0:new Promise((f,m)=>{s=setTimeout(()=>{m(new Ne(e.status,u))},u),s.unref?.()});try{for(;;){let f=o.read(),{done:m,value:h}=p?await Promise.race([f,p]):await f;if(m)break;if(l+=h.byteLength,l>n)throw o.cancel().catch(()=>{}),new Te(e.status,n,t.oversizeKind);a.push(Buffer.from(h))}}catch(f){throw f instanceof Ne&&o.cancel(f).catch(()=>{}),f}finally{s!==void 0&&clearTimeout(s);try{o.releaseLock()}catch{}}return Buffer.concat(a,l).toString("utf8")}var Fr="X-AllScale-Api-Key",Mr=3e4,Gr=32*1024*1024,Vr=4*1024*1024;function qr(e,n){let t=new AbortController,i=!1,r=()=>{t.abort(e?.reason)};e?.aborted?r():e?.addEventListener("abort",r,{once:!0});let o=setTimeout(()=>{i=!0,t.abort()},n);return{signal:t.signal,timedOut:()=>i,dispose:()=>{clearTimeout(o),e?.removeEventListener("abort",r)}}}function Kr(e,n){return n?n.aborted?Promise.reject(Object.assign(new Error("The operation was aborted"),{name:"AbortError"})):new Promise((t,i)=>{let r=()=>{i(Object.assign(new Error("The operation was aborted"),{name:"AbortError"}))};n.addEventListener("abort",r,{once:!0}),e.then(t,i).finally(()=>{n.removeEventListener("abort",r)})}):e}function Hr(e,n){if(!(e<300||e>=400))throw new d("transport.network",`API returned HTTP ${e} (a redirect) for ${I(n||"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 $t(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Hr(e.status,e.url)}}var Ut="--dns-result-order=ipv4first";async function Ee(e,n){if(e.status!==403)return;let t=e.headers.get("content-type")?.toLowerCase()??"",i=e.headers.get("cf-ray")??"",r=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=t.includes("text/html"),a=n?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),s=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||l)&&(r||n!==void 0&&s)))return;if(n===void 0)try{e.body?.cancel().catch(()=>{})}catch{}let p=/^[A-Za-z0-9-]{1,128}$/.test(i)?i:void 0;throw new d("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=${Ut} and report the Cloudflare Ray ID to support; the CLI will not automatically retry a possibly mutating request.`,{status:403,edge_provider:"cloudflare",...p?{cf_ray:p}:{},ipv4_workaround:`NODE_OPTIONS=${Ut}`})}var M=class{constructor(n){this.opts=n}opts;refreshInFlight=null;async requestWithMetadata(n){return this.requestInternal(n,{withMetadata:!0})}async request(n){return this.requestInternal(n,{withMetadata:!1})}async requestInternal(n,t){let i=n.timeoutMs??this.opts.requestTimeoutMs??Mr;if(!Number.isFinite(i)||i<1)throw new d("input.invalid","HTTP request timeout must be a positive number of milliseconds.");W(this.opts.apiBase),me(this.opts.apiBase);let r=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=qr(n.signal,i);try{return await this.requestWithinDeadline({...n,signal:o.signal},t,r)}catch(a){throw o.timedOut()?new d("transport.timeout",`Request to ${I(new URL(n.path,this.opts.apiBase).toString())} timed out after ${i}ms.`,{timeout_ms:i}):n.signal?.aborted&&!(a instanceof d)?new d("transport.network",`Request to ${I(new URL(n.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(n,t,i){let r=new URL(n.path,this.opts.apiBase).toString();lt(this.opts.apiBase,r);let o=i?.agent_key,a=n.auth??"auto",l=Ft(n.path),s=a==="required"?!0:a==="none"?!1:Jr(n.path);if((l||a==="required")&&!n._isRefresh&&!this.opts.override&&!i?.access_token&&!o)throw Pt({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let u=vt(n.body),p=!!o||!!i?.access_token;s&&p&&!this.opts.override&&tn(this.opts.apiBase,i?.api_base);let f=this.buildHeaders({attachAuth:s&&p,bodyForSig:u,tokens:i,extra:n.headers}),m=Date.now();S({type:"request",method:n.method??"GET",url:r,...n._isRefresh?{refresh:!0}:{}});let h;try{h=await fetch(r,{method:n.method??"GET",headers:f,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(A){throw new d("transport.network",`Network error contacting ${I(r)}: ${A instanceof Error?A.message:String(A)}`)}if(S({type:"response",status:h.status,durationMs:Date.now()-m}),s&&!!i?.access_token&&!o&&h.status===401&&!n._isRefresh&&!this.opts.override){let A=await Kr(this.refreshSingleFlight(),n.signal),se=this.buildHeaders({attachAuth:s&&!!A.access_token,bodyForSig:u,tokens:A,extra:n.headers}),ui=Date.now();S({type:"request",method:n.method??"GET",url:r});let Ie;try{Ie=await fetch(r,{method:n.method??"GET",headers:se,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(ve){throw new d("transport.network",`Network error contacting ${I(r)} on refresh-retry: ${ve instanceof Error?ve.message:String(ve)}`)}return S({type:"response",status:Ie.status,durationMs:Date.now()-ui}),xt(Ie,{withMetadata:t.withMetadata,authBearing:s,responseKind:Bt(n)})}return xt(h,{withMetadata:t.withMetadata,authBearing:s&&p,agentKeyAuth:s&&!!o,responseKind:Bt(n)})}buildHeaders(n){let i={Accept:"application/json","Content-Type":"application/json",...An(n.bodyForSig,this.opts.apiBase),...n.extra};if(n.attachAuth){i.Authorization=Rt;let r=n.tokens;if(r?.agent_key)return i[Fr]=r.agent_key,i;let o=r?.access_token;o&&(i.Cookie=gn([{name:Le,value:o}]))}return i}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async doRefresh(){let n=await this.opts.tokenStore.get(this.opts.profile);if(!n?.access_token||!n?.refresh_token)throw new d("auth.token_expired",`No refresh token available; log in again \u2014 ${Me()}.`);if(tn(this.opts.apiBase,n.api_base),n.agent_key)throw new d("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 t=new URL("/api/public/auth/refresh_token",this.opts.apiBase).toString(),i=gn([{name:Le,value:n.access_token},{name:hn,value:n.refresh_token}]),r=An("",this.opts.apiBase);S({type:"request",method:"POST",url:t,refresh:!0});let o=new AbortController,a=!1,l=setTimeout(()=>{a=!0,o.abort()},1e4),s;try{s=await fetch(t,{method:"POST",headers:{Accept:"application/json",Cookie:i,...r},signal:o.signal,redirect:"manual"})}catch(h){throw S({type:"refresh",ok:!1}),new d("transport.network",a&&h instanceof Error&&h.name==="AbortError"?`Token refresh against ${I(t)} timed out after 10s with no response.`:`Network error during token refresh against ${I(t)}: ${h instanceof Error?h.message:String(h)}`)}finally{clearTimeout(l)}S({type:"response",status:s.status,durationMs:0});try{await $t(s)}catch(h){throw S({type:"refresh",ok:!1}),h}if(s.status!==200){S({type:"refresh",ok:!1}),await Ee(s);let h=await Xr(s);throw await Ee(s,h),Mt(s.status,h),new d("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Me()}.`,{status:s.status})}let u=bt(s.headers),p=_n(u,Le),f=_n(u,hn);if(!p||!f)throw S({type:"refresh",ok:!1}),new d("auth.token_expired","Refresh response did not include new access/refresh cookies.");let m={...n,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,m),S({type:"refresh",ok:!0}),m}},Yr=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Ft(e){let n=e.split(/[?#]/,1)[0];return Yr.some(t=>n===t||n.startsWith(`${t}/`))}var jr=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function Tn(e){let n=e.split(/[?#]/,1)[0];return jr.some(t=>t.test(n))}function Jr(e){return Ft(e)||Tn(e)}async function xt(e,n={}){await $t(e);let t=e.status>=200&&e.status<300;t||await Ee(e);let i=n.responseKind??"mutation",o=await Ln(e,t?i==="query"?Gr:Vr:kn,{oversizeKind:t?i==="query"?"successful-query":"successful-mutation":"backend-envelope"});t||await Ee(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(n.withMetadata){let s={};return e.headers.forEach((u,p)=>{s[p]=u}),{status:e.status,headers:s,body:a}}return a}let l=Qr(a)??`HTTP ${e.status}`;if(Mt(e.status,a),e.status===401){if(n.agentKeyAuth)throw new d("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let s=n.authBearing?"auth.token_expired":"input.invalid";throw new d(s,l,{status:401,body:a})}throw e.status===403?new d("auth.permission_denied",l,{status:403,body:a}):e.status===404?new d("not_found",l,{status:404,body:a}):e.status===429?new d("rate_limited",l,{status:429,body:a}):e.status>=500?new d("backend.internal",l,{status:e.status,body:a}):new d("input.invalid",l,{status:e.status,body:a})}function Bt(e){if(e.responseKind)return e.responseKind;let n=(e.method??"GET").toUpperCase();return n==="GET"||n==="HEAD"?"query":"mutation"}var Dt=2014;function Wr(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}if(!n||typeof n!="object")return!1;let t=n.code;return t===Dt||t===String(Dt)}var zr=1e4;async function Xr(e,n=zr){if(e.status>=200&&e.status<300)return"";try{return await Ln(e,kn,{timeoutMs:n})}catch{return""}}function Mt(e,n){if(!(e>=200&&e<300)&&Wr(n))throw new d("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 n=="string"?n.slice(0,500):n})}function Qr(e){if(!e||typeof e!="object")return;let n=e;if(typeof n.message=="string")return n.message;if(typeof n.detail=="string")return n.detail;if(Array.isArray(n.detail))return JSON.stringify(n.detail)}var Zr=/^\/(api\/)?(v1\/)?public\//;function Gt(e,n={}){let t=typeof n.pathHint=="string"?n.pathHint:"",i=t&&Zr.test(t),r=t&&Tn(t),o=i&&!r&&!n.forceAuth;if(e.token)return new M({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new M({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new M({apiBase:e.apiBase,tokenStore:Et({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(r)return new M({apiBase:e.apiBase,tokenStore:ke(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var be=[{name:"create_claim_link",kind:"mutation",description:"Create a single App claim link. Returns the pending link, funding address, exact deposit total, and bearer claim URL. The link becomes available after the sender's deposit is confirmed. No claim-back.",args:[{name:"input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateClaimLinkInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"CreateClaimLinkResult",ofType:null}},deprecated:null},{name:"create_contact",kind:"mutation",description:"create a new contact",args:[{name:"create_input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateContactInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"create_payment",kind:"mutation",description:"create a new payment",args:[{name:"payment",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreatePaymentInput",ofType:null}},defaultValue:null},{name:"wallet_ids",description:null,type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"create_store",kind:"mutation",description:"create store",args:[{name:"input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"CreateStoreInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"StoreCreateResult",ofType:null}},deprecated:null},{name:"update_payment",kind:"mutation",description:"update an existing payment status by its ID",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"payment",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"UpdatePaymentInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"activities",kind:"query",description:"Get current user's activity list with multi-dimensional filters (type, status, contact, wallet, time range, amount range)",args:[{name:"filter_input",description:null,type:{kind:"INPUT_OBJECT",name:"ActivityFilterInput",ofType:null},defaultValue:"null"},{name:"skip",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"limit",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"20"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ActivityItemPaginatedResponse",ofType:null}},deprecated:null},{name:"auto_payout_session_status",kind:"query",description:"Return the current merchant auto-payout status, expiry, total/used/remaining USD cap, per-transaction limit, and authorized chain/token pairs. Merchants without an active setup receive provisioned=false with null money/expiry fields and no pairs.",args:[],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"AutoPayoutSessionStatus",ofType:null}},deprecated:null},{name:"business",kind:"query",description:"get one business by it's id",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Business",ofType:null}},deprecated:null},{name:"business_transaction_records",kind:"query",description:"get transaction records for business",args:[{name:"direction",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"transaction_type",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"status",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"TransactionPaginatedResponse",ofType:null}},deprecated:null},{name:"business_wallets",kind:"query",description:"List the CALLER'S OWN non-custodial wallets (id, chain, address, coin balances). Takes no business id \u2014 the owner is derived from the authenticated identity, so there is no caller-supplied id to mismatch and no way to read another merchant's wallets. Returns [] when the account has no wallet yet.",args:[],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"WalletEmbedded",ofType:null}}}},deprecated:null},{name:"claim_link",kind:"query",description:"Get one of the caller's own claim links by id (sender surface). A non-owned or unknown id returns CLAIM_LINK_NOT_AVAILABLE \u2014 no existence leak.",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},deprecated:null},{name:"claim_link_fee_preview",kind:"query",description:"Preview the Amount / Network fee / Service fee / Total breakdown without creating a link. Asset and precision validation matches create, but create-time amount and rate limits are enforced only when the link is created, so a successful preview does not guarantee create will succeed. per_transfer_gas is the withdrawal gas estimate in token units.",args:[{name:"amount",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"token_symbol",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"per_transfer_gas",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},deprecated:null},{name:"contact",kind:"query",description:"get one contact by it's id",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"contact_by_email",kind:"query",description:"get one contact by it's email",args:[{name:"email",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}},deprecated:null},{name:"contacts",kind:"query",description:"get multi contacts by owner business id",args:[{name:"owner_business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ContactPaginatedResponse",ofType:null}},deprecated:null},{name:"my_claim_links",kind:"query",description:"List the caller's claim links, newest first. Optional status and link_source filters narrow the results; query_input controls pagination, ordering, and the created_at time range.",args:[{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"},{name:"status",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"link_source",description:null,type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkPaginatedResponse",ofType:null}},deprecated:null},{name:"my_transactions",kind:"query",description:"get one user's successful transactions by query",args:[{name:"query_input",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"TransactionPaginatedResponse",ofType:null}},deprecated:null},{name:"payment",kind:"query",description:"get one payment by its ID",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}},deprecated:null},{name:"payments",kind:"query",description:"All payments by business ID as sender or recipient",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"recipient_payments",kind:"query",description:"Get multiple payments by business ID as recipient",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"sender_payments",kind:"query",description:"Get multiple payments by business ID as sender",args:[{name:"business_id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"query_input",description:null,type:{kind:"INPUT_OBJECT",name:"QueryInput",ofType:null},defaultValue:"null"}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"PaymentPaginatedResponse",ofType:null}},deprecated:null},{name:"transaction",kind:"query",description:"get one transaction by id_str",args:[{name:"id_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}],returnType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Transaction",ofType:null}},deprecated:null}],P=[{name:"ActivityFilterInput",kind:"INPUT",description:null,inputFields:[{name:"transaction_types",description:"Filter by transaction types (OR): 1=PAYMENT, 2=REWARD, 3=WITHDRAWAL, 8=CHECKOUT_INTENT_EPHEMERAL, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 11=CHECKOUT_INTENT_EPHEMERAL_REFUND, 13=CHECKOUT_INTENT_EPHEMERAL_NET_INCOME, 14=CLAIM_LINK",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"transaction_statuses",description:"Filter by transaction statuses (OR): 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"payment_statuses",description:"Filter by payment statuses (OR): -4=OVERDUE, -1=FAILED, 0=DRAFT, 1=SENT, 2=ACKNOWLEDGED, 3=PROCESSING, 10=PAID",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"withdraw_statuses",description:"Filter by withdraw statuses (OR): -4=CANCELED, -1=FAILED, 1=CREATED, 20=CONFIRMED",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"directions",description:"Filter by transaction direction (OR): 1=INFLOW, -1=OUTFLOW",type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}}},defaultValue:"null"},{name:"contact_keyword",description:"Fuzzy search by contact name/email or store name. OR relationship with wallet_address.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"wallet_address",description:"Fuzzy search by counterparty wallet address (tx_from/tx_to). OR relationship with contact_keyword.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"start_time",description:"Filter transactions after this time, ISO8601 format (e.g. 2024-01-01T00:00:00.000Z)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"end_time",description:"Filter transactions before this time, ISO8601 format",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"min_amount",description:"Filter transactions with amount >= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"max_amount",description:"Filter transactions with amount <= this value (Decimal string)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"is_claim_link",description:"When true, return only claim-link activity: a receiver's claim (an ON_CHAIN_TX tagged with claim_link_id) OR a sender's CLAIM_LINK row (single claim_link_id / batch claim_link_batch_id). Matched by claim-link linkage presence, NOT transaction_types \u2014 a receiver's claim shares transaction_type=ON_CHAIN_TX(10) with a plain deposit, so it cannot be selected by type alone (bug 6935616).",type:{kind:"SCALAR",name:"Boolean",ofType:null},defaultValue:"null"}]},{name:"ActivityItem",kind:"OBJECT",description:null,fields:[{name:"transaction_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Transaction record ID"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Transaction amount in cryptocurrency"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Transaction amount in fiat cents"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"When the transaction occurred on-chain"},{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Record creation time in UTC"},{name:"transaction_status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Status: 0=NEW, 1=SUCCESS, 2=FAILED, 3=CONFIRMING"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked payment ID for PAYMENT type transactions"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Type: 1=PAYMENT, 2=REWARD, 3=SEND, 4=SERVICE_FEE, 9=CHECKOUT_INTENT, 10=ON_CHAIN_TX, 14=CLAIM_LINK"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Direction: 1=INFLOW (received), -1=OUTFLOW (sent)"},{name:"wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Counterparty wallet address (sender if INFLOW, recipient if OUTFLOW)"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"On-chain transaction hash"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Blockchain network type"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Block number of the on-chain transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"User-provided memo or notes"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Cryptocurrency type (e.g. USDT)"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"Fiat currency type (e.g. USD, CNY)"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee = network_fee + service_fee"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"On-chain gas/network fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"AllScale platform service fee"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Counterparty's business ID if they are an AllScale user"},{name:"claim_link_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"Linked claim link ID for CLAIM_LINK type transactions"}]},{name:"ActivityItemPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ActivityItem",ofType:null}}}},description:null}]},{name:"AuthorizedPolicyPair",kind:"OBJECT",description:null,fields:[{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain identified by its BlockChainType value (for example BASE = 5) \u2014 not the EIP-155 chain id."},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Stablecoin symbol: USDT or USDC"}]},{name:"AutoPayoutSessionStatus",kind:"OBJECT",description:null,fields:[{name:"provisioned",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether auto-payout setup has been completed for this merchant."},{name:"active",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"True iff provisioned AND the session has not expired (the runtime auto-pay gate)"},{name:"session_expires_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"Session expiry (drives the countdown); null when not provisioned"},{name:"total_cap_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified session total cap in USD (decimal string); null when not provisioned"},{name:"used_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"Cumulative USD spent (reserved + committed) this session (decimal string); populated only for an ACTIVE session, else null"},{name:"remaining_usd",type:{kind:"SCALAR",name:"String",ofType:null},description:"max(0, total_cap - used) in USD (decimal string); populated only for an ACTIVE session, else null"},{name:"per_transaction_limit",type:{kind:"SCALAR",name:"String",ofType:null},description:"Unified single-transaction limit (token-unit decimal string, stablecoin $ 1:1) recorded when auto-payout is enabled; null when not provisioned or when recorded entries have different limits. Retained after a session expires, so it still reports what was recorded."},{name:"authorized_pairs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"AuthorizedPolicyPair",ofType:null}}}},description:"The (chain, stable-coin) pairs the merchant authorized when enabling auto-payout; empty when auto-payout was never provisioned. Retained after a session expires, so it still reports what was authorized."},{name:"sponsor_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"Lowercased sponsor address used to validate authorized payouts. Populated whether or not auto-payout is provisioned, so it is readable while enabling; null when unavailable."}]},{name:"Business",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"user name"},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"email of the user"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"description of the user"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the business"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address field for business"},{name:"country",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"country code of business"},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"contact name of business"},{name:"contact_avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact avatar url of business"},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"contact phone of business"},{name:"avatar",type:{kind:"SCALAR",name:"String",ofType:null},description:"avatar url of business"},{name:"default_currency",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"default currency for business"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the business"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax id of the business"},{name:"about",type:{kind:"SCALAR",name:"String",ofType:null},description:"about of the business, can be changed by business"},{name:"business_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"business type"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of accepted stablecoins for invoices (StableCoinFlag)"},{name:"employee_count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"total active employees in the business"}]},{name:"ClaimLink",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim link id"},{name:"business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"sender business that owns the link"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"ClaimLinkStatus lifecycle state"},{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount, decimal string in token units"},{name:"token_symbol",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"stablecoin symbol, e.g. USDT / USDC"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"BlockChainType the link is locked to"},{name:"sender_display_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name shown to the receiver (person or Store name)"},{name:"sender_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional message shown on the claim page"},{name:"receiver_email",type:{kind:"SCALAR",name:"String",ofType:null},description:"receiver email, if the sender supplied one"},{name:"reference_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"Optional merchant-supplied reference identifier."},{name:"expected_deposit_total",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the expected POOL balance (principal). The sender's gross outlay is the fee breakdown's total"},{name:"service_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"AllScale service fee fixed when the claim link is created; null when not applicable."},{name:"network_fee",type:{kind:"SCALAR",name:"String",ofType:null},description:"Network fee fixed when the claim link is created; null when not applicable."},{name:"funded_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"decimal string; the deposit actually received at the pool wallet"},{name:"funded_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the confirming sender deposit"},{name:"expiry_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC; the resolved claim-window deadline (funded_at + the chosen window, default 14d); None until link_sent"},{name:"claimed_via",type:{kind:"SCALAR",name:"String",ofType:null},description:"how it was claimed: masked receiver email or 0x address"},{name:"claim_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the successful claim"},{name:"refund_tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"on-chain tx hash of the expiry refund back to the sender"},{name:"refunded_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC when the expiry refund proved on-chain"},{name:"cancel_requested_at",type:{kind:"SCALAR",name:"String",ofType:null},description:"ISO-8601 UTC timestamp set when the sender requests cancellation while a claim is in progress. The request stays pending until the in-flight payout resolves: it is cleared if that payout completes (the cancellation is moot and the link is claimed), and retained if the payout did not go through and the link is cancelled and refunded. Null therefore means either no mid-claim cancellation was requested, or one that was resolved by a completed payout."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL returned by create and single-link detail operations. The sender distributes this URL themselves; it is never emailed to the receiver. Null when unavailable, and always null on list operations \u2014 selecting it there returns the field as null rather than omitting it."}]},{name:"ClaimLinkFeeBreakdown",kind:"OBJECT",description:null,fields:[{name:"amount",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"claim amount the receiver gets, decimal string"},{name:"network_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"gas reserve = gas_shares \xD7 per_transfer_gas, decimal string"},{name:"service_fee",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"AllScale service fee for the chain, decimal string"},{name:"total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"amount + network_fee + service_fee \u2014 what the sender pays"},{name:"per_transfer_gas",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"one transfer's gas in token units (echoed for audit)"},{name:"gas_shares",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Number of per_transfer_gas shares reserved; currently 2 for a single claim link."}]},{name:"ClaimLinkPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}}}},description:null}]},{name:"CoinBalanceEmbedded",kind:"OBJECT",description:null,fields:[{name:"coin_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Stablecoin held, as the numeric StableCoin value (1 = USDT, 2 = USDC). `wallet list` decorates each balance with the derived `coin_name`."},{name:"balance",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Decimal",ofType:null}},description:"Balance of the coin"}]},{name:"Contact",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"id of the contact"},{name:"owner_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"owner id of the contact"},{name:"contact_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"contact id if contact is allscale business"},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name of the contact"},{name:"binding_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"the way of binding an allscale business id to the contact, by email matching(1) or scan qrcode(2), etc."},{name:"email",type:{kind:"SCALAR",name:"String",ofType:null},description:"email of the contact"},{name:"evm_wallet_address",type:{kind:"SCALAR",name:"String",ofType:null},description:"evm wallet address of the contact"},{name:"tax_number",type:{kind:"SCALAR",name:"String",ofType:null},description:"tax number of the contact"},{name:"address",type:{kind:"SCALAR",name:"String",ofType:null},description:"address of the contact"},{name:"phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"phone number of the contact"},{name:"last_payment_created_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last payment date of the contact"},{name:"last_paid_at",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"last successful pay date"},{name:"description",type:{kind:"SCALAR",name:"String",ofType:null},description:"Free-form description of the contact."},{name:"is_favourite",type:{kind:"SCALAR",name:"Boolean",ofType:null},description:"is favourite or not"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the contact"}]},{name:"ContactPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Contact",ofType:null}}}},description:null}]},{name:"CreateClaimLinkInput",kind:"INPUT",description:null,inputFields:[{name:"amount",description:"claim amount, decimal string in token units (e.g. '10.5')",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"token_symbol",description:"stablecoin symbol: 'USDT' or 'USDC'",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"BlockChainType value the link is locked to (EVM only)",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"per_transfer_gas",description:"one ERC-20 transfer's gas in TOKEN units (decimal string); from the App's withdraw estimate",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"receiver_email",description:"optional receiver email \u2014 a SENDER-SIDE LABEL ONLY, recording who the link is meant for. AllScale does NOT email the receiver (no invite, no expiry reminder, no resend); the sender must distribute `claim_url` themselves.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_display_name",description:"name shown to the receiver (person or Store name)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_message",description:"optional message shown on the claim page (<= 200 chars)",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"idempotency_key",description:"optional client retry-safety token; a retried create with the same key returns the existing link instead of a duplicate",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_window_seconds",description:"Optional positive claim-window duration in seconds. Defaults to 14 days. The window starts when funding is confirmed; after it expires, unclaimed funds are returned to the sender.",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreateClaimLinkResult",kind:"OBJECT",description:null,fields:[{name:"claim_link",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLink",ofType:null}},description:"the newly created link (pending_deposit)"},{name:"claim_token",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Bearer claim token returned only when the claim link is created and never available again. Capture and store it securely immediately; it preserves claim authority when claim_url is unavailable."},{name:"claim_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Bearer claim URL; null when no claim-page URL is configured."},{name:"pool_wallet_address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"ERC-4337 address the sender funds"},{name:"expected_deposit_total",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"the expected POOL balance (principal), decimal string; the sender's gross outlay is the fee breakdown's total"},{name:"fees",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"ClaimLinkFeeBreakdown",ofType:null}},description:"the frozen fee breakdown"}]},{name:"CreateContactInput",kind:"INPUT",description:null,inputFields:[{name:"owner_business_id",description:"owner id of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"name",description:"name of the contact",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"email",description:"email of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"evm_wallet_address",description:"evm wallet address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"address",description:"address of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"phone",description:"phone number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_number",description:"tax number of the contact",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"description",description:"Free-form description of the contact.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"binding_type",description:"binding type of the contact",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"CreatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"sender_contact_id",description:"contact id of the payer/sender",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"payment_type",description:"payment type of the payment",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"accepted_stable_coins",description:"optional per-invoice bitflag (StableCoinFlag) overriding the recipient business's accepted_stable_coins setting",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"payment_extra_info",description:"payment extra info of the payment, JSON object string",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"currency",description:"currency of the payment, only if the payment_type is CURRENCY",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_cents",description:"amount of the payment in cents",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"amount_coins",description:"amount of the payment in coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"html_template",description:"HTML template for the invoice",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"tax_id",description:"optional taxpayer identification for the invoice",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"datetime the payment is due",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"},{name:"wallets",description:"list of wallets address",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"INPUT_OBJECT",name:"PlainWalletEmbeddedInput",ofType:null}}}},defaultValue:null}]},{name:"CreateStoreInput",kind:"INPUT",description:null,inputFields:[{name:"name",description:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"logo_url",description:"logo url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:null},{name:"business_id",description:"pay account business id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},defaultValue:null},{name:"type",description:"type of the store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"1"},{name:"default_timeout_seconds",description:"default timeout seconds for checkout intents",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"3600"},{name:"swidge_enabled",description:"whether Swidge cross-chain checkout is enabled for this store",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"claim_link_claim_notify_enabled",description:"Whether AllScale sends merchant claim-notification emails for this store; defaults to false.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"false"},{name:"description",description:"description",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"scopes",description:"permission scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:'["*"]'},{name:"ip_allowlist",description:"allowed IPs/CIDRs",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},defaultValue:"[]"},{name:"is_sandbox",description:"Whether to create the store in sandbox mode.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},defaultValue:"true"},{name:"rate_limit_per_minute",description:"Optional request-per-minute limit; defaults to 300, and 0 uses the platform default.",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"300"},{name:"replay_window_seconds",description:"override replay window seconds",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"},{name:"transaction_webhook",description:"transaction webhook url",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"claim_link_webhook_url",description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"redirect_url",description:"Redirect URL used after payment completes.",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"fee_rate",description:"fee rate",type:{kind:"SCALAR",name:"Decimal",ofType:null},defaultValue:"null"},{name:"accepted_stable_coins",description:"bitflag of accepted stablecoins for checkout (StableCoinFlag); null inherits from business",type:{kind:"SCALAR",name:"Int",ofType:null},defaultValue:"null"}]},{name:"Payment",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the payment"},{name:"recipient_business_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"business id of the payee/recipient"},{name:"sender_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the payer/sender"},{name:"sender_contact_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"contact id of the payer/sender"},{name:"payment_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"payment type of the payment"},{name:"accepted_stable_coins",type:{kind:"SCALAR",name:"Int",ofType:null},description:"bitflag of stablecoins accepted for this payment (StableCoinFlag). None on payments created before the multi-coin rollout."},{name:"payment_extra_info",type:{kind:"SCALAR",name:"String",ofType:null},description:"payment extra info of the payment, JSON object string"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the payment, only if the payment_type is CURRENCY"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the payment"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount of the payment in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount of the payment in coins"},{name:"invoice_url",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice url of the payment"},{name:"invoice_visible_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"invoice visible id of the pdf"},{name:"tax_id",type:{kind:"SCALAR",name:"String",ofType:null},description:"optional taxpayer identification for the invoice"},{name:"error_message",type:{kind:"SCALAR",name:"String",ofType:null},description:"error message of the payment if status is failed"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the payment"},{name:"due_datetime",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"datetime the payment is due"},{name:"display_amount",type:{kind:"SCALAR",name:"String",ofType:null},description:"display amount of the payment"},{name:"encrypted_id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Opaque payment identifier used in public payment links."}]},{name:"PaymentPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Payment",ofType:null}}}},description:null}]},{name:"PlainWalletEmbeddedInput",kind:"INPUT",description:null,inputFields:[{name:"id_str",description:"Unique identifier for the wallet",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null},{name:"chain",description:"Blockchain type of the address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:null},{name:"address",description:"Blockchain address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:null}]},{name:"QueryInput",kind:"INPUT",description:null,inputFields:[{name:"limit",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"skip",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},defaultValue:"0"},{name:"order_by",description:null,type:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}},defaultValue:"null"},{name:"raw_filter_str",description:null,type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},defaultValue:'"{}"'},{name:"created_at_lte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"created_at_gte",description:null,type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"}]},{name:"Store",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"Unique store identifier."},{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"name"},{name:"type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the store"},{name:"scopes",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}}}},description:"permission scopes"},{name:"is_sandbox",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Boolean",ofType:null}},description:"Whether this store uses sandbox mode."},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the store"},{name:"transaction_webhook",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction webhook url"},{name:"claim_link_webhook_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Merchant webhook URL for claim-link terminal-state callbacks; distinct from transaction_webhook."},{name:"redirect_url",type:{kind:"SCALAR",name:"String",ofType:null},description:"Redirect URL used after payment completes."}]},{name:"StoreCreateResult",kind:"OBJECT",description:null,fields:[{name:"store",type:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Store",ofType:null}},description:"store"},{name:"api_secret",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Store API secret returned only when the store is created and never available again. Capture and store it securely immediately."}]},{name:"Transaction",kind:"OBJECT",description:null,fields:[{name:"created_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"created timestamp, UTC timezone"},{name:"updated_at",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"updated timestamp, UTC timezone"},{name:"id",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null}},description:"db id of the transaction record"},{name:"owner_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"owner user type of the record"},{name:"owner_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id that owns this transaction record"},{name:"owner_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id that owns this transaction record"},{name:"transaction_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"type of the transaction"},{name:"direction",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"direction of the transaction"},{name:"reference_type",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"reference type of the related record"},{name:"payment_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"payment id when reference_type is PAYMENT"},{name:"counterparty_business_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"business id of the counterparty"},{name:"counterparty_employee_id",type:{kind:"SCALAR",name:"ObjectIdScalar",ofType:null},description:"employee id of the counterparty"},{name:"counterparty_name",type:{kind:"SCALAR",name:"String",ofType:null},description:"name of the counterparty"},{name:"payment_type",type:{kind:"SCALAR",name:"Int",ofType:null},description:"payment type if this is a payment transaction"},{name:"currency",type:{kind:"SCALAR",name:"Int",ofType:null},description:"currency of the transaction"},{name:"amount_cents",type:{kind:"SCALAR",name:"Int",ofType:null},description:"amount in cents"},{name:"amount_coins",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"amount in coins"},{name:"status",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"status of the transaction"},{name:"memo",type:{kind:"SCALAR",name:"String",ofType:null},description:"memo of the transaction"},{name:"transaction_time",type:{kind:"SCALAR",name:"DateTime",ofType:null},description:"actual transaction time"},{name:"tx_hash",type:{kind:"SCALAR",name:"String",ofType:null},description:"hash of the transaction"},{name:"tx_block_chain",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block chain of the transaction"},{name:"tx_from",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction sender address"},{name:"tx_to",type:{kind:"SCALAR",name:"String",ofType:null},description:"transaction receiver address"},{name:"tx_block_number",type:{kind:"SCALAR",name:"Int",ofType:null},description:"block number of the transaction"},{name:"total_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Total fee (network_fee + service_fee)"},{name:"network_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Network/gas fee"},{name:"service_fee",type:{kind:"SCALAR",name:"Decimal",ofType:null},description:"Allscale service fee (0.03%)"}]},{name:"TransactionPaginatedResponse",kind:"OBJECT",description:null,fields:[{name:"count",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:null},{name:"items",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"NON_NULL",name:null,ofType:{kind:"OBJECT",name:"Transaction",ofType:null}}}},description:null}]},{name:"UpdatePaymentInput",kind:"INPUT",description:null,inputFields:[{name:"memo",description:"memo of the payment",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"sender_business_id",description:"sender business id of the payer",type:{kind:"SCALAR",name:"String",ofType:null},defaultValue:"null"},{name:"due_datetime",description:"new payment deadline for an OVERDUE invoice. Only an overdue invoice may be extended, and only FORWARD. Extending past now also revives the invoice (back to SENT/ACKNOWLEDGED) so buyers can pay again.",type:{kind:"SCALAR",name:"DateTime",ofType:null},defaultValue:"null"}]},{name:"WalletEmbedded",kind:"OBJECT",description:null,fields:[{name:"id_str",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet id"},{name:"chain",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"Int",ofType:null}},description:"Chain the wallet lives on, as the numeric BlockChainType value (NOT a name). `wallet list` decorates each wallet with the derived `chain_name` and `eip155_chain_id`."},{name:"address",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"wallet address"},{name:"coin_balances",type:{kind:"NON_NULL",name:null,ofType:{kind:"LIST",name:null,ofType:{kind:"OBJECT",name:"CoinBalanceEmbedded",ofType:null}}},description:"wallet balance"}]}];var we=new Set(["SCALAR","ENUM"]),eo=new Set(["password","password_hash","totp_secret","credential","credentials","private_key","encryption_key"]),no=[/(^|_)password(_|$)/i,/(^|_)secret(_|$)/i,/(^|_)token(_|$)/i,/(^|_)api[_-]?key(_|$)/i,/(^|_)signing[_-]?key(_|$)/i,/(^|_)private[_-]?key(_|$)/i,/(^|_)credential(_|$)/i],to=new Set(["CreateClaimLinkResult.claim_token","StoreCreateResult.api_secret"]),io=new Map([["StoreCreateResult.store",["id","name"]],["CreateClaimLinkResult.claim_link",["id","token_symbol","status"]]]),ro=new Set(["token_symbol"]);function R(e){return ro.has(e.toLowerCase())?!1:eo.has(e)?!0:no.some(n=>n.test(e))}function oo(e,n){return to.has(`${e}.${n}`)}function Nn(e){return e.kind==="NON_NULL"&&e.ofType?`${Nn(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${Nn(e.ofType)}]`:e.name??"Unknown"}function E(e){let n=e;for(;n&&n.ofType;)n=n.ofType;return!n||!n.name?null:{kind:n.kind,name:n.name}}function En(e,n){let t=n.find(a=>a.name===e);if(!t||t.kind==="SCALAR"||t.kind==="ENUM")return"";if(t.kind==="UNION")return"__typename";let i=t.fields??[];if(i.length===0)return"";let r=[],o=!1;for(let a of i){let l=E(a.type);if(!l)continue;if(we.has(l.kind)){if(R(a.name)&&!oo(e,a.name))continue;r.push(a.name);continue}let s=io.get(`${e}.${a.name}`);if(s){let u=n.find(m=>m.name===l.name),p=new Set((u?.fields??[]).filter(m=>{let h=E(m.type);return h!==null&&we.has(h.kind)&&!R(m.name)}).map(m=>m.name)),f=s.filter(m=>!p.has(m));if(f.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${f.join(", ")}] that are not selectable scalars on ${l.name}; fix the entry or the public registry.`);r.push(`${a.name} { ${s.join(" ")} }`);continue}if(!o&&a.name==="items"&&a.type.kind==="NON_NULL"&&a.type.ofType?.kind==="LIST"){let u=ao(a.type)?.name;if(u){let p=so(u,n);p&&r.push(`items { ${p} }`),o=!0}}}return r.length>0?r.join(" "):"__typename"}function ao(e){return E(e)}function so(e,n){let t=n.find(o=>o.name===e);if(!t||t.kind==="UNION")return"__typename";let i=t.fields??[],r=[];for(let o of i){let a=E(o.type);if(a&&we.has(a.kind)){if(R(o.name))continue;r.push(o.name)}}return r.length>0?r.join(" "):"__typename"}function Vt(e,n,t){let i=lo(e.name),r=e.args.map(p=>{let f=Nn(p.type);return p.defaultValue!==null&&p.defaultValue!==void 0?`$${p.name}: ${f} = ${p.defaultValue}`:`$${p.name}: ${f}`}).join(", "),o=e.args.map(p=>`${p.name}: $${p.name}`).join(", "),a=r.length>0?`${e.kind} ${i}(${r})`:`${e.kind} ${i}`,l=o.length>0?`${e.name}(${o})`:e.name,s=E(e.returnType),u;if(s&&we.has(s.kind))u=l;else{let p=t&&t.trim().length>0?t.trim():s&&En(s.name,n)||"__typename";u=`${l} { ${p} }`}return`${a} { ${u} }`}function qt(e,n){let i=e.args.filter(r=>r.type.kind==="NON_NULL"&&r.defaultValue===null).map(r=>r.name).filter(r=>!(r in n));return i.length===0?{ok:!0}:{ok:!1,missing:i}}function Ce(e,n,t){return e.find(i=>i.kind===n&&i.name===t)??null}function Kt(e){if(!e||typeof e!="object")return!1;let n=e.errors;return Array.isArray(n)&&n.length>0}function Ht(e,n=3){let t=e.errors;return!Array.isArray(t)||t.length===0?"":t.slice(0,n).map(i=>typeof i=="object"&&i!==null&&typeof i.message=="string"?i.message:JSON.stringify(i)).join("; ")}function lo(e){return e.replace(/[^_0-9A-Za-z]/g,"_")}var Yt=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"]),jt=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Jt(e){let n=e.lastIndexOf(":");return n===-1?e:e.slice(0,n)}function Wt(e,n){if(e===n)return!0;let t=":read_only";return n.endsWith(t)&&e===`${n.slice(0,-t.length)}:all`}var co={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"},uo={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"},po=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,fo=/is not available to API keys/i,zt=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Xt(e){if(typeof e!="string")return;let n=po.exec(e);if(!n)return;let t=n[1].trim(),i=n[2].trim(),r=fo.test(t),o=!r&&zt.test(t)?t:void 0,a;if(i.toLowerCase()==="none")a=[];else{let l=i.split(",").map(s=>s.trim()).filter(s=>zt.test(s));a=l.length>0?l:void 0}if(!(o===void 0&&!r))return{required:o,granted:a,notAvailableToKeys:r}}function Qt(e){let n=uo[e];if(n!==void 0)return{ungrantableReason:n};let t=co[e];if(t!==void 0)return{scope:t}}function Zt(e){if(jt.has(Jt(e)))return{kind:"ungrantable"};for(let n of Yt)if(Wt(n,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function ni(e,n){let t=ti(e),i={graphql_error_count:mo(e.errors),...t===void 0?{}:{backend_code:t}};if(t===2102)throw yo(e,n,i);if(t===3400)throw new d("not_found",`GraphQL ${n.kind} '${n.operationName}' could not find the requested resource.`,i);if(Kt(e))throw new d("input.invalid",`GraphQL ${n.kind} '${n.operationName}' returned errors: ${Ht(e)}`,i);if(t!==void 0)throw new d("input.invalid",`GraphQL ${n.kind} '${n.operationName}' failed with backend code ${t}.`,i)}function ti(e){let n=ei(e.code);if(n!==void 0)return n;if(Array.isArray(e.errors))for(let t of e.errors){if(!t||typeof t!="object")continue;let i=t.extensions;if(!i||typeof i!="object")continue;let r=ei(i.code);if(r!==void 0)return r}}function ei(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e=="string"&&/^\d+$/.test(e)){let n=Number(e);if(Number.isSafeInteger(n)&&n>0)return n}}function mo(e){return Array.isArray(e)?e.length:e==null?0:1}function yo(e,n,t){let i=`GraphQL ${n.kind} '${n.operationName}'`,r={...t,operation:n.operationName},o=Xt(ho(e,ti(e))),a=Qt(n.operationName),l=o?.notAvailableToKeys===!0,s=o?.required??a?.scope,u=o?.granted,p=u===void 0?"":` This key holds ${u.length>0?u.join(", "):"no scopes"}.`;if(l||a?.ungrantableReason!==void 0){let f=a?.ungrantableReason!==void 0?`: ${a.ungrantableReason}`:"";return new d("auth.permission_denied",`${i} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...r,missing_scopes:[],...u===void 0?{}:{granted_scopes:u},ungrantable:!0})}if(s!==void 0){let f=Zt(s),m=f.kind==="ungrantable"?`\`${s}\` cannot be granted to any key (the backend clips this category to nothing), so re-authorizing will NOT help.`:f.kind==="approval_screen"?`Re-run \`allscale device-login\` and enable it on the approval screen, or \`${Z()}\` with \`--scopes ${s}\`.`:`The browser approval screen does not offer \`${s}\`, so \`device-login\` cannot grant it \u2014 use \`${Z()}\` with \`--scopes ${s}\`.`;return new d("auth.permission_denied",`The current agent key lacks \`${s}\`, required by ${i}.${p} ${m}`,{...r,missing_scopes:[s],...u===void 0?{}:{granted_scopes:u},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new d("auth.permission_denied",`The current agent key does not have the scope required by ${i}.${p} Re-run \`allscale device-login\` (or \`${Z()}\`) and grant the required scope.`,r)}function ho(e,n){let t=e.errors;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let i=r=>{if(r===null||typeof r!="object")return;let o=r.message;return typeof o=="string"?o:void 0};if(n!==void 0)for(let r of t){if(r===null||typeof r!="object")continue;let o=r.extensions;if(!o||typeof o!="object")continue;let a=o.code;if(a===n||typeof a=="string"&&Number(a)===n){let s=i(r);if(s!==void 0)return s}}for(let r of t){let o=i(r);if(o!==void 0)return o}return""}async function ii(e,n,t,i,r={}){let o=Ce(be,n,t);if(!o)throw new d("input.invalid",`No ${n} named '${t}' in the schema. Run \`allscale operations --kind ${n}\` to list options.`);let a=qt(o,i);if(!a.ok)throw new d("input.invalid",`Missing required variables for ${t}: ${a.missing.join(", ")}`,{required:a.missing});let l=Vt(o,P,r.selection);return go(e,{...r,kind:n,operationName:o.name,document:l,variables:i})}async function go(e,n){n.showDoc&&process.stderr.write(`${n.document}
17
+ `);let t=Gt(e),i=n.path??"/api/secure/graphql",r=await t.request({method:"POST",path:i,responseKind:n.kind,body:{query:n.document,...Object.keys(n.variables).length>0?{variables:n.variables}:{},operationName:n.operationName}});ni(r,{kind:n.kind,operationName:n.operationName});let o=r.data?.[n.operationName];return o===void 0?null:o}var ri="Override the default selection set with a GraphQL fragment.",oi="Pass --show-doc to print the exact GraphQL document that gets sent.";function si(...e){let n=_o(...e);if(n.length===0)return`${ri} ${oi}`;let t=[];for(let a of n){let l=t.find(s=>s.typeName===a.typeName);l?l.labels.push(...a.labels):t.push({...a,labels:[...a.labels]})}let i=[ri],r=n.length<e.length,o=t.length>1||r;for(let a of t){let l=o&&a.labels.length>0?`Default (${a.labels.join(", ")})`:"Default";a.preset&&i.push(`${l}: '${a.preset}'.`);for(let s of a.others){let u=s.example?` Object and list fields among them need their own sub-selection, e.g. --select '${s.example}'.`:"",p=s.hasSuppressedFields?" This list is not exhaustive \u2014 a deliberately broad credential-name filter withholds some fields from it.":"";if(s.fields.length===0){i.push(`Beyond the default, ${s.typeName} has further selectable fields, all withheld by a deliberately broad credential-name filter.`);continue}i.push(`Other selectable fields on ${s.typeName}: ${s.fields.join(", ")}.${u}${p}`)}}return i.push(oi),i.join(" ")}function _o(...e){return e.map(n=>{try{return So(n)}catch{return null}}).filter(n=>n!==null)}function So(e){let n=Ce(be,e.kind,e.name);if(!n)return null;let t=E(n.returnType);if(!t)return null;let i=e.preset?.trim();if(e.preset!==void 0&&!i)return null;let r=i??En(t.name,P),o=P.find(m=>m.name===t.name),a=new Set(wn(r)),l=(o?.fields??[]).filter(m=>!a.has(m.name)),s=l.filter(m=>!R(m.name)),u=[],p=l.length-s.length;(s.length>0||p>0)&&u.push({typeName:t.name,fields:s.map(m=>m.name),example:ai(s,bn(wn(r),t.name)),hasSuppressedFields:p>0});let f=Ao(o,a,r);return f&&u.push({typeName:`${t.name}.${f.fieldName} (${f.typeName})`,fields:f.others.map(m=>m.name),example:ai(f.others,f.anchorField,f.fieldName,f.wrapperScalars),hasSuppressedFields:f.hasSuppressedFields}),{labels:e.label?[e.label]:[],typeName:t.name,preset:r,others:u}}function Ao(e,n,t){let i=null;for(let r of e?.fields??[]){if(!n.has(r.name))continue;let o=E(r.type);if(!o||Oe.has(o.kind))continue;let a=P.find(f=>f.name===o.name);if(!a)continue;let l=wn(ko(t,r.name)??""),s=new Set(l),u=(a.fields??[]).filter(f=>!s.has(f.name)),p=u.filter(f=>!R(f.name));if(p.length===0){u.length>0&&i===null&&(i={fieldName:r.name,typeName:o.name,others:[],hasSuppressedFields:!0,anchorField:bn(l,o.name),wrapperScalars:[]});continue}return{fieldName:r.name,typeName:o.name,others:p,hasSuppressedFields:u.length>p.length,anchorField:bn(l,o.name),wrapperScalars:(e?.fields??[]).filter(f=>{if(f.name===r.name||!n.has(f.name)||R(f.name))return!1;let m=E(f.type);return m!==null&&Oe.has(m.kind)}).map(f=>f.name)}}return i}function bn(e,n){let t=P.find(r=>r.name===n),i=r=>{if(R(r))return!1;let o=(t?.fields??[]).find(l=>l.name===r),a=o?E(o.type):null;return a!==null&&Oe.has(a.kind)};return e.includes("id")&&i("id")?"id":e.find(i)??null}function ai(e,n,t,i=[]){for(let r of e){let o=E(r.type);if(!o)continue;let l=(P.find(s=>s.name===o.name)?.fields??[]).filter(s=>{let u=E(s.type);return u!==null&&Oe.has(u.kind)}).map(s=>s.name).filter(s=>!R(s)).slice(0,2);if(l.length>0){let s=`${r.name} { ${l.join(" ")} }`,u=n?`${n} ${s}`:s;return t?[...i,`${t} { ${u} }`].join(" "):u}}return null}var Oe=new Set(["SCALAR","ENUM"]);function wn(e){let n=[],t=0;for(let i of li(e))i==="{"?t+=1:i==="}"?t=Math.max(0,t-1):t===0&&n.push(i);return n}function ko(e,n){let t=li(e),i=0;for(let r=0;r<t.length;r+=1){let o=t[r];if(o==="{"){i+=1;continue}if(o==="}"){i=Math.max(0,i-1);continue}if(i!==0||o!==n||t[r+1]!=="{")continue;let a=[],l=0;for(let s=r+1;s<t.length;s+=1){let u=t[s];if(u==="{"){if(l+=1,l===1)continue}else if(u==="}"&&(l-=1,l===0))return a.join(" ");a.push(u)}return a.join(" ")}return null}function li(e){return e.split(/([{}])/).flatMap(n=>n==="{"||n==="}"?[n]:n.split(/\s+/)).filter(n=>n.length>0)}var Re=class e extends ne{static description="Fetch one invoice by id. Wraps the `payment` GraphQL query.";static examples=["$ allscale invoice get 65ab1234567890abcdef0123","$ allscale invoice get 65ab... --select 'id status amount currency'"];static args={id:ci.Args.string({description:"Invoice id_str (the backend's Payment.id_str)",required:!0})};static flags={select:te.Flags.string({char:"s",description:si({kind:"query",name:"payment"})}),"show-doc":te.Flags.boolean({description:"Print the generated GraphQL document to stderr",default:!1}),...ne.baseFlags};async runCommand(){let{args:n,flags:t}=await this.parse(e),i=this.resolveContext(t);return ii(i,"query","payment",{id_str:n.id},{selection:t.select,showDoc:!!t["show-doc"]})}};
18
+ //# sourceMappingURL=get.js.map