@alva-ai/toolkit 0.32.0 → 0.33.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 +22 -0
- package/dist/browser.global.js +45 -45
- package/dist/browser.global.js.map +1 -1
- package/dist/cli.d.ts +49 -0
- package/dist/cli.js +287 -103
- package/dist/cli.js.map +1 -1
- package/dist/dispatch.d.ts +49 -0
- package/dist/dispatch.js +102 -17
- package/dist/dispatch.js.map +1 -1
- package/dist/index.cjs +230 -93
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +50 -1
- package/dist/index.d.ts +50 -1
- package/dist/index.js +229 -93
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/browser.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AlvaToolkit=(()=>{var Se=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var On=Object.prototype.hasOwnProperty;var r=(t,e)=>Se(t,"name",{value:e,configurable:!0});var Mn=(t,e)=>{for(var n in e)Se(t,n,{get:e[n],enumerable:!0})},$n=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Gn(e))!On.call(t,s)&&s!==n&&Se(t,s,{get:()=>e[s],enumerable:!(i=Fn(e,s))||i.enumerable});return t};var jn=t=>$n(Se({},"__esModule",{value:!0}),t);var Zr={};Mn(Zr,{AlertsResource:()=>z,AlvaClient:()=>dt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>_e,AutomationResource:()=>K,CliUsageError:()=>ve,CompanyNewsResource:()=>ie,ForYouResource:()=>W,MarketsResource:()=>J,PBSV_UPDATE_MESSAGE:()=>Ut,SUBSCRIBE_MANAGE_MESSAGE:()=>$t,SUBSCRIBE_PROPOSE_MESSAGE:()=>Ot,SUBSCRIBE_RESULT_MESSAGE:()=>Mt,SchedulesResource:()=>X,StewardResource:()=>Z,ThesesResource:()=>ne,TradingPairsResource:()=>ee,UDF_AUTH_REQUIRED_MESSAGE:()=>Gt,UDF_CONSENT_REQUEST_MESSAGE:()=>Lt,UDF_CONSENT_RESPONSE_MESSAGE:()=>Ft,UdfAuthRequiredError:()=>Q,UdfConsentDeniedError:()=>ue,UdfConsentRequiredError:()=>ae,UdfConsentTimeoutError:()=>ce,UdfError:()=>R,UdfExecutionError:()=>he,UdfFunctionDisabledError:()=>pe,UdfFunctionNotFoundError:()=>de,UdfInsufficientCredits:()=>le,UdfPidMismatchError:()=>F,UdfRateLimitedError:()=>me,UdfTokenExpiredError:()=>se,UdfTokenInvalidError:()=>oe,UdfTransportError:()=>V,VERSION:()=>Xr,getViewerToken:()=>fe,installPlaybookRuntime:()=>bt,mapUdfErrorResponse:()=>yt,playbookIdFromToken:()=>ft,subscribe:()=>Ht,udf:()=>Wt});var R=class extends Error{static{r(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:i={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=i,this.status=s}},Q=class extends R{static{r(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},se=class extends R{static{r(this,"UdfTokenExpiredError")}},oe=class extends R{static{r(this,"UdfTokenInvalidError")}},F=class extends R{static{r(this,"UdfPidMismatchError")}},ae=class extends R{static{r(this,"UdfConsentRequiredError")}},ue=class extends R{static{r(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},ce=class extends R{static{r(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},le=class extends R{static{r(this,"UdfInsufficientCredits")}},de=class extends R{static{r(this,"UdfFunctionNotFoundError")}},pe=class extends R{static{r(this,"UdfFunctionDisabledError")}},me=class extends R{static{r(this,"UdfRateLimitedError")}},he=class extends R{static{r(this,"UdfExecutionError")}},V=class extends R{static{r(this,"UdfTransportError")}},Ut="alva:pbsv:update",Lt="alva:udf:consent-request",Ft="alva:udf:consent-response",Gt="alva:udf:auth-required",Ot="alva:subscribe:propose",Mt="alva:subscribe:result",$t="alva:subscribe:manage",jt="https://api-llm.prd.alva.ai",Bt=300*1e3,re=null,C=null,ht=jt,q=null,S=null,Dt=!1,Ee=new Map,Ae=new Map,Bn=r(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Qn=r(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),ft=r(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Qn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),fe=r(()=>re,"getViewerToken"),B=r(()=>!!fe(),"isAuthenticated"),Vn=r(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Yn=r(t=>{let e=new URLSearchParams(t.location.search);re=e.get("_pbsv"),C=e.get("parent_origin"),ht=(e.get("api_origin")||jt).replace(/\/$/,""),q=ft(re),re&&Vn(t)},"parseBootParams"),Qt=r(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Hn=r(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),Wn=r(t=>{let e=t;return{...e,result:Hn(e.result)}},"normalizeInvokeResponse"),Vt=r(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),yt=r((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=Vt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new se(i,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new oe(i,o);case"PBSV_PID_MISMATCH":return new F(i,o);case"CONSENT_REQUIRED":return new ae(i,o);case"INSUFFICIENT_CREDITS":return new le(i,o);case"FUNCTION_NOT_FOUND":return new de(i,o);case"FUNCTION_DISABLED":return new pe(i,o);case"RESOURCE_EXHAUSTED":return new me(i,o);case"EXECUTION_FAILED":return new he(i,o);default:return new V(i,o)}},"mapUdfErrorResponse"),Kn=r(t=>{if(!S||!C||t.origin!==C||t.source!==S.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===Ut){typeof e.token=="string"&&e.token.length>0&&(re=e.token,q=ft(e.token));return}if(e.type===Mt){if(typeof e.request_id!="string")return;let i=Ae.get(e.request_id);if(!i)return;clearTimeout(i.timer),Ae.delete(e.request_id),i.resolve(Bn(e.status));return}if(e.type!==Ft||typeof e.request_id!="string")return;let n=Ee.get(e.request_id);n&&(clearTimeout(n.timer),Ee.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Yt=r(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),zn=r(()=>{if(!q)return null;let t=Number(q);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),Jn=r(async(t,e)=>{if(!S||!C)return"denied";let n=C,i=Yt();return new Promise(s=>{let o=setTimeout(()=>{Ee.delete(i),s("timeout")},Bt);Ee.set(i,{resolve:s,timer:o}),S?.parent.postMessage({type:Lt,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Xn=r(async t=>{if(!S||!C)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let i=C,s=Yt();return new Promise(o=>{let a=setTimeout(()=>{Ae.delete(s),o("timeout")},Bt);Ae.set(s,{resolve:o,timer:a}),S?.parent.postMessage({type:Ot,request_id:s,playbook_id:q,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Zn=r(()=>{!S||!C||S.parent.postMessage({type:$t,playbook_id:q},C)},"manageSubscriptions"),Ht={propose:Xn,manage:Zn},ei=r(t=>{!S||!C||S.parent.postMessage({type:Gt,function_name:t},C)},"requestAuthentication"),gt=r(async(t,e,n=!1)=>{let i=fe();if(!i)throw new Q;if(!q)throw new F("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=zn();if(!s)throw new F("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${ht}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new V("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Qt(o);if(o.ok)return Wn(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=Vt(a),c=typeof u.playbook_id=="string"?u.playbook_id:q,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,h=await Jn(c,d);if(h==="granted")return gt(t,e,!0);throw h==="timeout"?new ce:new ue}throw yt(a,o.status)},"call"),ti=r(async()=>{let t=fe();if(!t)throw new Q;if(!q)throw new F("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${ht}/api/v1/service/functions`);e.searchParams.set("playbook_id",q);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await Qt(n);if(!n.ok)throw yt(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),mt=r((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),ni=r(t=>{if(typeof t!="string")return t;let n=S?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),ii=r((t,e)=>{if(!S)throw new Error("Playbook runtime is not installed.");let n=ni(t),i=S.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=B()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),B()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!B()){ei(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=o,mt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await gt(e.functionName,e.params??{});mt(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){mt(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=B()?s:a,B()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),Wt={call:gt,list:ti,getViewerToken:fe,isAuthenticated:B,renderButton:ii,UdfError:R,UdfAuthRequiredError:Q,UdfTokenExpiredError:se,UdfTokenInvalidError:oe,UdfPidMismatchError:F,UdfConsentRequiredError:ae,UdfConsentDeniedError:ue,UdfConsentTimeoutError:ce,UdfInsufficientCredits:le,UdfFunctionNotFoundError:de,UdfFunctionDisabledError:pe,UdfRateLimitedError:me,UdfExecutionError:he,UdfTransportError:V},bt=r(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Dt)return;S=e,Dt=!0,Yn(e),e.addEventListener("message",Kn);let n=e,i=n.alva||{};n.alva={...i,udf:Wt,subscribe:Ht}},"installPlaybookRuntime");var l=class extends Error{static{r(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},ve=class extends Error{static{r(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Kt(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}r(Kt,"isArrayBuffer");var zt=1;function ri(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,o=0;if(n>=194&&n<=223)i=1,s=128,o=n&31;else if(n>=224&&n<=239)i=2,s=2048,o=n&15;else if(n>=240&&n<=244)i=3,s=65536,o=n&7;else return!1;if(e+i>=t.length)return!1;for(let a=1;a<=i;a+=1){let u=t[e+a];if((u&192)!==128)return!1;o=o<<6|u&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=i+1}return!0}r(ri,"isValidUtf8");var Ie=class{constructor(e){this.client=e}client;static{r(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Kt(n)||!ri(new Uint8Array(n)))return n;let i=new TextDecoder("utf-8").decode(n);try{return JSON.parse(i)}catch{return i}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:zt}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:zt}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var Jt="9007199254740991";function Xt(t,e,n,i){let s=t.length+e,o=n.length+i;if(s!==o)return s>o;for(let a=0;a<s;a++){let u=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(u!==c)return u>c}return!1}r(Xt,"scaledIntegerGreater");function si(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,i=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+i).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-i.length;return a>=0?Xt(o,a,Jt,0):Xt(o,0,Jt,-a)}r(si,"numberOutsideSafeRange");function oi(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(si(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}r(oi,"validateJSONNumberTokens");function _t(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((i,s)=>_t(i,`${e}[${s}]`,n));else{let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);_t(o.value,`${e}.${s}`,n)}}n.delete(t)}}r(_t,"assertPlainJSONData");function ye(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");_t(t,"args",new Set);let e=JSON.stringify(t);return Zt(e),e}r(ye,"serializeStructuredArgs");function Zt(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");oi(t)}r(Zt,"validateSerializedArgs");function ge(t,e,n){let i=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Zt(n),i.push([e,n])),`{${i.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}r(ge,"objectWithRawJSONField");var Ce=class{constructor(e){this.client=e}client;static{r(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ye(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let i={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:i}:{jsonBody:ge(i,"args",n)},timeoutMs:e.timeout_ms})}};var xe=class{constructor(e){this.client=e}client;static{r(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ye(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let i={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:i}:{jsonBody:ge(i,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,ye(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:i,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${i}`,{...n===void 0?{body:s}:{jsonBody:ge(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var qe=class{constructor(e){this.client=e}client;static{r(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Ne=class{constructor(e){this.client=e}client;static{r(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var Ue=class{constructor(e){this.client=e}client;static{r(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=De(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=De(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=De(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=De(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function De(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}r(De,"requireFeedID");function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(p,"record");function k(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}r(k,"isPositiveInt64");var Y=`
|
|
1
|
+
"use strict";var AlvaToolkit=(()=>{var ve=Object.defineProperty;var Bn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var Vn=Object.prototype.hasOwnProperty;var i=(t,e)=>ve(t,"name",{value:e,configurable:!0});var Hn=(t,e)=>{for(var n in e)ve(t,n,{get:e[n],enumerable:!0})},Yn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qn(e))!Vn.call(t,s)&&s!==n&&ve(t,s,{get:()=>e[s],enumerable:!(r=Bn(e,s))||r.enumerable});return t};var Wn=t=>Yn(ve({},"__esModule",{value:!0}),t);var os={};Hn(os,{AlertsResource:()=>Z,AlvaClient:()=>ht,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>we,AutomationResource:()=>J,CliUsageError:()=>xe,CompanyNewsResource:()=>oe,ForYouResource:()=>z,MarketsResource:()=>ee,PBSV_UPDATE_MESSAGE:()=>Ot,SUBSCRIBE_MANAGE_MESSAGE:()=>Qt,SUBSCRIBE_PROPOSE_MESSAGE:()=>jt,SUBSCRIBE_RESULT_MESSAGE:()=>Bt,SchedulesResource:()=>te,StewardResource:()=>ne,ThesesResource:()=>se,TradingPairsResource:()=>re,UDF_AUTH_REQUIRED_MESSAGE:()=>$t,UDF_CONSENT_REQUEST_MESSAGE:()=>Gt,UDF_CONSENT_RESPONSE_MESSAGE:()=>Mt,UdfAuthRequiredError:()=>H,UdfConsentDeniedError:()=>de,UdfConsentRequiredError:()=>le,UdfConsentTimeoutError:()=>pe,UdfError:()=>R,UdfExecutionError:()=>ge,UdfFunctionDisabledError:()=>fe,UdfFunctionNotFoundError:()=>he,UdfInsufficientCredits:()=>me,UdfPidMismatchError:()=>G,UdfRateLimitedError:()=>ye,UdfTokenExpiredError:()=>ue,UdfTokenInvalidError:()=>ce,UdfTransportError:()=>Y,VERSION:()=>ss,XResource:()=>W,getViewerToken:()=>be,installPlaybookRuntime:()=>Rt,mapUdfErrorResponse:()=>_t,playbookIdFromToken:()=>bt,subscribe:()=>Xt,udf:()=>zt});var R=class extends Error{static{i(this,"UdfError")}code;metadata;status;constructor(e,{code:n,metadata:r={},status:s}){super(e),this.name=new.target.name,this.code=n,this.metadata=r,this.status=s}},H=class extends R{static{i(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},ue=class extends R{static{i(this,"UdfTokenExpiredError")}},ce=class extends R{static{i(this,"UdfTokenInvalidError")}},G=class extends R{static{i(this,"UdfPidMismatchError")}},le=class extends R{static{i(this,"UdfConsentRequiredError")}},de=class extends R{static{i(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},pe=class extends R{static{i(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},me=class extends R{static{i(this,"UdfInsufficientCredits")}},he=class extends R{static{i(this,"UdfFunctionNotFoundError")}},fe=class extends R{static{i(this,"UdfFunctionDisabledError")}},ye=class extends R{static{i(this,"UdfRateLimitedError")}},ge=class extends R{static{i(this,"UdfExecutionError")}},Y=class extends R{static{i(this,"UdfTransportError")}},Ot="alva:pbsv:update",Gt="alva:udf:consent-request",Mt="alva:udf:consent-response",$t="alva:udf:auth-required",jt="alva:subscribe:propose",Bt="alva:subscribe:result",Qt="alva:subscribe:manage",Vt="https://api-llm.prd.alva.ai",Ht=300*1e3,ae=null,x=null,gt=Vt,N=null,S=null,Ft=!1,Ie=new Map,Ce=new Map,Kn=i(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Xn=i(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),bt=i(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Xn(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),be=i(()=>ae,"getViewerToken"),V=i(()=>!!be(),"isAuthenticated"),zn=i(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Jn=i(t=>{let e=new URLSearchParams(t.location.search);ae=e.get("_pbsv"),x=e.get("parent_origin"),gt=(e.get("api_origin")||Vt).replace(/\/$/,""),N=bt(ae),ae&&zn(t)},"parseBootParams"),Yt=i(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Zn=i(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),er=i(t=>{let e=t;return{...e,result:Zn(e.result)}},"normalizeInvokeResponse"),Wt=i(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),_t=i((t,e)=>{let n=t.error?.code||"TRANSPORT",r=t.error?.message||n,s=Wt(t),o={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new ue(r,o);case"PBSV_INVALID":case"UNAUTHENTICATED":return new ce(r,o);case"PBSV_PID_MISMATCH":return new G(r,o);case"CONSENT_REQUIRED":return new le(r,o);case"INSUFFICIENT_CREDITS":return new me(r,o);case"FUNCTION_NOT_FOUND":return new he(r,o);case"FUNCTION_DISABLED":return new fe(r,o);case"RESOURCE_EXHAUSTED":return new ye(r,o);case"EXECUTION_FAILED":return new ge(r,o);default:return new Y(r,o)}},"mapUdfErrorResponse"),tr=i(t=>{if(!S||!x||t.origin!==x||t.source!==S.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===Ot){typeof e.token=="string"&&e.token.length>0&&(ae=e.token,N=bt(e.token));return}if(e.type===Bt){if(typeof e.request_id!="string")return;let r=Ce.get(e.request_id);if(!r)return;clearTimeout(r.timer),Ce.delete(e.request_id),r.resolve(Kn(e.status));return}if(e.type!==Mt||typeof e.request_id!="string")return;let n=Ie.get(e.request_id);n&&(clearTimeout(n.timer),Ie.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),Kt=i(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),nr=i(()=>{if(!N)return null;let t=Number(N);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),rr=i(async(t,e)=>{if(!S||!x)return"denied";let n=x,r=Kt();return new Promise(s=>{let o=setTimeout(()=>{Ie.delete(r),s("timeout")},Ht);Ie.set(r,{resolve:s,timer:o}),S?.parent.postMessage({type:Gt,request_id:r,playbook_id:t,min_allowance:e},n)})},"requestConsent"),ir=i(async t=>{if(!S||!x)return"error";let e=typeof t?.feedOwner=="string"?t.feedOwner.trim():"",n=typeof t?.feedName=="string"?t.feedName.trim():"";if(!e||!n)return"error";let r=x,s=Kt();return new Promise(o=>{let a=setTimeout(()=>{Ce.delete(s),o("timeout")},Ht);Ce.set(s,{resolve:o,timer:a}),S?.parent.postMessage({type:jt,request_id:s,playbook_id:N,feed:{owner:e,name:n}},r)})},"proposeSubscribe"),sr=i(()=>{!S||!x||S.parent.postMessage({type:Qt,playbook_id:N},x)},"manageSubscriptions"),Xt={propose:ir,manage:sr},or=i(t=>{!S||!x||S.parent.postMessage({type:$t,function_name:t},x)},"requestAuthentication"),Pt=i(async(t,e,n=!1)=>{let r=be();if(!r)throw new H;if(!N)throw new G("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=nr();if(!s)throw new G("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let o;try{o=await fetch(`${gt}/api/v1/service/invoke`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"X-Pbsv":"1","Content-Type":"application/json"},body:JSON.stringify({playbook_id:s,function_name:t,parameters_json:JSON.stringify(e)})})}catch{throw new Y("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await Yt(o);if(o.ok)return er(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=Wt(a),c=typeof u.playbook_id=="string"?u.playbook_id:N,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,h=await rr(c,d);if(h==="granted")return Pt(t,e,!0);throw h==="timeout"?new pe:new de}throw _t(a,o.status)},"call"),ar=i(async()=>{let t=be();if(!t)throw new H;if(!N)throw new G("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${gt}/api/v1/service/functions`);e.searchParams.set("playbook_id",N);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),r=await Yt(n);if(!n.ok)throw _t(r,n.status);let s=r.functions;return Array.isArray(s)?s:[]},"list"),yt=i((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),ur=i(t=>{if(typeof t!="string")return t;let n=S?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),cr=i((t,e)=>{if(!S)throw new Error("Playbook runtime is not installed.");let n=ur(t),r=S.document.createElement("button"),s=e.label||e.functionName,o=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return r.type="button",r.className="alva-udf-button",r.textContent=V()?s:a,r.disabled=!1,r.setAttribute("data-function-name",e.functionName),V()||r.setAttribute("aria-disabled","true"),r.addEventListener("click",async()=>{if(!V()){or(e.functionName);return}if(!r.disabled){r.disabled=!0,r.textContent=o,yt(r,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await Pt(e.functionName,e.params??{});yt(r,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){yt(r,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{r.disabled=!1,r.textContent=V()?s:a,V()||r.setAttribute("aria-disabled","true")}}}),n.appendChild(r),r},"renderButton"),zt={call:Pt,list:ar,getViewerToken:be,isAuthenticated:V,renderButton:cr,UdfError:R,UdfAuthRequiredError:H,UdfTokenExpiredError:ue,UdfTokenInvalidError:ce,UdfPidMismatchError:G,UdfConsentRequiredError:le,UdfConsentDeniedError:de,UdfConsentTimeoutError:pe,UdfInsufficientCredits:me,UdfFunctionNotFoundError:he,UdfFunctionDisabledError:fe,UdfRateLimitedError:ye,UdfExecutionError:ge,UdfTransportError:Y},Rt=i(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||Ft)return;S=e,Ft=!0,Jn(e),e.addEventListener("message",tr);let n=e,r=n.alva||{};n.alva={...r,udf:zt,subscribe:Xt}},"installPlaybookRuntime");var l=class extends Error{static{i(this,"AlvaError")}code;status;details;constructor(e,n,r,s){super(n),this.name="AlvaError",this.code=e,this.status=r,this.details=s}},xe=class extends Error{static{i(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function Jt(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}i(Jt,"isArrayBuffer");var Zt=1;function lr(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let r=0,s=0,o=0;if(n>=194&&n<=223)r=1,s=128,o=n&31;else if(n>=224&&n<=239)r=2,s=2048,o=n&15;else if(n>=240&&n<=244)r=3,s=65536,o=n&7;else return!1;if(e+r>=t.length)return!1;for(let a=1;a<=r;a+=1){let u=t[e+a];if((u&192)!==128)return!1;o=o<<6|u&63}if(o<s||o>1114111||o>=55296&&o<=57343)return!1;e+=r+1}return!0}i(lr,"isValidUtf8");var qe=class{constructor(e){this.client=e}client;static{i(this,"FsResource")}async read(e){let n=await this.client._request("GET","/api/v1/fs/read",{query:{path:e.path,offset:e.offset,size:e.size}});if(!Jt(n)||!lr(new Uint8Array(n)))return n;let r=new TextDecoder("utf-8").decode(n);try{return JSON.parse(r)}catch{return r}}async write(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{body:{path:e.path,data:e.data,mkdir_parents:e.mkdir_parents,...e.append?{flags:Zt}:{}}})}async rawWrite(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/fs/write",{query:{path:e.path,mkdir_parents:e.mkdir_parents,...e.append?{flags:Zt}:{}},rawBody:e.body})}async stat(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/stat",{query:{path:e.path}})}async readdir(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readdir",{query:{path:e.path,recursive:e.recursive}})}async mkdir(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/mkdir",{body:{path:e.path}})}async remove(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/fs/remove",{query:{path:e.path,recursive:e.recursive}})}async rename(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/rename",{body:{old_path:e.old_path,new_path:e.new_path}})}async copy(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/copy",{body:{src_path:e.src_path,dst_path:e.dst_path}})}async symlink(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/symlink",{body:{target_path:e.target_path,link_path:e.link_path}})}async readlink(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/fs/readlink",{query:{path:e.path}})}async chmod(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/chmod",{body:{path:e.path,mode:e.mode}})}async grant(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/grant",{body:{path:e.path,subject:e.subject,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/fs/revoke",{body:{path:e.path,subject:e.subject,permission:e.permission}})}};var en="9007199254740991";function tn(t,e,n,r){let s=t.length+e,o=n.length+r;if(s!==o)return s>o;for(let a=0;a<s;a++){let u=a<t.length?t[a]:"0",c=a<n.length?n[a]:"0";if(u!==c)return u>c}return!1}i(tn,"scaledIntegerGreater");function dr(t){let e=t.match(/^-?(?<whole>\d+)(?:\.(?<fraction>\d+))?(?:[eE](?<exponent>[+-]?\d+))?$/);if(!e?.groups)return!0;let n=e.groups.whole,r=e.groups.fraction??"",s=Number(e.groups.exponent??"0");if(!Number.isSafeInteger(s))return!0;let o=(n+r).replace(/^0+/,"")||"0";if(o==="0")return!1;let a=s-r.length;return a>=0?tn(o,a,en,0):tn(o,0,en,-a)}i(dr,"numberOutsideSafeRange");function pr(t){let e=0;for(;e<t.length;){if(t[e]==='"'){for(e++;e<t.length;)if(t[e]==="\\")e+=2;else if(t[e++]==='"')break;continue}if(t[e]==="-"||/\d/.test(t[e]??"")){let n=t.slice(e).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);if(n){if(dr(n[0]))throw new TypeError("args contains a number outside JavaScript's safe range; use a string for int64 and identifier values");e+=n[0].length;continue}}e++}}i(pr,"validateJSONNumberTokens");function wt(t,e,n){if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`${e} must contain only finite numbers`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`${e} contains a number outside JavaScript's safe range; use a string for int64 and identifier values`);return}if(typeof t!="object")throw new TypeError(`${e} must contain only JSON data`);if(n.has(t))throw new TypeError(`${e} must not contain circular references`);if(n.add(t),Array.isArray(t))t.forEach((r,s)=>wt(r,`${e}[${s}]`,n));else{let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`${e} must contain only plain JSON objects`);for(let[s,o]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(o.enumerable){if(!("value"in o))throw new TypeError(`${e} must not contain accessors`);wt(o.value,`${e}.${s}`,n)}}n.delete(t)}}i(wt,"assertPlainJSONData");function _e(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");wt(t,"args",new Set);let e=JSON.stringify(t);return nn(e),e}i(_e,"serializeStructuredArgs");function nn(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");pr(t)}i(nn,"validateSerializedArgs");function Pe(t,e,n){let r=Object.entries(t).filter(([s,o])=>o!==void 0&&(n===void 0||s!==e));return n!==void 0&&(nn(n),r.push([e,n])),`{${r.map(([s,o])=>{let a=s===e&&n!==void 0?n:JSON.stringify(o);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}i(Pe,"objectWithRawJSONField");var Ne=class{constructor(e){this.client=e}client;static{i(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,_e(e.args))}async _executeSerializedArgs(e,n){return this.client._requireAuth(),this.request(e,n)}request(e,n){let r={code:e.code,entry_path:e.entry_path,working_dir:e.working_dir,args:e.args,max_heap_size_mb:e.max_heap_size_mb};return this.client._request("POST","/api/v1/run",{...n===void 0?{body:r}:{jsonBody:Pe(r,"args",n)},timeoutMs:e.timeout_ms})}};var De=class{constructor(e){this.client=e}client;static{i(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,_e(e.args))}async _createSerializedArgs(e,n){return this.client._requireAuth(),this.createRequest(e,n)}createRequest(e,n){let r={name:e.name,path:e.path,cron_expression:e.cron_expression,args:e.args,push_notify:e.push_notify,max_heap_size_mb:e.max_heap_size_mb,execution_timeout_seconds:e.execution_timeout_seconds,run_as_user_id:e.run_as_user_id,start_at:e.start_at,end_at:e.end_at,max_runs:e.max_runs};return this.client._request("POST","/api/v1/deploy/cronjob",{...n===void 0?{body:r}:{jsonBody:Pe(r,"args",n)}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/deploy/cronjobs",{query:{limit:e?.limit,cursor:e?.cursor}})}async get(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.id}`)}async update(e){return this.client._requireAuth(),e.args===void 0?this.updateRequest(e):this.updateRequest(e,_e(e.args))}async _updateSerializedArgs(e,n){return this.client._requireAuth(),this.updateRequest(e,n)}updateRequest(e,n){let{id:r,...s}=e;return this.client._request("PATCH",`/api/v1/deploy/cronjob/${r}`,{...n===void 0?{body:s}:{jsonBody:Pe(s,"args",n)}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/deploy/cronjob/${e.id}`)}async pause(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/pause`)}async resume(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/resume`)}async trigger(e){return this.client._requireAuth(),this.client._request("POST",`/api/v1/deploy/cronjob/${e.id}/trigger`)}async listRuns(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs`,{query:{first:e.first,cursor:e.cursor}})}async getRunStatus(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/by-workflow/${encodeURIComponent(e.workflow_run_id)}`)}async getRunLogs(e){return this.client._requireAuth(),this.client._request("GET",`/api/v1/deploy/cronjob/${e.cronjob_id}/runs/${e.run_id}/logs`)}};var Ue=class{constructor(e){this.client=e}client;static{i(this,"ServiceAccountResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service-account",{body:{display_name:e.display_name}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/service-accounts")}async delete(e){this.client._requireAuth(),await this.client._request("DELETE",`/api/v1/service-account/${e.id}`)}async grant(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/grant`,{body:{path:e.path,permission:e.permission}})}async revoke(e){this.client._requireAuth(),await this.client._request("POST",`/api/v1/service-account/${e.id}/revoke`,{body:{path:e.path,permission:e.permission}})}};var Le=class{constructor(e){this.client=e}client;static{i(this,"ReleaseResource")}async feed(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/feed",{body:{name:e.name,version:e.version,cronjob_id:e.cronjob_id,view_json:e.view_json,description:e.description,changelog:e.changelog,agent_type:e.agent_type,skip_auto_trigger:e.skip_auto_trigger}})}async playbookDraft(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/draft/playbook",{body:{name:e.name,display_name:e.display_name,description:e.description,feeds:e.feeds,trading_symbols:e.trading_symbols,skill_id:e.skill_id,tags:e.tags}})}async playbook(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/release/playbook",{body:{name:e.name,version:e.version,feeds:e.feeds,changelog:e.changelog,readme_url:e.readme_url,confirm_bundled_feed_exposure:e.confirm_bundled_feed_exposure}})}};var Oe=class{constructor(e){this.client=e}client;static{i(this,"FeedResource")}async list(e={}){return this.client._requireAuth(),this.client._request("GET","/api/v1/feed",{query:{limit:e.limit,cursor:e.cursor,status:e.status}})}async stop(e){this.client._requireAuth();let n=Fe(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=Fe(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=Fe(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=Fe(e.id);if(e.visibility!=="public"&&e.visibility!=="private")throw new Error("visibility must be 'public' or 'private'");return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/visibility`,{body:{visibility:e.visibility}})}};function Fe(t){if(typeof t=="string"){if(!/^[1-9]\d*$/.test(t))throw new Error("feed id must be a positive integer");return t}if(!Number.isSafeInteger(t)||t<=0)throw new Error("feed id must be a positive integer");return t}i(Fe,"requireFeedID");var rn={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function v(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(v,"record");function mr(t){if(!v(t))throw new Error("X read parameters must be an object");let e=t.first??20;if(t.first===null||typeof e!="number"||!Number.isInteger(e)||e<5||e>100)throw new Error("first must be an integer between 5 and 100");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()||t.after.length>4096))throw new Error("after must be a non-empty X cursor of at most 4096 characters")}i(mr,"validateXReadParams");function D(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${t} response`,502)}i(D,"invalidResponse");function sn(t,e){if(!v(t))return D(e);if(t.errors!==void 0){if(!Array.isArray(t.errors))return D(e);if(t.errors.length>0){let n=t.errors.flatMap(o=>v(o)&&typeof o.message=="string"?[o.message]:[]),r=t.errors.map(o=>v(o)&&v(o.extensions)?o.extensions.code:void 0),s=typeof r[0]=="string"&&Object.hasOwn(rn,r[0])&&r.every(o=>o===r[0])?r[0]:"GRAPHQL_ERROR";throw new l(s,n.join("; ")||"X read failed",rn[s]??502,{errors:t.errors})}}return!v(t.data)||!v(t.data.viewer)?D(e):t.data.viewer[e]}i(sn,"viewerField");function hr(t,e,n){if(!v(t)||!Array.isArray(t.edges)||!v(t.pageInfo))return D(e);let r=t.pageInfo;if(typeof r.startCursor!="string"||typeof r.endCursor!="string"||typeof r.hasNextPage!="boolean"||typeof r.hasPreviousPage!="boolean"||r.hasNextPage&&!r.endCursor)return D(e);for(let a of t.edges){if(!v(a)||typeof a.cursor!="string"||!a.cursor||!v(a.node))return D(e);let u=a.node;if(n.some(c=>typeof u[c]!="string")||!u.id)return D(e)}let s=t.edges[0],o=t.edges[t.edges.length-1];return r.startCursor!==(s?.cursor??"")||o&&r.endCursor!==o.cursor?D(e):{edges:t.edges,pageInfo:r,retrievedAt:new Date().toISOString()}}i(hr,"readPage");var W=class{constructor(e){this.client=e}client;static{i(this,"XResource")}async status(){this.client._requireAuth();let e=await this.client._request("POST","/query",{body:{query:"query ToolkitXStatus { viewer { xConnection { connected canReadFollowing canReadPosts } } }"}}),n=sn(e,"xConnection");return!v(n)||["connected","canReadFollowing","canReadPosts"].some(r=>typeof n[r]!="boolean")?D("xConnection"):n}async following(e={}){return this.read("xFollowing","id username name",e)}async posts(e={}){return this.read("xPosts","id text authorId createdAt",e)}async read(e,n,r){mr(r),this.client._requireAuth();let s=await this.client._request("POST","/query",{body:{query:`query ToolkitXRead($first: Int, $after: String) { viewer { ${e}(first: $first, after: $after) { edges { cursor node { ${n} } } pageInfo { startCursor endCursor hasNextPage hasPreviousPage } } } }`,variables:{first:r.first??20,after:r.after}}});return hr(sn(s,e),e,n.split(" "))}};function p(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(p,"record");function k(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}i(k,"isPositiveInt64");var K=`
|
|
2
2
|
thesisId playbookId authorVersionId materialVersionId itemKey
|
|
3
3
|
title body publishedAtMs changeKind visibility
|
|
4
4
|
closed archived note closingNote researchPaused
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
title sourceKind sourceContentId publicUrl sourceTimeMs locator
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
-
`;function
|
|
22
|
+
`;function on(t){return Array.isArray(t)&&t.every(k)}i(on,"positiveInt64List");function fr(t){return Array.isArray(t)&&t.every(e=>p(e)&&k(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}i(fr,"stanceList");function yr(t){return Array.isArray(t)&&t.every(e=>p(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}i(yr,"entityList");function gr(t){return Array.isArray(t)&&t.every(e=>p(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}i(gr,"mediaList");function br(t){return Array.isArray(t)&&t.every(e=>p(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&_r(e.sourceTimeMs)&&typeof e.locator=="string")}i(br,"sourceRefList");function _r(t){return t===null||typeof t=="number"&&Number.isFinite(t)}i(_r,"nullableMs");function Pr(t){return p(t)&&k(t.versionId)&&k(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&br(t.sourceRefs)}i(Pr,"snapshot");function Rr(t){return p(t)&&(t.__typename==="Person"&&typeof t.slug=="string"||t.__typename==="PublicUser"&&typeof t.username=="string")&&typeof t.id=="string"&&t.id.trim()!==""&&typeof t.displayName=="string"&&typeof t.avatarUrl=="string"&&typeof t.bio=="string"&&typeof t.followersCount=="number"&&Number.isInteger(t.followersCount)&&p(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}i(Rr,"publisher");function X(t){if(!p(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!k(t[e]))return!1;if(typeof t.itemKey!="string"||!t.itemKey.trim()||typeof t.title!="string"||typeof t.body!="string"||typeof t.publishedAtMs!="number"||!Number.isFinite(t.publishedAtMs)||typeof t.changeKind!="string"||!t.changeKind.trim()||typeof t.visibility!="string"||typeof t.note!="string"||typeof t.closingNote!="string")return!1;for(let e of["closed","archived","researchPaused"])if(typeof t[e]!="boolean")return!1;return!on(t.entityIds)||!on(t.categoryIds)||!fr(t.entityStances)||!yr(t.entities)||!gr(t.medias)||!Rr(t.publisher)||!Pr(t.snapshotRelease)?!1:t.signalFeed===null||p(t.signalFeed)&&k(t.signalFeed.id)}i(X,"isThesisPublication");var wr=`
|
|
23
23
|
query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
24
24
|
viewer {
|
|
25
25
|
forYou(input: $input) {
|
|
@@ -46,7 +46,7 @@ query ToolkitForYou($input: FeedEntryConnectionInput) {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
|
-
`.trim();function
|
|
49
|
+
`.trim();function Tr(t){if(!p(t))throw new Error("For You parameters must be an object");let e=t.first===void 0?20:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw new Error("first must be an integer between 1 and 50");for(let n of["after","newerThan"]){let r=t[n];if(r!==void 0&&(typeof r!="string"||!r.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!k(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}i(Tr,"validateForYouListParams");function Re(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}i(Re,"invalidResponse");function kr(t){if(!p(t)||!Array.isArray(t.edges)||!p(t.pageInfo))return Re();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return Re();for(let s of t.edges){if(!p(s)||typeof s.cursor!="string"||!s.cursor.trim()||!p(s.node))return Re();let o=s.node;if(typeof o.id!="string"||!o.id.startsWith("FeedEntry:")||!k(o.id.slice(10))||!p(o.feed)||!k(o.feed.id)||!p(o.major)||typeof o.major.id!="string"||!k(o.major.feedId)||typeof o.title!="string"||typeof o.body!="string")return Re()}let n=t.edges[0],r=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(r?.cursor??"")||t.edges.length===0&&e.hasNextPage?Re():t}i(kr,"connection");var Sr=`
|
|
50
50
|
query ToolkitForYouTheses($input: ThesisRecommendationInput) {
|
|
51
51
|
viewer {
|
|
52
52
|
thesisRecommendations(input: $input) {
|
|
@@ -57,14 +57,14 @@ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
|
|
|
57
57
|
node {
|
|
58
58
|
itemKey
|
|
59
59
|
publication {
|
|
60
|
-
${
|
|
60
|
+
${K}
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
-
`.trim();function
|
|
67
|
+
`.trim();function Ar(t){if(!p(t))throw new Error("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>10)throw new Error("first must be an integer between 1 and 10");if(t.after!==void 0&&(typeof t.after!="string"||!t.after.trim()))throw new Error("after must be a non-empty cursor")}i(Ar,"validateForYouThesesParams");function an(t,e){if(!p(t))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors!==void 0){if(!Array.isArray(t.errors))throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${e} response`,502);if(t.errors.length>0){let n=t.errors.flatMap(r=>p(r)&&typeof r.message=="string"?[r.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!p(t.data)||!p(t.data.viewer)||t.data.viewer[e]==null)throw new l("GRAPHQL_EMPTY_RESPONSE",`GraphQL response did not include viewer.${e}`,502);return t.data.viewer[e]}i(an,"graphqlViewerField");function Ge(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}i(Ge,"invalidPage");function Er(t){if(!p(t)||!Array.isArray(t.edges)||!p(t.pageInfo)||typeof t.listId!="string"||typeof t.pageCursor!="string"||typeof t.exhausted!="boolean"||typeof t.scanLimited!="boolean"||t.nextCursor!==null&&typeof t.nextCursor!="string")return Ge();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean"||e.hasNextPage!==(t.nextCursor!==null))return Ge();for(let r of t.edges)if(!p(r)||typeof r.cursor!="string"||!r.cursor.trim()||!p(r.node)||typeof r.node.itemKey!="string"||!r.node.itemKey.trim()||!X(r.node.publication))return Ge();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Ge():t}i(Er,"recommendationPage");var z=class{constructor(e){this.client=e}client;static{i(this,"ForYouResource")}async list(e={}){Tr(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:wr,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return kr(an(n,"forYou"))}async theses(e={}){Ar(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:Sr,variables:{input:{first:e.first??10,after:e.after}}}}),r=an(n,"thesisRecommendations");return Er(r)}};var vr=`
|
|
68
68
|
query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
69
69
|
automation(id: $automationId) {
|
|
70
70
|
alertDelivery {
|
|
@@ -74,7 +74,7 @@ query ToolkitAutomationAlertDelivery($automationId: ID!) {
|
|
|
74
74
|
}
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
|
-
`.trim(),
|
|
77
|
+
`.trim(),Ir=`
|
|
78
78
|
mutation ToolkitUpdateAutomationAlertDelivery(
|
|
79
79
|
$input: UpdateAutomationAlertDeliveryInput!
|
|
80
80
|
$includeAlvaChannels: Boolean!
|
|
@@ -89,7 +89,7 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
`.trim(),K=class{constructor(e){this.client=e;this.delivery=new _e(e)}client;static{r(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=wi(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Fe(e.id);if(!Ti(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},_e=class{constructor(e){this.client=e}client;static{r(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Fe(e.id),s=(await this.graphql(Pi,{automationId:n})).automation?.alertDelivery;if(!s)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Fe(e.id),i=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!i&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=i?ki(e.alvaChannelIds??[]):void 0,u=(await this.graphql(Ri,{input:{automationId:n,...i?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:i,includeEmail:s})).updateAutomationAlertDelivery;if(!u)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return u}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Si(i.errors),400,{errors:i.errors});if(!i.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return i.data}};function wi(t){if(typeof t=="string")return Fe(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}r(wi,"requireAutomationID");function Fe(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}r(Fe,"requireAutomationIDString");function Ti(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}r(Ti,"hasAutomationUpdate");function ki(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}r(ki,"uniqueAlvaChannelIDs");function Si(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}r(Si,"graphQLErrorMessage");var nn=["public","private","paid"];var Ge=class{constructor(e){this.client=e}client;static{r(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let i=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:i,cursor:o,limit:100}),u=a.items.find(c=>c.name===s);if(u)return u;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let i=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Ei(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(o=>Ai(o,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!nn.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${nn.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Ei(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let i=n[1].toLowerCase();return i==="prd"?"https://alva.ai":`https://${i}.alva.ai`}}catch{}return"https://alva.ai"}r(Ei,"webOriginFromApiBase");function Ai(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,o=n&&i?`/u/${n}/playbooks/${i}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:i,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}r(Ai,"toAgentPlaybook");var Oe=class{constructor(e){this.client=e}client;static{r(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Me=class{constructor(e){this.client=e}client;static{r(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var rn=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function sn(t,e){return rn.find(n=>n.skill===t&&n.file===e)}r(sn,"getSkillEndpointMetadata");function Pt(t){return rn.filter(e=>e.skill===t)}r(Pt,"listSkillEndpointMetadata");var $e=class{constructor(e){this.client=e}client;static{r(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...on(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=Pt(e.name);return{...s,...on(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=sn(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function on(t){let e=Pt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}r(on,"metadataSummaryForSkill");function an(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}r(an,"normalizePlaybookSkillSummary");function un(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}r(un,"parsePlaybookSkillId");var je=class{constructor(e){this.client=e}client;static{r(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(an)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=un(e),s=encodeURIComponent(n),o=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...an(u),files:u.files??[]}}async file(e,n){let{username:i,name:s}=un(e),o=encodeURIComponent(i),a=encodeURIComponent(s),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${u}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var Be=class{constructor(e){this.client=e}client;static{r(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Qe=class{constructor(e){this.client=e}client;static{r(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var Ve=class{constructor(e){this.client=e}client;static{r(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Ye=class{constructor(e){this.client=e}client;static{r(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var He=class{constructor(e){this.client=e}client;static{r(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var We=class{constructor(e){this.client=e}client;static{r(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Ke=class{constructor(e){this.client=e}client;static{r(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var ze=class{constructor(e){this.client=e}client;static{r(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:vi(e)})}};function vi(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}r(vi,"buildQuery");var Je=class{constructor(e){this.client=e}client;static{r(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var Xe=class{constructor(e){this.client=e}client;static{r(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var z=class{constructor(e){this.client=e}client;static{r(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var Ze=class{constructor(e){this.client=e}client;static{r(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:cn(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:cn(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function cn(t){return`{"session_id":${ln(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${ln(t.target_id)}}`}r(cn,"mutationBody");function ln(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}r(ln,"idLiteral");var et=class{constructor(e){this.client=e}client;static{r(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var tt=class{constructor(e){this.client=e}client;static{r(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Ci(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return Rt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>Rt(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:Ii(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function Rt(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=dn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=dn(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),i!==void 0&&(e.updated_at_ms=i),e}r(Rt,"normalizeAllowance");function Ii(t){let e=Rt(t);if(!e)throw new Error("allowance response missing allowance");return e}r(Ii,"requireAllowance");function dn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,i=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}r(dn,"timestampMs");function Ci(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}r(Ci,"parseResultPayload");var xi=`
|
|
92
|
+
`.trim(),J=class{constructor(e){this.client=e;this.delivery=new we(e)}client;static{i(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=Cr(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Me(e.id);if(!xr(e))throw new Error("automation update requires at least one field or trigger=true");return this.client._request("PATCH",`/api/v1/automation/${encodeURIComponent(String(n))}`,{body:{version:e.version,cronjob_id:e.cronjob_id,description:e.description,changelog:e.changelog,agent_type:e.agent_type,trigger:e.trigger}})}stop(e){return this.client.feed.stop(e)}resume(e){return this.client.feed.resume(e)}delete(e){return this.client.feed.delete(e)}publish(e){return this.client.release.feed(e)}},we=class{constructor(e){this.client=e}client;static{i(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Me(e.id),s=(await this.graphql(vr,{automationId:n})).automation?.alertDelivery;if(!s)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include automation.alertDelivery",502);return s}async update(e){this.client._requireAuth();let n=Me(e.id),r=e.alvaChannelIds!==void 0,s=e.emailEnabled!==void 0;if(!r&&!s)throw new Error("automation delivery update requires alvaChannelIds or emailEnabled");let o=r?qr(e.alvaChannelIds??[]):void 0,u=(await this.graphql(Ir,{input:{automationId:n,...r?{alvaChannelIds:o}:{},...s?{emailEnabled:e.emailEnabled}:{}},includeAlvaChannels:r,includeEmail:s})).updateAutomationAlertDelivery;if(!u)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include updateAutomationAlertDelivery",502);return u}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response was empty",502);if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",Nr(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};function Cr(t){if(typeof t=="string")return Me(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}i(Cr,"requireAutomationID");function Me(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}i(Me,"requireAutomationIDString");function xr(t){return t.version!==void 0||t.cronjob_id!==void 0||t.description!==void 0||t.changelog!==void 0||t.agent_type!==void 0||t.trigger===!0}i(xr,"hasAutomationUpdate");function qr(t){let e=[...new Set(t)];for(let n of e)if(!/^(0|[1-9]\d*)$/.test(n))throw new Error("Alva channel ids must be positive integer strings or the agent sentinel 0");return e}i(qr,"uniqueAlvaChannelIDs");function Nr(t){let e=t.map(n=>n&&typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(Nr,"graphQLErrorMessage");var un=["public","private","paid"];var $e=class{constructor(e){this.client=e}client;static{i(this,"PlaybooksResource")}async getByIds(e){return await this.client._request("GET","/api/v1/playbooks",{query:{ids:e.join(",")}})}async listByOwner(e){let n={owner:e.owner};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbooks",{query:n})}async listOwn(e={}){let n={};return e.filter&&(n.filter=e.filter),e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),await this.client._request("GET","/api/v1/playbook",{query:n})}async get(e){if(e.id)return(await this.getByIds([e.id])).items[0]??null;if(e.ref){let n=e.ref.indexOf("/");if(n<=0||n===e.ref.length-1)throw new l("INVALID_ARGUMENT",`Invalid ref "${e.ref}". Expected "owner/name".`,400);let r=e.ref.slice(0,n),s=e.ref.slice(n+1),o;for(;;){let a=await this.listByOwner({owner:r,cursor:o,limit:100}),u=a.items.find(c=>c.name===s);if(u)return u;if(!a.has_next||!a.next_cursor)return null;o=a.next_cursor}}throw new l("INVALID_ARGUMENT","id or ref is required",400)}async trending(e={}){let n={};e.cursor&&(n.cursor=e.cursor),e.current&&(n.current=e.current),e.limit!==void 0&&(n.limit=e.limit),e.dir&&(n.dir=e.dir),e.sort&&(n.sort=e.sort),e.keyword&&(n.keyword=e.keyword),e.tags&&e.tags.length>0&&(n.tags=e.tags.join(","));let r=await this.client._request("GET","/api/v1/playbooks/trending",{query:n}),s=Dr(this.client.baseUrl);return{playbooks:(r.playbooks??[]).map(o=>Ur(o,s)),has_next:r.has_next??!1}}async setVisibility(e){if(!un.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${un.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Dr(t){try{let e=new URL(t).hostname,n=/^api-llm\.([a-z0-9-]+)\.alva\.ai$/i.exec(e);if(n){let r=n[1].toLowerCase();return r==="prd"?"https://alva.ai":`https://${r}.alva.ai`}}catch{}return"https://alva.ai"}i(Dr,"webOriginFromApiBase");function Ur(t,e){let n=t.creator?.name??"",r=t.name??"",s=n&&r?`${n}/${r}`:r,o=n&&r?`/u/${n}/playbooks/${r}`:"";return{id:t.id===void 0?"":String(t.id),ref:s,username:n,name:r,display_name:t.display_name??"",description:t.description??"",tags:t.tags??[],follow_count:t.follow_count??0,url_path:o,url:o?`${e}${o}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}i(Ur,"toAgentPlaybook");var je=class{constructor(e){this.client=e}client;static{i(this,"SecretsResource")}async create(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/secrets",{body:{name:e.name,value:e.value}})}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/secrets")}async get(e){this.client._requireAuth();let n=encodeURIComponent(e.name);return this.client._request("GET",`/api/v1/secrets/${n}`)}async update(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("PUT",`/api/v1/secrets/${n}`,{body:{value:e.value}})}async delete(e){this.client._requireAuth();let n=encodeURIComponent(e.name);await this.client._request("DELETE",`/api/v1/secrets/${n}`)}};var Be=class{constructor(e){this.client=e}client;static{i(this,"SdkDocsResource")}async doc(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/doc",{query:{name:e.name}})}async partitions(){return this.client._requireAuth(),this.client._request("GET","/api/v1/sdk/partitions")}async partitionSummary(e){this.client._requireAuth();let n=encodeURIComponent(e.partition);return this.client._request("GET",`/api/v1/sdk/partitions/${n}/summary`)}};var cn=[{skill:"arrays-data-api-crypto-futures-data",file:"binance-perp-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/perp/usdt/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"binance-spot-usdt-kline",method:"GET",path:"/api/v1/crypto/binance/spot/usdt/kline"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"fear-greed-index",method:"GET",path:"/api/v1/crypto/fear-greed-index"},{skill:"arrays-data-api-crypto-futures-data",file:"funding-rate",method:"GET",path:"/api/v1/crypto/funding-rate"},{skill:"arrays-data-api-crypto-futures-data",file:"hyperliquid-perp-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/perp/usdc/kline"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"hyperliquid-spot-usdc-kline",method:"GET",path:"/api/v1/crypto/hyperliquid/spot/usdc/kline"},{skill:"arrays-data-api-crypto-futures-data",file:"long-short-ratio",method:"GET",path:"/api/v1/crypto/long-short-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-market-cap",method:"GET",path:"/api/v1/crypto/market-cap"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"market-metrics",method:"GET",path:"/api/v1/crypto/market-metrics"},{skill:"arrays-data-api-crypto-futures-data",file:"open-interest",method:"GET",path:"/api/v1/crypto/open-interest"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics",method:"GET",path:"/api/v1/crypto/screener/metrics"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"screener-metrics-timerange",method:"GET",path:"/api/v1/crypto/screener/metrics/timerange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-detail",method:"GET",path:"/api/v1/crypto/detail"},{skill:"arrays-data-api-etf-fundamentals",file:"country-weightings",method:"GET",path:"/api/v1/etf/country-weightings"},{skill:"arrays-data-api-etf-fundamentals",file:"holdings",method:"GET",path:"/api/v1/etf/holdings"},{skill:"arrays-data-api-etf-fundamentals",file:"info",method:"GET",path:"/api/v1/etf/info"},{skill:"arrays-data-api-etf-fundamentals",file:"sector-weightings",method:"GET",path:"/api/v1/etf/sector-weightings"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-historical",method:"GET",path:"/api/v1/macro/commodity/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-real-time",method:"GET",path:"/api/v1/macro/commodity/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-commodity-symbol-list",method:"GET",path:"/api/v1/macro/commodity/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"economic-indicators",method:"GET",path:"/api/v1/macro/economic-indicators"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-historical",method:"GET",path:"/api/v1/macro/forex/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-real-time",method:"GET",path:"/api/v1/macro/forex/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"macro-forex-symbol-list",method:"GET",path:"/api/v1/macro/forex/symbols"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-historical",method:"GET",path:"/api/v1/macro/index/historical"},{skill:"arrays-data-api-macro-and-economics",file:"macro-index-real-time",method:"GET",path:"/api/v1/macro/index/real-time"},{skill:"arrays-data-api-macro-and-economics",file:"rates",method:"GET",path:"/api/v1/macro/treasury-rates"},{skill:"arrays-data-api-equity-fundamentals",file:"company-balance-sheets",method:"GET",path:"/api/v1/stocks/company/balance-sheets"},{skill:"arrays-data-api-equity-fundamentals",file:"company-cashflow-statements",method:"GET",path:"/api/v1/stocks/company/cashflow-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail",method:"GET",path:"/api/v1/stocks/company/detail"},{skill:"arrays-data-api-equity-fundamentals",file:"company-income-statements",method:"GET",path:"/api/v1/stocks/company/income-statements"},{skill:"arrays-data-api-equity-fundamentals",file:"company-kpi",method:"GET",path:"/api/v1/stocks/company/kpi"},{skill:"arrays-data-api-equity-events",file:"crowdfunding-offerings",method:"GET",path:"/api/v1/stocks/crowdfunding/offerings"},{skill:"arrays-data-api-equity-events",file:"dividends",method:"GET",path:"/api/v1/stocks/dividends"},{skill:"arrays-data-api-equity-events",file:"earnings-calendar",method:"GET",path:"/api/v1/stocks/earnings-calendar"},{skill:"arrays-data-api-equity-events",file:"equity-offering",method:"GET",path:"/api/v1/stocks/equity-offering"},{skill:"arrays-data-api-stock-metrics",file:"financial-metrics",method:"GET",path:"/api/v1/stocks/financial-metrics"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates",method:"GET",path:"/api/v1/stocks/fiscal-dates"},{skill:"arrays-data-api-equity-fundamentals",file:"fiscal-dates-range",method:"GET",path:"/api/v1/stocks/fiscal-dates/range"},{skill:"arrays-data-api-equity-events",file:"ipo-calendar",method:"GET",path:"/api/v1/stocks/ipo-calendar"},{skill:"arrays-data-api-equity-events",file:"ipo-confirmed-calendar",method:"GET",path:"/api/v1/stocks/ipo-confirmed-calendar"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-kline",method:"GET",path:"/api/v1/stocks/kline"},{skill:"arrays-data-api-stock-metrics",file:"market-metrics",method:"GET",path:"/api/v1/stocks/market-metrics"},{skill:"arrays-data-api-equity-events",file:"mergers-acquisitions",method:"GET",path:"/api/v1/stocks/mergers-acquisitions"},{skill:"arrays-data-api-equity-fundamentals",file:"outstanding-shares",method:"GET",path:"/api/v1/stocks/outstanding-shares"},{skill:"arrays-data-api-stock-metrics",file:"ratings",method:"GET",path:"/api/v1/stocks/ratings"},{skill:"arrays-data-api-stock-screener",file:"basic-info-screener",method:"GET",path:"/api/v1/stocks/screener/basic-info/{sub}"},{skill:"arrays-data-api-stock-screener",file:"event-screener",method:"GET",path:"/api/v1/stocks/screener/events"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics",method:"GET",path:"/api/v1/stocks/screener/financial-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-financial-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/financial-metrics/timerange"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics",method:"GET",path:"/api/v1/stocks/screener/technical-metrics"},{skill:"arrays-data-api-stock-screener",file:"screener-technical-metrics-timerange",method:"GET",path:"/api/v1/stocks/screener/technical-metrics/timerange"},{skill:"arrays-data-api-equity-events",file:"sec-earnings-release",method:"GET",path:"/api/v1/stocks/sec-earnings-release"},{skill:"arrays-data-api-equity-fundamentals",file:"shares-float",method:"GET",path:"/api/v1/stocks/shares-float"},{skill:"arrays-data-api-equity-events",file:"splits",method:"GET",path:"/api/v1/stocks/splits"},{skill:"arrays-data-api-crypto-exchange-flow",file:"exchange-flows",method:"GET",path:"/api/v1/crypto/exchange-flows"},{skill:"arrays-data-api-company-crypto-holdings",file:"crypto-holdings",method:"GET",path:"/api/v1/crypto/holdings"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-inflow-cdd",method:"GET",path:"/api/v1/crypto/metrics/inflow-cdd"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-leverage-ratio",method:"GET",path:"/api/v1/crypto/metrics/leverage-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-miner-to-exchange",method:"GET",path:"/api/v1/crypto/metrics/miner-to-exchange"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-mvrv",method:"GET",path:"/api/v1/crypto/metrics/mvrv"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-nupl",method:"GET",path:"/api/v1/crypto/metrics/nupl"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-puell-multiple",method:"GET",path:"/api/v1/crypto/metrics/puell-multiple"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-realized-price",method:"GET",path:"/api/v1/crypto/metrics/realized-price"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-sopr",method:"GET",path:"/api/v1/crypto/metrics/sopr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-ssr",method:"GET",path:"/api/v1/crypto/metrics/ssr"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"metrics-whale-ratio",method:"GET",path:"/api/v1/crypto/metrics/whale-ratio"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"crypto-supply",method:"GET",path:"/api/v1/crypto/supply"},{skill:"arrays-data-api-crypto-futures-data",file:"taker-buy-sell-volume",method:"GET",path:"/api/v1/crypto/taker-buy-sell-volume"},{skill:"arrays-data-api-crypto-metrics-and-screener",file:"unlock-events",method:"GET",path:"/api/v1/crypto/unlock-events"},{skill:"arrays-data-api-etf-fundamentals",file:"flow",method:"GET",path:"/api/v1/etf/flow"},{skill:"arrays-data-api-options",file:"contracts",method:"GET",path:"/api/v1/options/contracts"},{skill:"arrays-data-api-options",file:"kline",method:"GET",path:"/api/v1/options/kline"},{skill:"arrays-data-api-options",file:"greeks",method:"GET",path:"/api/v1/options/greeks"},{skill:"arrays-data-api-options",file:"chain",method:"GET",path:"/api/v1/options/chain"},{skill:"arrays-data-api-equity-fundamentals",file:"company-executives",method:"GET",path:"/api/v1/stocks/company/executives"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-consensus",method:"GET",path:"/api/v1/stocks/company/price-target-consensus"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-news",method:"GET",path:"/api/v1/stocks/company/price-target-news"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"company-price-target-summary",method:"GET",path:"/api/v1/stocks/company/price-target-summary"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"congress-recent-trades",method:"GET",path:"/api/v1/stocks/congress/recent-trades"},{skill:"arrays-data-api-stock-metrics",file:"darkpool",method:"GET",path:"/api/v1/stocks/darkpool"},{skill:"arrays-data-api-equity-estimates-and-targets",file:"estimates-guidance",method:"GET",path:"/api/v1/stocks/estimates-guidance"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"insider-transactions",method:"GET",path:"/api/v1/stocks/insider/transactions"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"institution-holder",method:"GET",path:"/api/v1/stocks/institution-holder"},{skill:"arrays-data-api-polymarket",file:"activity",method:"GET",path:"polymarket:/activity"},{skill:"arrays-data-api-polymarket",file:"book",method:"GET",path:"polymarket:/book"},{skill:"arrays-data-api-polymarket",file:"closed-positions",method:"GET",path:"polymarket:/closed-positions"},{skill:"arrays-data-api-polymarket",file:"events",method:"GET",path:"polymarket:/events"},{skill:"arrays-data-api-polymarket",file:"holders",method:"GET",path:"polymarket:/holders"},{skill:"arrays-data-api-polymarket",file:"markets",method:"GET",path:"polymarket:/markets"},{skill:"arrays-data-api-polymarket",file:"midpoint",method:"GET",path:"polymarket:/midpoint"},{skill:"arrays-data-api-polymarket",file:"oi",method:"GET",path:"polymarket:/oi"},{skill:"arrays-data-api-polymarket",file:"positions",method:"GET",path:"polymarket:/positions"},{skill:"arrays-data-api-polymarket",file:"price",method:"GET",path:"polymarket:/price"},{skill:"arrays-data-api-polymarket",file:"prices-history",method:"GET",path:"polymarket:/prices-history"},{skill:"arrays-data-api-polymarket",file:"public-search",method:"GET",path:"polymarket:/public-search"},{skill:"arrays-data-api-polymarket",file:"series",method:"GET",path:"polymarket:/series"},{skill:"arrays-data-api-polymarket",file:"sports",method:"GET",path:"polymarket:/sports"},{skill:"arrays-data-api-polymarket",file:"spread",method:"GET",path:"polymarket:/spread"},{skill:"arrays-data-api-polymarket",file:"tags",method:"GET",path:"polymarket:/tags"},{skill:"arrays-data-api-polymarket",file:"trades",method:"GET",path:"polymarket:/trades"},{skill:"arrays-data-api-polymarket",file:"value",method:"GET",path:"polymarket:/value"},{skill:"arrays-data-api-equity-events",file:"earnings-transcript",method:"GET",path:"/api/v1/stocks/earnings-transcript"},{skill:"arrays-data-api-news",file:"market-news",method:"GET",path:"/api/v1/stocks/market-news"},{skill:"arrays-data-api-social-feeds",file:"x-by-handle",method:"GET",path:"/api/v1/social-feeds/x/by-handle"},{skill:"arrays-data-api-social-feeds",file:"x-by-url",method:"GET",path:"/api/v1/social-feeds/x/by-url"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handle",method:"GET",path:"/api/v1/social-feeds/x/entities/handle/{twitter_handle}"},{skill:"arrays-data-api-social-feeds",file:"x-entities-handles",method:"GET",path:"/api/v1/social-feeds/x/entities/handles"},{skill:"arrays-data-api-equity-fundamentals",file:"company-detail-non-us",method:"GET",path:"/api/v1/stocks/non-us/company/detail"},{skill:"arrays-data-api-social-feeds",file:"x-search",method:"GET",path:"/api/v1/social-feeds/x/search"},{skill:"arrays-data-api-spot-market-price-and-volume",file:"stocks-non-us-kline",method:"GET",path:"/api/v1/stocks/non-us/kline"},{skill:"arrays-data-api-semiconductor-price",file:"dram-spot-price",method:"GET",path:"/api/v1/other/semiconductor/dram-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"dram-contract-price",method:"GET",path:"/api/v1/other/semiconductor/dram-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-spot-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-spot-price"},{skill:"arrays-data-api-semiconductor-price",file:"nand-flash-contract-price",method:"GET",path:"/api/v1/other/semiconductor/nand-flash-contract-price"},{skill:"arrays-data-api-semiconductor-price",file:"memory-card-price",method:"GET",path:"/api/v1/other/semiconductor/memory-card-price"},{skill:"arrays-data-api-semiconductor-price",file:"dxi-index",method:"GET",path:"/api/v1/other/semiconductor/dxi-index"},{skill:"arrays-data-api-equity-ownership-and-flow",file:"short-interest",method:"GET",path:"/api/v1/stocks/short-interest"},{skill:"arrays-data-api-social-feeds",file:"x-handles",method:"POST",path:"/api/v1/social-feeds/x/handles"}];function ln(t,e){return cn.find(n=>n.skill===t&&n.file===e)}i(ln,"getSkillEndpointMetadata");function Tt(t){return cn.filter(e=>e.skill===t)}i(Tt,"listSkillEndpointMetadata");var Qe=class{constructor(e){this.client=e}client;static{i(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...dn(n.name)}))}}async summary(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data?.[0];if(!s)throw new Error(`empty skills summary response for "${e.name}"`);let o=Tt(e.name);return{...s,...dn(e.name),...o.length>0?{endpoint_metadata:o}:{}}}async endpoint(e){let n=encodeURIComponent(e.name),s=(await this.client._request("GET",`/api/v1/skills/${n}`,{baseUrl:this.client.arraysBaseUrl,noAuth:!0,query:{endpoint:e.file}})).data?.[0];if(!s)throw new Error(`empty skills endpoint response for "${e.name}" file "${e.file}"`);let o=ln(e.name,e.file);return{...s,...o?{metadata:o}:{}}}};function dn(t){let e=Tt(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}i(dn,"metadataSummaryForSkill");function pn(t){return{username:t.username,name:t.name,display_name:t.display_name,description:t.description,tags:t.tags,creator_uid:t.creator_uid,updated_at:t.updated_at}}i(pn,"normalizePlaybookSkillSummary");function mn(t){let e=t.split("/");if(e.length!==2||!e[0]||!e[1])throw new l("INVALID_ARGUMENT",`playbook skill identifier must be "<user>/<name>", got "${t}"`,0);return{username:e[0],name:e[1]}}i(mn,"parsePlaybookSkillId");var Ve=class{constructor(e){this.client=e}client;static{i(this,"PlaybookSkillsResource")}async list(e){let n={};return e?.tag&&(n.tag=e.tag),e?.username&&(n.username=e.username),{skills:((await this.client._request("GET","/api/v1/skills",{query:n})).data??[]).map(pn)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:r}=mn(e),s=encodeURIComponent(n),o=encodeURIComponent(r),u=(await this.client._request("GET",`/api/v1/skills/${s}/${o}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...pn(u),files:u.files??[]}}async file(e,n){let{username:r,name:s}=mn(e),o=encodeURIComponent(r),a=encodeURIComponent(s),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${o}/${a}/files/${u}`)).data?.[0];if(!d)throw new l("NOT_FOUND",`empty playbook skills file response for ${e} path ${n}`,0);return d}};var He=class{constructor(e){this.client=e}client;static{i(this,"CommentsResource")}async create(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment",{body:{username:e.username,name:e.name,content:e.content,parent_id:e.parent_id}})}async pin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/pin",{body:{comment_id:e.comment_id}})}async unpin(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/playbook/comment/unpin",{body:{comment_id:e.comment_id}})}};var Ye=class{constructor(e){this.client=e}client;static{i(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var We=class{constructor(e){this.client=e}client;static{i(this,"ScreenshotResource")}async capture(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/screenshot",{query:{url:e.url,selector:e.selector,xpath:e.xpath,compress:e.compress,compress_quality:e.compressQuality,compress_max_width:e.compressMaxWidth}})}};var Ke=class{constructor(e){this.client=e}client;static{i(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var Xe=class{constructor(e){this.client=e}client;static{i(this,"TradingResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/accounts")}async portfolio(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/portfolio",{query:{accountId:e}})}async orders(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/orders",{query:{accountId:e.accountId,source:e.source,since:e.since,limit:e.limit}})}async subscriptions(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/subscriptions",{query:{accountId:e}})}async equityHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/equity-history",{query:{accountId:e.accountId,timeframe:e.timeframe,sinceMs:e.sinceMs,untilMs:e.untilMs}})}async riskRules(){return this.client._requireAuth(),this.client._request("GET","/api/v1/trading/risk-rules")}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/subscribe",{body:e})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/unsubscribe",{body:{subscriptionId:e}})}async execute(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/trading/execute",{body:e})}async updateRiskRules(e){return this.client._requireAuth(),this.client._request("PUT","/api/v1/trading/risk-rules",{body:e})}};var ze=class{constructor(e){this.client=e}client;static{i(this,"PortfolioResource")}async accounts(){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/accounts")}async summary(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/summary",{query:{accountId:e}})}async activities(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/portfolio/activities",{query:{accountId:e.accountId,limit:e.limit,pageToken:e.pageToken}})}};var Je=class{constructor(e){this.client=e}client;static{i(this,"ArraysJwtResource")}async ensure(){return this.client._requireAuth(),this.client._request("POST","/api/v1/arrays-jwt/ensure")}async status(){return this.client._requireAuth(),this.client._request("GET","/api/v1/arrays-jwt/status")}};var Ze=class{constructor(e){this.client=e}client;static{i(this,"NotificationsResource")}async listFeed(e){this.client._requireAuth();let n=`/api/v1/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}/notifications`;return this.client._request("GET",n,{query:Lr(e)})}};function Lr(t){let e={};return t.channel&&(e.channel=t.channel),t.status&&(e.status=t.status),t.since_time!==void 0&&t.since_time>0&&(e.since_time=String(t.since_time)),t.first!==void 0&&t.first>0&&(e.first=String(t.first)),t.cursor&&(e.cursor=t.cursor),e}i(Lr,"buildQuery");var et=class{constructor(e){this.client=e}client;static{i(this,"NotificationPreferencesResource")}async list(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me/notifications/preferences")}async update(e){return this.client._requireAuth(),this.client._request("PATCH",`/api/v1/me/notifications/preferences/${encodeURIComponent(e.key)}`,{body:{enabled:e.enabled}})}};var tt=class{constructor(e){this.client=e}client;static{i(this,"SubscriptionsResource")}async followPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("POST",n)}async unfollowPlaybook(e){this.client._requireAuth();let n=`/api/v1/follows/playbook/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async subscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return e.channelId===void 0?this.client._request("POST",n):this.client._request("POST",n,{body:{channel_id:e.channelId}})}async unsubscribeFeed(e){this.client._requireAuth();let n=`/api/v1/subscriptions/feed/${encodeURIComponent(e.username)}/${encodeURIComponent(e.name)}`;return this.client._request("DELETE",n)}async list(e={}){this.client._requireAuth();let n={};return e.first!==void 0&&e.first>0&&(n.first=String(e.first)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/subscriptions",{query:n})}async follows(e={}){this.client._requireAuth();let n={};return e.limit!==void 0&&e.limit>0&&(n.limit=String(e.limit)),e.cursor&&(n.cursor=e.cursor),this.client._request("GET","/api/v1/me/follows",{query:n})}async subscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/subscribe-batch",{body:{feed_ids:e.feedIds,channel_id:e.channelId}})}async unsubscribeBatch(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/subscriptions/unsubscribe-batch",{body:{feed_ids:e.feedIds}})}};var Z=class{constructor(e){this.client=e}client;static{i(this,"AlertsResource")}list(e={}){return this.client.subscriptions.list(e)}follows(e={}){return this.client.subscriptions.follows(e)}enableAutomation(e){return this.client.subscriptions.subscribeFeed(e)}disableAutomation(e){return this.client.subscriptions.unsubscribeFeed(e)}enableBatch(e){return this.client.subscriptions.subscribeBatch(e)}disableBatch(e){return this.client.subscriptions.unsubscribeBatch(e)}historyAutomation(e){return this.client.notifications.listFeed(e)}preferences(){return this.client.notificationPreferences.list()}updatePreference(e){return this.client.notificationPreferences.update(e)}};var nt=class{constructor(e){this.client=e}client;static{i(this,"ChannelGroupSubscriptionsResource")}async context(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions/context",{query:{session_id:e.session_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-subscriptions",{query:{session_id:e.session_id}})}async subscribe(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/channel/group-subscriptions",{jsonBody:hn(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:hn(e)})}async getGroupChatHistory(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/channel/group-history",{query:{channel:e.channel,remote_chat_id:e.remote_chat_id,from_micros:String(e.from_micros),to_micros:String(e.to_micros)}})}};function hn(t){return`{"session_id":${fn(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${fn(t.target_id)}}`}i(hn,"mutationBody");function fn(t){if(typeof t=="number"){if(!Number.isInteger(t)||t<=0||!Number.isSafeInteger(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive safe integers; pass large int64 ids as strings",0);return String(t)}if(!/^[1-9]\d*$/.test(t))throw new l("INVALID_ARGUMENT","channel group subscription ids must be positive integer strings",0);return t}i(fn,"idLiteral");var rt=class{constructor(e){this.client=e}client;static{i(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var it=class{constructor(e){this.client=e}client;static{i(this,"FunctionsResource")}async register(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/service/functions",{body:{playbook_id:e.playbook_id,function_name:e.function_name,entry_script_path:e.entry_script_path,params_schema:e.params_schema,allow_charges:e.allow_charges,run_as_user_id:e.run_as_user_id}})}async list(e){return this.client._requireAuth(),this.client._request("GET","/api/v1/service/functions",{query:{playbook_id:e.playbook_id}})}async delete(e){this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/functions",{query:{playbook_id:e.playbook_id,function_name:e.function_name}})}async invoke(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/invoke",{body:{playbook_id:e.playbook_id,function_name:e.function_name,parameters_json:JSON.stringify(e.parameters??{})}});return{...n,result:Or(n.result)}}async getAllowance(e){this.client._requireAuth();let n=await this.client._request("GET","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}});return kt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>kt(n)).filter(n=>n!==null)}}async createAllowance(e){this.client._requireAuth();let n=await this.client._request("POST","/api/v1/service/allowance",{body:{playbook_id:e.playbook_id,amount:e.amount}});return{allowance:Fr(n.allowance)}}async revokeAllowance(e){return this.client._requireAuth(),await this.client._request("DELETE","/api/v1/service/allowance",{query:{playbook_id:e.playbook_id}}),{ok:!0}}};function kt(t){if(!t)return null;let e={id:t.id??"",consumer_uid:t.consumer_uid??t.consumerUid??"",playbook_id:t.playbook_id??t.playbookId??"",amount:t.amount??0,used:t.used??0,remaining:t.remaining??0},n=yn(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),r=yn(t.updated_at_ms??t.updatedAtMs??t.updated_at??t.updatedAt);return n!==void 0&&(e.created_at_ms=n),r!==void 0&&(e.updated_at_ms=r),e}i(kt,"normalizeAllowance");function Fr(t){let e=kt(t);if(!e)throw new Error("allowance response missing allowance");return e}i(Fr,"requireAllowance");function yn(t){if(t==null)return;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s;let o=Date.parse(t);return Number.isNaN(o)?void 0:o}if(typeof t!="object")return;let e=t,n=typeof e.seconds=="number"?e.seconds:typeof e.seconds=="string"?Number(e.seconds):void 0,r=typeof e.nanos=="number"?e.nanos:typeof e.nanos=="string"?Number(e.nanos):0;if(!(n===void 0||!Number.isFinite(n)))return n*1e3+Math.floor((Number.isFinite(r)?r:0)/1e6)}i(yn,"timestampMs");function Or(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}i(Or,"parseResultPayload");var Gr=`
|
|
93
93
|
query ToolkitCreditWallet {
|
|
94
94
|
viewer {
|
|
95
95
|
creditWallet {
|
|
@@ -99,7 +99,7 @@ query ToolkitCreditWallet {
|
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
101
|
}
|
|
102
|
-
`.trim(),
|
|
102
|
+
`.trim(),Mr=`
|
|
103
103
|
query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
104
104
|
viewer {
|
|
105
105
|
creditWallet {
|
|
@@ -131,7 +131,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
|
-
`.trim();function
|
|
134
|
+
`.trim();function $r(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i($r,"graphQLErrorMessage");var st=class{constructor(e){this.client=e}client;static{i(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(Gr)).viewer?.creditWallet;if(!n)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet",502);return n}async items(e){this.client._requireAuth();let r=(await this.graphql(Mr,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!r)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return r}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",$r(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var jr=["Q1","Q2","Q3","Q4"],Br=["latest-completed","next-confirmed"],Qr=`
|
|
135
135
|
query ToolkitCompanyNarrative($ticker: String!) {
|
|
136
136
|
market {
|
|
137
137
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -157,7 +157,7 @@ query ToolkitCompanyNarrative($ticker: String!) {
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`.trim(),
|
|
160
|
+
`.trim(),Vr=`
|
|
161
161
|
query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
162
162
|
market {
|
|
163
163
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -188,7 +188,7 @@ query ToolkitCompanyEarningsCatalog($ticker: String!) {
|
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
|
-
`.trim(),
|
|
191
|
+
`.trim(),Hr=`
|
|
192
192
|
query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
193
193
|
market {
|
|
194
194
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -258,7 +258,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
258
258
|
}
|
|
259
259
|
}
|
|
260
260
|
}
|
|
261
|
-
`.trim();function
|
|
261
|
+
`.trim();function Yr(t){let e=t.map(n=>typeof n.message=="string"&&n.message?n.message:void 0).filter(n=>!!n);return e.length>0?e.join("; "):"GraphQL request failed"}i(Yr,"graphQLErrorMessage");function St(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}i(St,"normalizedTicker");var ee=class{constructor(e){this.client=e}client;static{i(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=St(e),s=(await this.graphql(Qr,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);return{ticker:s.ticker,current:s.companyInsight,history:s.companyInsightHistory}}async earningsPeriods(e){this.client._requireAuth();let n=St(e),s=(await this.graphql(Vr,{ticker:n})).market?.entity;if(!s)throw this.notFound(n);if(!s.earningsPeriods)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings periods are available for ${s.ticker}`,404,{ticker:s.ticker});return s.earningsPeriods}async earnings(e){this.client._requireAuth();let n=St(e.ticker),r=e.event,s=e.fiscalYear,o=e.fiscalQuarter;if(r!==void 0&&(s!==void 0||o!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(o===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(r!==void 0&&!Br.includes(r))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${r}`,400);if(s!==void 0&&(!Number.isInteger(s)||s<1900||s>9999))throw new l("INVALID_ARGUMENT","fiscalYear must be an integer between 1900 and 9999",400);if(o!==void 0&&!jr.includes(o))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let u,c;if(s!==void 0&&o!==void 0)u=s,c=o;else{let f=r??"latest-completed",E=await this.earningsPeriods(n),L=this.selectPeriod(E,f,n);u=L.fiscalYear,c=L.fiscalQuarter}let h=(await this.graphql(Hr,{ticker:n,input:{fiscalYear:u,fiscalQuarter:c}})).market?.entity;if(!h)throw this.notFound(n);if(!h.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${h.ticker} FY${u} ${c}`,404,{ticker:h.ticker,fiscalYear:u,fiscalQuarter:c});return{ticker:h.ticker,...h.earnings}}selectPeriod(e,n,r){if(n==="latest-completed"){if(e.defaultPeriod)return e.defaultPeriod}else{let s=e.periods.filter(o=>o.status==="UPCOMING").sort((o,a)=>o.earningsDate.localeCompare(a.earningsDate));if(s.length>0)return s[0]}throw new l("MARKETS_EARNINGS_EVENT_NOT_FOUND",`No ${n} earnings event is available for ${r}`,404,{ticker:r,event:n})}notFound(e){return new l("MARKETS_ENTITY_NOT_FOUND",`No stock entity was found for ${e}`,404,{ticker:e})}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(r.errors&&r.errors.length>0)throw new l("GRAPHQL_ERROR",Yr(r.errors),400,{errors:r.errors});if(!r.data)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include data",502);return r.data}};var ot=`
|
|
262
262
|
id
|
|
263
263
|
name
|
|
264
264
|
rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
|
|
@@ -271,45 +271,45 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
271
271
|
nextFireAtMs
|
|
272
272
|
createdAtMs
|
|
273
273
|
updatedAtMs
|
|
274
|
-
`,
|
|
274
|
+
`,Wr=`
|
|
275
275
|
query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
|
|
276
276
|
viewer { channel(id: $channelId) {
|
|
277
277
|
schedules(input: { first: 64, after: $after }) {
|
|
278
|
-
edges { node { channel { id } ${
|
|
278
|
+
edges { node { channel { id } ${ot} } }
|
|
279
279
|
pageInfo { hasNextPage endCursor }
|
|
280
280
|
}
|
|
281
281
|
} }
|
|
282
|
-
}`.trim()
|
|
282
|
+
}`.trim(),Kr=`
|
|
283
283
|
mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
|
|
284
284
|
updateChannelSchedule(input: $input) {
|
|
285
|
-
schedule { channel { id } ${
|
|
285
|
+
schedule { channel { id } ${ot} }
|
|
286
286
|
deleted
|
|
287
287
|
}
|
|
288
|
-
}`.trim(),
|
|
288
|
+
}`.trim(),Xr=`
|
|
289
289
|
query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
|
|
290
290
|
viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
|
|
291
|
-
edges { node { ${
|
|
291
|
+
edges { node { ${ot} } }
|
|
292
292
|
pageInfo { hasNextPage endCursor }
|
|
293
293
|
} }
|
|
294
|
-
}`.trim(),
|
|
294
|
+
}`.trim(),zr=`
|
|
295
295
|
mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
|
|
296
296
|
updateSessionSchedule(input: $input) {
|
|
297
|
-
schedule { ${
|
|
297
|
+
schedule { ${ot} }
|
|
298
298
|
deleted
|
|
299
299
|
}
|
|
300
|
-
}`.trim(),
|
|
300
|
+
}`.trim(),Jr=`
|
|
301
301
|
query ToolkitAgentChannel {
|
|
302
302
|
viewer { channels { id kind } }
|
|
303
|
-
}`.trim(),
|
|
303
|
+
}`.trim(),Zr=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,ei=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,ti=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,ni=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,ri={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},te=class{constructor(e){this.client=e}client;static{i(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Et(e),r="inboxPath"in n,s=[],o=null,a=new Set;for(;;){let u=await this.graphql(r?Xr:Wr,{...n,after:o}),c=r?u.viewer?.sessionSchedules:u.viewer?.channel?.schedules;if(!c?.edges)throw bn();for(let h of c.edges){if(!h?.node)throw w();s.push(At(h.node))}if(c.pageInfo?.hasNextPage!==!0)return s;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw w();a.add(d),o=d}}async put(e){this.client._requireAuth();let n={...Et(e),name:_n(e.name),definition:{...ii(e.rule,e.bounds),message:{text:ui(e.text)}}},r=(await this.update(n))?.schedule;if(!r)throw w();return At(r)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({...gn(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw w()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(Jr)).viewer?.channels?.find(r=>r.kind==="AGENT")?.id;if(!n)throw bn();return n}async manage(e,n){this.client._requireAuth();let r=(await this.update({...gn(n),lifecycle:e}))?.schedule;if(!r)throw w();return At(r)}async update(e){let n="inboxPath"in e,r=await this.graphql(n?zr:Kr,{input:e});return n?r.updateSessionSchedule:r.updateChannelSchedule}async graphql(e,n){let r=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(r.errors?.length){let s=r.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,u=a?ri[a]:void 0,c=a!==void 0&&u!==void 0?a:"GRAPHQL_ERROR";throw new l(c,r.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",u??502,{errors:r.errors})}if(!r.data)throw w();return r.data}};function ii(t,e){let n=si(e);switch(t.kind){case"after":if(n)throw b("after does not accept recurring bounds");let r=Date.now()+Pn(t.duration,1),s=Math.ceil(r/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw b("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw b("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:vt(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:ci(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw b("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}i(ii,"ruleInput");function si(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=vt(t.startsAt)),t.until!==void 0&&(e.untilMs=vt(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw b("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}i(si,"boundsInput");function At(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw w();let r=t.bounds??{},s=t.message??{},o={name:t.name,rule:oi(t.rule),bounds:{...r.startsAtMs!=null?{startsAt:B(r.startsAtMs,!0)}:{},...r.untilMs!=null?{until:B(r.untilMs,!0)}:{},...r.maxOccurrences!=null?{maxOccurrences:It(r.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:It(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:B(t.nextFireAtMs,!0)}:{},createdAt:B(t.createdAtMs),updatedAt:B(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw w();let u={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!u)throw w();o.failure={code:u,...t.failureAtMs!=null?{at:B(t.failureAtMs)}:{}}}return o}i(At,"fromWireSchedule");function oi(t){switch(t.kind){case"AT":if(t.atMs==null)throw w();return{kind:"at",timestamp:B(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw w();return{kind:"every",interval:`PT${It(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw w();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw w()}i(oi,"fromWireRule");function gn(t){return{...Et(t),name:_n(t.name)}}i(gn,"managementInput");function Et(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw b("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:ai(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?Rn(e):void 0;if(typeof e!="string"||n===void 0||n>2048||!e.startsWith("/")||e.includes("\0")||e.slice(1).split("/").some(s=>s===""||s==="."||s===".."))throw b("inboxPath must be a canonical absolute ALFS Inbox path");let r=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(r===void 0||/\.inbox(?:\.jsonl)?$/.test(r)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(r)||r.endsWith("/.jsonl"))throw b("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}i(Et,"targetInput");function ai(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw b("numeric channelId must be a positive safe integer; use a decimal string for larger IDs");let e=String(t);if(!/^[1-9]\d*$/.test(e))throw b("channelId must be a positive integer");return e}i(ai,"channelID");function _n(t){if(!Zr.test(t))throw b("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}i(_n,"requireName");function ui(t){let e=Rn(t);if(e===void 0||!t.trim()||e>16*1024)throw b("text must be 1..16384 UTF-8 bytes");return t}i(ui,"requireText");function ci(t){let e=Pn(t,60);if(e%1e3!==0)throw b("duration must resolve to whole seconds");return e/1e3}i(ci,"durationSeconds");function Pn(t,e){let n=ni.exec(t);if(!n||n.slice(1,5).every(d=>d===void 0)||t.includes("T")&&n.slice(2,5).every(d=>d===void 0))throw b("duration must be a positive ISO 8601 day/time duration");let[r,s,o,a]=n.slice(1,5).map(d=>BigInt(d??"0")),u=((r*24n+s)*60n+o)*60n+a;if(u<BigInt(e))throw b(`duration must be at least ${e} whole seconds`);let c=Number(u*1000n);if(!Number.isSafeInteger(c))throw b("duration is out of range");return c}i(Pn,"durationMilliseconds");function vt(t,e=!1){let n=(e?ti:ei).exec(t);if(!n)throw b("timestamp must be RFC3339 with a timezone");let[r,s,o,a,u,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),h=Number(n[9]??0),f=new Date(Date.UTC(r,s,0)).getUTCDate(),E=Date.parse(t);if(!Number.isFinite(E)||r<1||r>9999||s<1||s>12||o<1||o>f||a>23||u>59||c>59||d>23||h>59)throw b("timestamp must be RFC3339 with a timezone");return E}i(vt,"timestampMilliseconds");function B(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw w();let n=new Date(t);if(Number.isNaN(n.getTime()))throw w();return n.toISOString()}i(B,"timestampString");function It(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw b(`${e} exceeds JavaScript safe integer range`);return n}i(It,"safeInteger");function b(t){return new l("INVALID_ARGUMENT",t,400)}i(b,"invalid");function Rn(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}i(Rn,"utf8Size");function bn(){return new l("NOT_FOUND","channel schedule target not found",404)}i(bn,"scheduleNotFound");function w(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}i(w,"scheduleEmptyResponse");var li={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504},di=`
|
|
304
304
|
mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
|
|
305
305
|
updateStewardDelivery(input: $input) { delivery { deliveryId state } }
|
|
306
|
-
}`.trim(),
|
|
306
|
+
}`.trim(),pi=`
|
|
307
307
|
mutation ToolkitStewardForward($input: UpdateStewardDeliveryInput!) {
|
|
308
308
|
updateStewardDelivery(input: $input) { delivery { deliveryId state channelMessageId } }
|
|
309
|
-
}`.trim(),
|
|
309
|
+
}`.trim(),mi=`
|
|
310
310
|
mutation ToolkitStewardSend($input: PostStewardMessageInput!) {
|
|
311
311
|
postStewardMessage(input: $input) { message { channelMessageId requestId } }
|
|
312
|
-
}`.trim(),
|
|
312
|
+
}`.trim(),hi=`
|
|
313
313
|
query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInput) {
|
|
314
314
|
viewer {
|
|
315
315
|
stewardDigestPending(inboxPath: $inboxPath, input: $input) {
|
|
@@ -322,40 +322,40 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
|
|
|
322
322
|
windowUntilMs
|
|
323
323
|
}
|
|
324
324
|
}
|
|
325
|
-
}`.trim(),
|
|
325
|
+
}`.trim(),fi=`
|
|
326
326
|
mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
|
|
327
327
|
completeStewardBrief(input: $input) { ok }
|
|
328
|
-
}`.trim(),
|
|
329
|
-
edges { cursor node { id latestRelease { thesisPublication { ${
|
|
330
|
-
${
|
|
331
|
-
}`,
|
|
332
|
-
scope: person(slug: $slug) { ${
|
|
333
|
-
}`,
|
|
334
|
-
scope: publicUser(username: $username) { ${
|
|
335
|
-
}`,
|
|
336
|
-
market { scope: entity(input: { id: $id }) { ${
|
|
337
|
-
theses(input: $input) { edges { cursor node { ${
|
|
328
|
+
}`.trim(),yi=new Set(["immediate","digest","suppress"]),gi=/^[1-9][0-9]{0,18}$/;function I(t){return new l("INVALID_ARGUMENT",t,400)}i(I,"invalid");function Te(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw I("steward commands require the steward Session Inbox path");return t.inboxPath}i(Te,"requireInboxPath");function Ct(t,e="delivery id"){if(!gi.test(t))throw I(`${e} must be a positive integer`);return t}i(Ct,"requireDeliveryId");function Tn(t){let e=new Set;for(let n of t){if(Ct(n),e.has(n))throw I(`duplicate delivery id ${n}`);e.add(n)}return[...e]}i(Tn,"normalizeDeliveryIds");function bi(t){if(t.length===0)throw I("at least one delivery id is required");return Tn(t)}i(bi,"requireDeliveryIds");function _i(t){if(!yi.has(t))throw I("decision must be one of immediate, digest, suppress");return t}i(_i,"requireDecision");function Pi(){let t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();let e=new Uint8Array(16);if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let r=0;r<e.length;r+=1)e[r]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}i(Pi,"generateRequestId");function wn(t){if(t===void 0)return Pi();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw I("request id must be a UUID");return t}i(wn,"requireRequestId");function M(){return new l("EMPTY_RESPONSE","steward response was empty",502)}i(M,"emptyResponse");var ne=class{constructor(e){this.client=e}client;static{i(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw I("a decision reason is required");let s=(await this.graphql(di,{input:{inboxPath:Te(e),deliveryId:Ct(e.deliveryId),decision:{decision:_i(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw M();return{state:s.state}}async forward(e){this.client._requireAuth();let r=(await this.graphql(pi,{input:{inboxPath:Te(e),deliveryId:Ct(e.deliveryId),forward:{requestId:wn(e.requestId)}}})).updateStewardDelivery?.delivery;if(!r||!r.channelMessageId)throw M();return{channelMessageId:r.channelMessageId,state:r.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw I("a message body is required");let r=(await this.graphql(mi,{input:{inboxPath:Te(e),requestId:wn(e.requestId),body:e.body,deliveryIds:Tn(e.deliveryIds??[])}})).postStewardMessage?.message;if(!r)throw M();return r}async pending(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw I("first must be an integer between 1 and 100");let r={first:n};if(e.after!==void 0&&e.after!=="")r.after=e.after;else{for(let[h,f]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(f!==void 0&&(!Number.isSafeInteger(f)||f<=0))throw I(`${h} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw I("untilMs must be after sinceMs");e.sinceMs!==void 0&&(r.sinceMs=e.sinceMs),e.untilMs!==void 0&&(r.untilMs=e.untilMs)}let o=(await this.graphql(hi,{inboxPath:Te(e),input:r})).viewer?.stewardDigestPending;if(!o||!Array.isArray(o.edges))throw M();let a=o.windowSinceMs??0,u=o.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw M();let c=o.edges.map(h=>h.node),d=o.pageInfo?.hasNextPage===!0&&o.pageInfo.endCursor?o.pageInfo.endCursor:null;return{items:c,nextCursor:d,windowSinceMs:a,windowUntilMs:u}}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw I("a digest run id is required");if((await this.graphql(fi,{input:{inboxPath:Te(e),deliveryIds:bi(e.deliveryIds),digestRunId:n}})).completeStewardBrief?.ok!==!0)throw M();return{ok:!0}}async graphql(e,n){let r=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!r||typeof r!="object")throw M();if(r.errors?.length){let s=r.errors.map(u=>u.extensions?.code),o=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=o?li[o]:void 0;throw new l(o!==void 0&&a!==void 0?o:"GRAPHQL_ERROR",r.errors.map(u=>u.message).filter(u=>typeof u=="string").join("; ")||"GraphQL request failed",a??502,{errors:r.errors})}if(!r.data)throw M();return r.data}};function $(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i($,"isRecord");function _(t){return typeof t=="string"&&t.trim()!==""?t:void 0}i(_,"stringValue");function at(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}i(at,"numberValue");function ct(t){return t===void 0?void 0:t.trim().toUpperCase()}i(ct,"upper");function Sn(t){return t.split("_")}i(Sn,"pairParts");function Ri(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Sn(e)[1]?.toLowerCase()??""}i(Ri,"inferInstrumentType");function wi(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}i(wi,"inferUnderlyingType");function kn(t,e){let n=_(t.trading_pair)??_(t.tradingPair)??_(t.symbol);if(n===void 0)return;let r=_(t.type),s=Sn(n),o=_(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=_(t.market)??_(t.exchange)??s[0]??"",u=_(t.quote)??s[s.length-1]??"",c=_(t.instrument_type)??_(t.instrumentType)??Ri(r,n),d=_(t.underlying_type)??_(t.underlyingType)??wi(r);return{symbol:o,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...r===void 0?{}:{type:r},..._(t.description)===void 0?{}:{description:_(t.description)},...at(t.fee_rate)===void 0?at(t.feeRate)===void 0?{}:{feeRate:at(t.feeRate)}:{feeRate:at(t.fee_rate)},..._(t.symbol_icon_url)===void 0?_(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:_(t.symbolIconUrl)}:{symbolIconUrl:_(t.symbol_icon_url)}}}i(kn,"normalizeCandidate");function Ti(t){if(!$(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>$(s)?[kn(s)].filter(o=>o!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let r=[];for(let s of n){if(!$(s))continue;let o=_(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!$(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!$(c))continue;let d=kn({...c,instrument_type:c.instrument_type??u.instrument_type},o);d!==void 0&&r.push(d)}}}return r}i(Ti,"flattenResponse");function ki(t,e){let n=e.trim();return t.tradingPair===n?!0:ct(t.symbol)===ct(n)}i(ki,"matchesQuery");function ut(t,e){return e===void 0||ct(t)===ct(e)}i(ut,"matchesFilter");function Si(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}i(Si,"dedupe");function Ai(t){let e=$(t)?t:{};return{market:typeof e.market=="string"?e.market:void 0,instrumentType:typeof e.instrumentType=="string"?e.instrumentType:void 0,underlyingType:typeof e.underlyingType=="string"?e.underlyingType:void 0,quote:typeof e.quote=="string"?e.quote:void 0}}i(Ai,"resolveFilters");function Ei(t,e){let n=t.split("_"),r=n[0],s=n[1],o=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!r||!s||!o||!a?{symbol:t,...e}:{symbol:o,market:e.market??r,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}i(Ei,"pairSearchParams");var re=class{constructor(e){this.client=e}client;static{i(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=$(e)?e.symbol:void 0,r=typeof n=="string"?n.trim():"";if(!r)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:r,strict:!0}}),o=Si(Ti(s)).filter(u=>ki(u,r)).filter(u=>ut(u.market,e.market)).filter(u=>ut(u.instrumentType,e.instrumentType)).filter(u=>ut(u.underlyingType,e.underlyingType)).filter(u=>ut(u.quote,e.quote)),a=e.limit;return a!==void 0&&o.length>a?{query:r,candidates:o.slice(0,a),truncated:!0}:{query:r,candidates:o}}async resolve(e){let n=$(e)?e:{},r=typeof n.pair=="string"?n.pair.trim():void 0,s=Ai(e),o=r===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:Ei(r,s),a=await this.search(o),u=r===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===r);if(u.length!==1)throw new l(u.length===0?"TRADING_PAIR_NOT_FOUND":"TRADING_PAIR_NOT_UNIQUE",u.length===0?`no canonical trading pair matched "${r??o.symbol}"`:`multiple canonical trading pairs matched "${o.symbol}"`,u.length===0?404:409,{query:r??o.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var vn="pageInfo { endCursor hasNextPage }",In="__typename id slug displayName bio",vi="__typename id username displayName bio",Cn="__typename id ticker name kind assetClass venue { id name }",xn=`theses(input: $input) {
|
|
329
|
+
edges { cursor node { id latestRelease { thesisPublication { ${K} } } } }
|
|
330
|
+
${vn}
|
|
331
|
+
}`,Ii=`query ToolkitPersonTheses($slug: String!, $input: ProfileThesisConnectionInput) {
|
|
332
|
+
scope: person(slug: $slug) { ${In} ${xn} }
|
|
333
|
+
}`,Ci=`query ToolkitUserTheses($username: String!, $input: ProfileThesisConnectionInput) {
|
|
334
|
+
scope: publicUser(username: $username) { ${vi} ${xn} }
|
|
335
|
+
}`,xi=`query ToolkitEntityTheses($id: ID!, $input: EntityThesisConnectionInput) {
|
|
336
|
+
market { scope: entity(input: { id: $id }) { ${Cn}
|
|
337
|
+
theses(input: $input) { edges { cursor node { ${K} } } ${vn} }
|
|
338
338
|
} }
|
|
339
|
-
}`,
|
|
339
|
+
}`,qi=`query ToolkitThesisPeople($query: String!) {
|
|
340
340
|
search: people(input: { query: $query, first: 50 }) {
|
|
341
|
-
edges { node { ${
|
|
341
|
+
edges { node { ${In} } } pageInfo { hasNextPage }
|
|
342
342
|
}
|
|
343
|
-
}`,
|
|
343
|
+
}`,Ni=`query ToolkitThesisEntities($query: String!) {
|
|
344
344
|
market { search: entities(input: { query: $query, first: 50, byPrefix: false }) {
|
|
345
|
-
edges { node { ${
|
|
345
|
+
edges { node { ${Cn} } } pageInfo { hasNextPage }
|
|
346
346
|
} }
|
|
347
|
-
}`,
|
|
347
|
+
}`,Di=`query ToolkitRelatedTheses($id: ID!, $input: RelatedThesisInput) {
|
|
348
348
|
node(id: $id) { ... on Playbook { relatedTheses(input: $input) {
|
|
349
349
|
state nextCursor
|
|
350
|
-
edges { cursor node { itemKey score publication { ${
|
|
350
|
+
edges { cursor node { itemKey score publication { ${K} } } }
|
|
351
351
|
} } }
|
|
352
|
-
}`,
|
|
352
|
+
}`,Ui=["person","personName","user","ticker","entityId"];function qn(t){if(!p(t))throw F("Thesis parameters must be an object");let e=t.first===void 0?10:t.first;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>50)throw F("first must be an integer between 1 and 50");if(t.cursor!==void 0&&!U(t.cursor))throw F("cursor must be non-empty")}i(qn,"validateThesisPageParams");function Li(t){qn(t);let e=Ui.filter(n=>t[n]!==void 0);if(e.length!==1)throw F("Choose exactly one of person, personName, user, ticker or entityId");if(!U(t[e[0]]))throw F(`${e[0]} must be non-empty`);if(t.entityId!==void 0&&!k(t.entityId))throw F("entityId must be a positive int64 string");if(t.status!==void 0&&t.status!=="ACTIVE"&&t.status!=="ARCHIVED")throw F("status must be ACTIVE or ARCHIVED");if(t.status!==void 0&&(t.ticker!==void 0||t.entityId!==void 0))throw F("status applies only to author lists")}i(Li,"validateListThesesParams");async function Nn(t,e){Li(e),t._requireAuth();let n={first:e.first??10,after:e.cursor},r=e.ticker===void 0?e.entityId:(await En(t,Ni,e.ticker,"Entity")).id;if(r!==void 0){let u=await ke(t,xi,{id:r,input:n});if(!p(u.market))throw T();return An(u.market.scope,c=>X(c)?{playbookId:c.playbookId,publication:c}:void 0)}let s={...n,status:e.status},o=e.personName===void 0?e.person:(await En(t,qi,e.personName,"Person")).slug,a=o===void 0?await ke(t,Ci,{username:e.user,input:s}):await ke(t,Ii,{slug:o,input:s});return An(a.scope,u=>{if(!k(u.id))return;let c=u.latestRelease;if(c===null)return{playbookId:u.id,publication:null};if(!p(c))return;let d=c.thesisPublication;if(!(d!==null&&!X(d)))return{playbookId:u.id,publication:d}})}i(Nn,"listTheses");async function Dn(t,e,n={}){if(qn(n),!k(e))throw F("id must be an internal positive int64 Playbook ID");t._requireAuth();let r=await ke(t,Di,{id:`Playbook:${e}`,input:{first:n.first??10,after:n.cursor}});if(r.node===null)throw xt();if(!p(r.node))throw T();let s=r.node.relatedTheses;if(!p(s)||!["GENERATING","READY","FAILED"].includes(s.state)||s.nextCursor!==null&&!U(s.nextCursor))throw T();for(let o of Ln(s))if(!U(o.node.itemKey)||typeof o.node.score!="number"||!X(o.node.publication))throw T();return{state:s.state,edges:s.edges,nextCursor:s.nextCursor}}i(Dn,"relatedTheses");function An(t,e){if(t===null)throw xt();let n=Un(t);if(!p(t)||!p(t.theses))throw T();let r=t.theses,s=Ln(r).map(o=>{let a=e(o.node);if(a===void 0)throw T();return{cursor:o.cursor,node:a}});return{scope:n,edges:s,nextCursor:Fi(r)}}i(An,"thesisPage");async function En(t,e,n,r){let s=await ke(t,e,{query:n}),o=p(s.market)?s.market.search:s.search;if(!p(o)||!Array.isArray(o.edges)||!p(o.pageInfo))throw T();let a=o.edges.map(c=>Un(p(c)?c.node:void 0));if(!a.every(c=>c.__typename===r))throw T();let u=o.pageInfo.hasNextPage===!0;if(a.length===1&&!u)return a[0];throw a.length===0&&!u?xt():new l("AMBIGUOUS_IDENTITY",`Choose an exact identity before reading theses. Candidates: ${JSON.stringify(a)}${u?" More matches exist; refine the name or ticker.":""}`,400,{candidates:a,more:u})}i(En,"resolveUnique");function Un(t){if(!p(t)||!U(t.id))throw T();if(t.__typename==="Entity"){if(!["ticker","name","kind","assetClass"].every(n=>typeof t[n]=="string")||t.venue!==null&&(!p(t.venue)||!U(t.venue.id)||typeof t.venue.name!="string"))throw T()}else if(typeof t.displayName!="string"||typeof t.bio!="string"||!(t.__typename==="Person"&&U(t.slug)||t.__typename==="PublicUser"&&U(t.username)))throw T();let e={...t};return delete e.theses,e}i(Un,"readScope");function Ln(t){if(!Array.isArray(t.edges)||!t.edges.every(e=>p(e)&&U(e.cursor)&&p(e.node)))throw T();return t.edges}i(Ln,"edges");function Fi(t){let e=t.pageInfo;if(!p(e)||typeof e.hasNextPage!="boolean"||e.hasNextPage&&!U(e.endCursor))throw T();return e.hasNextPage?e.endCursor:null}i(Fi,"nextCursor");async function ke(t,e,n){let r=await t._request("POST","/query",{body:{query:e,variables:n}});if(!p(r))throw T();if(r.errors!==void 0){if(!Array.isArray(r.errors))throw T();if(r.errors.length){let s=r.errors.flatMap(c=>p(c)&&typeof c.message=="string"?[c.message]:[]),o=new Set(r.errors.map(c=>p(c)&&p(c.extensions)?c.extensions.code:void 0)),[a]=o,u=o.size===1&&typeof a=="string"?Oi.get(a):void 0;throw new l(u===void 0?"GRAPHQL_ERROR":String(a),s.join("; ")||"GraphQL request failed",u??400,{errors:r.errors})}}if(!p(r.data))throw T();return r.data}i(ke,"graphql");var Oi=new Map([["NOT_FOUND",404],["PERMISSION_DENIED",403],["UNAUTHENTICATED",401]]);function U(t){return typeof t=="string"&&t.trim().length>0}i(U,"nonempty");function F(t){return new l("INVALID_ARGUMENT",t,400)}i(F,"argument");function T(){return new l("GRAPHQL_INVALID_RESPONSE","Invalid Thesis read response",502)}i(T,"invalid");function xt(){return new l("NOT_FOUND","No visible matching identity or Thesis found",404)}i(xt,"notFound");var Gi=9223372036854775807n,Mi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$i=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,Fn=new TextEncoder,se=class{constructor(e){this.client=e}client;static{i(this,"ThesesResource")}list(e){return Nn(this.client,e)}related(e,n={}){return Dn(this.client,e,n)}async assetCandidates(e){this.client._requireAuth();let n=Ae(e),r=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
|
|
353
353
|
viewer { thesisAssetCandidates(input: $input) {
|
|
354
354
|
mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
|
|
355
355
|
} }
|
|
356
|
-
}`,variables:{input:{text:n}}}});if(Array.isArray(i?.errors)&&i.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:i.errors});let s=i?.data,o=g(s)?s.viewer:void 0,a=g(o)?o.thesisAssetCandidates:void 0;if(!g(a)||!Array.isArray(a.mentions))throw m("asset candidates response must contain mentions");return{mentions:a.mentions.map((c,d)=>{if(!g(c)||typeof c.quote!="string"||typeof c.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(c.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(c.stance)||!Array.isArray(c.candidates))throw m(`asset mention ${d} is invalid`);let h=c.candidates.map(f=>{if(!g(f)||typeof f.ticker!="string"||typeof f.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(f.kind))throw m(`asset mention ${d} has invalid candidate`);return{entityId:I(f.entityId,`asset mention ${d} candidate.entityId`),ticker:f.ticker,name:f.name,kind:f.kind}});return{...c,candidates:h}})}}async create(e){this.client._requireAuth();let n=Dr(e);return te(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),Fr(await this.client._request("GET",`/api/v1/theses/${E(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let i=E(e,"id"),s=E(n,"author_version_id"),o=te(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(o.thesis.id!==i||o.thesis.author_version_id!==s)throw m("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return Gr(await this.client._request("GET",`/api/v1/theses/${E(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Lr(n);return te(await this.client._request("PUT",`/api/v1/theses/${E(e,"id")}`,{body:i}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let i=E(e,"id"),s=ct(n.visibility),o=te(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==i||o.thesis.visibility!==s)throw m("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let i={expected_author_version_id:E(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(i.note=M(n.note,"note")),te(await this.client._request("POST",`/api/v1/theses/${E(e,"id")}/close`,{body:i}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${E(e,"id")}`);if(n===void 0)return{};if(!g(n)||Object.keys(n).length!==0)throw m("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Te(e.body),i=e.mode===void 0?"reformat":Mr(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:i}});if(!g(s)||typeof s.body!="string")throw m("rewrite response must contain a string body");return{body:Un(s.body)}}};function Dr(t){let e={request_id:Nn(t.request_id),body:Te(t.body),title:Ct(t.title??""),entity_ids:Dn(t.entity_ids??[],"entity_ids"),visibility:ct(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=Or(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=Ur(t.entity_stances,e.entity_ids)),e}r(Dr,"createBody");function Ur(t,e){if(!Array.isArray(t)||t.length>we)throw y("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,o)=>{if(!g(s))throw y(`entity_stances[${o}] must be an object`);let a=E(s.entity_id,`entity_stances[${o}].entity_id`);if(!n.has(a)||i.has(a))throw y("entity stance must reference one unique entity_id");if(i.add(a),!["unknown","bullish","bearish"].includes(s.stance))throw y(`entity_stances[${o}].stance is invalid`);return{entity_id:a,stance:s.stance}})}r(Ur,"requireEntityStances");function Lr(t){return{request_id:Nn(t.request_id),expected_author_version_id:E(t.expected_author_version_id,"expected_author_version_id"),body:Te(t.body),title:Ct(t.title??""),entity_ids:Dn(t.entity_ids??[],"entity_ids"),visibility:ct(t.visibility),editorial:t.editorial??!1}}r(Lr,"updateBody");function te(t){if(!g(t)||!g(t.thesis))throw m("response must contain thesis");let e=t.thesis,n={id:I(e.id,"thesis.id"),author_version_id:I(e.author_version_id,"thesis.author_version_id"),material_version_id:I(e.material_version_id,"thesis.material_version_id"),title:Qr(e.title),body:Un(e.body),entity_ids:$r(e.entity_ids,"thesis.entity_ids"),visibility:Br(e.visibility),closed:ut(e.closed,"thesis.closed"),closing_note:jr(e.closing_note),author_kind:P(e.author_kind,"thesis.author_kind"),author_ref:P(e.author_ref,"thesis.author_ref")};if(e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw m("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!g(i))throw m("thesis.entity_stances contains invalid entry");let s=I(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))throw m("entity stance must reference a thesis entity");if(!["unknown","bullish","bearish"].includes(i.stance))throw m("thesis.entity_stances contains invalid stance");return{entity_id:s,stance:i.stance}})}return{thesis:n}}r(te,"thesisResponse");function Fr(t){let e=te(t);if(!g(t)||!g(t.author))throw m("response must contain author");let n=t.author,i={id:I(n.id,"author.id"),kind:P(n.kind,"author.kind"),display_name:P(n.display_name,"author.display_name"),avatar_url:P(n.avatar_url,"author.avatar_url"),username:P(n.username,"author.username")};if(!Array.isArray(t.entities))throw m("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw m("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!g(o))throw m(`entities[${a}] must be an object`);let u={id:I(o.id,`entities[${a}].id`),ticker:P(o.ticker,`entities[${a}].ticker`),name:P(o.name,`entities[${a}].name`),icon_url:P(o.icon_url,`entities[${a}].icon_url`),kind:P(o.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw m("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:i,entities:s}}r(Fr,"thesisGetResponse");function Gr(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw m("invalid Signal history response");let i=t.research,s={state:P(i.state,"research.state"),pending_work:at(i.pending_work,"research.pending_work"),read_complete:ut(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=at(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=at(i.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(u=>{if(!g(u)||!g(u.signal)||!g(u.signal.source))throw m("entry must include a Signal and source");let c=u.signal,d=c.source,h=I(c.thesis_id,"signal.thesis_id");if(h!==e)throw m("Signal belongs to another Thesis");let f=It(u.cursor,"entry.cursor"),A={title:P(d.title,"source.title")};d.url!==void 0&&(A.url=P(d.url,"source.url")),d.published_at_ms!==void 0&&(A.published_at_ms=at(d.published_at_ms,"source.published_at_ms"));let D={id:I(c.id,"signal.id"),thesis_id:h,author_version_id:I(c.author_version_id,"signal.author_version_id"),statement_snapshot:It(c.statement_snapshot,"signal.statement_snapshot"),stance:P(c.stance,"signal.stance"),explanation:P(c.explanation,"signal.explanation"),information_kind:P(c.information_kind,"signal.information_kind"),source:A};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw m("invalid evidence excerpt");D.evidence_excerpt={text:It(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:ut(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:ut(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:I(u.feed_entry_id,"feed_entry_id"),cursor:f,signal:D}}),a=P(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}r(Gr,"thesisSignalsResponse");function at(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}r(at,"responseNonnegativeInteger");function It(t,e){let n=P(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}r(It,"responseNonemptyText");function Nn(t){if(!qr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}r(Nn,"requireRequestID");function E(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>xr)throw y(`${e} must be a positive int64 decimal string`);return t}r(E,"requireID");var we=100;function Dn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>we)throw y(`${e} must contain at most ${we} IDs`);return t.map((n,i)=>E(n,`${e}[${i}]`))}r(Dn,"requireIDs");function Or(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let i=M(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return i})}r(Or,"requireTickers");function Te(t){let e=M(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(qn.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}r(Te,"requireBody");function Ct(t){let e=M(t,"title");if(qn.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}r(Ct,"requireTitle");function ct(t){let e=M(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}r(ct,"requireVisibility");function Mr(t){let e=M(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}r(Mr,"requireRewriteMode");function M(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if(Nr.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}r(M,"requireText");function I(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return E(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}r(I,"responseID");function $r(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>we)throw m(`${e} must contain at most ${we} IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}r($r,"responseIDs");function P(t,e){try{return M(t,e)}catch{throw m(`${e} must be valid text`)}}r(P,"responseText");function jr(t){try{return M(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}r(jr,"responseClosingNote");function ut(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}r(ut,"responseBoolean");function Br(t){try{return ct(t)}catch{throw m("thesis.visibility must be public or private")}}r(Br,"responseVisibility");function Un(t){try{return Te(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}r(Un,"responseBody");function Qr(t){try{return Ct(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}r(Qr,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}r(g,"isRecord");function y(t){return new l("INVALID_ARGUMENT",t,400)}r(y,"invalidArgument");function m(t){return new l("INVALID_RESPONSE",t,502)}r(m,"invalidResponse");var Vr=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
|
|
356
|
+
}`,variables:{input:{text:n}}}});if(Array.isArray(r?.errors)&&r.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:r.errors});let s=r?.data,o=g(s)?s.viewer:void 0,a=g(o)?o.thesisAssetCandidates:void 0;if(!g(a)||!Array.isArray(a.mentions))throw m("asset candidates response must contain mentions");return{mentions:a.mentions.map((c,d)=>{if(!g(c)||typeof c.quote!="string"||typeof c.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(c.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(c.stance)||!Array.isArray(c.candidates))throw m(`asset mention ${d} is invalid`);let h=c.candidates.map(f=>{if(!g(f)||typeof f.ticker!="string"||typeof f.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(f.kind))throw m(`asset mention ${d} has invalid candidate`);return{entityId:C(f.entityId,`asset mention ${d} candidate.entityId`),ticker:f.ticker,name:f.name,kind:f.kind}});return{...c,candidates:h}})}}async create(e){this.client._requireAuth();let n=ji(e);return ie(await this.client._request("POST","/api/v1/theses",{body:n}))}async get(e){return this.client._requireAuth(),Qi(await this.client._request("GET",`/api/v1/theses/${A(e,"id")}`))}async getVersion(e,n){this.client._requireAuth();let r=A(e,"id"),s=A(n,"author_version_id"),o=ie(await this.client._request("GET",`/api/v1/theses/${r}/versions/${s}`));if(o.thesis.id!==r||o.thesis.author_version_id!==s)throw m("version response must match the requested thesis and author version");return o}async signals(e,n={}){this.client._requireAuth();let r=n.first??20;if(!Number.isInteger(r)||r<1||r>50)throw y("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw y("cursor must be a string");return Vi(await this.client._request("GET",`/api/v1/theses/${A(e,"id")}/signals`,{query:{first:r,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,r)}async update(e,n){this.client._requireAuth();let r=Bi(n);return ie(await this.client._request("PUT",`/api/v1/theses/${A(e,"id")}`,{body:r}))}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw y("params is required");let r=A(e,"id"),s=pt(n.visibility),o=ie(await this.client._request("POST",`/api/v1/theses/${r}/visibility`,{body:{visibility:s}}));if(o.thesis.id!==r||o.thesis.visibility!==s)throw m("visibility response must match the requested thesis and visibility");return o}async close(e,n){this.client._requireAuth();let r={expected_author_version_id:A(n.expected_author_version_id,"expected_author_version_id")};return n.note!==void 0&&(r.note=j(n.note,"note")),ie(await this.client._request("POST",`/api/v1/theses/${A(e,"id")}/close`,{body:r}))}async delete(e){this.client._requireAuth();let n=await this.client._request("DELETE",`/api/v1/theses/${A(e,"id")}`);if(n===void 0)return{};if(!g(n)||Object.keys(n).length!==0)throw m("delete response must be {}");return{}}async rewrite(e){this.client._requireAuth();let n=Ae(e.body),r=e.mode===void 0?"reformat":Yi(e.mode),s=await this.client._request("POST","/api/v1/theses/rewrite",{body:{body:n,mode:r}});if(!g(s)||typeof s.body!="string")throw m("rewrite response must contain a string body");return{body:$n(s.body)}}};function ji(t){let e={request_id:Gn(t.request_id),body:Ae(t.body),title:Nt(t.title??""),entity_ids:Mn(t.entity_ids??[],"entity_ids"),visibility:pt(t.visibility??"public")};return t.tickers!==void 0&&(e.tickers=Hi(t.tickers)),t.entity_stances!==void 0&&(e.entity_stances=On(t.entity_stances,e.entity_ids)),e}i(ji,"createBody");function On(t,e){if(!Array.isArray(t)||t.length>Se)throw y("entity_stances must contain at most 100 values");let n=new Set(e),r=new Set;return t.map((s,o)=>{if(!g(s))throw y(`entity_stances[${o}] must be an object`);let a=A(s.entity_id,`entity_stances[${o}].entity_id`);if(!n.has(a)||r.has(a))throw y("entity stance must reference one unique entity_id");if(r.add(a),!["unknown","bullish","bearish"].includes(s.stance))throw y(`entity_stances[${o}].stance is invalid`);return{entity_id:a,stance:s.stance}})}i(On,"requireEntityStances");function Bi(t){let e={request_id:Gn(t.request_id),expected_author_version_id:A(t.expected_author_version_id,"expected_author_version_id"),body:Ae(t.body),title:Nt(t.title??""),entity_ids:Mn(t.entity_ids??[],"entity_ids"),visibility:pt(t.visibility),editorial:t.editorial??!1};return t.entity_stances!==void 0&&(e.entity_stances=On(t.entity_stances,e.entity_ids)),e}i(Bi,"updateBody");function ie(t){if(!g(t)||!g(t.thesis))throw m("response must contain thesis");let e=t.thesis,n={id:C(e.id,"thesis.id"),author_version_id:C(e.author_version_id,"thesis.author_version_id"),material_version_id:C(e.material_version_id,"thesis.material_version_id"),title:zi(e.title),body:$n(e.body),entity_ids:Wi(e.entity_ids,"thesis.entity_ids"),visibility:Xi(e.visibility),closed:dt(e.closed,"thesis.closed"),closing_note:Ki(e.closing_note),author_kind:P(e.author_kind,"thesis.author_kind"),author_ref:P(e.author_ref,"thesis.author_ref")};if(e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw m("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(r=>{if(!g(r))throw m("thesis.entity_stances contains invalid entry");let s=C(r.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))throw m("entity stance must reference a thesis entity");if(!["unknown","bullish","bearish"].includes(r.stance))throw m("thesis.entity_stances contains invalid stance");return{entity_id:s,stance:r.stance}})}return{thesis:n}}i(ie,"thesisResponse");function Qi(t){let e=ie(t);if(!g(t)||!g(t.author))throw m("response must contain author");let n=t.author,r={id:C(n.id,"author.id"),kind:P(n.kind,"author.kind"),display_name:P(n.display_name,"author.display_name"),avatar_url:P(n.avatar_url,"author.avatar_url"),username:P(n.username,"author.username")};if(!Array.isArray(t.entities))throw m("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw m("entities must match thesis.entity_ids");let s=t.entities.map((o,a)=>{if(!g(o))throw m(`entities[${a}] must be an object`);let u={id:C(o.id,`entities[${a}].id`),ticker:P(o.ticker,`entities[${a}].ticker`),name:P(o.name,`entities[${a}].name`),icon_url:P(o.icon_url,`entities[${a}].icon_url`),kind:P(o.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw m("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:r,entities:s}}i(Qi,"thesisGetResponse");function Vi(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw m("invalid Signal history response");let r=t.research,s={state:P(r.state,"research.state"),pending_work:lt(r.pending_work,"research.pending_work"),read_complete:dt(r.read_complete,"research.read_complete")};r.last_attempt_ms!==void 0&&(s.last_attempt_ms=lt(r.last_attempt_ms,"research.last_attempt_ms")),r.last_completed_ms!==void 0&&(s.last_completed_ms=lt(r.last_completed_ms,"research.last_completed_ms"));let o=t.entries.map(u=>{if(!g(u)||!g(u.signal)||!g(u.signal.source))throw m("entry must include a Signal and source");let c=u.signal,d=c.source,h=C(c.thesis_id,"signal.thesis_id");if(h!==e)throw m("Signal belongs to another Thesis");let f=qt(u.cursor,"entry.cursor"),E={title:P(d.title,"source.title")};d.url!==void 0&&(E.url=P(d.url,"source.url")),d.published_at_ms!==void 0&&(E.published_at_ms=lt(d.published_at_ms,"source.published_at_ms"));let L={id:C(c.id,"signal.id"),thesis_id:h,author_version_id:C(c.author_version_id,"signal.author_version_id"),statement_snapshot:qt(c.statement_snapshot,"signal.statement_snapshot"),stance:P(c.stance,"signal.stance"),explanation:P(c.explanation,"signal.explanation"),information_kind:P(c.information_kind,"signal.information_kind"),source:E};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw m("invalid evidence excerpt");L.evidence_excerpt={text:qt(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:dt(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:dt(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:C(u.feed_entry_id,"feed_entry_id"),cursor:f,signal:L}}),a=P(t.next_cursor,"next_cursor");if(a&&a!==o[o.length-1]?.cursor)throw m("next_cursor must match the final entry");return{research:s,entries:o,next_cursor:a}}i(Vi,"thesisSignalsResponse");function lt(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw m(e+" must be a nonnegative safe integer");return t}i(lt,"responseNonnegativeInteger");function qt(t,e){let n=P(t,e);if(!n.trim())throw m(e+" must be nonempty");return n}i(qt,"responseNonemptyText");function Gn(t){if(!Mi.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw y("request_id must be a non-zero RFC 4122 UUID");return t}i(Gn,"requireRequestID");function A(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw y(`${e} must be a positive int64 decimal string`);if(BigInt(t)>Gi)throw y(`${e} must be a positive int64 decimal string`);return t}i(A,"requireID");var Se=100;function Mn(t,e){if(!Array.isArray(t))throw y(`${e} must be an array`);if(t.length>Se)throw y(`${e} must contain at most ${Se} IDs`);return t.map((n,r)=>A(n,`${e}[${r}]`))}i(Mn,"requireIDs");function Hi(t){if(!Array.isArray(t))throw y("tickers must be an array");if(t.length>100)throw y("tickers must contain at most 100 values");return t.map((e,n)=>{let r=j(e,`tickers[${n}]`);if(r.trim()===""||r.includes("\0"))throw y(`tickers[${n}] must be non-empty`);return r})}i(Hi,"requireTickers");function Ae(t){let e=j(t,"body");if(e.trim().length===0)throw y("body must not be blank");if(Fn.encode(e).byteLength>65536)throw y("body must be at most 65536 UTF-8 bytes");return e}i(Ae,"requireBody");function Nt(t){let e=j(t,"title");if(Fn.encode(e).byteLength>500)throw y("title must be at most 500 UTF-8 bytes");return e}i(Nt,"requireTitle");function pt(t){let e=j(t,"visibility");if(e!=="public"&&e!=="private")throw y("visibility must be public or private");return e}i(pt,"requireVisibility");function Yi(t){let e=j(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw y("mode must be reformat, shorten, or enrich")}i(Yi,"requireRewriteMode");function j(t,e){if(typeof t!="string")throw y(`${e} must be a string`);if($i.test(t))throw y(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw y(`${e} must not contain NUL`);return t}i(j,"requireText");function C(t,e){if(typeof t=="number")throw m(`${e} must be a decimal string; numeric IDs are unsafe`);try{return A(t,e)}catch{throw m(`${e} must be a positive int64 decimal string`)}}i(C,"responseID");function Wi(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>Se)throw m(`${e} must contain at most ${Se} IDs`);return t.map((n,r)=>C(n,`${e}[${r}]`))}i(Wi,"responseIDs");function P(t,e){try{return j(t,e)}catch{throw m(`${e} must be valid text`)}}i(P,"responseText");function Ki(t){try{return j(t,"note")}catch{throw m("thesis.closing_note must be valid text")}}i(Ki,"responseClosingNote");function dt(t,e){if(typeof t!="boolean")throw m(`${e} must be boolean`);return t}i(dt,"responseBoolean");function Xi(t){try{return pt(t)}catch{throw m("thesis.visibility must be public or private")}}i(Xi,"responseVisibility");function $n(t){try{return Ae(t)}catch{throw m("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}i($n,"responseBody");function zi(t){try{return Nt(t)}catch{throw m("response title must be valid text at most 500 UTF-8 bytes")}}i(zi,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}i(g,"isRecord");function y(t){return new l("INVALID_ARGUMENT",t,400)}i(y,"invalidArgument");function m(t){return new l("INVALID_RESPONSE",t,502)}i(m,"invalidResponse");var Ji=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
|
|
357
357
|
companyNews {
|
|
358
358
|
createFeed(input: $input) { id producer { id } }
|
|
359
359
|
}
|
|
360
|
-
}`,
|
|
360
|
+
}`,Zi={INVALID_ARGUMENT:400,UNAUTHENTICATED:401,PERMISSION_DENIED:403,NOT_FOUND:404,ALREADY_EXISTS:409,ABORTED:409,FAILED_PRECONDITION:412,RESOURCE_EXHAUSTED:429,INTERNAL:500,UNKNOWN:500,DATA_LOSS:500,UNAVAILABLE:503,DEADLINE_EXCEEDED:504};function es(t){if(typeof t?.name!="string"||t.name.trim()!==t.name||!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/.test(t.name)||t.name==="news-lane")throw new l("INVALID_ARGUMENT","name must be 1-64 alphanumeric/hyphen characters and distinct from news-lane",400);if(!Array.isArray(t.tickers)||t.tickers.length<1||t.tickers.length>1e3||t.tickers.some(e=>typeof e!="string"||e.trim()!==e||!/^[A-Z0-9][A-Z0-9.-]{0,19}$/.test(e))||new Set(t.tickers).size!==t.tickers.length)throw new l("INVALID_ARGUMENT","tickers must contain 1-1000 unique uppercase symbols",400);for(let[e,n]of[["initial_lookback_hours",168],["page_size",100]]){let r=t[e];if(r!==void 0&&(!Number.isInteger(r)||r<0||r>n))throw new l("INVALID_ARGUMENT",`${e} must be an integer from 0 to ${n} (0 selects the default)`,400)}}i(es,"validateCompanyNewsCreateParams");var oe=class{constructor(e){this.client=e}client;static{i(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),es(e);let n={name:e.name,tickers:e.tickers,...e.initial_lookback_hours===void 0?{}:{initialLookbackHours:e.initial_lookback_hours},...e.page_size===void 0?{}:{pageSize:e.page_size}},r=await this.client._request("POST","/query",{body:{query:Ji,variables:{input:n}}});if(Array.isArray(r?.errors)&&r.errors.length>0){let a=r.errors.map(c=>c?.extensions?.code),u=typeof a[0]=="string"&&a.every(c=>c===a[0])?a[0]:"GRAPHQL_ERROR";throw new l(u,r.errors.map(c=>c?.message).filter(Boolean).join("; ")||"Company News creation failed",Zi[u]??502,{errors:r.errors})}let s=r?.data?.companyNews?.createFeed,o={feed_id:s?.id,cronjob_id:s?.producer?.id};if(typeof o!="object"||o===null||!("feed_id"in o)||!jn(o.feed_id)||!("cronjob_id"in o)||!jn(o.cronjob_id))throw new l("INVALID_RESPONSE","company news response must contain decimal int64 feed_id and cronjob_id strings",502);return{feed_id:o.feed_id,cronjob_id:o.cronjob_id}}};function jn(t){return typeof t=="string"&&t.trim()===t&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}i(jn,"validID");var ts="https://api-llm.prd.alva.ai",ns="https://data-tools.prd.space.id";function Dt(t){return typeof t=="object"&&t!==null}i(Dt,"isRecord");function mt(t,e){if(!Dt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}i(mt,"stringField");function rs(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let r=mt(t,"code");r&&(e.code=r)}else if(Dt(t)){let r=mt(t,"code"),s=mt(t,"name"),o=mt(t,"message");r&&(e.code=r),s&&(e.name=s),o&&(e.message=o)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(r=>!!r);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}i(rs,"describeCause");function is(t){let e=t instanceof Error&&t.message?t.message:"Network request failed",n={};t instanceof Error?(n.name=t.name,n.message=t.message):n.message=String(t);let{message:r,details:s}=rs(Dt(t)?t.cause:void 0);return s&&(n.cause=s),{message:r?`${e}; cause: ${r}`:e,details:n}}i(is,"describeFetchFailure");var ht=class{static{i(this,"AlvaClient")}baseUrl;arraysBaseUrl;viewer_token;pbsvToken;apiKey;gaClientId;gaSessionId;utmParams;signal;originSessionId;originSessionKind;originInboxPath;_fs;_run;_deploy;_serviceAccount;_release;_feed;_x;_forYou;_automation;_playbooks;_secrets;_sdk;_dataSkills;_playbookSkills;_comments;_remix;_screenshot;_user;_trading;_portfolio;_arraysJwt;_notifications;_notificationPreferences;_subscriptions;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;_companyNews;constructor(e){this.baseUrl=e.baseUrl??ts,this.arraysBaseUrl=e.arraysBaseUrl??ns,this.viewer_token=e.viewer_token,this.pbsvToken=e.pbsvToken,this.apiKey=e.apiKey,this.gaClientId=e.gaClientId,this.gaSessionId=e.gaSessionId,this.utmParams=e.utmParams,this.signal=e.signal,this.originSessionId=e.originSessionId,this.originSessionKind=e.originSessionKind,this.originInboxPath=e.originInboxPath}get fs(){return this._fs??=new qe(this)}get run(){return this._run??=new Ne(this)}get deploy(){return this._deploy??=new De(this)}get serviceAccount(){return this._serviceAccount??=new Ue(this)}get release(){return this._release??=new Le(this)}get feed(){return this._feed??=new Oe(this)}get automation(){return this._automation??=new J(this)}get playbooks(){return this._playbooks??=new $e(this)}get secrets(){return this._secrets??=new je(this)}get sdk(){return this._sdk??=new Be(this)}get dataSkills(){return this._dataSkills??=new Qe(this)}get playbookSkills(){return this._playbookSkills??=new Ve(this)}get comments(){return this._comments??=new He(this)}get remix(){return this._remix??=new Ye(this)}get screenshot(){return this._screenshot??=new We(this)}get user(){return this._user??=new Ke(this)}get trading(){return this._trading??=new Xe(this)}get portfolio(){return this._portfolio??=new ze(this)}get arraysJwt(){return this._arraysJwt??=new Je(this)}get notifications(){return this._notifications??=new Ze(this)}get notificationPreferences(){return this._notificationPreferences??=new et(this)}get subscriptions(){return this._subscriptions??=new tt(this)}get alerts(){return this._alerts??=new Z(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new nt(this)}get feedback(){return this._feedback??=new rt(this)}get functions(){return this._functions??=new it(this)}get credits(){return this._credits??=new st(this)}get markets(){return this._markets??=new ee(this)}get tradingPairs(){return this._tradingPairs??=new re(this)}get schedules(){return this._schedules??=new te(this)}get steward(){return this._steward??=new ne(this)}get theses(){return this._theses??=new se(this)}get companyNews(){return this._companyNews??=new oe(this)}_requireAuth(){if(!this.pbsvToken&&!this.viewer_token&&!this.apiKey)throw new l("UNAUTHENTICATED","Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",401)}get x(){return this._x??=new W(this)}get forYou(){return this._forYou??=new z(this)}async _request(e,n,r){let o=`${r?.baseUrl??this.baseUrl}${n}`;if(r?.query){let q=new URLSearchParams;for(let[O,ft]of Object.entries(r.query))ft!=null&&q.set(O,String(ft));let Q=q.toString();Q&&(o+=`?${Q}`)}let a={};r?.noAuth||(this.pbsvToken?(a.Authorization=`Bearer ${this.pbsvToken}`,a["X-Pbsv"]="1"):this.viewer_token?a["x-Playbook-Viewer"]=this.viewer_token:this.apiKey&&(a["X-Alva-Api-Key"]=this.apiKey)),this.gaClientId&&(a["X-Alva-GA-Client-ID"]=this.gaClientId),this.gaSessionId&&(a["X-Alva-GA-Session-ID"]=this.gaSessionId),this.utmParams&&(a["X-Alva-UTM-Params"]=this.utmParams),this.originSessionId&&!r?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let u;r?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",u=r.rawBody):r?.jsonBody!==void 0?(a["Content-Type"]="application/json",u=r.jsonBody):r?.body!==void 0&&(a["Content-Type"]="application/json",u=JSON.stringify(r.body));let c,d=r?.timeoutMs,h=r?.signal??this.signal;if(h?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let f=d!==void 0?new AbortController:void 0,E=!1,L,Ee;f&&d!==void 0&&(h&&(Ee=i(()=>f.abort(h.reason),"abortListener"),h.addEventListener("abort",Ee,{once:!0})),L=setTimeout(()=>{E=!0,f.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let Ut={method:e,headers:a,body:u,signal:f?.signal??h};d!==void 0&&(Ut.timeout=d);try{c=await fetch(o,Ut)}catch(q){if(h?.aborted&&!E)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(E)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let Q=is(q);throw new l("NETWORK_ERROR",Q.message,0,{method:e,path:n,...Q.details})}finally{Ee&&h&&h.removeEventListener("abort",Ee),L!==void 0&&clearTimeout(L)}if(!c.ok){let q="";try{q=await Promise.resolve(c.text())}catch{q=""}if((c.headers.get("content-type")??"").includes("application/json")&&q)try{let O=JSON.parse(q);if(O.error)throw new l(O.error.code??"UNKNOWN",O.error.message??`HTTP ${c.status}`,c.status)}catch(O){if(O instanceof l)throw O}throw new l("UNKNOWN",`HTTP ${c.status}: ${q.slice(0,200)}`,c.status)}if(c.status===204)return;let Lt=(c.headers.get("content-type")??"").toLowerCase();return Lt.includes("application/json")||Lt.includes("+json")?c.json():c.arrayBuffer()}};var ss="0.33.1";Rt();return Wn(os);})();
|
|
361
361
|
//# sourceMappingURL=browser.global.js.map
|