@allscale/cli 0.1.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -41
- package/bin/dev.js +11 -1
- package/bin/run-oclif.js +216 -27
- package/bin/run.js +19 -1
- package/dist/commands/build-info.js +13 -13
- package/dist/commands/claim-link/claim.js +14 -14
- package/dist/commands/claim-link/create.js +40 -37
- package/dist/commands/claim-link/get.js +26 -15
- package/dist/commands/claim-link/list.js +15 -15
- package/dist/commands/claim-link/status.js +13 -13
- package/dist/commands/describe.js +13 -13
- package/dist/commands/device-login.js +23 -24
- package/dist/commands/invoice/get.js +15 -15
- package/dist/commands/invoice/list.js +16 -16
- package/dist/commands/invoice/pay.js +40 -41
- package/dist/commands/invoice/received.js +16 -16
- package/dist/commands/invoice/send.js +42 -34
- package/dist/commands/invoice/sent.js +15 -15
- package/dist/commands/invoice/update.js +17 -15
- package/dist/commands/logout.js +14 -14
- package/dist/commands/operations.js +13 -13
- package/dist/commands/otp-login.js +21 -20
- package/dist/commands/otp-send.js +13 -13
- package/dist/commands/payout/send.js +14 -14
- package/dist/commands/payout/status.js +15 -15
- package/dist/commands/scope.js +17 -16
- package/dist/commands/store/create.js +17 -17
- package/dist/commands/transaction/get.js +15 -15
- package/dist/commands/transaction/list.js +15 -15
- package/dist/commands/wallet/list.js +15 -15
- package/dist/commands/wallet/send.js +40 -43
- package/dist/commands/whoami.js +14 -14
- package/dist/hooks/version-suffix.js +1 -1
- package/dist/index.js +14 -14
- package/dist/lib/help.js +7 -2
- package/dist/lib/output/audit-lifecycle.js +7 -0
- package/oclif.manifest.json +123 -292
- package/package.json +4 -6
- package/dist/commands/claim-link/preview.js +0 -18
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).some(n=>
|
|
3
|
-
`)}var
|
|
4
|
-
`)}else In.stderr.write(n)}var
|
|
5
|
-
`);return}
|
|
6
|
-
`);return}
|
|
7
|
-
`)}catch(i){if(
|
|
8
|
-
`)}catch{}}}var
|
|
9
|
-
|
|
10
|
-
The CLI default is now ${Se} (production), but a saved profile wins over the default,
|
|
1
|
+
"use strict";var Hr=Object.create;var $e=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var qr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var Vr=(e,n)=>{for(var t in n)$e(e,t,{get:n[t],enumerable:!0})},Tt=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Jr(n))!Yr.call(e,r)&&r!==t&&$e(e,r,{get:()=>n[r],enumerable:!(i=Kr(n,r))||i.enumerable});return e};var C=(e,n,t)=>(t=e!=null?Hr(qr(e)):{},Tt(n||!e||!e.__esModule?$e(t,"default",{value:e,enumerable:!0}):t,e)),jr=e=>Tt($e({},"__esModule",{value:!0}),e);var zs={};Vr(zs,{default:()=>yn});module.exports=jr(zs);var Dr=require("process"),$r=require("@oclif/core");var J=require("@oclif/core");var At="public",wt="https://app.allscale.io";var Lt=["https://app.allscale.io"];var gn="Override the API base URL (public builds accept only https://app.allscale.io)";var _e="Only https://app.allscale.io is allowed, and URL userinfo is forbidden.";function bt(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 Et(e){return bt(e)!==null}function le(e){let n=bt(e);return n!==null&&Lt.includes(n.origin)}function _n(e){return le(e)}function Se(){return"".trim()||void 0}function ke(){return"public"}function z(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 Te(){{let e="[]".trim();if(e.length===0)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}return Sn()}function Sn(){let e=process.env.ALLSCALE_BUILD_PAIRS?.trim()??"";if(e.length>0)try{let i=JSON.parse(e);if(!Array.isArray(i))return[];let r=[];for(let o of i){if(typeof o!="object"||o===null)continue;let{base:a,key:c,keyId:l}=o;if(typeof a!="string"||a.trim().length===0||typeof c!="string"||c.trim().length===0)continue;let u=typeof l=="string"?l.trim():"";r.push({base:a.trim(),key:c,keyId:u.length>0?u:"cli-1"})}return r}catch{return[]}let n=process.env.ALLSCALE_SIGNING_KEY??"",t=process.env.ALLSCALE_BUILD_API_BASE?.trim()??"";if(n.trim().length>0&&t.length>0){let i=process.env.ALLSCALE_SIGNING_KEY_ID?.trim();return[{base:t,key:n,keyId:i&&i.length>0?i:"cli-1"}]}return[]}var wn="device-login",Wr=/^[A-Za-z0-9._-]{1,64}$/;function Ln(e){return Wr.test(e)?e:"<profile>"}function Ae(e){return"allscale otp-login --profile "+(e===void 0?"<profile>":Ln(e))+" --email <you@example.com> --scopes <scope> --otp-stdin"}function Fe(){return"`allscale device-login` (or `allscale otp-login` \u2014 requires `--email` and `--scopes` \u2014 for headless automation)"}function Ct(e){let n=Ln(e);return`No tokens stored for profile '${e}'. Run \`allscale device-login --profile ${n}\` (recommended), or use \`${Ae(e)}\` for headless automation.`}function Ot(e){return`Unknown profile '${e}' \u2014 no such profile is saved on this machine. Check the spelling first; to deliberately create '${e}', run \`allscale ${wn} --profile ${Ln(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_op_expired":3,"wallet.bridge_invalid_response":9,"wallet.transaction_reverted":12,"wallet.transaction_status_unknown":9,"raw.disabled":10,internal:1},Xr=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(Xr,"")}var Qr=64;function Tn(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>=Qr)return e;if(Array.isArray(e)){let a=[];n.set(e,a);for(let c of e)a.push(Tn(c,n,t+1));return a}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let o={};n.set(e,o);for(let[a,c]of Object.entries(e))Object.defineProperty(o,a,{value:Tn(c,n,t+1),writable:!0,enumerable:!0,configurable:!0});return o}var s=class extends Error{code;details;constructor(n,t,i){super(bn(t)),this.code=n,this.details=i&&Tn(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 Rt(e){if(e instanceof s)return e;if(e instanceof Error){if(no(e)){let n=io(e),t={};return e.name&&e.name!=="Error"&&(t.name=e.name),Object.keys(n).length>0&&(t.oclif=n),new s("input.invalid",e.message,Object.keys(t).length>0?t:void 0)}return new s("internal",e.message,{name:e.name})}return new s("internal","Unknown error",{value:String(e)})}var Zr=new Set(["CLIError","CLIParseError","RequiredArgsError","RequiredFlagError","UnexpectedArgsError","FlagInvalidOptionError","ArgInvalidOptionError","InvalidArgsSpecError"]),eo=[/^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 no(e){if(to(e))return!0;let n=e.name??"";return Zr.has(n)?n==="CLIError"?An(e,"parse")||Nt(e.message):!0:Nt(e.message)}function to(e){if(!An(e,"oclif"))return!1;let n=e.oclif;return typeof n=="object"&&n!==null&&n.exit===2&&An(e,"parse")}function Nt(e){return e?bn(e).split(`
|
|
2
|
+
`).some(n=>eo.some(t=>t.test(n.trim()))):!1}function An(e,n){return typeof e=="object"&&e!==null&&Object.prototype.hasOwnProperty.call(e,n)}function io(e){let n=e,t={};for(let i of["code","exitCode","suggestions","ref"])n[i]!==void 0&&(t[i]=n[i]);return t}function It(e){process.stdout.write(`${JSON.stringify({data:e},null,2)}
|
|
3
|
+
`)}var k=C(require("fs")),Je=C(require("path")),$t=C(require("crypto"));var ro="...<truncated>",oo=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g,ao=/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi,Rn=String.raw`(?:(?:Bearer|Basic)\s+)?(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s,;)}\]]+)`,En=String.raw`(?:proxy[_-]?)?authorization`,so=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${En}"|'${En}'|${En})\s*[:=]\s*)((?:Bearer|Basic)\s+)?(?!<redacted(?:-jwt)?>)${Rn}`,"gi"),lo=/\b(https?:\/\/)[^\s/?#]+@/gi,co=String.raw`(?:[A-Za-z0-9]+[_-])*`,uo=String.raw`(?:[A-Za-z0-9]{1,32}[_-]){0,8}`,xt=e=>String.raw`(?:password|passwd|passphrase|otp(?:[_-]?code)?|signature|hmac|sig|session[_-]?id|mnemonic|seed|cookie|bearer|${e}(?:token|secret)|(?:api|access|private|signing)[_-]?key|credential|claim[_-]?url)`,vt=xt(co),po=xt(uo),fo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${vt}"|'${vt}'|${po})\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)`,mo=new RegExp(String.raw`(^|[^A-Za-z0-9])((?:"${Nn}"|'${Nn}'|${Nn})\s*[:=]\s*)(?!<redacted(?:-jwt)?>)${Rn}`,"g");function Me(e){return e.replace(lo,"$1<redacted>@").replace(oo,"<redacted-jwt>").replace(so,"$1$2$3<redacted>").replace(fo,"$1$2<redacted>").replace(mo,"$1$2<redacted>").replace(ao,"Bearer <redacted>")}var yo=/(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 Ge(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return yo.test(n)}function Pt(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 He(e,n,t=ro){if(n<=0)return"";if(Buffer.byteLength(e,"utf8")<=n)return e;let i=Buffer.byteLength(t,"utf8");if(i>=n){let c="",l=0;for(let u of t){let p=Buffer.byteLength(u,"utf8");if(l+p>n)break;c+=u,l+=p}return c}let r=n-i,o="",a=0;for(let c of e){let l=Buffer.byteLength(c,"utf8");if(a+l>r)break;o+=c,a+=l}return`${o}${t}`}function I(e,n=16384){return He(Pt(Me(e)),n)}var Cn=100,ho=8,go=8*1024;function Ke(){return{remaining:go}}function On(e,n){let t=Math.min(16384,n.remaining),i=He(e,t);return n.remaining-=Buffer.byteLength(i,"utf8"),i}function ce(e,n,t=0,i={}){if(t>ho)return On("<truncated>",n);if(typeof e=="string"){let r=Me(e);return On(i.escapeControls?Pt(r):r,n)}if(Array.isArray(e)){let r=e.slice(0,Cn),o=r.map(a=>ce(a,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[a,c]of o.slice(0,Cn))r[a]=ce(c,n,t+1,i);return o.length>Cn&&(r.output_truncated=!0),r}return e}var In=require("process");var vn=!1;function xn(e){vn=e}function Ut(){return vn}var Bt="1";function ue(e,n){if(vn){let t={...e};delete t.version;let i=Ke(),r={event:t.event,...t},o=ce(r,i,0,{escapeControls:!0}),a=JSON.stringify({version:Bt,...o});Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Bt,event:o.event,output_truncated:!0})),In.stderr.write(`${a}
|
|
4
|
+
`)}else In.stderr.write(n)}var Dt="2",pe=null,P=null,fe=!1,we=!1;function _o(){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=$t.randomBytes(4).toString("hex");return Je.join(n,`allscale-output-${t}-${i}.ndjson`)}return null}var Pn=64*1024*1024,So=null;function Bn(e={}){if(e.quiet&&(we=!0),fe)return;let n=_o();if(!n)return;pe=null;let t=null;try{if((So??process.platform)==="win32")throw new Error("owner-only sidecar ACLs cannot be enforced on Windows; sidecar output is disabled");let i=Je.dirname(n);if(k.mkdirSync(i,{recursive:!0,mode:448}),!process.env.ALLSCALE_OUTPUT_FILE_PATH&&process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY){let l=k.statSync(i),u=l.mode&511;if(!l.isDirectory()||(u&63)!==0)throw new Error(`output directory must be owner-only (no group/other permissions); current mode is ${u.toString(8).padStart(3,"0")}`)}let r=k.constants.O_NOFOLLOW??0;t=k.openSync(n,k.constants.O_APPEND|k.constants.O_CREAT|k.constants.O_WRONLY|(k.constants.O_NONBLOCK??0)|r,384);let o=k.fstatSync(t),a=k.lstatSync(n);if(!o.isFile()||a.isSymbolicLink()||a.dev!==o.dev||a.ino!==o.ino)throw new Error("target changed while it was being opened or is not a regular file");if(typeof process.geteuid=="function"&&o.uid!==process.geteuid())throw new Error("existing sidecar file is not owned by the current effective user");let c=o.mode&511;if((c&63)!==0)throw new Error(`existing sidecar file must already be owner-only; current mode is ${c.toString(8).padStart(3,"0")}. Rotate or remove it before retrying`);k.fchmodSync(t,384)}catch(i){if(t!==null)try{k.closeSync(t)}catch{}we||ue({event:"sidecar_disabled",reason:"open_failed",detail:I(`sidecar path '${n}' could not be opened safely (${i.message})`)},`${I(`[allscale] sidecar path '${n}' could not be opened safely (${i.message}); refusing to write. Sidecar disabled for this run.`)}
|
|
5
|
+
`);return}pe=n,P=t,fe=!0}var ko=[/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 To(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2");return ko.some(t=>t.test(n))}function Ft(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=Ao(n.pathname);let r=t;n.pathname!==i&&(r=!0);for(let[o]of n.searchParams)To(o)&&(n.searchParams.set(o,"<redacted>"),r=!0);return r?n.toString():e}catch{return e}}function Ao(e){return e.replace(/(\/(?:api\/)?(?:v1\/)?public\/claim-links\/)([^/:]+)(:claim)?(?=\/?$)/,"$1<redacted>$3").replace(/(\/(?:api\/)?public\/claim-links\/)([^/]+)(\/claim)(?=\/?$)/,"$1<redacted>$3")}function wo(e){return(e.type==="request"||e.type==="bridge_browser_open")&&typeof e.url=="string"?{...e,url:Ft(e.url)}:e}function Lo(e){let n=new Date().toISOString(),t=e,{type:i,...r}=t,o=ce(r,Ke()),a=JSON.stringify({version:Dt,timestamp:n,type:i,...o});return Buffer.byteLength(a,"utf8")+1>65536&&(a=JSON.stringify({version:Dt,timestamp:n,type:i,output_truncated:!0})),a}function h(e){if(!fe||!pe||P===null)return;let n=wo(e),t=Lo(n);try{if(k.fstatSync(P).size+Buffer.byteLength(t,"utf8")+1>Pn){fe=!1;try{k.closeSync(P)}catch{}P=null,we||ue({event:"sidecar_disabled",reason:"size_limit",...pe===null?{}:{path:I(pe)},max_bytes:Pn},`${I(`[allscale] sidecar exceeded ${Pn} bytes; disabling it for the rest of this run. Rotate or remove ${pe}, or point ALLSCALE_OUTPUT_FILE_DIRECTORY at a directory so each run gets its own file.`)}
|
|
6
|
+
`);return}k.appendFileSync(P,`${t}
|
|
7
|
+
`)}catch(i){if(fe=!1,P!==null){try{k.closeSync(P)}catch{}P=null}try{we||ue({event:"sidecar_disabled",reason:"write_failed",detail:I(i.message)},`${I(`[allscale] sidecar write failed (${i.message}); disabling sidecar for the rest of this run.`)}
|
|
8
|
+
`)}catch{}}}var Y=Ft;function Mt(){return!!(process.env.ALLSCALE_OUTPUT_FILE_PATH||process.env.ALLSCALE_OUTPUT_FILE_DIRECTORY)}function Le(){if(we=!1,fe=!1,P!==null){try{k.closeSync(P)}catch{}P=null}}function Gt(e=!1){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;return e||Mt()||!n}var be=new Set(["--password","-p","--token","-t","--otp","--otp-id","--api-base","--payout-api-base","--browser-base","--input","-i","--claim-token","--claim-url","--api-key","--api-secret"]),bo=new Set(Array.from(be).filter(e=>e.startsWith("-")&&!e.startsWith("--")&&e.length===2)),Eo=Array.from(be).filter(e=>e.startsWith("--")).sort((e,n)=>n.length-e.length),No=new Set(["--otp-stdin","--password-stdin"]);function Un(e){let n=[];for(let t=0;t<e.length;t+=1){let i=e[t];if(i.startsWith("-")){let o=i.indexOf("=");if(o!==-1){let a=i.slice(0,o);if(be.has(a)){n.push(`${a}=<redacted>`);continue}}}if(be.has(i)){n.push(i),t+1<e.length&&(be.has(e[t+1])||(n.push("<redacted>"),t+=1));continue}if(i.startsWith("-")&&!i.startsWith("--")&&i.length>2&&i[1]!=="="){let o=i.slice(0,2);if(bo.has(o)){n.push(`${o}<redacted>`);continue}}let r=No.has(i)?void 0:Eo.find(o=>i.length>o.length&&i.startsWith(o));if(r){n.push(`${r}<redacted>`);continue}n.push(i)}return n}function Ht(e){h({type:"error",code:e.code,message:I(e.message)}),h({type:"command-end",ok:!1,exitCode:e.exitCode}),Le()}var Ee=Se()??wt,ye={TOKEN:"ALLSCALE_TOKEN",PROFILE:"ALLSCALE_PROFILE",API_BASE:"ALLSCALE_API_BASE",PAYOUT_API_BASE:"ALLSCALE_PAYOUT_API_BASE",PRETTY:"ALLSCALE_PRETTY",LOG_LEVEL:"ALLSCALE_LOG_LEVEL",INSECURE_STORAGE:"ALLSCALE_INSECURE_STORAGE",NO_KEYCHAIN:"ALLSCALE_NO_KEYCHAIN",ALLOW_RAW:"ALLSCALE_ALLOW_RAW",OUTPUT_FILE_PATH:"ALLSCALE_OUTPUT_FILE_PATH",OUTPUT_FILE_DIRECTORY:"ALLSCALE_OUTPUT_FILE_DIRECTORY",STORE_API_KEY:"ALLSCALE_STORE_API_KEY",STORE_API_SECRET:"ALLSCALE_STORE_API_SECRET"};function V(e){return Et(e)?new URL(e).origin:null}function v(e){try{let n=new URL(e);return`${n.protocol}//${n.host}`}catch{return"<unparseable URL>"}}function Kt(){let e=process.env[ye.TOKEN]?.trim();return e&&e.length>0?e:void 0}function Dn(){let e=process.env[ye.PROFILE]?.trim();return e&&e.length>0?e:void 0}function qe(){let e=process.env[ye.API_BASE]?.trim();return e&&e.length>0?e:void 0}function Jt(){let e=process.env[ye.INSECURE_STORAGE]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function qt(){let e=process.env[ye.NO_KEYCHAIN]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Yt(){let e=process.env[ye.ALLOW_RAW]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Vt(e){let{resolvedApiBase:n,fromExplicitOverride:t,profileApiBase:i,profileApiBaseSource:r}=e;if(Se()===void 0&&Ee!==""&&"".length!==0&&!t&&r!=="explicit"&&i===""&&n==="")return`Notice: this profile is pinned to ${""} (staging) in ~/.allscale/config.toml.
|
|
9
|
+
The CLI default is now ${Ee} (production), but a saved profile wins over the default,
|
|
11
10
|
so this session still uses staging. That pin was written before the default changed, so it may just be
|
|
12
11
|
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:
|
|
15
|
-
`}var
|
|
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
|
|
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=
|
|
20
|
-
`,
|
|
21
|
-
`).find(
|
|
22
|
-
`)&&(
|
|
23
|
-
`)
|
|
24
|
-
`)
|
|
12
|
+
To keep staging, re-run \`allscale device-login\` with --api-base ${""} (recorded as deliberate, silences this).
|
|
13
|
+
To move to production, run: allscale device-login --api-base ${Ee}
|
|
14
|
+
`}var X=C(require("fs")),jt=C(require("os")),$n=C(require("path")),Fn=C(require("@iarna/toml"));var Ro=".allscale",Io="config.toml";function Ne(){return $n.join(jt.homedir(),Ro)}function vo(){return $n.join(Ne(),Io)}function Ye(){let e=vo();if(!X.existsSync(e))return{};let n=X.readFileSync(e,"utf-8");try{return Fn.parse(n)}catch(t){throw new s("internal",`Failed to parse ${e}: ${t.message}`)}}function Wt(e){return Object.keys(e.profile??{}).sort()}function zt(e,n){return e.profile?.[n]}function Xt(e,n,t){let i=n??t??e.default??"default";if(i.includes(":"))throw new s("input.invalid",`Invalid profile name '${i}': ':' is reserved as the keychain namespace separator \u2014 pick a name without ':'.`);return i}function he(e){if(!le(e))throw new s("input.invalid",`Refusing to send credentials to API base ${v(e)}. `+_e)}function Ve(e,n){he(e);let t=V(e),i=typeof n=="string"?V(n):null;if(t&&i===t)return;let r=typeof n=="string"?v(n):"<missing origin binding>";throw new s("input.invalid",`Refusing to send stored credentials: API base ${v(e)} does not match their bound origin ${r}. Re-login against the intended API base before retrying.`)}function Qt(e,n){let t=V(e),i=V(n);if(!(t&&i===t))throw new s("input.invalid",`Refusing API request to ${v(n)} because it is outside the configured API origin ${v(e)}.`)}function je(e){let n=Se();if(n===void 0||z(e))return;let t=V(e),i=Te();if(i.length>0){let o=i.map(c=>V(c.base)).filter(c=>c!==null);if(t!==null&&o.includes(t))return;let a=i.map(c=>v(c.base)).join(", ");throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for: ${a}. Re-login against one of this build's environments, or use a build that includes the one you need.`)}let r=V(n);if(!(t!==null&&t===r))throw new s("input.invalid",`Refusing to send to ${v(e)} \u2014 this build only signs for ${v(n)}. Re-login against this build's environment, or use a build for that one.`)}var Zt=require("@noble/hashes/sha3");var We=(a=>(a[a.ETHEREUM=1]="ETHEREUM",a[a.BASE=5]="BASE",a[a.BNB=6]="BNB",a[a.ARBITRUM=7]="ARBITRUM",a[a.POLYGON=8]="POLYGON",a[a.OPTIMISM=9]="OPTIMISM",a))(We||{});var xo={eth:1,ethereum:1,bsc:6,bnb:6,base:5,polygon:8,matic:8,arbitrum:7,arb:7,optimism:9,op:9},ei=["ethereum","bsc","base","polygon","arbitrum","optimism"],ze=["USDT","USDC"];function ni(e){return xo[e.toLowerCase()]??null}function ti(e){let n=e.toUpperCase();return n==="USDT"?1:n==="USDC"?2:null}function ii(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,Zt.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 a=Number.parseInt(i[r],16)>=8;if(a&&o!==o.toUpperCase()||!a&&o!==o.toLowerCase())return!1}return!0}var Po=new Set([`0x${"0".repeat(40)}`,`0x${"0".repeat(36)}dead`]);function ri(e){return Po.has(e.toLowerCase())}function Xe(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 M(e){return{1:"Ethereum",6:"BSC (BEP20)",5:"Base",8:"Polygon",9:"Optimism",7:"Arbitrum"}[e]}function Ce(e){return e===1?"USDT":"USDC"}var j=require("@oclif/core"),Oe=class e extends J.Command{static enableJsonFlag=!0;static legacyStagingNoticeShown=!1;static emitsOwnOutput=!1;static requiresEscapeHatch=!1;static requiresInput=!1;static isLocalOnly=!1;static baseFlags={profile:J.Flags.string({description:"Named profile from ~/.allscale/config.toml",helpGroup:"GLOBAL"}),token:J.Flags.string({description:"Override the access token for this invocation (precedence: --token > ALLSCALE_TOKEN > --profile)",helpGroup:"GLOBAL",hidden:ke()==="public"}),"api-base":J.Flags.string({description:gn,helpGroup:"GLOBAL",hidden:ke()==="public"}),"insecure-storage":J.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{xn(this.jsonEnabled()),Bn(),h({type:"session-start",command:this.id??"",argv:Un(this.argv)});let n=this.constructor;if(ke()==="public"){if(this.argv.some(o=>o==="--token"||o.startsWith("--token=")))throw new s("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 s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!n.isLocalOnly&&qe()!==void 0)throw new s("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=Gt(this.jsonEnabled()),i=this.argv.length===0&&!t&&Go(n)?this.config.findCommand(this.id??""):void 0;if(i){Le();let o=await(0,J.loadHelpClass)(this.config),a=this.config.pjson.oclif?.helpOptions??this.config.pjson.helpOptions;await new o(this.config,a).showCommandHelp(i,this.config.topics);return}if(n.requiresEscapeHatch&&!Yt())throw this.argv.length>0&&await this.parse(),new s("raw.disabled","This command is an opt-in escape hatch and is disabled by default. Set ALLSCALE_ALLOW_RAW=1 to enable raw GraphQL/REST passthroughs and schema introspection. Access remains governed by the key's granted scopes, which the backend checks on each request.");let r=await this.runCommand();return h({type:"command-end",ok:!0}),Le(),n.emitsOwnOutput?void 0:(this.jsonEnabled()||It(r),{data:r})}catch(n){let t=Rt(n);Ht({code:t.code,message:t.message,exitCode:t.exitCode}),this.emitError(t),process.exitCode=t.exitCode;return}finally{xn(!1)}}resolveSessionApiBaseChain(n){let t=Ye(),i=n.profile??void 0,r=n["api-base"]??void 0,o=i!==void 0||Dn()!==void 0,a=Xt(t,i,Dn()),c=zt(t,a),l=r??qe(),u=l??c?.api_base??Ee,p=Vt({resolvedApiBase:u,fromExplicitOverride:l!==void 0,profileApiBase:c?.api_base,profileApiBaseSource:c?.api_base_source});return p&&!e.legacyStagingNoticeShown&&(e.legacyStagingNoticeShown=!0,ue({event:"legacy_staging_profile",api_base:u,profile:a},p)),{apiBase:u,explicitApiBase:l,profileApiBase:c?.api_base,profile:a,profileExplicit:o}}resolveSessionApiBaseForPayoutDerivation(n){let{apiBase:t}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||he(t),t}resolveContext(n){if(ke()==="public"){if(n.token!==void 0)throw new s("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 s("input.invalid","--api-base is not supported in this build; it always talks to its bound AllScale environment.");if(!this.constructor.isLocalOnly&&qe()!==void 0)throw new s("input.invalid","ALLSCALE_API_BASE is not supported in this build; unset it \u2014 this build always talks to its bound AllScale environment.")}let t=n.token??void 0,i=!!n["insecure-storage"],{apiBase:r,explicitApiBase:o,profile:a,profileApiBase:c,profileExplicit:l}=this.resolveSessionApiBaseChain(n);return this.constructor.isLocalOnly||(he(r),je(r)),{apiBase:r,profile:a,token:t??Kt(),insecureStorage:i||Jt(),apiBaseSource:o!==void 0?"explicit":c!==void 0?"profile":"default",profileExplicit:l}}emitError(n){process.stderr.write(`${Mo(n)}
|
|
15
|
+
`)}};var Bo=/_(removed|cleared|count|total)$/i;function Uo(e,n){return typeof n=="number"&&Bo.test(e)}var Do=new Set(ze);function $o(e,n){return e==="token_symbol"&&typeof n=="string"&&Do.has(n)}var Qe=100;function Ze(e,n=0){if(n>8)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,Qe),i=t.map(r=>Ze(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]=Ge(r)&&!Uo(r,o)&&!$o(r,o)?"<redacted>":Ze(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}if(typeof e=="string"){let t=Fo(e);return t!==void 0?I(JSON.stringify(Ze(t,n+1))):I(e)}return e}function Fo(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function Mo(e){let n=Ut()?void 0:2,t=Ze(e.toJSON()),i=JSON.stringify(t,null,n);return Buffer.byteLength(i,"utf8")+1<=65536?i:JSON.stringify({error:{code:e.code,message:I(e.message),details:{output_truncated:!0,max_output_bytes:65536}}},null,n)}function Go(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 Ho(e,n={}){let t;try{t=Wt(Ye())}catch{return}if(!(t.length===0||t.includes(e)))return new s("auth.unknown_profile",Ot(e)+(n.messageSuffix??""),{profile:e})}function en(e){if(e.profileExplicit){let n=Ho(e.profile);if(n)return n}return new s("auth.no_token",Ct(e.profile))}var gi=C(require("path"));var Hn=require("crypto"),d=C(require("fs")),w=C(require("path"));var nn=1024*1024,Ko=5e3,Jo=20,qo=3e4,Mn=4096,Yo=new Int32Array(new SharedArrayBuffer(4)),Re=class extends Error{constructor(){super("credential-store data file must not have hard links"),this.name="PrivateCredentialFileHardLinkError"}};function tn(e){return e instanceof Re}var x=class extends Error{constructor(){super("credential-store lock changed during concurrent inspection")}},Vo=null;function Z(){return new s("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 rn(){return(Vo??process.platform)!=="win32"}function pi(){if(!rn())throw Z()}function fi(e){try{return d.default.lstatSync(e),!1}catch(n){if(!A(n,"ENOENT"))throw n}try{let n=d.default.lstatSync(w.dirname(e));return!n.isSymbolicLink()&&n.isDirectory()}catch(n){if(A(n,"ENOENT"))return!0;throw n}}function A(e,n){return typeof e=="object"&&e!==null&&e.code===n}function Ie(e,n){if(typeof process.geteuid=="function"&&e.uid!==process.geteuid())throw new Error(`${n} is not owned by the current effective user`)}function ve(e,n){return e.dev===n.dev&&e.ino===n.ino}function jo(e){Atomics.wait(Yo,0,0,e)}function mi(e){try{return process.kill(e,0),!0}catch(n){return!A(n,"ESRCH")}}function Wo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oi(e,n){let t=w.dirname(e);n&&d.default.mkdirSync(t,{recursive:!0,mode:448});let i;try{i=d.default.lstatSync(t)}catch(o){if(!n&&A(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=d.default.openSync(t,d.default.constants.O_RDONLY|(d.default.constants.O_DIRECTORY??0)|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0));let o=d.default.fstatSync(r),a=d.default.lstatSync(t);if(!o.isDirectory()||a.isSymbolicLink()||!a.isDirectory()||!ve(o,a))throw new Error("credential-store parent changed while it was being inspected");Ie(o,"credential-store parent");let c=o;if((o.mode&63)!==0&&w.basename(t)===".allscale"&&(d.default.fchmodSync(r,448),c=d.default.fstatSync(r)),(c.mode&63)!==0)throw new Error("credential-store parent must not grant group or other permissions")}finally{r!==null&&d.default.closeSync(r)}return!0}function q(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=d.default.lstatSync(e)}catch(o){throw i.retryOnPathChange&&A(o,"ENOENT")?new x:o}if(!ve(t,r))throw i.retryOnPathChange?new x: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 Re;if(Ie(t,"credential-store file"),process.platform!=="win32"){d.default.fchmodSync(n,384);let o=d.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 zo(e,n){if(n.size>nn)throw new Error("credential-store file exceeds the maximum supported size");let t=Buffer.alloc(nn+1),i=0;for(;i<t.length;){let r=d.default.readSync(e,t,i,t.length-i,null);if(r===0)break;i+=r}if(i>nn)throw new Error("credential-store file exceeds the maximum supported size");return t.subarray(0,i).toString("utf8")}function ai(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT"))try{if(d.default.lstatSync(e).isSymbolicLink())throw new Error("credential-store target must not be a symbolic link")}catch(o){if(A(o,"ENOENT"))return null;throw o}throw r}let t=d.default.fstatSync(n),i=q(e,n,t);return zo(n,i)}finally{n!==null&&d.default.closeSync(n)}}function si(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(r){if(A(r,"ENOENT")&&fi(e))return;throw r}let t=d.default.fstatSync(n),i=q(e,n,t);ee(e,i)}finally{n!==null&&d.default.closeSync(n)}hi(w.dirname(e))}function Xo(e){let n;try{n=d.default.lstatSync(e)}catch(t){if(A(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 Re;Ie(n,"credential-store replacement target")}function Qo(e,n){for(let t=0;t<8;t+=1){let i=(0,Hn.randomBytes)(12).toString("hex"),r=w.join(e,`.${n}.${process.pid}.${i}.tmp`);try{return{fd:d.default.openSync(r,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_WRONLY|(d.default.constants.O_NOFOLLOW??0),384),tempPath:r}}catch(o){if(A(o,"EEXIST"))continue;throw o}}throw new Error("could not allocate a unique credential-store temp file")}function yi(e,n){let t=0;for(;t<n.length;){let i=d.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 hi(e){if(process.platform==="win32")return;let n=null;try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_DIRECTORY??0)|(d.default.constants.O_NOFOLLOW??0)),d.default.fsyncSync(n)}catch{}finally{if(n!==null)try{d.default.closeSync(n)}catch{}}}function Zo(e,n){let t=Buffer.from(n,"utf8");if(t.length>nn)throw new Error("credential-store file exceeds the maximum supported size");let i=w.dirname(e),r=w.basename(e),o=null,a=null,c=!1;try{let l=Qo(i,r);o=l.fd,a=l.tempPath;let u=d.default.fstatSync(o);if((q(a,o,u).mode&63)!==0&&process.platform!=="win32")throw new Error("credential-store temp file is not owner-only");yi(o,t),d.default.fsyncSync(o),q(a,o,d.default.fstatSync(o));let f=o;o=null,d.default.closeSync(f),Xo(e),d.default.renameSync(a,e),c=!0}finally{if(o!==null)try{d.default.closeSync(o)}catch{}if(!c&&a!==null)try{d.default.unlinkSync(a)}catch{}}hi(i)}function ea(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock`)}function na(e){return w.join(w.dirname(e),`.${w.basename(e)}.lock-recovery`)}function ta(e,n){if(n.size>Mn)return null;let t=Buffer.alloc(Mn+1),i=0;for(;i<t.length;){let o=d.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 ee(e,n){let t=d.default.lstatSync(e);if(t.isSymbolicLink()||!t.isFile()||!ve(t,n))throw new Error("credential-store lock changed while it was being inspected");Ie(t,"credential-store lock"),d.default.unlinkSync(e)}function li(e,n){let t=null;try{try{t=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(l){if(A(l,"ENOENT"))try{let u=d.default.lstatSync(e);throw u.isSymbolicLink()||!u.isFile()?new Error("credential-store lock must be a real regular file"):new x}catch(u){if(A(u,"ENOENT"))return{state:"absent"};throw u}throw l}let i=d.default.fstatSync(t),r=q(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0}),o=ta(t,r);return{state:(o?.target===n&&o?!mi(o.pid):Date.now()-r.mtimeMs>=qo)?"stale":"active",stats:r}}finally{t!==null&&d.default.closeSync(t)}}function ia(e,n){for(let t=0;t<8;t+=1){let i=(0,Hn.randomBytes)(12).toString("hex"),r=w.join(e,`.${n}.${process.pid}.${i}.lock-claim`),o={pid:process.pid,nonce:i,target:n},a=null;try{a=d.default.openSync(r,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_WRONLY|(d.default.constants.O_NOFOLLOW??0),384);let c=d.default.fstatSync(a),l=q(r,a,c,{allowMultipleLinks:!0});return yi(a,Buffer.from(JSON.stringify(o),"utf8")),d.default.fsyncSync(a),{claimPath:r,metadata:o,stats:l}}catch(c){if(A(c,"EEXIST"))continue;try{d.default.unlinkSync(r)}catch{}throw c}finally{a!==null&&d.default.closeSync(a)}}throw new Error("could not allocate a unique credential-store lock claim")}function ra(e,n){let t;try{t=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(i){throw A(i,"ENOENT")?new x:i}try{let i=d.default.fstatSync(t),r=q(e,t,i,{allowMultipleLinks:!0,retryOnPathChange:!0});if(!ve(r,n))throw new x;return{fd:t,lockPath:e,stats:r}}catch(i){throw d.default.closeSync(t),i}}function ci(e){let n=null;try{try{n=d.default.openSync(e,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(t){if(A(t,"ENOENT"))try{let i=d.default.lstatSync(e);throw i.isSymbolicLink()||!i.isFile()?new Error("credential-store recovery gate must be a real regular file"):new x}catch(i){if(A(i,"ENOENT"))return!1;throw i}throw t}return q(e,n,d.default.fstatSync(n),{allowMultipleLinks:!0,retryOnPathChange:!0}),!0}finally{n!==null&&d.default.closeSync(n)}}function oa(e){let n;try{n=d.default.openSync(e,d.default.constants.O_CREAT|d.default.constants.O_EXCL|d.default.constants.O_RDWR|(d.default.constants.O_NOFOLLOW??0),384)}catch(i){if(A(i,"EEXIST"))return null;throw i}let t=null;try{t=d.default.fstatSync(n);let i=q(e,n,t,{allowMultipleLinks:!0,retryOnPathChange:!0});return{fd:n,lockPath:e,stats:i}}catch(i){if(t!==null)try{ee(e,t)}catch{}throw d.default.closeSync(n),i}}function Q(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(Jo)}function di(e){let n=w.dirname(e),t=w.basename(e),i=ea(e),r=na(e),o=ia(n,t),a=Date.now()+Ko,c=!1,l=!1,u=null,p;try{for(;u===null;)try{if(ci(r)){Q(a,!0);continue}d.default.linkSync(o.claimPath,i),l=!0,u=ra(i,o.stats),c=!0}catch(f){if(l&&!c){try{ee(i,o.stats)}catch{}l=!1}if(f instanceof x){Q(a,!1);continue}if(!A(f,"EEXIST"))throw f;let y;try{y=li(i,t)}catch(g){if(g instanceof x){Q(a,!1);continue}throw g}if(y.state==="absent")continue;if(y.state==="stale"){let g;try{g=oa(r)}catch(_){if(_ instanceof x){Q(a,!1);continue}throw _}if(g!==null){try{let _;try{_=li(i,t)}catch(N){if(N instanceof x){Q(a,!1);continue}throw N}_.state==="stale"&&ee(i,_.stats)}finally{Gn(g)}continue}}let m;try{m=ci(r)}catch(g){if(g instanceof x){Q(a,!1);continue}throw g}Q(a,m)}}catch(f){p=f}try{ee(o.claimPath,o.stats)}catch(f){!A(f,"ENOENT")&&!c&&p===void 0&&(p=f)}if(p!==void 0)throw p;if(u===null)throw new Error("credential-store lock acquisition failed");return u}function Gn(e){try{ee(e.lockPath,e.stats)}finally{d.default.closeSync(e.fd)}}function aa(e,n){let t=Wo(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 ui(e){let n=w.dirname(e),t=w.basename(e);for(let i of d.default.readdirSync(n)){let r=aa(i,t);if(r===null||mi(r))continue;let o=w.join(n,i),a=null;try{try{a=d.default.openSync(o,d.default.constants.O_RDONLY|(d.default.constants.O_NOFOLLOW??0)|(d.default.constants.O_NONBLOCK??0))}catch(u){if(A(u,"ENOENT")||A(u,"ELOOP"))continue;throw u}let c=d.default.fstatSync(a),l=d.default.lstatSync(o);if(!c.isFile()||l.isSymbolicLink()||!l.isFile()||!ve(c,l))continue;try{Ie(c,"credential-store orphan")}catch{continue}ee(o,c)}catch(c){if(!A(c,"ENOENT"))throw c}finally{a!==null&&d.default.closeSync(a)}}}function xe(e,n,t){if(!rn()){if(n.allowUnsupportedPlatformCleanup){if(n.createParent)throw Z();if(!oi(e,!1))return t({read:()=>null,remove:()=>{},write:()=>{throw Z()}});let a=di(e);try{return ui(e),t({read:()=>ai(e),remove:()=>si(e),write:()=>{throw Z()}})}finally{Gn(a)}}if(!n.createParent){let o=!1;try{o=fi(e)}catch{throw Z()}if(o)return t({read:()=>null,remove:()=>{},write:()=>{throw Z()}})}throw Z()}if(!oi(e,n.createParent))return t({read:()=>null,remove:()=>{},write:()=>{throw new Error("credential-store parent does not exist")}});let r=di(e);try{return ui(e),t({read:()=>ai(e),remove:()=>si(e),write:o=>Zo(e,o)})}finally{Gn(r)}}var Kn="allscale-cli";function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _i(e){return Vn(e)&&typeof e.access_token=="string"&&typeof e.refresh_token=="string"}function te(e){return new s("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 s("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 on(){return new s("internal","The session credential store in the plaintext file could not be written safely. Any previous credential file was left unchanged.")}var ne,qn=!1;function sa(){return qt()?"ALLSCALE_NO_KEYCHAIN":process.env.KEYTAR_DISABLE==="1"?"KEYTAR_DISABLE":null}function la(e){if(typeof e!="object"||e===null||e.code!=="MODULE_NOT_FOUND")return!1;let n=e.message;return typeof n=="string"&&n.split(`
|
|
16
|
+
`,1)[0]==="Cannot find module 'keytar'"}function ca(){if(ne!==void 0)return ne;if(sa())return qn=!1,ne=null,ne;try{ne=require("keytar"),qn=!1}catch(e){qn=!la(e),ne=null}return ne}function Si(){let e=rn()?"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 s("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 Yn(e){try{return await e()}catch{throw Si()}}var jn=class{constructor(n){this.keytar=n}keytar;kind="keychain";async read(n){let t=await Yn(()=>this.keytar.getPassword(Kn,n));if(t===null)return null;let i;try{i=JSON.parse(t)}catch{throw te("OS keychain")}if(!_i(i))throw te("OS keychain");return i}async get(n){return this.read(n)}async set(n,t){await this.read(n),await Yn(()=>this.keytar.setPassword(Kn,n,JSON.stringify(t)))}async delete(n){await this.read(n),await Yn(()=>this.keytar.deletePassword(Kn,n))}},da="credentials.json",Wn=class{kind="insecure-file";filePath;constructor(n){this.filePath=n??gi.join(Ne(),da)}read(n){let t;try{t=n.read()}catch(r){throw tn(r)?Jn():te("plaintext file")}if(t===null)return{profiles:{}};let i;try{i=JSON.parse(t)}catch{throw te("plaintext file")}if(!Vn(i)||!Vn(i.profiles))throw te("plaintext file");return i}write(n,t){try{n.write(JSON.stringify(t,null,2))}catch(i){throw tn(i)?Jn():on()}}profileTokens(n,t){let i=n.profiles[t];if(i!==void 0){if(!_i(i))throw te("plaintext file");return i}}async get(n){try{return xe(this.filePath,{createParent:!1},t=>this.profileTokens(this.read(t),n)??null)}catch(t){throw t instanceof s?t:te("plaintext file")}}async set(n,t){try{xe(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 s?i:on()}}async delete(n){try{xe(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 s?t:on()}}async clearProfile(n){try{return xe(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 s?t:tn(t)?Jn():on()}}};function an(e){if(e.insecureStorage)return pi(),new Wn(e.insecureFilePath);let n=ca();if(n)return new jn(n);throw Si()}var zn=class{kind="insecure-file";async get(n){return null}async set(n,t){throw new s("internal","NoopTokenStore: refusing to persist tokens \u2014 caller used --token override path.")}async delete(n){}};function sn(){return new zn}async function ki(e){if(e.token)return{kind:"override",accessToken:e.token};let t=await an({insecureStorage:e.insecureStorage}).get(e.profile),i=t?.api_base;return t?.agent_key?{kind:"agent",storedApiBase:i,businessId:Xn(t.business_id),userEmail:Xn(t.user_email),scopes:ua(t.scopes)}:t?.access_token?{kind:"human",storedApiBase:i,accessToken:t.access_token,userEmail:Xn(t.user_email)}:{kind:"none"}}function Xn(e){return typeof e=="string"&&e.length>0?e:void 0}function ua(e){if(!Array.isArray(e))return;let n=e.filter(t=>typeof t=="string"&&t.length>0);return n.length>0?n:void 0}function Ti(e){let n=e.split(".");if(n.length!==3)throw new s("auth.token_expired","This token is not a JWT session. Agent API keys are not JWTs \u2014 this path needs a human session token.");try{let t=Buffer.from(n[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf-8");return JSON.parse(t)}catch(t){throw new s("auth.token_expired",`Failed to decode JWT payload: ${t.message}`)}}async function pa(e){let n=i=>{let r=Ti(i);return typeof r.user_id=="string"&&r.user_id.length>0?r.user_id:void 0},t=await ki(e);switch(t.kind){case"override":case"human":return n(t.accessToken);case"agent":return t.businessId;case"none":throw en({profile:e.profile,profileExplicit:e.profileExplicit});default:return fa(t)}}function fa(e){throw new s("internal",`Unhandled credential kind: ${JSON.stringify(e.kind)}`)}var ma=/^[0-9a-f]{24}$/i;async function Ai(e,n){if(typeof n!="string"||n.length===0)return;if(!ma.test(n))throw new s("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 pa(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.
|
|
17
|
+
`);return}if(t.toLowerCase()!==n.toLowerCase())throw new s("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 ln="allscale_access_token",Qn="allscale_refresh_token";function wi(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 Zn(e){return e.map(n=>`${n.name}=${n.value}`).join("; ")}function et(e,n){return e.find(t=>t.name===n)?.value??null}var Li=C(require("crypto")),bi=C(require("fs")),Ei=C(require("path"));var ya="key-id",ha="x-allscale-cli-version",nt="cli-1",ga="aScaLe_cli_obf_v1",_a="WWoBD3QEZwECUTEuOD4dTgdWawQSKAQ8UlRaaw==";function Sa(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 ka=Sa(_a,ga),Ni=`Bearer ${ka}`;function Ci(e,n){let t=kn(e);if(t!==null)return n.find(i=>kn(i.base)===t)}function Ta(e){if("f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2".trim().length>0)return"f17372513b233456b90621e793c1d0759bce34f8eec3415abc6c2f08270faef2";let n=Te();if(n.length>0){let i=Ci(e,n);if(i)return i.key;if(z(e)){let r=process.env.ALLSCALE_SIGNING_KEY;return r&&r.trim().length>0?r:z(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 Aa(e){{let i="cli-1".trim();if(i.length>0)return i}let n=Te();if(n.length>0){let i=e!==void 0?Ci(e,n):void 0;if(i)return i.keyId;if(e!==void 0&&z(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():nt}if(!z(n[0].base))return nt}return n[0].keyId}let t=process.env.ALLSCALE_SIGNING_KEY_ID;return t!==void 0?t.trim():nt}function wa(){return"1.0.1"}function La(){return new s("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 tt(e,n){let t=Ta(n);if(!t)throw La();let i=Aa(n),r=Math.floor(Date.now()/1e3).toString(),o=Li.createHash("sha256").update(`${t}${r}${e}`).digest("hex"),a={timestamp:r,"secret-key":o,[ha]:wa()};return i.length>0&&(a[ya]=i),a}function Oi(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e)}var ba=500,Ea=8,Ri=100;function it(e,n=0){if(n>Ea)return"<truncated>";if(Array.isArray(e)){let t=e.slice(0,Ri),i=t.map(r=>it(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);for(let[i,r]of Object.entries(e).slice(0,Ri))t[i]=Ge(i)?"<redacted>":it(r,n+1);return t}return e}function Na(e){let n=e.trim();if(!n.startsWith("{")&&!n.startsWith("["))return;let t;try{t=JSON.parse(n)}catch{return}return t!==null&&typeof t=="object"?t:void 0}function Ii(e,n=ba){let t=Na(e),i=t===void 0?Me(e):JSON.stringify(it(t));return He(i,n)}var rt=256*1024,cn=class extends s{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"}},dn=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 ot(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 cn(e.status,n,t.oversizeKind);if(!e.body)return"";let o=e.body.getReader(),a=[],c=0,l,u=t.timeoutMs,p=u===void 0?void 0:new Promise((f,y)=>{l=setTimeout(()=>{y(new dn(e.status,u))},u),l.unref?.()});try{for(;;){let f=o.read(),{done:y,value:m}=p?await Promise.race([f,p]):await f;if(y)break;if(c+=m.byteLength,c>n)throw o.cancel().catch(()=>{}),new cn(e.status,n,t.oversizeKind);a.push(Buffer.from(m))}}catch(f){throw f instanceof dn&&o.cancel(f).catch(()=>{}),f}finally{l!==void 0&&clearTimeout(l);try{o.releaseLock()}catch{}}return Buffer.concat(a,c).toString("utf8")}var Ca="X-AllScale-Api-Key",Oa=3e4,Ra=32*1024*1024,Ia=4*1024*1024;function va(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 xa(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 Pa(e,n){if(!(e<300||e>=400))throw new s("transport.network",`API returned HTTP ${e} (a redirect) for ${Y(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 Ui(e){if(!(e.status<300||e.status>=400)){try{await e.body?.cancel()}catch{}Pa(e.status,e.url)}}var vi="--dns-result-order=ipv4first";async function un(e,n){if(e.status!==403)return;let t=e.headers.get("content-type")?.toLowerCase()??"",i=e.headers.get("cf-ray")??"",r=e.headers.get("cf-mitigated")?.trim().toLowerCase()==="challenge",o=t.includes("text/html"),a=n?.slice(0,4096)??"",c=/^\s*(?:<!doctype\s+html|<html\b)/i.test(a),l=/cf-error-details|\/cdn-cgi\/(?:challenge-platform|styles\/cf\.errors)|sorry,\s*you have been blocked|attention required[^<]{0,160}cloudflare|cloudflare ray id|error\s*(?:code\s*)?1020/i.test(a);if(!((o||c)&&(r||n!==void 0&&l)))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 s("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=${vi} 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=${vi}`})}var ie=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??Oa;if(!Number.isFinite(i)||i<1)throw new s("input.invalid","HTTP request timeout must be a positive number of milliseconds.");he(this.opts.apiBase),je(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=va(n.signal,i);try{return await this.requestWithinDeadline({...n,signal:o.signal},t,r)}catch(a){throw o.timedOut()?new s("transport.timeout",`Request to ${Y(new URL(n.path,this.opts.apiBase).toString())} timed out after ${i}ms.`,{timeout_ms:i}):n.signal?.aborted&&!(a instanceof s)?new s("transport.network",`Request to ${Y(new URL(n.path,this.opts.apiBase).toString())} was aborted by the caller.`):a}finally{o.dispose()}}async requestWithinDeadline(n,t,i){let r=new URL(n.path,this.opts.apiBase).toString();Qt(this.opts.apiBase,r);let o=i?.agent_key,a=n.auth??"auto",c=Di(n.path),l=a==="required"?!0:a==="none"?!1:Da(n.path);if((c||a==="required")&&!n._isRefresh&&!this.opts.override&&!i?.access_token&&!o)throw en({profile:this.opts.profile,profileExplicit:this.opts.profileExplicit});let u=Oi(n.body),p=!!o||!!i?.access_token;l&&p&&!this.opts.override&&Ve(this.opts.apiBase,i?.api_base);let f=this.buildHeaders({attachAuth:l&&p,bodyForSig:u,tokens:i,extra:n.headers}),y=Date.now();h({type:"request",method:n.method??"GET",url:r,...n._isRefresh?{refresh:!0}:{}});let m;try{m=await fetch(r,{method:n.method??"GET",headers:f,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(_){throw new s("transport.network",`Network error contacting ${Y(r)}: ${_ instanceof Error?_.message:String(_)}`)}if(h({type:"response",status:m.status,durationMs:Date.now()-y}),l&&!!i?.access_token&&!o&&m.status===401&&!n._isRefresh&&!this.opts.override){let _=await xa(this.refreshSingleFlight(),n.signal),N=this.buildHeaders({attachAuth:l&&!!_.access_token,bodyForSig:u,tokens:_,extra:n.headers}),R=Date.now();h({type:"request",method:n.method??"GET",url:r});let S;try{S=await fetch(r,{method:n.method??"GET",headers:N,body:n.body!==void 0?u:void 0,signal:n.signal,redirect:"manual"})}catch(B){throw new s("transport.network",`Network error contacting ${Y(r)} on refresh-retry: ${B instanceof Error?B.message:String(B)}`)}return h({type:"response",status:S.status,durationMs:Date.now()-R}),xi(S,{withMetadata:t.withMetadata,authBearing:l,responseKind:Pi(n)})}return xi(m,{withMetadata:t.withMetadata,authBearing:l&&p,agentKeyAuth:l&&!!o,responseKind:Pi(n)})}buildHeaders(n){let i={Accept:"application/json","Content-Type":"application/json",...tt(n.bodyForSig,this.opts.apiBase),...n.extra};if(n.attachAuth){i.Authorization=Ni;let r=n.tokens;if(r?.agent_key)return i[Ca]=r.agent_key,i;let o=r?.access_token;o&&(i.Cookie=Zn([{name:ln,value:o}]))}return i}async refreshSingleFlight(){return this.refreshInFlight?this.refreshInFlight:(this.refreshInFlight=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight)}async adoptConcurrentlyRotatedTokens(n){let t;try{t=await this.opts.tokenStore.get(this.opts.profile)}catch{return null}if(!t?.access_token||!t?.refresh_token||t.refresh_token===n.refresh_token)return null;if(Ve(this.opts.apiBase,t.api_base),t.agent_key)throw new s("auth.credential_changed","The stored credential for this profile changed to a scoped agent key while a session refresh was in flight; the refresh was abandoned rather than use it. Re-run the command \u2014 it will use the agent key. No re-authentication is needed.");return t}async doRefresh(){let n=await this.opts.tokenStore.get(this.opts.profile);if(!n?.access_token||!n?.refresh_token)throw new s("auth.token_expired",`No refresh token available; log in again \u2014 ${Fe()}.`);if(Ve(this.opts.apiBase,n.api_base),n.agent_key)throw new s("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=Zn([{name:ln,value:n.access_token},{name:Qn,value:n.refresh_token}]),r=tt("",this.opts.apiBase);h({type:"request",method:"POST",url:t,refresh:!0});let o=new AbortController,a=!1,c=setTimeout(()=>{a=!0,o.abort()},1e4),l;try{l=await fetch(t,{method:"POST",headers:{Accept:"application/json",Cookie:i,...r},signal:o.signal,redirect:"manual"})}catch(m){throw h({type:"refresh",ok:!1}),new s("transport.network",a&&m instanceof Error&&m.name==="AbortError"?`Token refresh against ${Y(t)} timed out after 10s with no response.`:`Network error during token refresh against ${Y(t)}: ${m instanceof Error?m.message:String(m)}`)}finally{clearTimeout(c)}h({type:"response",status:l.status,durationMs:0});try{await Ui(l)}catch(m){throw h({type:"refresh",ok:!1}),m}if(l.status!==200){let m=null;try{await un(l);let g=await Ha(l);await un(l,g),Fi(l.status,g),l.status===401&&(m=await this.adoptConcurrentlyRotatedTokens(n))}catch(g){throw h({type:"refresh",ok:!1}),g}if(m)return h({type:"refresh",ok:!0,adopted:!0}),m;throw h({type:"refresh",ok:!1}),new s("auth.token_expired",`Refresh token was rejected; re-authenticate \u2014 ${Fe()}.`,{status:l.status})}let u=wi(l.headers),p=et(u,ln),f=et(u,Qn);if(!p||!f)throw h({type:"refresh",ok:!1}),new s("auth.token_expired","Refresh response did not include new access/refresh cookies.");let y={...n,access_token:p,refresh_token:f};return await this.opts.tokenStore.set(this.opts.profile,y),h({type:"refresh",ok:!0}),y}},Ba=["/secure","/api/secure","/v1/secure","/api/v1/secure"];function Di(e){let n=e.split(/[?#]/,1)[0];return Ba.some(t=>n===t||n.startsWith(`${t}/`))}var Ua=[/^\/(api\/)?(v1\/)?public\/businesses\/payments?(\/|$)/,/^\/(api\/)?(v1\/)?public\/businesses\/transactions?(\/|$)/];function at(e){let n=e.split(/[?#]/,1)[0];return Ua.some(t=>t.test(n))}function Da(e){return Di(e)||at(e)}async function xi(e,n={}){await Ui(e);let t=e.status>=200&&e.status<300;t||await un(e);let i=n.responseKind??"mutation",o=await ot(e,t?i==="query"?Ra:Ia:rt,{oversizeKind:t?i==="query"?"successful-query":"successful-mutation":"backend-envelope"});t||await un(e,o);let a=null;if(o.length>0)try{a=JSON.parse(o)}catch{a={raw:o}}if(e.status>=200&&e.status<300){if(n.withMetadata){let l={};return e.headers.forEach((u,p)=>{l[p]=u}),{status:e.status,headers:l,body:a}}return a}let c=Ka(a)??`HTTP ${e.status}`;if(Fi(e.status,a),Ma(e.status,a,n),e.status===401){if(n.agentKeyAuth)throw new s("auth.token_expired","Agent key was rejected (expired or revoked). Re-run `allscale device-login` to mint a new scoped key.",{status:401,body:a});let l=n.authBearing?"auth.token_expired":"input.invalid";throw new s(l,c,{status:401,body:a})}throw e.status===403?new s("auth.permission_denied",c,{status:403,body:a}):e.status===404?new s("not_found",c,{status:404,body:a}):e.status===429?new s("rate_limited",c,{status:429,body:a}):e.status>=500?new s("backend.internal",c,{status:e.status,body:a}):new s("input.invalid",c,{status:e.status,body:a})}function Pi(e){if(e.responseKind)return e.responseKind;let n=(e.method??"GET").toUpperCase();return n==="GET"||n==="HEAD"?"query":"mutation"}var $a=2014,Bi=2004;function $i(e,n){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!="object")return!1;let i=t.code;return i===n||i===String(n)}function Fa(e){return $i(e,$a)}function Ma(e,n,t){if(!(e>=200&&e<300)&&t.authBearing&&!(e===401&&t.agentKeyAuth)&&$i(n,Bi))throw new s("auth.token_expired",`The API rejected this credential as invalid. Re-authenticate with ${Fe()} and retry. If that does not help, upgrade the CLI \u2014 the API may have rotated the client credential this build carries.`,{status:e,backend_code:Bi})}var Ga=1e4;async function Ha(e,n=Ga){if(e.status>=200&&e.status<300)return"";try{return await ot(e,rt,{timeoutMs:n})}catch{return""}}function Fi(e,n){if(!(e>=200&&e<300)&&Fa(n))throw new s("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"?Ii(n):n})}function Ka(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 Ja=/^\/(api\/)?(v1\/)?public\//;function re(e,n={}){let t=typeof n.pathHint=="string"?n.pathHint:"",i=t&&Ja.test(t),r=t&&at(t),o=i&&!r&&!n.forceAuth;if(e.token)return new ie({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit,override:{access_token:e.token}});if(o)return new ie({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});try{return new ie({apiBase:e.apiBase,tokenStore:an({insecureStorage:e.insecureStorage}),profile:e.profile,profileExplicit:e.profileExplicit})}catch(a){if(r)return new ie({apiBase:e.apiBase,tokenStore:sn(),profile:e.profile,profileExplicit:e.profileExplicit});throw a}}var Mi=[{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_contact_by_email",kind:"query",description:"Look up the contact card of the business whose login email is given. Used to fill the invoice header's From: block with the same name/email/phone the web editor shows.",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:"BusinessContact",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:"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}],Gi=[{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:"BusinessContact",kind:"OBJECT",description:null,fields:[{name:"name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Display name of the business's user account."},{name:"email",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Login email of the business's user account."},{name:"contact_name",type:{kind:"NON_NULL",name:null,ofType:{kind:"SCALAR",name:"String",ofType:null}},description:"Contact person the business presents on its invoices. Preferred over `name` when both are set."},{name:"contact_phone",type:{kind:"SCALAR",name:"String",ofType:null},description:"Contact phone the business presents on its invoices. Null when the business has not set one."}]},{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 pn=new Set(["SCALAR","ENUM"]),qa=new Set(["password","password_hash","totp_secret","credential","credentials","private_key","encryption_key"]),Ya=[/(^|_)password(_|$)/i,/(^|_)secret(_|$)/i,/(^|_)token(_|$)/i,/(^|_)api[_-]?key(_|$)/i,/(^|_)signing[_-]?key(_|$)/i,/(^|_)private[_-]?key(_|$)/i,/(^|_)credential(_|$)/i],Va=new Set(["CreateClaimLinkResult.claim_token","StoreCreateResult.api_secret"]),ja=new Map([["StoreCreateResult.store",["id","name"]],["CreateClaimLinkResult.claim_link",["id","token_symbol","status"]]]),Wa=new Set(["token_symbol"]),za=new Set;function st(e,n){return za.has(`${e}.${n}`)}function lt(e){return Wa.has(e.toLowerCase())?!1:qa.has(e)?!0:Ya.some(n=>n.test(e))}function Xa(e,n){return Va.has(`${e}.${n}`)}function ct(e){return e.kind==="NON_NULL"&&e.ofType?`${ct(e.ofType)}!`:e.kind==="LIST"&&e.ofType?`[${ct(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 Qa(e,n){let t=n.find(a=>a.name===e);if(!t||t.kind==="SCALAR"||t.kind==="ENUM")return"";if(t.kind==="UNION")return"__typename";let i=t.fields??[];if(i.length===0)return"";let r=[],o=!1;for(let a of i){let c=Pe(a.type);if(!c)continue;if(pn.has(c.kind)){if(lt(a.name)&&!Xa(e,a.name)||st(e,a.name))continue;r.push(a.name);continue}let l=ja.get(`${e}.${a.name}`);if(l){let u=n.find(m=>m.name===c.name),p=new Set((u?.fields??[]).filter(m=>{let g=Pe(m.type);return g!==null&&pn.has(g.kind)&&!lt(m.name)}).map(m=>m.name)),f=l.filter(m=>!p.has(m));if(f.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${f.join(", ")}] that are not selectable scalars on ${c.name}; fix the entry or the public registry.`);let y=l.filter(m=>st(c.name,m));if(y.length>0)throw new Error(`EXPLICIT_NESTED_DEFAULT_FIELDS["${e}.${a.name}"] names field(s) [${y.join(", ")}] that DEFAULT_SELECTION_EXCLUSIONS keeps out of default selections on ${c.name}; drop the field from the nested entry, or remove the exclusion if it is no longer true.`);r.push(`${a.name} { ${l.join(" ")} }`);continue}if(!o&&a.name==="items"&&a.type.kind==="NON_NULL"&&a.type.ofType?.kind==="LIST"){let u=Za(a.type)?.name;if(u){let p=es(u,n);p&&r.push(`items { ${p} }`),o=!0}}}return r.length>0?r.join(" "):"__typename"}function Za(e){return Pe(e)}function es(e,n){let t=n.find(o=>o.name===e);if(!t||t.kind==="UNION")return"__typename";let i=t.fields??[],r=[];for(let o of i){let a=Pe(o.type);if(a&&pn.has(a.kind)){if(lt(o.name)||st(e,o.name))continue;r.push(o.name)}}return r.length>0?r.join(" "):"__typename"}function Hi(e,n,t){let i=ns(e.name),r=e.args.map(p=>{let f=ct(p.type);return p.defaultValue!==null&&p.defaultValue!==void 0?`$${p.name}: ${f} = ${p.defaultValue}`:`$${p.name}: ${f}`}).join(", "),o=e.args.map(p=>`${p.name}: $${p.name}`).join(", "),a=r.length>0?`${e.kind} ${i}(${r})`:`${e.kind} ${i}`,c=o.length>0?`${e.name}(${o})`:e.name,l=Pe(e.returnType),u;if(l&&pn.has(l.kind))u=c;else{let p=t&&t.trim().length>0?t.trim():l&&Qa(l.name,n)||"__typename";u=`${c} { ${p} }`}return`${a} { ${u} }`}function Ki(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 Ji(e,n,t){return e.find(i=>i.kind===n&&i.name===t)??null}function qi(e){if(!e||typeof e!="object")return!1;let n=e.errors;return Array.isArray(n)&&n.length>0}function Yi(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 ns(e){return e.replace(/[^_0-9A-Za-z]/g,"_")}var ts=new Set;var is=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","claim_link:read_only","claim_link:all","transaction:read_only","transaction:all","store:read_only","store:all","wallet:read_only","wallet:all"]),dt=new Set(["invoice:read_only","invoice:all","contact:read_only","contact:all","transaction:read_only","wallet:read_only","claim_link:read_only","claim_link:all","store:read_only","store:all"]),ut=new Set(["payroll","admin:user","admin:org","admin:audit"]);function fn(e){let n=e.lastIndexOf(":");return n===-1?e:e.slice(0,n)}function Vi(e,n){if(e===n)return!0;let t=":read_only";return n.endsWith(t)&&e===`${n.slice(0,-t.length)}:all`}var rs=new Set(["cli_op:all"]),os=new Set([...rs].map(fn));var Hc=new Set([...[...is,...dt,...ts].map(fn),...ut,...os]);var as={payments:"invoice:read_only",payment:"invoice:read_only",sender_payments:"invoice:read_only",recipient_payments:"invoice:read_only",business_contact_by_email:"invoice:read_only",create_payment:"invoice:all",update_payment:"invoice:all",contact_by_email:"contact:read_only",contact:"contact:read_only",contacts:"contact:read_only",create_contact:"contact:all",transaction:"transaction:read_only",my_transactions:"transaction:read_only",business_transaction_records:"transaction:read_only",activities:"transaction:read_only",business_wallets:"wallet:read_only",business_invoice:"payroll:read_only",auto_payout_session_status:"store:read_only",create_store:"store:all",my_claim_links:"claim_link:read_only",claim_link:"claim_link:read_only",claim_link_fee_preview:"claim_link:read_only",claim_link_limits:"claim_link:read_only",create_claim_link:"claim_link:all",claim_link_funding_by_idempotency_key:"claim_link:all"},ss={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"},ls=/API key scope not granted:\s*requires\s+(.+?),\s*key has\s+(.+?)\.?\s*$/i,cs=/is not available to API keys/i,ji=/^[a-z_]+(?::[a-z_]+)*:[a-z_]+$/;function Wi(e){if(typeof e!="string")return;let n=ls.exec(e);if(!n)return;let t=n[1].trim(),i=n[2].trim(),r=cs.test(t),o=!r&&ji.test(t)?t:void 0,a;if(i.toLowerCase()==="none")a=[];else{let c=i.split(",").map(l=>l.trim()).filter(l=>ji.test(l));a=c.length>0?c:void 0}if(!(o===void 0&&!r))return{required:o,granted:a,notAvailableToKeys:r}}function zi(e){let n=ss[e];if(n!==void 0)return{ungrantableReason:n};let t=as[e];if(t!==void 0)return{scope:t}}function Xi(e){if(ut.has(fn(e)))return{kind:"ungrantable"};for(let n of dt)if(Vi(n,e))return{kind:"approval_screen"};return{kind:"otp_login_only"}}var ds=new Set([3e3,3200,3300,3400,3500,3600,4e3,4100,4200,4300,4400,4600,4700,4800,4900,4901,5e3,5100,5150,5200,5300,5400,5500,5600,6050,8300,8301,8302,8306]);function Zi(e,n){let t=er(e),i={graphql_error_count:us(e.errors),...t===void 0?{}:{backend_code:t}};if(t===2102)throw ps(e,n,i);if(t===429)throw new s("rate_limited",`GraphQL ${n.kind} '${n.operationName}' was rate limited. Retry after a backoff.`,i);if(t===1002)throw new s("auth.permission_denied",`The signed-in account is not permitted to perform GraphQL ${n.kind} '${n.operationName}'. This is a role or ownership restriction, not a missing agent-key scope \u2014 re-authorizing will not grant it.`,i);if(t!==void 0&&ds.has(t))throw new s("not_found",`GraphQL ${n.kind} '${n.operationName}' could not find the requested resource.`,i);if(qi(e))throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' returned errors: ${Yi(e)}`,i);if(t!==void 0)throw new s("input.invalid",`GraphQL ${n.kind} '${n.operationName}' failed with backend code ${t}.`,i)}function er(e){let n=Qi(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=Qi(i.code);if(r!==void 0)return r}}function Qi(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 us(e){return Array.isArray(e)?e.length:e==null?0:1}function ps(e,n,t){let i=`GraphQL ${n.kind} '${n.operationName}'`,r={...t,operation:n.operationName},o=Wi(fs(e,er(e))),a=zi(n.operationName),c=o?.notAvailableToKeys===!0,l=o?.required??a?.scope,u=o?.granted,p=u===void 0?"":` This key holds ${u.length>0?u.join(", "):"no scopes"}.`;if(c||a?.ungrantableReason!==void 0){let f=a?.ungrantableReason!==void 0?`: ${a.ungrantableReason}`:"";return new s("auth.permission_denied",`${i} is not available to agent keys${f}. Re-authorizing will NOT help \u2014 no scope grants it.${p} Use a command that does not need it, or perform this action in the AllScale dashboard.`,{...r,missing_scopes:[],...u===void 0?{}:{granted_scopes:u},ungrantable:!0})}if(l!==void 0){let f=Xi(l),y=f.kind==="ungrantable"?`\`${l}\` 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 \`${Ae()}\` with \`--scopes ${l}\`.`:`The browser approval screen does not offer \`${l}\`, so \`device-login\` cannot grant it \u2014 use \`${Ae()}\` with \`--scopes ${l}\`.`;return new s("auth.permission_denied",`The current agent key lacks \`${l}\`, required by ${i}.${p} ${y}`,{...r,missing_scopes:[l],...u===void 0?{}:{granted_scopes:u},...f.kind==="ungrantable"?{ungrantable:!0}:{}})}return new s("auth.permission_denied",`The current agent key does not have the scope required by ${i}.${p} Re-run \`allscale device-login\` (or \`${Ae()}\`) and grant the required scope.`,r)}function fs(e,n){let t=e.errors;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let i=r=>{if(r===null||typeof r!="object")return;let o=r.message;return typeof o=="string"?o:void 0};if(n!==void 0)for(let r of t){if(r===null||typeof r!="object")continue;let o=r.extensions;if(!o||typeof o!="object")continue;let a=o.code;if(a===n||typeof a=="string"&&Number(a)===n){let l=i(r);if(l!==void 0)return l}}for(let r of t){let o=i(r);if(o!==void 0)return o}return""}async function pt(e,n,t,i,r={}){let o=Ji(Mi,n,t);if(!o)throw new s("input.invalid",`No ${n} named '${t}' in the schema. Run \`allscale operations --kind ${n}\` to list options.`);let a=Ki(o,i);if(!a.ok)throw new s("input.invalid",`Missing required variables for ${t}: ${a.missing.join(", ")}`,{required:a.missing});let c=Hi(o,Gi,r.selection);return ms(e,{...r,kind:n,operationName:o.name,document:c,variables:i})}async function ms(e,n){n.showDoc&&process.stderr.write(`${n.document}
|
|
18
|
+
`);let t=re(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 fr=require("crypto"),E=require("process");var oe=/^0x[0-9a-fA-F]{64}$/,ys=["wallet.bridge_timeout","wallet.bridge_op_expired","wallet.bridge_invalid_response","wallet.transaction_reverted","wallet.transaction_status_unknown"];function nr(e){return typeof e=="string"&&ys.includes(e)}var D={CLI_OP_NOT_FOUND:7400,CLI_OP_EXPIRED:7401,CLI_OP_UNAUTHORIZED:7402,CLI_OP_UNKNOWN_TYPE:7403,CLI_OP_INVALID_PAYLOAD:7404,CLI_OP_SELF_TRANSFER:7405,CLI_OP_INSUFFICIENT_BALANCE:7406,CLI_OP_PREFLIGHT_UNAVAILABLE:7407,CLI_OP_WALLET_STATE_CONFLICT:7408,CLI_OP_TOKEN_CONSUMED:7411},hs=new Set(Object.values(D));async function tr(e,n,t){let{body:i,headers:r}=await Ss(e,"/api/secure/wallet/cli_op_init",{op:n,payload:t},"cli_op_init");return{...i,server_now_ms:gs(r)}}function gs(e){let n=e.date??e.Date??Object.entries(e).find(([i])=>i.toLowerCase()==="date")?.[1];if(n===void 0)return null;let t=Date.parse(n);return Number.isFinite(t)?t:null}async function ft(e,n){return _s(e,"/api/secure/wallet/cli_op_result",{result_token:n},"cli_op_result")}async function _s(e,n,t,i){let r;try{r=await e.request({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=ir(o,i);if(a!==null)throw a}throw o}return rr(r,i)}async function Ss(e,n,t,i){let r;try{r=await e.requestWithMetadata({method:"POST",path:n,body:t})}catch(o){if(o instanceof s){let a=ir(o,i);if(a!==null)throw a}throw o}return{body:rr(r.body,i),headers:r.headers??{}}}function ir(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||!hs.has(r))return null;let o=typeof i.errors=="string"?i.errors:typeof i.message=="string"?i.message:e.message;return or(r,o,n)}function rr(e,n){if(e.code!==void 0&&e.code!==0)throw or(e.code,e.message,n);if(e.data===void 0)throw new s("backend.internal",`Broker ${n} returned no data envelope`,{envelope:e});return e.data}function or(e,n,t){let i=n??`Broker ${t} returned code ${e}`;switch(e){case D.CLI_OP_NOT_FOUND:return new s("not_found",i,{broker_code:e});case D.CLI_OP_EXPIRED:return new s("wallet.bridge_op_expired","The confirmation link expired before it was confirmed; raising --bridge-timeout cannot extend a link past the broker's op TTL.",{broker_code:e,broker_message:i});case D.CLI_OP_UNAUTHORIZED:return new s("auth.permission_denied",i,{broker_code:e});case D.CLI_OP_UNKNOWN_TYPE:return new s("input.invalid",i,{broker_code:e});case D.CLI_OP_INVALID_PAYLOAD:case D.CLI_OP_SELF_TRANSFER:case D.CLI_OP_INSUFFICIENT_BALANCE:case D.CLI_OP_WALLET_STATE_CONFLICT:return new s("input.invalid",i,{broker_code:e});case D.CLI_OP_PREFLIGHT_UNAVAILABLE:return new s("backend.internal",i,{broker_code:e});case D.CLI_OP_TOKEN_CONSUMED:return new s("input.invalid",i,{broker_code:e});default:return new s("backend.internal",i,{broker_code:e})}}var lr=require("child_process");function ar(e){let n=e?.trim();return n?n!=="0"&&n.toLowerCase()!=="false":!1}var ks=["JENKINS_URL","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION"];function Ts(e,n,t,i){if(ar(e.CI)||ks.some(a=>ar(e[a])))return"ci";let o=n!=="darwin"&&n!=="win32"&&!!e.DISPLAY;return(e.SSH_CONNECTION||e.SSH_TTY)&&!o?"ssh":t===!0||i===!0?null:"no-tty"}function As(e){let n=" Use `allscale otp-login` or `allscale device-login --no-browser`, which are built for headless and CI hosts.",t=" Set BROWSER=<launcher> to force a launch anyway.";return e==="ci"?"Refusing to open a browser: this looks like a CI or automation run, so there is nobody to complete the sign-in."+n+t:e==="ssh"?"Refusing to open a browser: this is an SSH session with no X11 forwarding, so the tab would open on the remote machine's desktop rather than on your screen."+n+t:"Refusing to open a browser: no terminal is attached (neither stdin nor stderr is a TTY), so there is nobody to complete the sign-in. Re-run from a terminal."+n+t}async function cr(e,n={}){if(!_n(e))throw new s("input.invalid",`Refusing to launch browser for untrusted origin: ${v(e)}`);let t=n._env??process.env,i=n._platform??process.platform,r=t.BROWSER?.trim();if(r&&r.toLowerCase()==="none")throw new s("wallet.requires_browser_auth","BROWSER=none is set. This command needs to open a browser tab. Re-run on a host with a graphical environment, or use a CLI token that was minted on such a host.");let o=r?null:Ts(t,i,n._stdinIsTTY??process.stdin.isTTY,n._stderrIsTTY??process.stderr.isTTY);if(o)throw new s("wallet.requires_browser_auth",As(o));if(i==="linux"&&!t.DISPLAY&&!r)throw new s("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 a=ws(i,r);await Ls(a.command,[...a.args,e])}function ws(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 Ls(e,n){return new Promise((t,i)=>{let r;try{r=(0,lr.spawn)(e,n,{detached:!0,stdio:"ignore"})}catch(a){i(sr(e,a));return}let o=!1;r.once("error",a=>{o||(o=!0,i(sr(e,a)))}),setImmediate(()=>{o||(o=!0,r.unref(),t())})})}function sr(e,n){return new s("wallet.requires_browser_auth",`Failed to launch browser via '${e}': ${n.message}. Re-run on a host with a graphical environment.`)}var dr=C(require("http"));var bs=9e4,Es=16*1024;function ur(e){let n=e.timeoutMs??bs;return new Promise((t,i)=>{let r=!1,o=!1,a=null,c,l,u=new Promise((f,y)=>{c=f,l=y}),p=dr.createServer((f,y)=>{Ns(f,y,{state:e.state,expectedOrigin:e.expectedOrigin,isConsumed:()=>r,tryConsume:()=>r?!1:(r=!0,!0),onSuccess:m=>{a&&clearTimeout(a),c(m),p.close()}})});p.on("error",f=>{let y=new s("transport.network",`Loopback listener error: ${f.message}`);o?l(y):i(y),a&&clearTimeout(a)}),p.listen({host:"127.0.0.1",port:e.port??0},()=>{let f=p.address();if(!f||typeof f=="string"){p.close(),i(new s("transport.network","Failed to read loopback listener port"));return}let y=e.deadlineAtMs!=null?e.deadlineAtMs-Date.now():null,m=y!=null?Math.max(1,Math.min(n,y)):n,g=y!=null&&y<=n;a=setTimeout(()=>{l(new s("wallet.bridge_timeout",`Bridge timed out after ${m}ms waiting for browser callback.`,{bridge_deadline:g?"op_ttl":"duration"})),p.close()},m),a.unref?.(),o=!0,t({port:f.port,awaitResult:u,close:()=>{a&&clearTimeout(a),p.close()}})})})}function Ns(e,n,t){let i=e.headers.origin??"";if(e.method==="OPTIONS"){if(i===t.expectedOrigin){let c={"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"&&(c["Access-Control-Allow-Private-Network"]="true"),n.writeHead(204,c)}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=[],a=!1;e.on("data",c=>{if(!a){if(r+=c.length,r>Es){a=!0,n.writeHead(413,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"payload_too_large"}));return}o.push(c)}}),e.on("end",()=>{if(a)return;let c=Buffer.concat(o).toString("utf-8"),l;try{l=JSON.parse(c)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_json"}));return}if(!l||typeof l!="object"){n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"invalid_body"}));return}let u=l,p=typeof u.state=="string"?u.state:"",f=typeof u.result_token=="string"?u.result_token:void 0,y=u.result_data!==void 0&&u.result_data!==null&&typeof u.result_data=="object"&&!Array.isArray(u.result_data)?u.result_data:void 0;if(!Cs(p,t.state)){n.writeHead(403,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"state_mismatch"}));return}if(f===void 0&&y===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:y})}),e.on("error",()=>{a||(a=!0)})}function Cs(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 mt(e){try{return JSON.parse(e),!0}catch{return!1}}function pr(){let e=process.stdin,n="",t=!1,i=()=>{},r=250,o=null,a=()=>{o&&(clearTimeout(o),o=null)},c=()=>{a(),o=setTimeout(()=>{t||(l(),i(n.trim()))},r),o.unref?.()},l=()=>{t=!0,a(),e.off("data",u),e.off("end",p),e.off("error",f),e.pause()},u=m=>{if(t)return;a(),n+=m.toString();let g=n.trim(),_=n.length-n.trimStart().length,N=n.indexOf(`
|
|
19
|
+
`,_),R=N===-1?"":n.slice(_,N).trim();if(g.startsWith("{")){if(mt(g)){l(),i(g);return}if(N===-1){c();return}if(!mt(R)&&!R.endsWith("}")){let S=n.slice(N+1),B=S.split(`
|
|
20
|
+
`).find(G=>G.trim()!=="")??"";if(R==="{"&&(!/\S/.test(S)||/^\s*"[^"]*"\s*:/.test(S)||/^\s*"[^"]*$/.test(B))){c();return}}l(),i(mt(R)?R:n.slice(_).trim());return}if(N!==-1){l(),i(R);return}else!g&&n.includes(`
|
|
21
|
+
`)&&(l(),i(""))},p=()=>{if(t)return;let m=n.trim();if(!m){l();return}l(),i(m)},f=()=>{t||l()},y=new Promise(m=>{i=m});return e.resume(),e.on("data",u),e.on("end",p),e.on("error",f),{promise:y,cancel:()=>{t||l()}}}function Os(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 mr(e){let n=re(e.ctx),t=e.browserBase??e.ctx.apiBase,i=Bs(t),r=e._openBrowser??cr,o=e._startListener??ur,a=e.mode??"ack",c=e._readPaste!==void 0||process.stdin.isTTY===!0,l=(0,fr.randomBytes)(32).toString("hex"),u=Date.now(),p=await tr(n,e.op,e.payload);h({type:"bridge_init",op_id:p.op_id,expires_at:p.expires_at});let y=p.server_now_ms!=null?p.expires_at*1e3-p.server_now_ms-1e3:null,m=2147483647,_=new Set(["withdraw_token","create_claim_link"]).has(e.op)?24e4:6e4,N=9e5,R=6e4,S=y!=null&&Number.isFinite(y)&&y>0?y:null,B=Math.max(0,Math.round((S??0)/1e3)),L=e.timeoutMs!=null&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:null,G=L!=null&&L<=m?L:null,$,H,U=!1,O=!1,F=!1;if(S!=null){let b=Math.min(S,m),K=S>m;G!=null&&G<b?($=G,H="caller"):($=b,H=K?"timer_ceiling":"op_ttl",U=!K&&L!=null&&L>b)}else{let b=p.expires_at*1e3-u,K=Number.isFinite(b)?Math.min(Math.max(b,R),N):N,ae=G??_;ae>K?($=K,H="op_ttl_unverified",O=L!=null&&L>K):($=ae,H=G!=null?"caller":"unknown_ttl"),F=L!=null&&G==null}let Be=H==="op_ttl",T=S!=null?`~${B}s`:"unknown";E.stderr.write(`Bridge op registered (op_id=${p.op_id}, op TTL ${T}, waiting up to ${Math.round($/1e3)}s for confirmation).
|
|
22
|
+
`),U&&E.stderr.write(`Note: the confirmation wait of ${L}ms is longer than the confirmation link's remaining life (${Math.round($/1e3)}s, from the server's stated expiry and its own clock), so the wait was capped at that.
|
|
23
|
+
`),O&&E.stderr.write(`Note: the confirmation wait of ${L}ms is longer than the confirmation link's remaining life (~${Math.round($/1e3)}s), so the wait was capped at that. No server-relative TTL was available, so that figure is the link's stated expiry read against THIS machine's clock \u2014 approximate: short if your clock runs fast, long if it runs slow.
|
|
24
|
+
`),F&&E.stderr.write(`Note: the requested confirmation wait of ${L}ms is outside the usable range (1ms-${m}ms), so it was ignored and the wait fell back to ~${Math.round($/1e3)}s.
|
|
25
|
+
`);let ge=await o({state:l,...S!=null?{deadlineAtMs:u+S}:{},expectedOrigin:i,timeoutMs:$}),Fr=ge.awaitResult.then(b=>({source:"loopback",...b}),b=>({source:"listener_error",error:b})),Mr=Date.now(),kt=setInterval(()=>{let b=Math.floor((Date.now()-Mr)/1e3);E.stderr.write(`Still waiting for confirmation\u2026 (${b}s elapsed)
|
|
26
|
+
`)},15e3);kt.unref?.();let Ue,hn=e.signal===void 0?void 0:Os(e.signal);try{let b=xs(t,{op_id:p.op_id,port:ge.port,state:l});h({type:"bridge_browser_open",url:b});let K=a==="ack"?"confirmation token":e.acceptBareTxHashPaste===!1?"full result JSON":"result";if(E.stderr.write(c?e.autoOpen===!1?`
|
|
25
27
|
Confirm this in your browser. Open the URL below on any device where
|
|
26
28
|
you're signed in to AllScale (local auto-open is disabled):
|
|
27
29
|
|
|
@@ -41,26 +43,23 @@ back from another device:
|
|
|
41
43
|
|
|
42
44
|
${b}
|
|
43
45
|
|
|
44
|
-
`),e.autoOpen===!1)
|
|
45
|
-
`);else try{await r(b),
|
|
46
|
-
`)}catch{
|
|
47
|
-
`)}
|
|
46
|
+
`),e.autoOpen===!1)E.stderr.write(`(browser auto-open skipped \u2014 use the link above)
|
|
47
|
+
`);else try{await r(b),E.stderr.write(`(opened in your default browser)
|
|
48
|
+
`)}catch{E.stderr.write(`(no local browser to open \u2014 use the link above)
|
|
49
|
+
`)}c?E.stderr.write(`The CLI continues automatically once the browser confirms. If it can't
|
|
48
50
|
reach this machine (e.g. you opened the link elsewhere over SSH), copy
|
|
49
|
-
the ${
|
|
51
|
+
the ${K} the page shows, paste it here, and press Enter:
|
|
50
52
|
|
|
51
|
-
`):
|
|
53
|
+
`):E.stderr.write(`stdin is non-interactive; waiting for the browser callback.
|
|
52
54
|
|
|
53
|
-
`),
|
|
54
|
-
`),await
|
|
55
|
-
`),await
|
|
56
|
-
`),{ack:i,result_data:t.result_data}}if(!t.result_data)throw new
|
|
57
|
-
`),{result_data:t.result_data}}async function
|
|
58
|
-
`),{ack:
|
|
59
|
-
`),{result_data:
|
|
60
|
-
`)
|
|
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
|
-
`)
|
|
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}};
|
|
55
|
+
`),c&&(Ue=e._readPaste?{promise:e._readPaste(),cancel:()=>{}}:pr());let ae=[Fr];Ue!==void 0&&ae.push(Ue.promise.then(Gr=>({source:"paste",line:Gr}))),hn!==void 0&&ae.push(hn.promise);let se=await Promise.race(ae);if(se.source==="aborted")throw new Error("Bridge wait cancelled after authoritative completion.");if(se.source==="listener_error")throw Rs(se.error,Be);if(se.source==="loopback")return E.stderr.write(`Browser returned result; processing\u2026
|
|
56
|
+
`),await Is(n,a,se);let De=se.line.trim();if(!De)throw new s("wallet.bridge_invalid_response","No value was pasted. The browser operation may still complete; inspect its result before retrying.");if(a==="ack"&&De.startsWith("{"))throw new s("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(a==="ack"&&/\s/.test(De))throw new s("wallet.bridge_invalid_response","Pasted value isn't a confirmation token (it contains whitespace/newlines). Copy the single-line token the /cli page shows, not the result JSON.");return E.stderr.write(`Received pasted ${K}; processing\u2026
|
|
57
|
+
`),await vs(n,a,De,e.acceptBareTxHashPaste!==!1)}finally{clearInterval(kt),hn?.cleanup(),Ue?.cancel(),ge.close()}}function Rs(e,n){let i=(e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details.bridge_deadline:void 0)==="op_ttl"?!0:n;return e instanceof s&&e.code==="wallet.bridge_timeout"&&i?new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} That was the confirmation link's own lifetime, so it has expired or is about to; a longer --bridge-timeout cannot extend a link past its lifetime.`,e.details):e instanceof s&&(e.code==="wallet.bridge_timeout"||e.code==="wallet.bridge_op_expired"||e.code==="wallet.bridge_invalid_response")?e:new s("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 Is(e,n,t){if(n==="ack"){if(!t.result_token)throw new s("wallet.bridge_invalid_response","Browser returned no result_token; CLI requested ack mode.");h({type:"bridge_result_received",source:"loopback"});let i=await ft(e,t.result_token);return h({type:"bridge_verified",op_id:i.op_id,source:"loopback"}),E.stderr.write(`Verified by broker.
|
|
58
|
+
`),{ack:i,result_data:t.result_data}}if(!t.result_data)throw new s("wallet.bridge_invalid_response","Browser returned no result_data; CLI requested data mode.");return h({type:"bridge_result_received",source:"loopback"}),h({type:"bridge_data_received",source:"loopback"}),E.stderr.write(`Result received from browser.
|
|
59
|
+
`),{result_data:t.result_data}}async function vs(e,n,t,i){if(n==="ack"){h({type:"bridge_result_received",source:"paste"});let o=await ft(e,t);return h({type:"bridge_verified",op_id:o.op_id,source:"paste"}),E.stderr.write(`Verified by broker.
|
|
60
|
+
`),{ack:o}}let r;try{r=Ps(t,{acceptBareTxHashPaste:i})}catch(o){throw o instanceof s&&o.code==="input.invalid"?new s("wallet.bridge_invalid_response",o.message):o}return h({type:"bridge_result_received",source:"paste"}),h({type:"bridge_data_received",source:"paste"}),E.stderr.write(`Result accepted.
|
|
61
|
+
`),{result_data:r}}function xs(e,n){let t=new URL("/cli",yr(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()}function Ps(e,n={}){try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}if(n.acceptBareTxHashPaste!==!1&&oe.test(e))return{tx_hash:e};throw new s("input.invalid",n.acceptBareTxHashPaste===!1?"Paste the complete JSON result object from the /cli page. A bare transaction hash is not accepted for this operation because it cannot distinguish confirmed, reverted, or unknown status.":`Pasted value was neither a JSON result object nor a valid 0x\u2026 transaction hash (got ${e.length} characters).`)}function Bs(e){return yr(e).origin}function yr(e){if(!le(e))throw new s("input.invalid",`Refusing browser base ${v(e)}: bridge state and operation identifiers may only be sent to a trusted destination. ${_e}`);return new URL(e)}var hr=["outcome","transaction_hash","error_code"],Us=["transaction_hash","error_code"];function gr(e){if(e.outcome==="confirmed")return Us.some(i=>Object.prototype.hasOwnProperty.call(e,i))||typeof e.tx_hash!="string"||!oe.test(e.tx_hash)?null:{outcome:"confirmed",transactionHash:e.tx_hash};if(Object.keys(e).length!==hr.length||!hr.every(i=>Object.prototype.hasOwnProperty.call(e,i)))return null;let t=e.transaction_hash;return typeof t!="string"||!oe.test(t)?null:e.outcome==="failed"&&e.error_code==="transaction_reverted"?{outcome:"failed",transactionHash:t,errorCode:"transaction_reverted"}:e.outcome==="ambiguous"&&(e.error_code==="receipt_confirmation_timeout"||e.error_code==="receipt_confirmation_unavailable")?{outcome:"ambiguous",transactionHash:t,errorCode:e.error_code}:null}var W=C(require("fs")),_r=C(require("path")),Sr=require("crypto");var Ds="device_id";function kr(){let e=null,n=null;try{e=Ne(),n=_r.join(e,Ds)}catch{}try{if(n){let i=W.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,Sr.randomBytes)(16).toString("hex")}`;try{if(!e||!n)throw new Error("persistence unavailable");W.mkdirSync(e,{recursive:!0,mode:448}),W.writeFileSync(n,`${t}
|
|
63
|
+
`,{mode:384});try{W.chmodSync(n,384)}catch{}}catch{}return t}function Ar(e){return re(e,{pathHint:"/api/v1/public/businesses/payments"})}var Tr=3e4;function $s(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 Fs(e,n){if(e==null)return;let t=typeof e.code=="number"?e.code:0,i=$s(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),a=i??r,c=typeof e.code!="number"&&e.code!=="0"&&!!e.code,u=(e.code==null||e.code===""||e.code==="0"||e.code===0||e.code===!1)&&!!a;if(t!==0||c||u){let p=o??`${n} returned code ${String(e.code??t)}`;throw new s("backend.internal",p,{broker_code:e.code})}return e.data}async function yt(e,n,t,i,r){let o=r??re(e,{pathHint:n}),a=new AbortController,c=!1,l=setTimeout(()=>{c=!0,a.abort()},Tr);try{let u=await o.request({method:"POST",path:n,body:t,signal:a.signal});return Fs(u,i)}catch(u){throw c&&u instanceof s&&u.code==="transport.network"?new s("backend.internal",`${i} timed out after ${Tr/1e3}s with no response from the backend.`):u}finally{clearTimeout(l)}}function wr(e){let n=e.sender_email?.trim();return{sender_fingerprint:e.sender_fingerprint,...n?{sender_email:n}:{}}}async function Lr(e,n,t,i){let r=await yt(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents`,wr(t),"ensurePayIntent",i);if(!r)throw new s("backend.internal","ensurePayIntent: server returned success but no payment data.");if(!r.pay_intent)throw new s("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 s("backend.internal","ensurePayIntent: server returned a pay_intent with no usable id \u2014 unexpected server response.");return{...r.pay_intent,id:o}}async function br(e,n,t){await yt(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 Er(e,n,t,i,r){await yt(e,`/api/v1/public/businesses/payments/${encodeURIComponent(n)}/intents/${encodeURIComponent(t)}:confirm`,wr(i),"confirmPayIntent",r)}function Ms(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_timeout",`${e.message.replace(/\.?$/,".")} No signed payment came back within the deadline. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run \`allscale ${wn}\` to refresh the session, then retry.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function Gs(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_op_expired",`${e.message.replace(/\.?$/,".")} No signed payment came back before the link expired. Check your wallet/the transfer status BEFORE retrying: if the transfer already shows there, do NOT run this command again (give the ids below to support) \u2014 a blind retry would pay twice. If nothing was sent, re-run the command to get a fresh confirmation link; raising --bridge-timeout will not help, as the link cannot outlive the broker's op TTL.`,{...t.broker_code!==void 0?{broker_code:t.broker_code}:{},...n})}function Hs(e,n){let t=e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:{};return new s("wallet.bridge_invalid_response",`${e.message.replace(/\.?$/,".")} Check your wallet/the transfer 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 Nr(e,n){return!(e instanceof s)||!nr(e.code)?null:e.code==="wallet.bridge_timeout"?Ms(e,n):e.code==="wallet.bridge_op_expired"?Gs(e,n):Hs(e,n)}function Cr(e,n){let t=e instanceof s&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?e.details:null;return{...t?{broker_code:t.broker_code}:{},...n}}function ht(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 s("backend.internal",o,i)}function Ks(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 Ir(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 s("input.invalid",`Invoice '${r}' is a fiat currency invoice (payment_type 0) and cannot be paid with crypto from the CLI.`);let a=Ks(n);if(a==="unsupported")throw new s("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(a!==null&&t!==null&&t!==a)throw new s("input.invalid",`This invoice must be paid in ${Ce(a)}, but --stable-coin ${i} was requested. Re-run without --stable-coin to use the invoice's coin.`);if(a===null&&t===null)throw new s("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:a??t,autoSelected:a!==null&&t===null}}function Js(e){return ri(e)}function _t(e,n){let t=e.filter(r=>r.chain===n);if(t.length!==1)return null;let i=t[0].address;return!i||!ii(i)||Js(i)?null:i}function vr(e,n){let t=[...new Set(n.map(i=>i.chain))];if(t.length===0)throw new s("input.invalid","This invoice exposes no receiving wallet to pay to.");if(e){let i=ni(e);if(i===null)throw new s("input.invalid",`--chain '${e}' is not supported.`);if(!t.includes(i))throw new s("input.invalid",`The invoice has no receiving wallet on ${M(i)}. Available: ${t.map(r=>M(r)).join(", ")}.`);return i}if(t.length===1)return t[0];throw new s("input.invalid",`This invoice can be paid on multiple chains (${t.map(i=>M(i)).join(", ")}). Pass --chain to choose one.`)}var gt=128,mn=String(Number.MAX_SAFE_INTEGER),qs=/^(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;function Ys(e){if(e.length===0)return{kind:"invalid"};if(e.length>gt)return{kind:"normalization_limit"};let n=qs.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 a=BigInt(n[3]??"0"),c=r.slice(o),l=BigInt(t.length)+a-BigInt(o),u=BigInt(c.length);if((l<=0n?2n-l+u:l>=u?l:u+1n)>BigInt(gt))return{kind:"normalization_limit"};if(l<=0n)return{kind:"ok",amount:`0.${"0".repeat(Number(-l))}${c}`};if(l>=u)return{kind:"ok",amount:`${c}${"0".repeat(Number(l-u))}`};let f=Number(l);return{kind:"ok",amount:`${c.slice(0,f)}.${c.slice(f)}`}}function Vs(e){let[n,t=""]=e.split(".");return n.length!==mn.length?n.length>mn.length:n!==mn?n>mn:/[1-9]/.test(t)}function St(e){let n=e==null?"":typeof e=="number"?String(e):e,t=Ys(n);if(t.kind==="normalization_limit")throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} cannot safely normalize within the ${gt}-character amount limit.`);if(t.kind==="invalid")throw new s("input.invalid",`The invoice has no positive payable amount (got ${JSON.stringify(e)}).`);if(Vs(t.amount))throw new s("input.invalid",`Invoice amount ${JSON.stringify(e)} is too large to represent exactly.`);return t.amount}function xr(e){try{return St(e)}catch(n){throw new s("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 Or=6,js=1000000n,Ws=10098n;function Rr(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>Or?null:BigInt(n)*js+BigInt(t.padEnd(Or,"0"))}function Pr(e,n){let t=Rr(e),i=Rr(n),r=t===null||i===null?null:i-t;if(t===null||t<=0n||i===null||i<=0n||r===null||r<0n||r>Ws)throw new s("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 Br=require("crypto");function Ur(e,n){return`cli-invoice-pay-${(0,Br.createHash)("sha256").update("allscale-cli:invoice-pay:v1\0","utf8").update(e,"utf8").update("\0","utf8").update(n,"utf8").digest("hex")}`}var yn=class e extends Oe{static description="Pay an invoice where you are the payer, from your AllScale wallet. Use `allscale invoice sent` to list the invoices you owe (add --status SENT --status ACKNOWLEDGED --status FAILED for the ones you can start paying). An OVERDUE invoice cannot start a new payment: if an earlier attempt of yours may still be in flight, reconcile that first \u2014 otherwise ask the issuer to extend its due date, which revives it. Resolves the invoice's destination + amount, moves the funds via the same signing path as `wallet send` (the transfer is confirmed in the browser), 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 LOGIN 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 65ab1234567890abcdef0123 --chain bsc --stable-coin USDT"];static args={id:$r.Args.string({description:"Invoice id to pay, as listed by `invoice sent`.",required:!0})};static flags={"business-id":j.Flags.string({char:"b",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:j.Flags.string({description:"Chain to pay on. Optional when the invoice lists a single receiving wallet; required when it lists several.",options:[...ei]}),"stable-coin":j.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:[...ze]}),"browser-base":j.Flags.string({description:"Override the base URL of the /cli confirmation link (defaults to the session API base)."}),"bridge-timeout":j.Flags.integer({description:"Shorten the confirmation deadline, in milliseconds. By default the CLI waits the broker op's remaining life (~5 min). The browser only returns after the on-chain receipt confirms (it may poll for up to ~2 min after signing), so a shortened deadline must budget for the signing ceremony PLUS that receipt wait. Capped by the broker op TTL: a larger value is clamped, because the confirmation link cannot outlive its broker op. If no usable server-relative TTL is available, a withdraw waits up to 240s and may be shortened by the best-effort bound from the stated expiry.",min:1e3}),...Oe.baseFlags};async runCommand(){let{args:n,flags:t}=await this.parse(e),i=this.resolveContext(t);await Ai(i,t["business-id"]);let r=n.id.trim();if(!r)throw new s("input.invalid","Invoice id cannot be blank.");let o=t["stable-coin"],a=o?ti(o):null;if(o&&a===null)throw new s("input.invalid",`--stable-coin '${o}' is not supported (USDT or USDC).`);let c=await pt(i,"query","payment",{id_str:r},{selection:"id encrypted_id amount_coins payment_type wallets { chain address }"}),l=(c?.wallets??[]).filter(T=>!!T&&typeof T.chain=="number"&&T.chain in We&&typeof T.address=="string"&&T.address.length>0);if(l.length===0)throw new s("input.invalid",c==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:u,autoSelected:p}=Ir({paymentType:c?.payment_type,requestedCoin:a,requestedSlug:o,paymentId:r});p&&Dr.stderr.write(`Paying in ${Ce(u)} (the invoice's currency).
|
|
64
|
+
`);let f=vr(t.chain,l);if(l.filter(T=>T.chain===f).length>1)throw new s("input.invalid",`This invoice has multiple receiving addresses on ${M(f)} \u2014 it's ambiguous which to pay. Contact support to resolve the duplicate wallet entries.`);let y=_t(l,f);if(!y)throw new s("input.invalid",`The invoice has no valid receiving address on ${M(f)}.`);let m=St(c?.amount_coins),g=typeof c?.encrypted_id=="string"?c.encrypted_id.trim():"";if(!g)throw new s("backend.internal","The invoice response did not include its public payment identifier; refusing to call the public payment endpoint with the internal id.");let _=await this.resolvePayerAddress(i,f);if(_.toLowerCase()===y.toLowerCase())throw new s("input.invalid","The invoice destination is your own wallet address; refusing a self-transfer.");let N=kr(),R=Ar(i),S=await Lr(i,g,{sender_fingerprint:N},R),B=S.amount_coins!=null?xr(S.amount_coins):m;S.amount_coins!=null&&Pr(m,B);let L=Ur(r,S.id),H=await mr({ctx:i,op:"withdraw_token",mode:"data",payload:{chain:f,to_address:y,amount:B,stable_coin:u,idempotency_key:L},timeoutMs:t["bridge-timeout"],browserBase:t["browser-base"],acceptBareTxHashPaste:!1}).catch(T=>{throw Nr(T,{payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:L})??T}),U=H.result_data??{},O=gr(U);if(O&&O.outcome!=="confirmed"){let T={outcome:O.outcome,error_code:O.errorCode,transaction_hash:O.transactionHash,chain:f,explorer_url:Xe(f,O.transactionHash)||void 0,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:H.idempotency_key??L};if(O.outcome==="failed")throw new s("wallet.transaction_reverted",`The transaction was broadcast (tx ${O.transactionHash}) but reverted on-chain, so the transfer did not complete and the invoice was not paid. Inspect the transaction and correct the cause before submitting another payment; do not retry this command automatically.`,T);let ge=O.errorCode==="receipt_confirmation_timeout"?"receipt confirmation timed out":"the receipt confirmation provider was unavailable";throw new s("wallet.transaction_status_unknown",`The transaction was broadcast (tx ${O.transactionHash}), but its on-chain status is unknown because ${ge}. Do not retry this payment blindly; inspect the transaction hash and the invoice status before deciding whether another submission is needed.`,T)}if(!O)throw new s("wallet.bridge_invalid_response","Browser returned an unconfirmed or invalid withdrawal result. A transaction hash alone does not prove receipt confirmation. 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.transaction_hash=="string"&&oe.test(U.transaction_hash)?U.transaction_hash:typeof U.tx_hash=="string"?U.tx_hash.slice(0,66):typeof U.transaction_hash=="string"?U.transaction_hash.slice(0,66):null,payment_id:r,pay_intent_id:S.id,tx_from:_,to_address:y,idempotency_key:H.idempotency_key??L});let F=O.transactionHash,Be=T=>Cr(T,{tx_hash:F,tx_from:_,payment_id:r,pay_intent_id:S.id,idempotency_key:L,explorer_url:Xe(f,F)||null});try{await br(i,{payment_id:r,tx_hash:F,tx_block_chain:f,dest_stable_coin:u,tx_from:_,sender_fingerprint:N},R)}catch(T){throw ht("record",F,T,Be(T))}try{await Er(i,r,S.id,{sender_fingerprint:N},R)}catch(T){throw ht("confirm",F,T,Be(T))}return{payment_id:r,pay_intent_id:S.id,tx_hash:F,chain:f,chain_name:M(f),amount:B,stable_coin:u,stable_coin_name:Ce(u),explorer_url:Xe(f,F)||null,idempotency_key:L,status_optimistic:!0,status:"processing"}}async resolvePayerAddress(n,t){let r=(await pt(n,"query","business_wallets",{},{selection:"chain address"})??[]).filter(a=>!!a&&typeof a.chain=="number"&&a.chain in We&&typeof a.address=="string"&&a.address.length>0);if(r.filter(a=>a.chain===t).length>1)throw new s("input.invalid",`Your AllScale wallet has multiple addresses on ${M(t)} \u2014 can't auto-select which to pay from. Contact support.`);let o=_t(r,t);if(!o)throw new s("input.invalid",`Your AllScale wallet has no valid address on ${M(t)} to pay from.`);return o}};
|
|
66
65
|
//# sourceMappingURL=pay.js.map
|