@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,66 @@
1
+ "use strict";var jr=Object.create;var Ue=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Vr=Object.prototype.hasOwnProperty;var Wr=(e,n)=>{for(var t in n)Ue(e,t,{get:n[t],enumerable:!0})},kt=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Jr(n))!Vr.call(e,r)&&r!==t&&Ue(e,r,{get:()=>n[r],enumerable:!(i=qr(n,r))||i.enumerable});return e};var C=(e,n,t)=>(t=e!=null?jr(Yr(e)):{},kt(n||!e||!e.__esModule?Ue(t,"default",{value:e,enumerable:!0}):t,e)),zr=e=>kt(Ue({},"__esModule",{value:!0}),e);var ja={};Wr(ja,{default:()=>fn});module.exports=zr(ja);var ht=require("process"),Hr=require("@oclif/core");var M=require("@oclif/core");var wt="public",mn="https://app.allscale.io";var Be=["https://app.allscale.io"];var yn="Override the API base URL (public builds accept only https://app.allscale.io)";var gn="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";var he={"app.allscale.io":{authProxyConfigId:"918de955-34ae-4914-914d-5732611edbe7",apiBaseUrl:"https://api.turnkey.com",authProxyUrl:"https://authproxy.turnkey.com"}};function Tt(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 St(e){return Tt(e)!==null}function ie(e){let n=Tt(e);return n!==null&&Be.includes(n.origin)}function hn(e){return ie(e)}function _e(){return"".trim()||void 0}function ke(){return"public"}function J(e){try{let{hostname:n}=new URL(e);return n==="127.0.0.1"||n==="localhost"||n==="[::1]"}catch{return!1}}function kn(e){try{return new URL(e).origin}catch{return null}}function we(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return _n()}function _n(){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:s,key:l,keyId:d}=o;if(typeof s!="string"||s.trim().length===0||typeof l!="string"||l.trim().length===0)continue;let c=typeof d=="string"?d.trim():"";r.push({base:s.trim(),key:l,keyId:c.length>0?c:"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 At="`allscale device-login` (or `allscale otp-login` for headless automation)",bt="Headless signing needs a legacy JWT session, which this build cannot create \u2014 drop `--headless` to sign through the browser bridge.";var Lt="drop `--headless` and use the browser-bridge flow with an agent-key session.",Et="allscale device-login",Nt=" Requires an existing legacy JWT session, which this build cannot create \u2014 use the browser-bridge flow instead.";var Sn="device-login";function Te(e){return"allscale otp-login --profile "+(e??"<profile>")+" --email <you@example.com> --scopes <scope> --otp-stdin"}function An(){return At}function De(){return bt}function Ot(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 `+Lt:`No tokens stored for profile '${e}'. Run \`allscale device-login --profile <profile>\` with the same profile (recommended), use \`${Te()}\` for headless automation`+"."}function Rt(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 ${Sn} --profile ${e}\`.`}var Zr={"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},Qr=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 bn(e){return(typeof e=="string"?e:String(e??"")).replace(Qr,"")}var eo=64;function wn(e,n=new Map,t=0){if(typeof e=="string")return bn(e);if(e===null||typeof e!="object")return e;let i=n.get(e);if(i!==void 0)return i;if(t>=eo)return e;if(Array.isArray(e)){let s=[];n.set(e,s);for(let l of e)s.push(wn(l,n,t+1));return s}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let o={};n.set(e,o);for(let[s,l]of Object.entries(e))Object.defineProperty(o,s,{value:wn(l,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var a=class extends Error{code;details;constructor(n,t,i){super(bn(t)),this.code=n,this.details=i&&wn(i),this.name="AllscaleError"}get exitCode(){return Zr[this.code]}toJSON(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}};function It(e){if(e instanceof a)return e;if(e instanceof Error){if(io(e)){let n=oo(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new a("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new a("internal",e.message,{name:e.name})}return new a("internal","Unknown error",{value:String(e)})}var no=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),to=[/^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 io(e){if(ro(e))return!0;let n=e.name??"";return no.has(n)?n==="CLIError"?Tn(e,"parse")||Ct(e.message):!0:Ct(e.message)}function ro(e){if(!Tn(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&Tn(e,"parse")}function Ct(e){return e?bn(e).split(`
2
+ `).some(n=>to.some(t=>t.test(n.trim()))):!1}function Tn(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function oo(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function vt(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
3
+ `)}var T=C(require("fs")),Fe=C(require("path")),Ft=C(require("crypto"));var so="...<truncated>",ao=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,lo=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Rn=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,Ln=String.raw`(?:proxy[_-]?)?authorization`,co=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Ln}"|'${Ln}'|${Ln})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Rn}`,"gi"),uo=/\b(https?:\/\/)[^\s/?#]+@/gi,En=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)`,po=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${En}"|'${En}'|${En})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Rn}`,"gi"),Nn=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)`,fo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Nn}"|'${Nn}'|${Nn})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Rn}`,"g");function Pt(e){return e.replace(uo,"$1<redacted>@").replace(ao,"<redacted-jwt>").replace(co,"$1$2$3<redacted>").replace(po,"$1$2<redacted>").replace(fo,"$1$2<redacted>").replace(lo,"Bearer <redacted>")}function xt(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 Ut(e,n,t=so){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let l="",d=0;for(let c of t){let p=Buffer.byteLength(c,"utf8");if(d+p>n)break;l+=c,d+=p}return l}let r=n-i,o="",s=0;for(let l of e){let d=Buffer.byteLength(l,"utf8");if(s+d>r)break;o+=l,s+=d}return`${o}${t}`}function v(e,n=16384){return Ut(xt(Pt(e)),n)}var Cn=100,mo=8,yo=8*1024;function $e(){return{remaining:yo}}function On(e,n){let t=Math.min(16384,n.remaining),i=Ut(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function re(e,n,t=0,i={}){if(t>mo)return On("<truncated>",n);if(typeof e=="string"){let r=Pt(e);return On(i.escapeControls?xt(r):r,n)}if(Array.isArray(e)){let r=e.slice(0,Cn),o=r.map(s=>re(s,n,t+1,i));return e.length>r.length&&o.push(On(`<${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[s,l]of o.slice(0,Cn))r[s]=re(l,n,t+1,i);return o.length>Cn&&(r.output_truncated=!0),r}return e}var In=require("process");var vn=!1;function Pn(e){vn=e}function Dt(){return vn}var Bt="1";function se(e,n){if(vn){let t={...e};delete t.version;let i=$e(),r={event:t.event,...t},o=re(r,i,0,{escapeControls:!0}),s=JSON.stringify({version:Bt,...o});Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:Bt,event:o.event,output_truncated:!0})),In.stderr.write(`${s}
4
+ `)}else In.stderr.write(n)}var $t="2",ae=null,P=null,le=!1;function go(){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=Ft.randomBytes(4).toString("hex");return Fe.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var xn=64*1024*1024,ho=null;function Mt(){if(le)return;let e=go();if(!e)return;ae=null;let n=null;try{if((ho??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let t=Fe.dirname(e);if(T.mkdirSync(t,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=T.statSync(t),d=l.mode&511;if(!l.isDirectory()||(d&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${d.toString(8).padStart(3,"0")}`)}let i=T.constants.O_NOFOLLOW??0;n=T.openSync(e,T.constants.O_APPEND|T.constants.O_CREAT|T.constants.O_WRONLY|(T.constants.O_NONBLOCK??0)|i,384);let r=T.fstatSync(n),o=T.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 s=r.mode&511;if((s&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${s.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);T.fchmodSync(n,384)}catch(t){if(n!==null)try{T.closeSync(n)}catch{}se({event:"sidecar_disabled",reason:"open_failed",detail:v(`sidecar path '${e}' could not be opened safely (${t.message})`)},`${v(`[allscale] sidecar path '${e}' could not be opened safely (${t.message}); refusing to write. Sidecar disabled for this run.`)}
5
+ `);return}ae=e,P=n,le=!0}var _o=[/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 ko(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return _o.some(t=>t.test(n))}function Kt(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=wo(n.pathname);let r=t;n.pathname!==i&&(r=!0);for(let[o]of n.searchParams)ko(o)&&(n.searchParams.set(o,"<redacted>"),r=!0);return r?n.toString():e}catch{return e}}function wo(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function To(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Kt(e.url)}:e}function So(e){let n=new Date().toISOString(),t=e,{type:i,...r}=t,o=re(r,$e()),s=JSON.stringify({version:$t,timestamp:n,type:i,...o});return Buffer.byteLength(s,"utf8")+1>65536&&(s=JSON.stringify({version:$t,timestamp:n,type:i,output_truncated:!0})),s}function w(e){if(!le||!ae||P===null)return;let n=To(e),t=So(n);try{if(T.fstatSync(P).size+Buffer.byteLength(t,"utf8")+1>xn){le=!1;try{T.closeSync(P)}catch{}P=null,se({event:"sidecar_disabled",reason:"size_limit",...ae===null?{}:{path:v(ae)},max_bytes:xn},`${v(`[allscale] sidecar exceeded ${xn} bytes; disabling it for the rest of this run. Rotate or remove ${ae}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
6
+ `);return}T.appendFileSync(P,`${t}
7
+ `)}catch(i){if(le=!1,P!==null){try{T.closeSync(P)}catch{}P=null}try{se({event:"sidecar_disabled",reason:"write_failed",detail:v(i.message)},`${v(`[allscale] sidecar write failed (${i.message}); disabling sidecar for the rest of this run.`)}
8
+ `)}catch{}}}var G=Kt;function Gt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Me(){if(le=!1,P!==null){try{T.closeSync(P)}catch{}P=null}}function Ht(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Gt()||!n}var Se=_e()??mn,ce={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 H(e){return St(e)?new URL(e).origin:null}function R(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function jt(){let e=process.env[ce.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Un(){let e=process.env[ce.PROFILE]?.trim();return e&&e.length>0?e:void 0}function Ke(){let e=process.env[ce.API_BASE]?.trim();return e&&e.length>0?e:void 0}function qt(){let e=process.env[ce.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Jt(){let e=process.env[ce.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[ce.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Vt(e){let n,t;try{n=new URL(e),t=new URL(mn)}catch{return}if(n.host===t.host)return;let i=he[n.host],r=he[t.host];if(!(i===void 0||r===void 0||i.authProxyConfigId!==r.authProxyConfigId))return`Notice: session ${n.origin} signs against the production Turnkey org (mainnet \u2014 real funds).
9
+ `}function Wt(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:r}=e;if(_e()===void 0&&Se!==""&&"".length!==0&&!t&&r!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
10
+ The CLI default is now ${Se} (production), but a saved profile wins over the default,
11
+ so this session still uses staging. That pin was written before the default changed, so it may just be
12
+ the old default rather than a deliberate choice.
13
+ To keep staging, re-run login with --api-base ${""} (recorded as deliberate, silences this).
14
+ To move to production, run: ${Et} --api-base ${Se}
15
+ `}var ue=C(require("fs")),zt=C(require("os")),Bn=C(require("path")),Dn=C(require("@iarna/toml"));var Lo=".allscale",Eo="config.toml";function Ae(){return Bn.join(zt.homedir(),Lo)}function No(){return Bn.join(Ae(),Eo)}function Ge(){let e=No();if(!ue.existsSync(e))return{};let n=ue.readFileSync(e,"utf-8");try{return Dn.parse(n)}catch(t){throw new a("internal",`Failed to parse ${e}: ${t.message}`)}}function Xt(e){return Object.keys(e.profile??{}).sort()}function Zt(e,n){return e.profile?.[n]}function Qt(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new a("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function F(e){if(!ie(e))throw new a("input.invalid",`Refusing to send credentials to API base ${R(e)}. `+gn)}function be(e,n){F(e);let t=H(e),i=typeof n=="string"?H(n):null;if(t&&i===t)return;let r=typeof n=="string"?R(n):"<missing origin binding>";throw new a("input.invalid",`Refusing to send stored credentials: API base ${R(e)} does not match their bound origin ${r}. Re-login against the intended API base before retrying.`)}function ei(e,n){let t=H(e),i=H(n);if(!(t&&i===t))throw new a("input.invalid",`Refusing API request to ${R(n)} because it is outside the configured API origin ${R(e)}.`)}function Y(e){let n=_e();if(n===void 0||J(e))return;let t=H(e),i=we();if(i.length>0){let o=i.map(l=>H(l.base)).filter(l=>l!==null);if(t!==null&&o.includes(t))return;let s=i.map(l=>R(l.base)).join(", ");throw new a("input.invalid",`Refusing to send to ${R(e)} \u2014 this build only signs for: ${s}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let r=H(n);if(!(t!==null&&t===r))throw new a("input.invalid",`Refusing to send to ${R(e)} \u2014 this build only signs for ${R(n)}. Re-login against this build's environment, or use a build for that one.`)}var ni=require("@noble/hashes/sha3"),He=(s=>(s[s.ETHEREUM=1]="ETHEREUM",s[s.BASE=5]="BASE",s[s.BNB=6]="BNB",s[s.ARBITRUM=7]="ARBITRUM",s[s.POLYGON=8]="POLYGON",s[s.OPTIMISM=9]="OPTIMISM",s))(He||{});var Co={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},ti=["ethereum","bsc","base","polygon","arbitrum","optimism"],je=["USDT","USDC"];function ii(e){return Co[e.toLowerCase()]??null}function ri(e){let n=e.toUpperCase();return n==="USDT"?1:n==="USDC"?2:null}function oi(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))return!1;let n=e.slice(2);if(n===n.toLowerCase()||n===n.toUpperCase())return!0;let t=n.toLowerCase(),i=Buffer.from((0,ni.keccak_256)(Buffer.from(t,"ascii"))).toString("hex");for(let r=0;r<n.length;r+=1){let o=n[r];if(!/[a-fA-F]/.test(o))continue;let s=Number.parseInt(i[r],16)>=8;if(s&&o!==o.toUpperCase()||!s&&o!==o.toLowerCase())return!1}return!0}var Oo=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function si(e){return Oo.has(e.toLowerCase())}function $n(e,n){let i={1:"https://etherscan.io/tx",6:"https://bscscan.com/tx",5:"https://basescan.org/tx",8:"https://polygonscan.com/tx",9:"https://optimistic.etherscan.io/tx",7:"https://arbiscan.io/tx"}[e];return i?`${i}/${n}`:""}function D(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Le(e){return e===1?"USDT":"USDC"}var x=require("@oclif/core"),Ee=class e extends M.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:M.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:M.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ke()==="public"}),"api-base":M.Flags.string({description:yn,helpGroup:"GLOBAL",hidden:ke()==="public"}),"insecure-storage":M.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{Pn(this.jsonEnabled()),Mt(),w({type:"session-start",command:this.id??"",argv:Io(this.argv)});let n=this.constructor;if(ke()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(this.argv.some(o=>o==="--api-base"||o.startsWith("--api-base=")))throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!n.isLocalOnly&&Ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}if(n.requiresEscapeHatch&&!Yt())throw this.argv.length>0&&await this.parse(),new a("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. The real access boundary is enforced server-side by the key's scope regardless.");let t=Ht(this.jsonEnabled()),i=this.argv.length===0&&!t&&Fo(n)?this.config.findCommand(this.id??""):void 0;if(i){Me();let o=await(0,M.loadHelpClass)(this.config),s=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,s).showCommandHelp(i,this.config.topics);return}let r=await this.runCommand();return w({type:"command-end",ok:!0}),Me(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||vt(r),{data:r})}catch(n){let t=It(n);w({type:"error",code:t.code,message:v(t.message)}),w({type:"command-end",ok:!1,exitCode:t.exitCode}),Me(),this.emitError(t),process.exitCode=t.exitCode;return}finally{Pn(!1)}}resolveSessionApiBaseChain(n){let t=Ge(),i=n.profile??void 0,r=n["api-base"]??void 0,o=i!==void 0||Un()!==void 0,s=Qt(t,i,Un()),l=Zt(t,s),d=r??Ke(),c=d??l?.api_base??Se,p=Wt({resolvedApiBase:c,fromExplicitOverride:d!==void 0,profileApiBase:l?.api_base,profileApiBaseSource:l?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,se({event:"legacy_staging_profile",api_base:c,profile:s},p)),{apiBase:c,explicitApiBase:d,profileApiBase:l?.api_base,profile:s,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||F(t),t}resolveContext(n){if(ke()==="public"){if(n.token!==void 0)throw new a("input.invalid","--token is not supported in this build. Set the ALLSCALE_TOKEN environment variable instead (it does not leak into shell history or process listings).");if(n["api-base"]!==void 0)throw new a("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&Ke()!==void 0)throw new a("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let t=n.token??void 0,i=!!n["insecure-storage"],{apiBase:r,explicitApiBase:o,profile:s,profileApiBase:l,profileExplicit:d}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(F(r),Y(r)),{apiBase:r,profile:s,token:t??jt(),insecureStorage:i||qt(),apiBaseSource:o!==void 0?"explicit":l!==void 0?"profile":"default",profileExplicit:d}}emitError(n){process.stderr.write(`${$o(n)}
16
+ `)}},Je=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"]),Ro=new Set(Array.from(Je).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2));function Io(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(Je.has(o)){n.push(`${o}=<redacted>`);continue}}}if(Je.has(i)){n.push(i),t+1<e.length&&(Je.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(Ro.has(r)){n.push(`${r}<redacted>`);continue}}n.push(i)}return n}var vo=/(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 Po(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return vo.test(n)}var xo=/_(removed|cleared|count|total)$/i;function Uo(e,n){return typeof n=="number"&&xo.test(e)}var Bo=new Set(je);function Do(e,n){return e==="token_symbol"&&typeof n=="string"&&Bo.has(n)}var qe=100;function Fn(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,qe),i=t.map(r=>Fn(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,qe))t[r]=Po(r)&&!Uo(r,o)&&!Do(r,o)?"<redacted>":Fn(o,n+1);if(i.length>qe){let r="<truncated>";for(;r in t;)r=`<${r}>`;t[r]=`${i.length-qe} more keys`}return t}return typeof e=="string"?v(e):e}function $o(e){let n=Dt()?void 0:2,t=Fn(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:v(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function Fo(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))}function Mo(e,n={}){let t;try{t=Xt(Ge())}catch{return}if(!(t.length===0||t.includes(e)))return new a("auth.unknown_profile",Rt(e,t)+(n.messageSuffix??""),{profile:e,known_profiles:t})}function pe(e){if(e.profileExplicit){let n=Mo(e.profile);if(n)return n}return new a("auth.no_token",Ot(e.profile,e.flow))}var ki=C(require("path"));var Gn=require("crypto"),u=C(require("fs")),A=C(require("path"));var Ye=1024*1024,Ko=5e3,Go=20,Ho=3e4,Mn=4096,jo=new Int32Array(new SharedArrayBuffer(4)),Ne=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function Ve(e){return e instanceof Ne}var I=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},qo=null;function W(){return new a("storage.unavailable","Owner-only plaintext credential ACLs cannot be enforced on Windows; --insecure-storage is disabled on this platform. Use Windows Credential Manager instead. `allscale logout` can still remove a legacy plaintext file when the requested profile is its only remaining profile.")}function We(){return(qo??process.platform)!=="win32"}function mi(){if(!We())throw W()}function yi(e){try{return u.default.lstatSync(e),!1}catch(n){if(!S(n,"ENOENT"))throw n}try{let n=u.default.lstatSync(A.dirname(e));return!n.isSymbolicLink()&&n.isDirectory()}catch(n){if(S(n,"ENOENT"))return!0;throw n}}function S(e,n){return typeof e=="object"&&e!==null&&e.code===n}function Ce(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 Jo(e){Atomics.wait(jo,0,0,e)}function gi(e){try{return process.kill(e,0),!0}catch(n){return!S(n,"ESRCH")}}function Yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ai(e,n){let t=A.dirname(e);n&&u.default.mkdirSync(t,{recursive:!0,mode:448});let i;try{i=u.default.lstatSync(t)}catch(o){if(!n&&S(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=u.default.openSync(t,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0));let o=u.default.fstatSync(r),s=u.default.lstatSync(t);if(!o.isDirectory()||s.isSymbolicLink()||!s.isDirectory()||!Oe(o,s))throw new Error("credential-store parent changed while it was being inspected");Ce(o,"credential-store parent");let l=o;if((o.mode&63)!==0&&A.basename(t)===".allscale"&&(u.default.fchmodSync(r,448),l=u.default.fstatSync(r)),(l.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{r!==null&&u.default.closeSync(r)}return!0}function K(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=u.default.lstatSync(e)}catch(o){throw i.retryOnPathChange&&S(o,"ENOENT")?new I:o}if(!Oe(t,r))throw i.retryOnPathChange?new I: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 Ne;if(Ce(t,"credential-store file"),process.platform!=="win32"){u.default.fchmodSync(n,384);let o=u.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 Vo(e,n){if(n.size>Ye)throw new Error("credential-store file exceeds the maximum supported size");let t=Buffer.alloc(Ye+1),i=0;for(;i<t.length;){let r=u.default.readSync(e,t,i,t.length-i,null);if(r===0)break;i+=r}if(i>Ye)throw new Error("credential-store file exceeds the maximum supported size");return t.subarray(0,i).toString("utf8")}function li(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){if(S(r,"ENOENT"))try{if(u.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(S(o,"ENOENT"))return null;throw o}throw r}let t=u.default.fstatSync(n),i=K(e,n,t);return Vo(n,i)}finally{n!==null&&u.default.closeSync(n)}}function di(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(r){if(S(r,"ENOENT")&&yi(e))return;throw r}let t=u.default.fstatSync(n),i=K(e,n,t);z(e,i)}finally{n!==null&&u.default.closeSync(n)}_i(A.dirname(e))}function Wo(e){let n;try{n=u.default.lstatSync(e)}catch(t){if(S(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 Ne;Ce(n,"credential-store replacement target")}function zo(e,n){for(let t=0;t<8;t+=1){let i=(0,Gn.randomBytes)(12).toString("hex"),r=A.join(e,`.${n}.${process.pid}.${i}.tmp`);try{return{fd:u.default.openSync(r,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384),tempPath:r}}catch(o){if(S(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function hi(e,n){let t=0;for(;t<n.length;){let i=u.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 _i(e){if(process.platform==="win32")return;let n=null;try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_DIRECTORY??0)|(u.default.constants.O_NOFOLLOW??0)),u.default.fsyncSync(n)}catch{}finally{if(n!==null)try{u.default.closeSync(n)}catch{}}}function Xo(e,n){let t=Buffer.from(n,"utf8");if(t.length>Ye)throw new Error("credential-store file exceeds the maximum supported size");let i=A.dirname(e),r=A.basename(e),o=null,s=null,l=!1;try{let d=zo(i,r);o=d.fd,s=d.tempPath;let c=u.default.fstatSync(o);if((K(s,o,c).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");hi(o,t),u.default.fsyncSync(o),K(s,o,u.default.fstatSync(o));let f=o;o=null,u.default.closeSync(f),Wo(e),u.default.renameSync(s,e),l=!0}finally{if(o!==null)try{u.default.closeSync(o)}catch{}if(!l&&s!==null)try{u.default.unlinkSync(s)}catch{}}_i(i)}function Zo(e){return A.join(A.dirname(e),`.${A.basename(e)}.lock`)}function Qo(e){return A.join(A.dirname(e),`.${A.basename(e)}.lock-recovery`)}function es(e,n){if(n.size>Mn)return null;let t=Buffer.alloc(Mn+1),i=0;for(;i<t.length;){let o=u.default.readSync(e,t,i,t.length-i,null);if(o===0)break;i+=o}if(i>Mn)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 z(e,n){let t=u.default.lstatSync(e);if(t.isSymbolicLink()||!t.isFile()||!Oe(t,n))throw new Error("credential-store lock changed while it was being inspected");Ce(t,"credential-store lock"),u.default.unlinkSync(e)}function ci(e,n){let t=null;try{try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(d){if(S(d,"ENOENT"))try{let c=u.default.lstatSync(e);throw c.isSymbolicLink()||!c.isFile()?new Error("credential-store lock must be a real regular file"):new I}catch(c){if(S(c,"ENOENT"))return{state:"absent"};throw c}throw d}let i=u.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=es(t,r);return{state:(o?.target===n&&o?!gi(o.pid):Date.now()-r.mtimeMs>=Ho)?"stale":"active",stats:r}}finally{t!==null&&u.default.closeSync(t)}}function ns(e,n){for(let t=0;t<8;t+=1){let i=(0,Gn.randomBytes)(12).toString("hex"),r=A.join(e,`.${n}.${process.pid}.${i}.lock-claim`),o={pid:process.pid,nonce:i,target:n},s=null;try{s=u.default.openSync(r,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_WRONLY|(u.default.constants.O_NOFOLLOW??0),384);let l=u.default.fstatSync(s),d=K(r,s,l,{allowMultipleLinks:!0});return hi(s,Buffer.from(JSON.stringify(o),"utf8")),u.default.fsyncSync(s),{claimPath:r,metadata:o,stats:d}}catch(l){if(S(l,"EEXIST"))continue;try{u.default.unlinkSync(r)}catch{}throw l}finally{s!==null&&u.default.closeSync(s)}}throw new Error("could not allocate a unique credential-store lock claim")}function ts(e,n){let t;try{t=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(i){throw S(i,"ENOENT")?new I:i}try{let i=u.default.fstatSync(t),r=K(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!Oe(r,n))throw new I;return{fd:t,lockPath:e,stats:r}}catch(i){throw u.default.closeSync(t),i}}function ui(e){let n=null;try{try{n=u.default.openSync(e,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(t){if(S(t,"ENOENT"))try{let i=u.default.lstatSync(e);throw i.isSymbolicLink()||!i.isFile()?new Error("credential-store recovery gate must be a real regular file"):new I}catch(i){if(S(i,"ENOENT"))return!1;throw i}throw t}return K(e,n,u.default.fstatSync(n),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{n!==null&&u.default.closeSync(n)}}function is(e){let n;try{n=u.default.openSync(e,u.default.constants.O_CREAT|u.default.constants.O_EXCL|u.default.constants.O_RDWR|(u.default.constants.O_NOFOLLOW??0),384)}catch(i){if(S(i,"EEXIST"))return null;throw i}let t=null;try{t=u.default.fstatSync(n);let i=K(e,n,t,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:n,lockPath:e,stats:i}}catch(i){if(t!==null)try{z(e,t)}catch{}throw u.default.closeSync(n),i}}function V(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");Jo(Go)}function pi(e){let n=A.dirname(e),t=A.basename(e),i=Zo(e),r=Qo(e),o=ns(n,t),s=Date.now()+Ko,l=!1,d=!1,c=null,p;try{for(;c===null;)try{if(ui(r)){V(s,!0);continue}u.default.linkSync(o.claimPath,i),d=!0,c=ts(i,o.stats),l=!0}catch(f){if(d&&!l){try{z(i,o.stats)}catch{}d=!1}if(f instanceof I){V(s,!1);continue}if(!S(f,"EEXIST"))throw f;let m;try{m=ci(i,t)}catch(_){if(_ instanceof I){V(s,!1);continue}throw _}if(m.state==="absent")continue;if(m.state==="stale"){let _;try{_=is(r)}catch(k){if(k instanceof I){V(s,!1);continue}throw k}if(_!==null){try{let k;try{k=ci(i,t)}catch(L){if(L instanceof I){V(s,!1);continue}throw L}k.state==="stale"&&z(i,k.stats)}finally{Kn(_)}continue}}let y;try{y=ui(r)}catch(_){if(_ instanceof I){V(s,!1);continue}throw _}V(s,y)}}catch(f){p=f}try{z(o.claimPath,o.stats)}catch(f){!S(f,"ENOENT")&&!l&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(c===null)throw new Error("credential-store lock acquisition failed");return c}function Kn(e){try{z(e.lockPath,e.stats)}finally{u.default.closeSync(e.fd)}}function rs(e,n){let t=Yo(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 fi(e){let n=A.dirname(e),t=A.basename(e);for(let i of u.default.readdirSync(n)){let r=rs(i,t);if(r===null||gi(r))continue;let o=A.join(n,i),s=null;try{try{s=u.default.openSync(o,u.default.constants.O_RDONLY|(u.default.constants.O_NOFOLLOW??0)|(u.default.constants.O_NONBLOCK??0))}catch(c){if(S(c,"ENOENT")||S(c,"ELOOP"))continue;throw c}let l=u.default.fstatSync(s),d=u.default.lstatSync(o);if(!l.isFile()||d.isSymbolicLink()||!d.isFile()||!Oe(l,d))continue;try{Ce(l,"credential-store orphan")}catch{continue}z(o,l)}catch(l){if(!S(l,"ENOENT"))throw l}finally{s!==null&&u.default.closeSync(s)}}}function Re(e,n,t){if(!We()){if(n.allowUnsupportedPlatformCleanup){if(n.createParent)throw W();if(!ai(e,!1))return t({read:()=>null,remove:()=>{},write:()=>{throw W()}});let s=pi(e);try{return fi(e),t({read:()=>li(e),remove:()=>di(e),write:()=>{throw W()}})}finally{Kn(s)}}if(!n.createParent){let o=!1;try{o=yi(e)}catch{throw W()}if(o)return t({read:()=>null,remove:()=>{},write:()=>{throw W()}})}throw W()}if(!ai(e,n.createParent))return t({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let r=pi(e);try{return fi(e),t({read:()=>li(e),remove:()=>di(e),write:o=>Xo(e,o)})}finally{Kn(r)}}var Hn="allscale-cli";function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wi(e){return Yn(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function Z(e){return new a("internal",`The session credential store in the ${e} exists but could not be read as valid credential data. Refusing to treat it as empty or overwrite it; session credentials may still remain on this machine.`)}function jn(){return new a("internal","The session credential store in the plaintext file has multiple hard links. Refusing to read, modify, or delete it because another directory entry may retain session credentials. Remove every extra hard link, then re-run the command. If you intentionally keep a deduplicated backup, revoke or rotate its credentials before treating logout as complete.")}function ze(){return new a("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var X,qn=!1;function os(){return Jt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function ss(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let n=e.message;return typeof n=="string"&&n.split(`
17
+ `,1)[0]==="Cannot find module 'keytar'"}function as(){if(X!==void 0)return X;if(os())return qn=!1,X=null,X;try{X=require("keytar"),qn=!1}catch(e){qn=!ss(e),X=null}return X}function Ti(){let e=We()?"Re-run with --insecure-storage (or set ALLSCALE_INSECURE_STORAGE=1) to use the owner-only plaintext credential file.":"Plaintext credential fallback is unavailable on Windows because owner-only ACLs cannot be verified; use Windows Credential Manager.";return new a("storage.unavailable","OS keychain could not be accessed on this system (keytar / libsecret may be unavailable, locked, or unusable). "+e+" Never silently downgrade in production.")}async function Jn(e){try{return await e()}catch{throw Ti()}}var Vn=class{constructor(n){this.keytar=n}keytar;kind="keychain";async read(n){let t=await Jn(()=>this.keytar.getPassword(Hn,n));if(t===null)return null;let i;try{i=JSON.parse(t)}catch{throw Z("OS keychain")}if(!wi(i))throw Z("OS keychain");return i}async get(n){return this.read(n)}async set(n,t){await this.read(n),await Jn(()=>this.keytar.setPassword(Hn,n,JSON.stringify(t)))}async delete(n){await this.read(n),await Jn(()=>this.keytar.deletePassword(Hn,n))}},ls="credentials.json",Wn=class{kind="insecure-file";filePath;constructor(n){this.filePath=n??ki.join(Ae(),ls)}read(n){let t;try{t=n.read()}catch(r){throw Ve(r)?jn():Z("plaintext file")}if(t===null)return{profiles:{}};let i;try{i=JSON.parse(t)}catch{throw Z("plaintext file")}if(!Yn(i)||!Yn(i.profiles))throw Z("plaintext file");return i}write(n,t){try{n.write(JSON.stringify(t,null,2))}catch(i){throw Ve(i)?jn():ze()}}profileTokens(n,t){let i=n.profiles[t];if(i!==void 0){if(!wi(i))throw Z("plaintext file");return i}}async get(n){try{return Re(this.filePath,{createParent:!1},t=>this.profileTokens(this.read(t),n)??null)}catch(t){throw t instanceof a?t:Z("plaintext file")}}async set(n,t){try{Re(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 a?i:ze()}}async delete(n){try{Re(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 a?t:ze()}}async clearProfile(n){try{return Re(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 a?t:Ve(t)?jn():ze()}}};function fe(e){if(e.insecureStorage)return mi(),new Wn(e.insecureFilePath);let n=as();if(n)return new Vn(n);throw Ti()}var zn=class{kind="insecure-file";async get(n){return null}async set(n,t){throw new a("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(n){}};function Xe(){return new zn}async function Si(e){if(e.token)return{kind:"override",accessToken:e.token};let t=await fe({insecureStorage:e.insecureStorage}).get(e.profile),i=t?.api_base;return t?.agent_key?{kind:"agent",storedApiBase:i,businessId:ds(t.business_id)}:t?.access_token?{kind:"human",storedApiBase:i,accessToken:t.access_token}:{kind:"none"}}function ds(e){return typeof e=="string"&&e.length>0?e:void 0}function Ze(e){let n=e.split(".");if(n.length!==3)throw new a("auth.token_expired","Stored token is not a valid JWT.");try{let t=Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(t)}catch(t){throw new a("auth.token_expired",`Failed to decode JWT payload: ${t.message}`)}}async function cs(e){let n=i=>{let r=Ze(i);return typeof r.user_id=="string"&&r.user_id.length>0?r.user_id:void 0},t=await Si(e);switch(t.kind){case"override":case"human":return n(t.accessToken);case"agent":return t.businessId;case"none":throw pe({profile:e.profile,profileExplicit:e.profileExplicit});default:return us(t)}}function us(e){throw new a("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}var ps=/^[0-9a-f]{24}$/i;async function Ai(e,n){if(typeof n!="string"||n.length===0)return;if(!ps.test(n))throw new a("input.invalid",`--business-id '${n}' is not a valid business id (expected 24 hexadecimal characters). Omit the flag to use the business you are signed in as.`);let t=await cs(e);if(t===void 0){process.stderr.write(`Note: could not verify that --business-id '${n}' is your own business \u2014 this session stores no business id (an agent-key login predating the backend returning it). The command acts as the business you are signed in as regardless. Re-run \`allscale device-login\` to store it and enable this check.
18
+ `);return}if(t.toLowerCase()!==n.toLowerCase())throw new a("auth.permission_denied",`--business-id '${n}' is not the business you are signed in as. This command always acts as the authenticated business, so a different business id cannot be used. Omit the flag, or sign in as that business.`)}var Q="allscale_access_token",Xn="allscale_refresh_token";function Qe(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 Ie(e){return e.map(n=>`${n.name}=${n.value}`).join("; ")}function Zn(e,n){return e.find(t=>t.name===n)?.value??null}var bi=C(require("crypto")),Li=C(require("fs")),Ei=C(require("path"));var fs="key-id",ms="x-allscale-cli-version",Qn="cli-1",ys="aScaLe_cli_obf_v1",gs="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function hs(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 _s=hs(gs,ys),en=`Bearer ${_s}`;function Ni(e,n){let t=kn(e);if(t!==null)return n.find(i=>kn(i.base)===t)}function ks(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let n=we();if(n.length>0){let i=Ni(e,n);if(i)return i.key;if(J(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?r:J(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 ws(e){{let i="cli-1".trim();if(i.length>0)return i}let n=we();if(n.length>0){let i=e!==void 0?Ni(e,n):void 0;if(i)return i.keyId;if(e!==void 0&&J(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():Qn}if(!J(n[0].base))return Qn}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():Qn}function Ts(){return"0.1.0"}function Ss(){return new a("signing.key_unavailable","No request-signing key is available for this destination in this build. Published builds embed one at publish time; when running from source or an internal build, set ALLSCALE_SIGNING_KEY + ALLSCALE_BUILD_API_BASE (or ALLSCALE_BUILD_PAIRS for more than one environment) in the environment.")}function me(e,n){let t=ks(n);if(!t)throw Ss();let i=ws(n),r=Math.floor(Date.now()/1e3).toString(),o=bi.createHash("sha256").update(`${t}${r}${e}`).digest("hex"),s={timestamp:r,"secret-key":o,[ms]:Ts()};return i.length>0&&(s[fs]=i),s}function ve(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var rn=256*1024,nn=class extends a{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"}},tn=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 et(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 nn(e.status,n,t.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),s=[],l=0,d,c=t.timeoutMs,p=c===void 0?void 0:new Promise((f,m)=>{d=setTimeout(()=>{m(new tn(e.status,c))},c),d.unref?.()});try{for(;;){let f=o.read(),{done:m,value:y}=p?await Promise.race([f,p]):await f;if(m)break;if(l+=y.byteLength,l>n)throw o.cancel().catch(()=>{}),new nn(e.status,n,t.oversizeKind);s.push(Buffer.from(y))}}catch(f){throw f instanceof tn&&o.cancel(f).catch(()=>{}),f}finally{d!==void 0&&clearTimeout(d);try{o.releaseLock()}catch{}}return Buffer.concat(s,l).toString("utf8")}var As="X-AllScale-Api-Key",bs=3e4,Ls=32*1024*1024,Es=4*1024*1024;function Ns(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 Cs(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 Os(e,n){if(!(e<300||e>=400))throw new a("transport.network",`API returned HTTP ${e} (a redirect) for ${G(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 nt(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Os(e.status,e.url)}}var Ci="--dns-result-order=ipv4first";async function on(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"),s=n?.slice(0,4096)??"",l=/^\s*(?:<!doctype\s+html|<html\b)/i.test(s),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(s);if(!((o||l)&&(r||n!==void 0&&d)))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 a("transport.network",`Cloudflare blocked this request before it reached the AllScale API (HTTP 403). This can happen when the release edge accepts IPv4 but rejects IPv6. Retry with NODE_OPTIONS=${Ci} 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=${Ci}`})}var ee=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??bs;if(!Number.isFinite(i)||i<1)throw new a("input.invalid","HTTP request timeout must be a positive number of milliseconds.");F(this.opts.apiBase),Y(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=Ns(n.signal,i);try{return await this.requestWithinDeadline({...n,signal:o.signal},t,r)}catch(s){throw o.timedOut()?new a("transport.timeout",`Request to ${G(new URL(n.path,this.opts.apiBase).toString())} timed out after ${i}ms.`,{timeout_ms:i}):n.signal?.aborted&&!(s instanceof a)?new a("transport.network",`Request to ${G(new URL(n.path,this.opts.apiBase).toString())} was aborted by the caller.`):s}finally{o.dispose()}}async requestWithinDeadline(n,t,i){let r=new URL(n.path,this.opts.apiBase).toString();ei(this.opts.apiBase,r);let o=i?.agent_key,s=n.auth??"auto",l=vi(n.path),d=s==="required"?!0:s==="none"?!1:vs(n.path);if((l||s==="required")&&!n._isRefresh&&!this.opts.override&&!i?.access_token&&!o)throw pe({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let c=ve(n.body),p=!!o||!!i?.access_token;d&&p&&!this.opts.override&&be(this.opts.apiBase,i?.api_base);let f=this.buildHeaders({attachAuth:d&&p,bodyForSig:c,tokens:i,extra:n.headers}),m=Date.now();w({type:"request",method:n.method??"GET",url:r,...n._isRefresh?{refresh:!0}:{}});let y;try{y=await fetch(r,{method:n.method??"GET",headers:f,body:n.body!==void 0?c:void 0,signal:n.signal,redirect:"manual"})}catch(k){throw new a("transport.network",`Network error contacting ${G(r)}: ${k instanceof Error?k.message:String(k)}`)}if(w({type:"response",status:y.status,durationMs:Date.now()-m}),d&&!!i?.access_token&&!o&&y.status===401&&!n._isRefresh&&!this.opts.override){let k=await Cs(this.refreshSingleFlight(),n.signal),L=this.buildHeaders({attachAuth:d&&!!k.access_token,bodyForSig:c,tokens:k,extra:n.headers}),g=Date.now();w({type:"request",method:n.method??"GET",url:r});let h;try{h=await fetch(r,{method:n.method??"GET",headers:L,body:n.body!==void 0?c:void 0,signal:n.signal,redirect:"manual"})}catch(E){throw new a("transport.network",`Network error contacting ${G(r)} on refresh-retry: ${E instanceof Error?E.message:String(E)}`)}return w({type:"response",status:h.status,durationMs:Date.now()-g}),Oi(h,{withMetadata:t.withMetadata,authBearing:d,responseKind:Ri(n)})}return Oi(y,{withMetadata:t.withMetadata,authBearing:d&&p,agentKeyAuth:d&&!!o,responseKind:Ri(n)})}buildHeaders(n){let i={Accept:"application/json","Content-Type":"application/json",...me(n.bodyForSig,this.opts.apiBase),...n.extra};if(n.attachAuth){i.Authorization=en;let r=n.tokens;if(r?.agent_key)return i[As]=r.agent_key,i;let o=r?.access_token;o&&(i.Cookie=Ie([{name:Q,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 a("auth.token_expired",`No refresh token available; log in again \u2014 ${An()}.`);if(be(this.opts.apiBase,n.api_base),n.agent_key)throw new a("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than 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=Ie([{name:Q,value:n.access_token},{name:Xn,value:n.refresh_token}]),r=me("",this.opts.apiBase);w({type:"request",method:"POST",url:t,refresh:!0});let o=new AbortController,s=!1,l=setTimeout(()=>{s=!0,o.abort()},1e4),d;try{d=await fetch(t,{method:"POST",headers:{Accept:"application/json",Cookie:i,...r},signal:o.signal,redirect:"manual"})}catch(y){throw w({type:"refresh",ok:!1}),new a("transport.network",s&&y instanceof Error&&y.name==="AbortError"?`Token refresh against ${G(t)} timed out after 10s with no response.`:`Network error during token refresh against ${G(t)}: ${y instanceof Error?y.message:String(y)}`)}finally{clearTimeout(l)}w({type:"response",status:d.status,durationMs:0});try{await nt(d)}catch(y){throw w({type:"refresh",ok:!1}),y}if(d.status!==200){w({type:"refresh",ok:!1}),await on(d);let y=await Pi(d);throw await on(d,y),ne(d.status,y),new a("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${An()}.`,{status:d.status})}let c=Qe(d.headers),p=Zn(c,Q),f=Zn(c,Xn);if(!p||!f)throw w({type:"refresh",ok:!1}),new a("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),w({type:"refresh",ok:!0}),m}},Rs=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function vi(e){let n=e.split(/[?#]/,1)[0];return Rs.some(t=>n===t||n.startsWith(`${t}/`))}var Is=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function tt(e){let n=e.split(/[?#]/,1)[0];return Is.some(t=>t.test(n))}function vs(e){return vi(e)||tt(e)}async function Oi(e,n={}){await nt(e);let t=e.status>=200&&e.status<300;t||await on(e);let i=n.responseKind??"mutation",o=await et(e,t?i==="query"?Ls:Es:rn,{oversizeKind:t?i==="query"?"successful-query":"successful-mutation":"backend-envelope"});t||await on(e,o);let s=null;if(o.length>0)try{s=JSON.parse(o)}catch{s={raw:o}}if(e.status>=200&&e.status<300){if(n.withMetadata){let d={};return e.headers.forEach((c,p)=>{d[p]=c}),{status:e.status,headers:d,body:s}}return s}let l=Us(s)??`HTTP ${e.status}`;if(ne(e.status,s),e.status===401){if(n.agentKeyAuth)throw new a("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:s});let d=n.authBearing?"auth.token_expired":"input.invalid";throw new a(d,l,{status:401,body:s})}throw e.status===403?new a("auth.permission_denied",l,{status:403,body:s}):e.status===404?new a("not_found",l,{status:404,body:s}):e.status===429?new a("rate_limited",l,{status:429,body:s}):e.status>=500?new a("backend.internal",l,{status:e.status,body:s}):new a("input.invalid",l,{status:e.status,body:s})}function Ri(e){if(e.responseKind)return e.responseKind;let n=(e.method??"GET").toUpperCase();return n==="GET"||n==="HEAD"?"query":"mutation"}var Ii=2014;function Ps(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===Ii||t===String(Ii)}var xs=1e4;async function Pi(e,n=xs){if(e.status>=200&&e.status<300)return"";try{return await et(e,rn,{timeoutMs:n})}catch{return""}}function ne(e,n){if(!(e>=200&&e<300)&&Ps(n))throw new a("auth.signature_rejected","The AllScale API rejected this CLI build's request signing key. Download the latest version \u2014 `npm install -g @allscale/cli@latest` \u2014 and retry: retiring an old signing key is how a release is made mandatory. If you are already on the latest version, this build's key row is missing or misprovisioned on the backend \u2014 contact AllScale support. Re-logging in will not help either way; the key ships inside the CLI build itself.",{status:e,body:typeof n=="string"?n.slice(0,500):n})}function Us(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 Bs=/^\/(api\/)?(v1\/)?public\//;function te(e,n={}){let t=typeof n.pathHint=="string"?n.pathHint:"",i=t&&Bs.test(t),r=t&&tt(t),o=i&&!r&&!n.forceAuth;if(e.token)return new ee({apiBase:e.apiBase,tokenStore:Xe(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new ee({apiBase:e.apiBase,tokenStore:Xe(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new ee({apiBase:e.apiBase,tokenStore:fe({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(s){if(r)return new ee({apiBase:e.apiBase,tokenStore:Xe(),profile:e.profile,profileExplicit:e.profileExplicit});throw s}}var xi=[{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}],Ui=[{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 sn=new Set(["SCALAR","ENUM"]),Ds=new Set(["password","password_hash","totp_secret","credential","credentials","private_key","encryption_key"]),$s=[/(^|_)password(_|$)/i,/(^|_)secret(_|$)/i,/(^|_)token(_|$)/i,/(^|_)api[_-]?key(_|$)/i,/(^|_)signing[_-]?key(_|$)/i,/(^|_)private[_-]?key(_|$)/i,/(^|_)credential(_|$)/i],Fs=new Set(["CreateClaimLinkResult.claim_token","StoreCreateResult.api_secret"]),Ms=new Map([["StoreCreateResult.store",["id","name"]],["CreateClaimLinkResult.claim_link",["id","token_symbol","status"]]]),Ks=new Set(["token_symbol"]);function it(e){return Ks.has(e.toLowerCase())?!1:Ds.has(e)?!0:$s.some(n=>n.test(e))}function Gs(e,n){return Fs.has(`${e}.${n}`)}function rt(e){return e.kind==="NON_NULL"&&e.ofType?`${rt(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${rt(e.ofType)}]`:e.name??"Unknown"}function Pe(e){let n=e;for(;n&&n.ofType;)n=n.ofType;return!n||!n.name?null:{kind:n.kind,name:n.name}}function Hs(e,n){let t=n.find(s=>s.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 s of i){let l=Pe(s.type);if(!l)continue;if(sn.has(l.kind)){if(it(s.name)&&!Gs(e,s.name))continue;r.push(s.name);continue}let d=Ms.get(`${e}.${s.name}`);if(d){let c=n.find(m=>m.name===l.name),p=new Set((c?.fields??[]).filter(m=>{let y=Pe(m.type);return y!==null&&sn.has(y.kind)&&!it(m.name)}).map(m=>m.name)),f=d.filter(m=>!p.has(m));if(f.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${s.name}"] names field(s) [${f.join(", ")}] that are not selectable scalars on ${l.name}; fix the entry or the public registry.`);r.push(`${s.name} { ${d.join(" ")} }`);continue}if(!o&&s.name==="items"&&s.type.kind==="NON_NULL"&&s.type.ofType?.kind==="LIST"){let c=js(s.type)?.name;if(c){let p=qs(c,n);p&&r.push(`items { ${p} }`),o=!0}}}return r.length>0?r.join(" "):"__typename"}function js(e){return Pe(e)}function qs(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 s=Pe(o.type);if(s&&sn.has(s.kind)){if(it(o.name))continue;r.push(o.name)}}return r.length>0?r.join(" "):"__typename"}function Bi(e,n,t){let i=Js(e.name),r=e.args.map(p=>{let f=rt(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(", "),s=r.length>0?`${e.kind} ${i}(${r})`:`${e.kind} ${i}`,l=o.length>0?`${e.name}(${o})`:e.name,d=Pe(e.returnType),c;if(d&&sn.has(d.kind))c=l;else{let p=t&&t.trim().length>0?t.trim():d&&Hs(d.name,n)||"__typename";c=`${l} { ${p} }`}return`${s} { ${c} }`}function Di(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 $i(e,n,t){return e.find(i=>i.kind===n&&i.name===t)??null}function Fi(e){if(!e||typeof e!="object")return!1;let n=e.errors;return Array.isArray(n)&&n.length>0}function Mi(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 Js(e){return e.replace(/[^_0-9A-Za-z]/g,"_")}var Ki=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"]),Gi=new Set(["payroll","admin:user","admin:org","admin:audit"]);function Hi(e){let n=e.lastIndexOf(":");return n===-1?e:e.slice(0,n)}function ji(e,n){if(e===n)return!0;let t=":read_only";return n.endsWith(t)&&e===`${n.slice(0,-t.length)}:all`}var Ys={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"},Vs={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"},Ws=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,zs=/is not available to API keys/i,qi=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Ji(e){if(typeof e!="string")return;let n=Ws.exec(e);if(!n)return;let t=n[1].trim(),i=n[2].trim(),r=zs.test(t),o=!r&&qi.test(t)?t:void 0,s;if(i.toLowerCase()==="none")s=[];else{let l=i.split(",").map(d=>d.trim()).filter(d=>qi.test(d));s=l.length>0?l:void 0}if(!(o===void 0&&!r))return{required:o,granted:s,notAvailableToKeys:r}}function Yi(e){let n=Vs[e];if(n!==void 0)return{ungrantableReason:n};let t=Ys[e];if(t!==void 0)return{scope:t}}function Vi(e){if(Gi.has(Hi(e)))return{kind:"ungrantable"};for(let n of Ki)if(ji(n,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}function zi(e,n){let t=Xi(e),i={graphql_error_count:Xs(e.errors),...t===void 0?{}:{backend_code:t}};if(t===2102)throw Zs(e,n,i);if(t===3400)throw new a("not_found",`GraphQL ${n.kind} '${n.operationName}' could not find the requested resource.`,i);if(Fi(e))throw new a("input.invalid",`GraphQL ${n.kind} '${n.operationName}' returned errors: ${Mi(e)}`,i);if(t!==void 0)throw new a("input.invalid",`GraphQL ${n.kind} '${n.operationName}' failed with backend code ${t}.`,i)}function Xi(e){let n=Wi(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=Wi(i.code);if(r!==void 0)return r}}function Wi(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 Xs(e){return Array.isArray(e)?e.length:e==null?0:1}function Zs(e,n,t){let i=`GraphQL ${n.kind} '${n.operationName}'`,r={...t,operation:n.operationName},o=Ji(Qs(e,Xi(e))),s=Yi(n.operationName),l=o?.notAvailableToKeys===!0,d=o?.required??s?.scope,c=o?.granted,p=c===void 0?"":` This key holds ${c.length>0?c.join(", "):"no scopes"}.`;if(l||s?.ungrantableReason!==void 0){let f=s?.ungrantableReason!==void 0?`: ${s.ungrantableReason}`:"";return new a("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:[],...c===void 0?{}:{granted_scopes:c},ungrantable:!0})}if(d!==void 0){let f=Vi(d),m=f.kind==="ungrantable"?`\`${d}\` 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 \`${Te()}\` with \`--scopes ${d}\`.`:`The browser approval screen does not offer \`${d}\`, so \`device-login\` cannot grant it \u2014 use \`${Te()}\` with \`--scopes ${d}\`.`;return new a("auth.permission_denied",`The current agent key lacks \`${d}\`, required by ${i}.${p} ${m}`,{...r,missing_scopes:[d],...c===void 0?{}:{granted_scopes:c},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new a("auth.permission_denied",`The current agent key does not have the scope required by ${i}.${p} Re-run \`allscale device-login\` (or \`${Te()}\`) and grant the required scope.`,r)}function Qs(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 s=o.code;if(s===n||typeof s=="string"&&Number(s)===n){let d=i(r);if(d!==void 0)return d}}for(let r of t){let o=i(r);if(o!==void 0)return o}return""}async function ot(e,n,t,i,r={}){let o=$i(xi,n,t);if(!o)throw new a("input.invalid",`No ${n} named '${t}' in the schema. Run \`allscale operations --kind ${n}\` to list options.`);let s=Di(o,i);if(!s.ok)throw new a("input.invalid",`Missing required variables for ${t}: ${s.missing.join(", ")}`,{required:s.missing});let l=Bi(o,Ui,r.selection);return ea(e,{...r,kind:n,operationName:o.name,document:l,variables:i})}async function ea(e,n){n.showDoc&&process.stderr.write(`${n.document}
19
+ `);let t=te(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}});zi(r,{kind:n.kind,operationName:n.operationName});let o=r.data?.[n.operationName];return o===void 0?null:o}var ar=require("crypto"),O=require("process");var ye={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_TOKEN_CONSUMED:7411},na=new Set(Object.values(ye));async function Zi(e,n,t){return Qi(e,"/api/secure/wallet/cli_op_init",{op:n,payload:t},"cli_op_init")}async function st(e,n){return Qi(e,"/api/secure/wallet/cli_op_result",{result_token:n},"cli_op_result")}async function Qi(e,n,t,i){let r;try{r=await e.request({method:"POST",path:n,body:t})}catch(o){if(o instanceof a){let s=ta(o,i);if(s!==null)throw s}throw o}return ia(r,i)}function ta(e,n){let t=e.details?.body;if(!t||typeof t!="object")return null;let i=t,r=typeof i.code=="number"?i.code:void 0;if(r===void 0||r===0||!na.has(r))return null;let o=typeof i.errors=="string"?i.errors:typeof i.message=="string"?i.message:e.message;return er(r,o,n)}function ia(e,n){if(e.code!==void 0&&e.code!==0)throw er(e.code,e.message,n);if(e.data===void 0)throw new a("backend.internal",`Broker ${n} returned no data envelope`,{envelope:e});return e.data}function er(e,n,t){let i=n??`Broker ${t} returned code ${e}`;switch(e){case ye.CLI_OP_NOT_FOUND:return new a("not_found",i,{broker_code:e});case ye.CLI_OP_EXPIRED:return new a("wallet.bridge_timeout",i,{broker_code:e});case ye.CLI_OP_UNAUTHORIZED:return new a("auth.permission_denied",i,{broker_code:e});case ye.CLI_OP_UNKNOWN_TYPE:return new a("input.invalid",i,{broker_code:e});case ye.CLI_OP_TOKEN_CONSUMED:return new a("input.invalid",i,{broker_code:e});default:return new a("backend.internal",i,{broker_code:e})}}var tr=require("child_process");async function ir(e,n={}){if(!hn(e))throw new a("input.invalid",`Refusing to launch browser for untrusted origin: ${R(e)}`);let t=n._env??process.env,i=n._platform??process.platform,r=t.BROWSER?.trim();if(r&&r.toLowerCase()==="none")throw new a("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(i==="linux"&&!t.DISPLAY&&!r)throw new a("wallet.requires_browser_auth","No DISPLAY available. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");if(n._execOverride){await n._execOverride(e);return}let o=ra(i,r);await oa(o.command,[...o.args,e])}function ra(e,n){return n&&n.length>0?{command:n,args:[]}:e==="darwin"?{command:"open",args:[]}:e==="win32"?{command:"rundll32",args:["url.dll,FileProtocolHandler"]}:{command:"xdg-open",args:[]}}function oa(e,n){return new Promise((t,i)=>{let r;try{r=(0,tr.spawn)(e,n,{detached:!0,stdio:"ignore"})}catch(s){i(nr(e,s));return}let o=!1;r.once("error",s=>{o||(o=!0,i(nr(e,s)))}),setImmediate(()=>{o||(o=!0,r.unref(),t())})})}function nr(e,n){return new a("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${n.message}. Re-run on a host with a graphical environment.`)}var rr=C(require("http"));var sa=9e4,aa=16*1024;function or(e){let n=e.timeoutMs??sa;return new Promise((t,i)=>{let r=!1,o=!1,s=null,l,d,c=new Promise((f,m)=>{l=f,d=m}),p=rr.createServer((f,m)=>{la(f,m,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>r,tryConsume:()=>r?!1:(r=!0,!0),onSuccess:y=>{s&&clearTimeout(s),l(y),p.close()}})});p.on("error",f=>{let m=new a("transport.network",`Loopback listener error: ${f.message}`);o?d(m):i(m),s&&clearTimeout(s)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),i(new a("transport.network","Failed to read loopback listener port"));return}s=setTimeout(()=>{d(new a("wallet.bridge_timeout",`Bridge timed out after ${n}ms waiting for browser callback.`)),p.close()},n),s.unref?.(),o=!0,t({port:f.port,awaitResult:c,close:()=>{s&&clearTimeout(s),p.close()}})})})}function la(e,n,t){let i=e.headers.origin??"";if(e.method==="OPTIONS"){if(i===t.expectedOrigin){let l={"Access-Control-Allow-Origin":t.expectedOrigin,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"content-type","Access-Control-Max-Age":"60"};e.headers["access-control-request-private-network"]==="true"&&(l["Access-Control-Allow-Private-Network"]="true"),n.writeHead(204,l)}else n.writeHead(403);n.end();return}if(e.method!=="POST"||e.url!=="/result"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"not_found"}));return}if(t.isConsumed()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}if(i!==t.expectedOrigin){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"origin_mismatch"}));return}let r=0,o=[],s=!1;e.on("data",l=>{if(!s){if(r+=l.length,r>aa){s=!0,n.writeHead(413,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"payload_too_large"}));return}o.push(l)}}),e.on("end",()=>{if(s)return;let l=Buffer.concat(o).toString("utf-8"),d;try{d=JSON.parse(l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_json"}));return}if(!d||typeof d!="object"){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_body"}));return}let c=d,p=typeof c.state=="string"?c.state:"",f=typeof c.result_token=="string"?c.result_token:void 0,m=c.result_data!==void 0&&c.result_data!==null&&typeof c.result_data=="object"&&!Array.isArray(c.result_data)?c.result_data:void 0;if(!da(p,t.state)){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&m===void 0){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"missing_result"}));return}if(!t.tryConsume()){n.writeHead(410,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"already_consumed"}));return}n.writeHead(200,{"Content-Type":"application/json","Access-Control-Allow-Origin":t.expectedOrigin}),n.end(JSON.stringify({ok:!0})),t.onSuccess({result_token:f,result_data:m})}),e.on("error",()=>{s||(s=!0)})}function da(e,n){if(e.length!==n.length)return!1;let t=0;for(let i=0;i<e.length;i+=1)t|=e.charCodeAt(i)^n.charCodeAt(i);return t===0}function at(e){try{return JSON.parse(e),!0}catch{return!1}}function sr(){let e=process.stdin,n="",t=!1,i=()=>{},r=250,o=null,s=()=>{o&&(clearTimeout(o),o=null)},l=()=>{s(),o=setTimeout(()=>{t||(d(),i(n.trim()))},r),o.unref?.()},d=()=>{t=!0,s(),e.off("data",c),e.off("end",p),e.off("error",f),e.pause()},c=y=>{if(t)return;s(),n+=y.toString();let _=n.trim(),k=n.length-n.trimStart().length,L=n.indexOf(`
20
+ `,k),g=L===-1?"":n.slice(k,L).trim();if(_.startsWith("{")){if(at(_)){d(),i(_);return}if(L===-1){l();return}if(!at(g)&&!g.endsWith("}")){let h=n.slice(L+1),E=h.split(`
21
+ `).find(q=>q.trim()!=="")??"";if(g==="{"&&(!/\S/.test(h)||/^\s*"[^"]*"\s*:/.test(h)||/^\s*"[^"]*$/.test(E))){l();return}}d(),i(at(g)?g:n.slice(k).trim());return}if(L!==-1){d(),i(g);return}else!_&&n.includes(`
22
+ `)&&(d(),i(""))},p=()=>{if(t)return;let y=n.trim();if(!y){d();return}d(),i(y)},f=()=>{t||d()},m=new Promise(y=>{i=y});return e.resume(),e.on("data",c),e.on("end",p),e.on("error",f),{promise:m,cancel:()=>{t||d()}}}function ca(e){let n;return{promise:new Promise(i=>{if(e.aborted){i({source:"aborted"});return}n=()=>i({source:"aborted"}),e.addEventListener("abort",n,{once:!0})}),cleanup:()=>{n!==void 0&&e.removeEventListener("abort",n)}}}async function lr(e){let n=te(e.ctx),t=e.browserBase??e.ctx.apiBase,i=ha(t),r=e._openBrowser??ir,o=e._startListener??or,s=e.mode??"ack",l=e._readPaste!==void 0||process.stdin.isTTY===!0,d=(0,ar.randomBytes)(32).toString("hex"),c=await Zi(n,e.op,e.payload);w({type:"bridge_init",op_id:c.op_id,expires_at:c.expires_at});let p=c.expires_at-Math.floor(Date.now()/1e3),f=Number.isFinite(p)?Math.max(0,p):0,m=Math.min(Math.max(6e4,f*1e3),2147483647),y=e.timeoutMs!=null&&e.timeoutMs>0&&e.timeoutMs<=2147483647?e.timeoutMs:m;O.stderr.write(`Bridge op registered (op_id=${c.op_id}, op TTL ~${f}s, waiting up to ${Math.round(y/1e3)}s for confirmation).
23
+ `);let _=await o({state:d,expectedOrigin:i,timeoutMs:y}),k=_.awaitResult.then(b=>({source:"loopback",...b}),b=>({source:"listener_error",error:b})),L=Date.now(),g=setInterval(()=>{let b=Math.floor((Date.now()-L)/1e3);O.stderr.write(`Still waiting for confirmation\u2026 (${b}s elapsed)
24
+ `)},15e3);g.unref?.();let h,E=e.signal===void 0?void 0:ca(e.signal);try{let b=ma(t,{op_id:c.op_id,port:_.port,state:d});w({type:"bridge_browser_open",url:b});let q=s==="ack"?"confirmation token":"result";if(O.stderr.write(l?e.autoOpen===!1?`
25
+ Confirm this in your browser. Open the URL below on any device where
26
+ you're signed in to AllScale (local auto-open is disabled):
27
+
28
+ ${b}
29
+
30
+ `:`
31
+ Confirm this in your browser. The URL is below \u2014 it auto-opens if a
32
+ browser is available on this machine; otherwise open it on any device
33
+ where you're signed in to AllScale:
34
+
35
+ ${b}
36
+
37
+ `:`
38
+ Confirm this in a browser on this machine. The callback must reach the
39
+ local listener; non-interactive stdin cannot accept a result pasted
40
+ back from another device:
41
+
42
+ ${b}
43
+
44
+ `),e.autoOpen===!1)O.stderr.write(`(browser auto-open skipped \u2014 use the link above)
45
+ `);else try{await r(b),O.stderr.write(`(opened in your default browser)
46
+ `)}catch{O.stderr.write(`(no local browser to open \u2014 use the link above)
47
+ `)}l?O.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
48
+ reach this machine (e.g. you opened the link elsewhere over SSH), copy
49
+ the ${q} the page shows, paste it here, and press Enter:
50
+
51
+ `):O.stderr.write(`stdin is non-interactive; waiting for the browser callback.
52
+
53
+ `),l&&(h=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:sr());let xe=[k];h!==void 0&&xe.push(h.promise.then(B=>({source:"paste",line:B}))),E!==void 0&&xe.push(E.promise);let $=await Promise.race(xe);if($.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if($.source==="listener_error")throw ua($.error);if($.source==="loopback")return O.stderr.write(`Browser returned result; processing\u2026
54
+ `),await pa(n,s,$);let U=$.line.trim();if(!U)throw new a("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(s==="ack"&&U.startsWith("{"))throw new a("wallet.bridge_invalid_response","Pasted value looks like JSON, not a confirmation token. Copy the single-line token the /cli page shows, not the result JSON.");if(s==="ack"&&/\s/.test(U))throw new a("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return O.stderr.write(`Received pasted ${q}; processing\u2026
55
+ `),await fa(n,s,U)}finally{clearInterval(g),E?.cleanup(),h?.cancel(),_.close()}}function ua(e){return e instanceof a&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_invalid_response")?e:new a("wallet.bridge_invalid_response","The loopback listener failed after the browser confirmation flow was opened. The operation may still complete; inspect its result before retrying.")}async function pa(e,n,t){if(n==="ack"){if(!t.result_token)throw new a("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");w({type:"bridge_result_received",source:"loopback"});let i=await st(e,t.result_token);return w({type:"bridge_verified",op_id:i.op_id,source:"loopback"}),O.stderr.write(`Verified by broker.
56
+ `),{ack:i,result_data:t.result_data}}if(!t.result_data)throw new a("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return w({type:"bridge_result_received",source:"loopback"}),w({type:"bridge_data_received",source:"loopback"}),O.stderr.write(`Result received from browser.
57
+ `),{result_data:t.result_data}}async function fa(e,n,t){if(n==="ack"){w({type:"bridge_result_received",source:"paste"});let r=await st(e,t);return w({type:"bridge_verified",op_id:r.op_id,source:"paste"}),O.stderr.write(`Verified by broker.
58
+ `),{ack:r}}let i;try{i=ga(t)}catch(r){throw r instanceof a&&r.code==="input.invalid"?new a("wallet.bridge_invalid_response",r.message):r}return w({type:"bridge_result_received",source:"paste"}),w({type:"bridge_data_received",source:"paste"}),O.stderr.write(`Result accepted.
59
+ `),{result_data:i}}function ma(e,n){let t=new URL("/cli",dr(e));return t.searchParams.set("op_id",n.op_id),t.searchParams.set("port",String(n.port)),t.searchParams.set("state",n.state),t.toString()}var ya=/^0x[0-9a-fA-F]{64}$/;function ga(e){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}if(ya.test(e))return{tx_hash:e};throw new a("input.invalid",`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function ha(e){return dr(e).origin}function dr(e){if(!ie(e))throw new a("input.invalid",`Refusing browser base ${R(e)}: bridge state and operation identifiers may only be sent to an exact trusted AllScale origin (${Be.join(", ")}) or an explicit loopback development origin. It must not contain embedded URL userinfo.`);return new URL(e)}var an=/^0x[0-9a-fA-F]{64}$/,_a=["wallet.bridge_timeout","wallet.bridge_invalid_response","wallet.headless_sign_failed"];function cr(e){return typeof e=="string"&&_a.includes(e)}var lt=require("process");var ge="ALLSCALE_OTP";function pr(e,n){if(typeof e=="string"&&e.trim().length>0||n)return!0;let t=process.env[ge];return!!(typeof t=="string"&&t.trim().length>0||process.stdin.isTTY)}async function fr(e,n){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(n){let i=process.env[ge];return typeof i=="string"&&i.trim().length>0&&lt.stderr.write(`warning: --otp-stdin is set, so ${ge} is ignored (stdin takes precedence).
60
+ `),ur()}let t=process.env[ge];if(typeof t=="string"&&t.trim().length>0)return t.trim();if(process.stdin.isTTY)return lt.stderr.write("OTP code: "),ur()}var ka=1024;async function ur(){let e="";try{for await(let n of process.stdin){e+=n;let t=e.indexOf(`
61
+ `);if(t!==-1)return e.slice(0,t).trim();if(Buffer.byteLength(e,"utf-8")>=ka)throw new a("input.invalid","OTP input exceeded the expected length (1 KB) before a newline; check the --otp-stdin pipe.")}}catch(n){throw n instanceof a?n:new a("input.invalid",`Failed to read OTP from stdin: ${n instanceof Error?n.message:String(n)}`)}return e.trim()}var Ar=require("crypto"),br=require("@turnkey/crypto"),un=require("@turnkey/api-key-stamper"),Lr=require("@turnkey/http");var j=C(require("fs")),mr=C(require("path")),yr=require("crypto");var wa="device_id";function ln(){let e=null,n=null;try{e=Ae(),n=mr.join(e,wa)}catch{}try{if(n){let i=j.readFileSync(n,"utf-8");if(i.length>70)throw new Error("oversized device_id");let r=i.split(`
62
+ `)[0].trim();if(r&&/^cli_[0-9a-f]{32}$/.test(r))return r}}catch{}let t=`cli_${(0,yr.randomBytes)(16).toString("hex")}`;try{if(!e||!n)throw new Error("persistence unavailable");j.mkdirSync(e,{recursive:!0,mode:448}),j.writeFileSync(n,`${t}
63
+ `,{mode:384});try{j.chmodSync(n,384)}catch{}}catch{}return t}var hr=require("crypto");var gr=128;function _r(e){if(e===void 0)return;let n=e.trim();if(!n||n.length>gr)throw new a("input.invalid",`--idempotency-key must contain 1-${gr} characters after trimming.`);return n}function kr(e,n){return`cli-invoice-pay-${(0,hr.createHash)("sha256").update("allscale-cli:invoice-pay:v1\0","utf8").update(e,"utf8").update("\0","utf8").update(n,"utf8").digest("hex")}`}var wr=he;function Ta(e){let n="";try{n=new URL(e).host}catch{}let t=wr[n];if(!t)throw new a("wallet.headless_config_missing",`Headless signing has no Turnkey config for '${n||"(unparseable URL)"}'. Supported hosts: ${Object.keys(wr).join(", ")}. Upgrade the CLI or contact support.`);if(!t.apiBaseUrl.startsWith("https:")||!t.authProxyUrl.startsWith("https:"))throw new a("wallet.headless_config_missing",`Headless Turnkey config for '${n}' has a non-HTTPS URL \u2014 refusing to send credentials.`);return t}var Sa=1,Er=4,Aa="CLIENT_SIGNATURE_SCHEME_API_P256",ba="900",ut=3e4,La=9e4,Tr=12e4,dn=256*1024;async function cn(e,n,t,i){if(!t.startsWith("/")||t.startsWith("//"))throw new a("backend.internal",`secureFetch: path must be root-relative with a single leading '/' (got '${t.split("?")[0]}')`);let r=new URL(t,e).toString(),o=t.split("?")[0],s=i.body===void 0?"":ve(i.body),l=me(s,e),d=[{name:Q,value:i.accessToken},...(i.extraCookies??[]).map(m=>({name:m.name,value:m.value}))],c;try{c=await fetch(r,{method:n,headers:{Accept:"application/json",...i.body!==void 0?{"Content-Type":"application/json"}:{},Authorization:en,Cookie:Ie(d),...l},body:i.body===void 0?void 0:s,redirect:"manual",signal:AbortSignal.timeout(i.timeoutMs??ut)})}catch(m){throw new a("transport.network",`Network error contacting AllScale API (${o}): ${m instanceof Error?m.message:String(m)}`)}let p=await Nr(c,o),f=null;if(p)try{f=JSON.parse(p)}catch{f=null}return{status:c.status,json:f,setCookies:Qe(c.headers)}}async function Nr(e,n){let t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>dn)throw new a("backend.internal",`Response body from ${n} declares ${t} bytes (over the ${dn} cap); refusing to read.`);if(!e.body)return"";let i=[],r=0;try{for await(let o of e.body){if(r+=o.byteLength,r>dn)throw new a("backend.internal",`Response body from ${n} is too large (over the ${dn}-byte cap); refusing to parse.`);i.push(Buffer.from(o))}}catch(o){if(o instanceof a)throw o}return Buffer.concat(i).toString("utf-8")}async function dt(e,n,t,i){if(!n.startsWith("/")||n.startsWith("//"))throw new a("backend.internal",`authProxyPost: path must be root-relative with a single leading '/' (got '${n.split("?")[0]}')`);let r;try{r=await fetch(new URL(n,e.authProxyUrl).toString(),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Auth-Proxy-Config-ID":e.authProxyConfigId},body:JSON.stringify(t),redirect:"manual",signal:AbortSignal.timeout(ut)})}catch(l){throw new a("transport.network",`Network error contacting Turnkey auth proxy (${i}): ${l instanceof Error?l.message:String(l)}`)}let o=await Nr(r,`Turnkey ${i}`),s={};if(o)try{let l=JSON.parse(o);s=l&&typeof l=="object"&&!Array.isArray(l)?l:{}}catch{s={}}if(r.status<200||r.status>=300){let l=r.status===401&&i==="otp_verify"?"Invalid or expired OTP code \u2014 re-request the code and try again.":r.status===400&&i==="otp_verify"?"Malformed OTP code \u2014 check the code format and try again.":r.status===400&&i==="otp_init"?"Turnkey rejected the account email for OTP delivery \u2014 the account may not be set up for email OTP; contact support.":`Turnkey ${i} failed: HTTP ${r.status}`,d=r.status===429?"rate_limited":r.status>=500?"backend.internal":i==="otp_verify"&&(r.status===400||r.status===401)?"input.invalid":"backend.internal";throw new a(d,l,{status:r.status,where:i})}return s}function Ea(e){try{let n=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf-8"));return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}function ct(e){return e===401?"auth.token_expired":e===429?"rate_limited":"backend.internal"}function Sr(e){let n=new Map;for(let t of e)t.name!==Q&&n.set(t.name,t);return[...n.values()]}async function Na(e){if(F(e.apiBase),Y(e.apiBase),e.token)return e.token;let t=await fe({insecureStorage:e.insecureStorage}).get(e.profile);if((t?.access_token||t?.agent_key)&&be(e.apiBase,t.api_base),t?.agent_key)throw new a("auth.permission_denied","Headless signing requires the user token from a legacy JWT session; agent keys do not contain it. The CLI no longer issues cookie sessions \u2014 use the browser-bridge flow instead (omit --headless).");if(!t?.access_token)throw pe({profile:e.profile,profileExplicit:e.profileExplicit,flow:"headless"});return t.access_token}async function Ca(e,n){let t=Ze(n).user_id,i=typeof t=="string"?t:"";if(!i)throw new a("auth.no_token","Access token has no user_id; re-login.");let o=await cn(e.apiBase,"POST","/api/secure/graphql",{accessToken:n,body:{query:"query($id:String!){business(id_str:$id){email turnkey{auth_type turnkey_sub_org_id turnkey_session_user_id}}}",variables:{id:i}}});if(o.status!==200)throw ne(o.status,o.json),new a(ct(o.status),`Failed to load account turnkey info (HTTP ${o.status}).`,{http_status:o.status});if(o.json?.errors?.length){let l=o.json.errors.some(d=>/unauth|forbidden|expired|denied|not.?allowed/i.test(d?.message??""));throw new a(l?"auth.token_expired":"backend.internal",l?`Account info query was rejected (authorization) \u2014 the access token may be stale. ${De()}`:"Account info query returned GraphQL errors.",{http_status:o.status,graphql_error_count:o.json.errors.length})}if(!o.json?.data?.business)throw new a("backend.internal",`Account info query returned no business data \u2014 the account may not exist or the access token may be stale. ${De()}`,{http_status:o.status});let s=o.json.data.business.turnkey;return{businessId:i,email:o.json.data.business.email??"",authType:s?.auth_type??0,subOrgId:s?.turnkey_sub_org_id??"",sessionUserId:s?.turnkey_session_user_id??""}}function Oa(e){return(e&Sa)!==0&&(e&Er)===0}async function Cr(e,n){let{ctx:t}=e;F(t.apiBase),Y(t.apiBase);let i=Ta(t.apiBase),r=Vt(t.apiBase);if(r!==void 0&&process.stderr.write(r),(e.otp?.trim()||process.env[ge]?.trim())&&!e.otpId?.trim()&&!e.otpStdin)throw new a("input.invalid","--otp / ALLSCALE_OTP without --otp-id always fails for headless signing: the CLI emails a fresh OTP at run time that a pre-set value can't match. Use --otp-stdin (pipe the just-emailed code), add --otp-id, or unset ALLSCALE_OTP to use the interactive prompt.");let s=_r(typeof e.payload.idempotency_key=="string"?e.payload.idempotency_key:void 0);if(!s)throw new a("input.invalid","Headless signing requires a caller-stable idempotency key.");let l=await Na(t),d=await Ca(t,l);if(!Oa(d.authType))throw new a("wallet.headless_not_supported",(d.authType&Er)!==0?"This account has a passkey enabled, which can't sign headless. Omit --headless to use the browser flow.":"This account isn't eligible for headless signing (it needs Turnkey email-OTP enabled and no passkey). Omit --headless to use the browser flow.");if(!d.email)throw new a("backend.internal","Account has no email for OTP delivery.");if(!d.subOrgId||!d.sessionUserId)throw new a("wallet.headless_setup_required","Account has no Turnkey session user yet \u2014 sign in once on the web app to provision it, then retry --headless.");let c=ln(),p=await cn(t.apiBase,"GET",`/api/v1/secure/turnkey/sessions/current/status?device_id_str=${encodeURIComponent(c)}`,{accessToken:l});if(p.status!==200)throw ne(p.status,p.json),new a(ct(p.status),`Failed to get Turnkey session status (HTTP ${p.status}).`,{http_status:p.status});if(!p.json?.data?.public_key)throw new a("backend.internal","Turnkey session status returned no session public key \u2014 the backend may need to re-provision it; contact support.",{http_status:p.status});let f=p.json.data.public_key,m=Sr(p.setCookies);if(m.length===0)throw new a("backend.internal","get_session_status returned no session cookie (only the access-token cookie, or none at all); cannot continue headless.");let y=(0,Ar.randomUUID)();await Ra({env:i,runId:y,subOrgId:d.subOrgId,sessionUserId:d.sessionUserId,email:d.email,sessionPublicKey:f,otp:e.otp,otpStdin:!!e.otpStdin,otpId:e.otpId,resolveOtp:n});let _=await cn(t.apiBase,"POST","/api/v1/secure/turnkey/sessions/current:activate",{accessToken:l,body:{device_id_str:c},extraCookies:m});if(_.status!==200)throw ne(_.status,_.json),new a(ct(_.status),`Failed to activate Turnkey session (HTTP ${_.status}).`,{http_status:_.status});if(typeof _.json?.data?.expires_at_ts!="number")throw new a("backend.internal","Turnkey session did not activate (empty, unreadable, or no-expiry response); not attempting to sign.",{http_status:_.status});let k=Sr(_.setCookies),L=k.length?k:m,g=s,h;try{h=await cn(t.apiBase,"POST","/api/v1/secure/web3/transfers:gasless-evm-token",{accessToken:l,body:{chain:e.payload.chain,to_address:e.payload.to_address,amount:e.payload.amount,stable_coin:e.payload.stable_coin,device_id_str:c,idempotency_key:g},extraCookies:L,timeoutMs:La})}catch{throw new a("wallet.headless_sign_failed","Headless signed transfer network call failed; the transaction may have been broadcast \u2014 verify on-chain before retrying.",{idempotency_key:g})}let E=h.json?.data?.tx_hash;if(h.status!==200||typeof E!="string"||!an.test(E))throw new a("wallet.headless_sign_failed",`Headless signed transfer failed (HTTP ${h.status}). The transaction may have been broadcast \u2014 verify on-chain before retrying.`,{idempotency_key:g,...h.status===401?{recovery_hint:`HTTP 401 usually means the AllScale access token expired and the transfer was rejected before broadcast \u2014 if nothing shows on-chain, re-login and retry. ${De()}`}:{}});return{result_data:{tx_hash:E},idempotency_key:g}}async function Ra(e){let{env:n}=e,t,i;try{t=(0,br.generateP256KeyPair)(),i=new un.ApiKeyStamper({apiPublicKey:t.publicKey,apiPrivateKey:t.privateKey})}catch{throw new a("backend.internal","Failed to generate the ephemeral Turnkey login key.")}let r=e.otpId?.trim(),o=r||(await dt(n,"/v1/otp_init",{otpType:"OTP_TYPE_EMAIL",contact:e.email},"otp_init")).otpId;if(!o)throw new a("backend.internal","Turnkey otp_init returned no otpId.");let s;if(e.otpStdin){let g,h=e.resolveOtp(e.otp,e.otpStdin);try{s=await Promise.race([h,new Promise((E,b)=>{g=setTimeout(()=>b(new a("input.invalid","Timed out waiting for the OTP on stdin (--otp-stdin). Pipe the emailed code within "+Math.round(Tr/1e3)+"s.")),Tr)})])}finally{g&&clearTimeout(g),h.catch(()=>{})}}else s=await e.resolveOtp(e.otp,e.otpStdin);if(!s)throw new a("input.invalid","No OTP code provided. Pass --otp, set ALLSCALE_OTP, or pipe via --otp-stdin.");let l=await dt(n,"/v1/otp_verify",{otpId:o,otpCode:s,publicKey:t.publicKey},"otp_verify").catch(g=>{let h=g instanceof a?g.details?.status:void 0;throw g instanceof a&&g.code==="input.invalid"&&r&&h===401?new a(g.code,g.message+" If you passed --otp-id, the prior otpId may itself have expired; re-run WITHOUT --otp-id to start a fresh OTP flow.",g.details):g});if(!l.verificationToken)throw new a("backend.internal","Turnkey otp_verify returned no verificationToken.");let d=Ea(l.verificationToken);if(typeof d.id!="string"||d.id.length===0)throw new a("backend.internal","Turnkey verification token has no id.");let c=JSON.stringify({login:{publicKey:t.publicKey},tokenId:d.id,type:"USAGE_TYPE_LOGIN"}),p;try{p=await i.sign(c,un.SignatureFormat.Raw)}catch{throw new a("backend.internal","Failed to stamp the Turnkey login request.")}let f={message:c,publicKey:t.publicKey,scheme:Aa,signature:p};await dt(n,"/v1/otp_login",{verificationToken:l.verificationToken,publicKey:t.publicKey,clientSignature:f,organizationId:e.subOrgId},"otp_login");let m=new Lr.TurnkeyClient({baseUrl:n.apiBaseUrl},i),y,_,k=m.createApiKeys({type:"ACTIVITY_TYPE_CREATE_API_KEYS_V2",timestampMs:String(Date.now()),organizationId:e.subOrgId,parameters:{apiKeys:[{apiKeyName:`cli-headless-${e.runId}`,publicKey:e.sessionPublicKey,curveType:"API_KEY_CURVE_P256",expirationSeconds:ba}],userId:e.sessionUserId}});try{y=await Promise.race([k,new Promise((g,h)=>{_=setTimeout(()=>h(new a("transport.network","Network error contacting Turnkey API (createApiKeys): timed out. A key registration may still be in flight \u2014 wait \u2265 30s before retrying.",{activity:"createApiKeys",hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"})),ut)})])}catch(g){if(g instanceof a)throw g;let h=g instanceof TypeError||g instanceof DOMException&&g.name==="AbortError"||g instanceof Error&&(g.name==="FetchError"||g.constructor.name==="FetchError");throw new a(h?"transport.network":"backend.internal",h?"Network error contacting Turnkey API (createApiKeys). A key registration may still be in flight \u2014 wait \u2265 30s before retrying.":"Turnkey API rejected the createApiKeys request.",{activity:"createApiKeys",...h?{hint:"a key registration may still be in flight \u2014 wait \u2265 30s before retrying"}:{}})}finally{_&&clearTimeout(_),k.catch(()=>{})}if(!y.activity?.result?.createApiKeysResult?.apiKeyIds?.[0])throw new a("backend.internal","Turnkey createApiKeys returned no apiKeyId.",{activity_status:y.activity?.status})}function Rr(e){return te(e,{pathHint:"/api/v1/public/businesses/payments"})}var Or=3e4;function Ia(e){if(typeof e=="string"&&e.length>0)return e;if(Array.isArray(e)){let n=e.filter(t=>t!=null&&t!==!1&&t!==0).map(t=>typeof t=="string"?t:JSON.stringify(t)).filter(t=>typeof t=="string"&&t.length>0&&t!=="null"&&t!=="{}"&&t!=="[]");return n.length>0?n.join("; "):void 0}if(e!==null&&typeof e=="object"){let n=JSON.stringify(e);if(n!=="{}")return n}}function va(e,n){if(e==null)return;let t=typeof e.code=="number"?e.code:0,i=Ia(e.errors),r=(()=>{let p=e.error;if(p==null||p===!1||p===0||p==="")return;if(typeof p=="string")return p;if(typeof p!="object")return"backend flagged an unspecified error";let f=JSON.stringify(p);return f&&f!=="{}"&&f!=="[]"&&f!=="null"?f:void 0})(),o=i??r??(typeof e.message=="string"&&e.message.length>0?e.message:void 0),s=i??r,l=typeof e.code!="number"&&e.code!=="0"&&!!e.code,c=(e.code==null||e.code===""||e.code==="0"||e.code===0||e.code===!1)&&!!s;if(t!==0||l||c){let p=o??`${n} returned code ${String(e.code??t)}`;throw new a("backend.internal",p,{broker_code:e.code})}return e.data}async function pt(e,n,t,i,r){let o=r??te(e,{pathHint:n}),s=new AbortController,l=!1,d=setTimeout(()=>{l=!0,s.abort()},Or);try{let c=await o.request({method:"POST",path:n,body:t,signal:s.signal});return va(c,i)}catch(c){throw l&&c instanceof a&&c.code==="transport.network"?new a("backend.internal",`${i} timed out after ${Or/1e3}s with no response from the backend.`):c}finally{clearTimeout(d)}}function Ir(e){let n=e.sender_email?.trim();return{sender_fingerprint:e.sender_fingerprint,...n?{sender_email:n}:{}}}async function vr(e,n,t,i){let r=await pt(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents`,Ir(t),"ensurePayIntent",i);if(!r)throw new a("backend.internal","ensurePayIntent: server returned success but no payment data.");if(!r.pay_intent)throw new a("input.invalid","This invoice has no crypto pay-intent \u2014 it may already be paid/processing, overdue, or a fiat-currency invoice that can't be paid from the CLI.",{status:r.status});let o=typeof r.pay_intent.id=="string"?r.pay_intent.id.trim():"";if(!o)throw new a("backend.internal","ensurePayIntent: server returned a pay_intent with no usable id \u2014 unexpected server response.");return{...r.pay_intent,id:o}}async function Pr(e,n,t){await pt(e,"/api/v1/public/businesses/transactions",{payment_id:n.payment_id,tx_hash:n.tx_hash,tx_block_chain:n.tx_block_chain,dest_stable_coin:n.dest_stable_coin,tx_from:n.tx_from,sender_fingerprint:n.sender_fingerprint,is_allscale_pay:!0},"reportTransaction",t)}async function xr(e,n,t,i,r){await pt(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents/${encodeURIComponent(t)}:confirm`,Ir(i),"confirmPayIntent",r)}function Pa(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the invoice status BEFORE retrying: if the transfer already shows there, do NOT run this command again (contact support with the invoice id) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${Sn}\` to refresh the session, then retry.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function xa(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the invoice status BEFORE retrying \u2014 if a transfer shows there, do NOT run this command again (give the ids below to support).`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function Ua(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new a("wallet.headless_sign_failed",`${e.message.replace(/\.?$/,".")} First check ${n.payment_id?"the invoice status":"the destination address on-chain"} \u2014 if the transfer shows there, do NOT run this command again (give the ids below to support).`,{...n,...t.recovery_hint!==void 0?{recovery_hint:t.recovery_hint}:{},...t.idempotency_key!==void 0?{idempotency_key:t.idempotency_key}:{}})}function Ur(e,n){return!(e instanceof a)||!cr(e.code)?null:e.code==="wallet.bridge_timeout"?Pa(e,n):e.code==="wallet.headless_sign_failed"?Ua(e,n):xa(e,n)}function Br(e,n){let t=e instanceof a&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:null;return{...t?{broker_code:t.broker_code}:{},...n}}function ft(e,n,t,i){let r=t instanceof Error?t.message:String(t),o=e==="record"?`Your payment was sent on-chain (tx ${n}) but the CLI could not record the transaction with AllScale: ${r}. The transfer is final \u2014 give this transaction hash to support so they can reconcile the invoice; do NOT pay again.`:`Your payment was sent on-chain (tx ${n}) AND recorded, but confirming it failed: ${r}. The transfer is final and the transaction is on file \u2014 the invoice's status flip may be delayed; give this hash to support if it doesn't clear, but do NOT pay again.`;return new a("backend.internal",o,i)}function Ba(e){if(e==null)return null;let n=typeof e=="string"?Number(e):e;return Number.isFinite(n)?n===0?null:n===1?1:n===2?2:"unsupported":"unsupported"}function Fr(e){let{paymentType:n,requestedCoin:t,requestedSlug:i,paymentId:r}=e,o=typeof n=="string"&&n.trim()==="";if(n!=null&&!o&&Number(n)===0)throw new a("input.invalid",`Invoice '${r}' is a fiat currency invoice (payment_type 0) and cannot be paid with crypto from the CLI.`);let s=Ba(n);if(s==="unsupported")throw new a("input.invalid",`Invoice '${r}' must be paid in a stablecoin the CLI can't send (payment_type ${n}; only USDT and USDC are supported) \u2014 pay it from the web app.`);if(s!==null&&t!==null&&t!==s)throw new a("input.invalid",`This invoice must be paid in ${Le(s)}, but --stable-coin ${i} was requested. Re-run without --stable-coin to use the invoice's coin.`);if(s===null&&t===null)throw new a("input.invalid","This invoice pins no stablecoin (no payment_type). Pass --stable-coin USDT or --stable-coin USDC to choose which token to send.");return{stableCoin:s??t,autoSelected:s!==null&&t===null}}function Da(e){return si(e)}function yt(e,n){let t=e.filter(r=>r.chain===n);if(t.length!==1)return null;let i=t[0].address;return!i||!oi(i)||Da(i)?null:i}function Mr(e,n){let t=[...new Set(n.map(i=>i.chain))];if(t.length===0)throw new a("input.invalid","This invoice exposes no receiving wallet to pay to.");if(e){let i=ii(e);if(i===null)throw new a("input.invalid",`--chain '${e}' is not supported.`);if(!t.includes(i))throw new a("input.invalid",`The invoice has no receiving wallet on ${D(i)}. Available: ${t.map(r=>D(r)).join(", ")}.`);return i}if(t.length===1)return t[0];throw new a("input.invalid",`This invoice can be paid on multiple chains (${t.map(i=>D(i)).join(", ")}). Pass --chain to choose one.`)}var mt=128,pn=String(Number.MAX_SAFE_INTEGER),$a=/^(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function Fa(e){if(e.length===0)return{kind:"invalid"};if(e.length>mt)return{kind:"normalization_limit"};let n=$a.exec(e);if(!n)return{kind:"invalid"};let t=n[1],i=n[2]??"",r=t+i,o=r.search(/[1-9]/);if(o===-1)return{kind:"invalid"};let s=BigInt(n[3]??"0"),l=r.slice(o),d=BigInt(t.length)+s-BigInt(o),c=BigInt(l.length);if((d<=0n?2n-d+c:d>=c?d:c+1n)>BigInt(mt))return{kind:"normalization_limit"};if(d<=0n)return{kind:"ok",amount:`0.${"0".repeat(Number(-d))}${l}`};if(d>=c)return{kind:"ok",amount:`${l}${"0".repeat(Number(d-c))}`};let f=Number(d);return{kind:"ok",amount:`${l.slice(0,f)}.${l.slice(f)}`}}function Ma(e){let[n,t=""]=e.split(".");return n.length!==pn.length?n.length>pn.length:n!==pn?n>pn:/[1-9]/.test(t)}function gt(e){let n=e==null?"":typeof e=="number"?String(e):e,t=Fa(n);if(t.kind==="normalization_limit")throw new a("input.invalid",`Invoice amount ${JSON.stringify(e)} cannot safely normalize within the ${mt}-character amount limit.`);if(t.kind==="invalid")throw new a("input.invalid",`The invoice has no positive payable amount (got ${JSON.stringify(e)}).`);if(Ma(t.amount))throw new a("input.invalid",`Invoice amount ${JSON.stringify(e)} is too large to represent exactly.`);return t.amount}function Kr(e){try{return gt(e)}catch(n){throw new a("backend.internal",`The pay-intent returned a non-positive or unverifiable settle amount (got ${JSON.stringify(e)}). Refusing to pay.`,{intent_amount:e,reason:n instanceof Error?n.message:String(n)})}}var Dr=6,Ka=1000000n,Ga=10098n;function $r(e){if(e.length===0||e.length>128||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let[n,t=""]=e.split(".");return t.length>Dr?null:BigInt(n)*Ka+BigInt(t.padEnd(Dr,"0"))}function Gr(e,n){let t=$r(e),i=$r(n),r=t===null||i===null?null:i-t;if(t===null||t<=0n||i===null||i<=0n||r===null||r<0n||r>Ga)throw new a("backend.internal",`Pay-intent amount (${n}) is outside the backend's expected settlement range for invoice amount (${e}). Refusing to open the bridge.`,{intent_amount:n,invoice_amount:e})}var Ha=18e4,fn=class e extends Ee{static description="Pay a received invoice from your AllScale wallet. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (confirmed in the browser at /cli), then reports and confirms the payment. Needs TWO scopes: `invoice:all` to create, report and confirm the pay intent, and `wallet:read_only` to look up the address you are paying FROM. Neither flow grants `invoice:all` for you: on `device-login` the Invoices toggle starts at Read, so tick its write tier on the approval screen; on `otp-login` pass BOTH --scopes invoice:all --scopes wallet:read_only, because naming any scope turns every unnamed category off.";static examples=["$ allscale invoice pay 65ab1234567890abcdef0123","$ allscale invoice pay 65ab... --chain bsc --stable-coin USDT"];static args={id:Hr.Args.string({description:"Invoice id_str (the backend Payment.id_str) to pay.",required:!0})};static flags={"business-id":x.Flags.string({description:"Your own business id. Optional and redundant \u2014 payment always comes from the wallet of the business you are signed in as. Supplying a different business id is rejected rather than silently paying from your own wallet; omit the flag unless a script needs to assert which business it is acting as."}),chain:x.Flags.string({description:"Chain to pay on. Optional when the invoice lists a single receiving wallet; required when it lists several.",options:[...ti]}),"stable-coin":x.Flags.string({description:"Stablecoin to pay with. Defaults to the invoice's own currency (from its payment_type); only needed to disambiguate an invoice that doesn't pin one. A value that conflicts with the invoice is rejected.",options:[...je]}),"browser-base":x.Flags.string({description:"Override the base URL of the /cli confirmation link (defaults to the session API base). (Browser-bridge only \u2014 not valid with --headless.)",exclusive:["headless"]}),"bridge-timeout":x.Flags.integer({description:"Override the confirmation deadline in milliseconds (default 180000). (Browser-bridge only \u2014 not valid with --headless.)",default:Ha,min:1e3,exclusive:["headless"]}),headless:x.Flags.boolean({description:`Pay without a browser via Turnkey email-OTP (accounts with email-OTP enabled and no passkey; passkey accounts must use the browser flow). Supply the OTP via --otp-stdin (recommended for automation) or interactively; --otp / ALLSCALE_OTP work ONLY combined with --otp-id. This removes the in-browser human confirmation, so use it only on a trusted machine.${Nt}`,default:!1}),otp:x.Flags.string({description:"Turnkey signing OTP code (with --headless). Only works combined with --otp-id (an externally-triggered flow): without --otp-id the CLI emails a FRESH code at run time, so any pre-set --otp / ALLSCALE_OTP value is stale and fails with 'Invalid or expired OTP code'. For automation prefer --otp-stdin (CLI emails; pipe the fresh code back). Passing --otp as a flag also exposes it in shell history AND the process list (ps / /proc/<pid>/cmdline).",exclusive:["otp-stdin"],dependsOn:["headless"]}),"otp-stdin":x.Flags.boolean({description:"Read the Turnkey signing OTP as one line from stdin (with --headless).",default:!1,dependsOn:["headless"]}),"otp-id":x.Flags.string({dependsOn:["headless"],description:"Skip the OTP-send step and reuse a prior Turnkey otpId (with --headless). The OTP code itself is still required via --otp / ALLSCALE_OTP / --otp-stdin."}),...Ee.baseFlags};async runCommand(){let{args:n,flags:t}=await this.parse(e),i=this.resolveContext(t);if(!t.headless&&(t.otp||t["otp-stdin"]||t["otp-id"]))throw new a("input.invalid","--otp / --otp-stdin / --otp-id require --headless.");if(t.otp?.trim()&&ht.stderr.write(`warning: --otp passes the code via argv (visible in shell history and the process list); prefer --otp-stdin.
64
+ `),await Ai(i,t["business-id"]),t.headless&&!pr(t.otp,t["otp-stdin"]))throw new a("input.invalid","Headless signing needs an OTP source: pass --otp, set ALLSCALE_OTP, use --otp-stdin, or run interactively.");let r=n.id.trim();if(!r)throw new a("input.invalid","Invoice id cannot be blank.");let o=t["stable-coin"],s=o?ri(o):null;if(o&&s===null)throw new a("input.invalid",`--stable-coin '${o}' is not supported (USDT or USDC).`);let l=await ot(i,"query","payment",{id_str:r},{selection:"id encrypted_id amount_coins payment_type wallets { chain address }"}),d=(l?.wallets??[]).filter(N=>!!N&&typeof N.chain=="number"&&N.chain in He&&typeof N.address=="string"&&N.address.length>0);if(d.length===0)throw new a("input.invalid",l==null?`Invoice '${r}' was not found. Check the id and try again.`:"This invoice exposes no receiving wallet the CLI can pay to \u2014 it may be a fiat invoice, a non-EVM invoice, or not yet payable.");let{stableCoin:c,autoSelected:p}=Fr({paymentType:l?.payment_type,requestedCoin:s,requestedSlug:o,paymentId:r});p&&ht.stderr.write(`Paying in ${Le(c)} (the invoice's currency).
65
+ `);let f=Mr(t.chain,d);if(d.filter(N=>N.chain===f).length>1)throw new a("input.invalid",`This invoice has multiple receiving addresses on ${D(f)} \u2014 it's ambiguous which to pay. Contact support to resolve the duplicate wallet entries.`);let m=yt(d,f);if(!m)throw new a("input.invalid",`The invoice has no valid receiving address on ${D(f)}.`);let y=gt(l?.amount_coins),_=typeof l?.encrypted_id=="string"?l.encrypted_id.trim():"";if(!_)throw new a("backend.internal","The invoice response did not include its public payment identifier; refusing to call the public payment endpoint with the internal id.");let k=await this.resolvePayerAddress(i,f);if(k.toLowerCase()===m.toLowerCase())throw new a("input.invalid","The invoice destination is your own wallet address; refusing a self-transfer.");let L=ln(),g=Rr(i),h=await vr(i,_,{sender_fingerprint:L},g),E=h.amount_coins!=null?Kr(h.amount_coins):y;h.amount_coins!=null&&Gr(y,E);let b=kr(r,h.id),q={chain:f,to_address:m,amount:E,stable_coin:c,idempotency_key:b},$=await(t.headless?Cr({ctx:i,payload:q,otp:t.otp,otpStdin:t["otp-stdin"],otpId:t["otp-id"]},fr):lr({ctx:i,op:"withdraw_token",mode:"data",payload:q,timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"]})).catch(N=>{throw Ur(N,{payment_id:r,pay_intent_id:h.id,tx_from:k,to_address:m,idempotency_key:b})??N}),U=$.result_data??{},B=typeof U.tx_hash=="string"&&an.test(U.tx_hash)?U.tx_hash:null;if(!B)throw new a(t.headless?"wallet.headless_sign_failed":"wallet.bridge_invalid_response",t.headless?"Headless signing returned no valid tx_hash \u2014 the transfer MAY have been broadcast but cannot be confirmed from the CLI. Check the invoice/payment status BEFORE retrying: if a transfer shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice.":"Browser returned no valid tx_hash \u2014 the transfer may have failed, but it cannot be confirmed from the CLI side. Check your wallet/the invoice status BEFORE retrying: if a transfer shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice.",{raw_tx_hash:typeof U.tx_hash=="string"?U.tx_hash.slice(0,66):null,payment_id:r,pay_intent_id:h.id,tx_from:k,to_address:m,idempotency_key:$.idempotency_key??b});let _t=N=>Br(N,{tx_hash:B,tx_from:k,payment_id:r,pay_intent_id:h.id,idempotency_key:b,explorer_url:$n(f,B)||null});try{await Pr(i,{payment_id:r,tx_hash:B,tx_block_chain:f,dest_stable_coin:c,tx_from:k,sender_fingerprint:L},g)}catch(N){throw ft("record",B,N,_t(N))}try{await xr(i,r,h.id,{sender_fingerprint:L},g)}catch(N){throw ft("confirm",B,N,_t(N))}return{payment_id:r,pay_intent_id:h.id,tx_hash:B,chain:f,chain_name:D(f),amount:E,stable_coin:c,stable_coin_name:Le(c),explorer_url:$n(f,B)||null,idempotency_key:b,status_optimistic:!0,status:"processing"}}async resolvePayerAddress(n,t){let r=(await ot(n,"query","business_wallets",{},{selection:"chain address"})??[]).filter(s=>!!s&&typeof s.chain=="number"&&s.chain in He&&typeof s.address=="string"&&s.address.length>0);if(r.filter(s=>s.chain===t).length>1)throw new a("input.invalid",`Your AllScale wallet has multiple addresses on ${D(t)} \u2014 can't auto-select which to pay from. Contact support.`);let o=yt(r,t);if(!o)throw new a("input.invalid",`Your AllScale wallet has no valid address on ${D(t)} to pay from.`);return o}};
66
+ //# sourceMappingURL=pay.js.map