@alva-ai/toolkit 0.38.0-beta.1 → 0.38.0-beta.2
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 +4 -1
- package/dist/browser.global.js +30 -30
- package/dist/browser.global.js.map +1 -1
- package/dist/cli.d.ts +5 -1
- package/dist/cli.js +77 -22
- package/dist/cli.js.map +1 -1
- package/dist/dispatch.d.ts +5 -1
- package/dist/dispatch.js +33 -21
- package/dist/dispatch.js.map +1 -1
- package/dist/index.cjs +17 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -2
- package/dist/index.d.ts +6 -2
- package/dist/index.js +17 -14
- 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 qe=Object.defineProperty;var Ci=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Ni=Object.prototype.hasOwnProperty;var o=(t,e)=>qe(t,"name",{value:e,configurable:!0});var qi=(t,e)=>{for(var n in e)qe(t,n,{get:e[n],enumerable:!0})},Di=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xi(e))!Ni.call(t,s)&&s!==n&&qe(t,s,{get:()=>e[s],enumerable:!(i=Ci(e,s))||i.enumerable});return t};var Ui=t=>Di(qe({},"__esModule",{value:!0}),t);var Eo={};qi(Eo,{AlertsResource:()=>ue,AlvaClient:()=>Pt,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>ve,AutomationResource:()=>re,CliUsageError:()=>Le,CompanyNewsResource:()=>he,FollowsResource:()=>ae,ForYouResource:()=>ie,MarketsResource:()=>ce,PBSV_UPDATE_MESSAGE:()=>tn,SUBSCRIBE_MANAGE_MESSAGE:()=>un,SUBSCRIBE_PROPOSE_MESSAGE:()=>on,SUBSCRIBE_RESULT_MESSAGE:()=>an,SchedulesResource:()=>le,StewardResource:()=>de,ThesesResource:()=>oe,TradingPairsResource:()=>pe,UDF_AUTH_REQUIRED_MESSAGE:()=>sn,UDF_CONSENT_REQUEST_MESSAGE:()=>nn,UDF_CONSENT_RESPONSE_MESSAGE:()=>rn,UdfAuthRequiredError:()=>J,UdfConsentDeniedError:()=>ye,UdfConsentRequiredError:()=>ge,UdfConsentTimeoutError:()=>be,UdfError:()=>A,UdfExecutionError:()=>Re,UdfFunctionDisabledError:()=>_e,UdfFunctionNotFoundError:()=>Pe,UdfInsufficientCredits:()=>we,UdfPidMismatchError:()=>Q,UdfRateLimitedError:()=>Te,UdfTokenExpiredError:()=>fe,UdfTokenInvalidError:()=>me,UdfTransportError:()=>Z,VERSION:()=>ko,XResource:()=>ee,getViewerToken:()=>Se,installPlaybookRuntime:()=>At,mapUdfErrorResponse:()=>kt,playbookIdFromToken:()=>St,subscribe:()=>fn,udf:()=>mn});var A=class extends Error{static{o(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}},J=class extends A{static{o(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},fe=class extends A{static{o(this,"UdfTokenExpiredError")}},me=class extends A{static{o(this,"UdfTokenInvalidError")}},Q=class extends A{static{o(this,"UdfPidMismatchError")}},ge=class extends A{static{o(this,"UdfConsentRequiredError")}},ye=class extends A{static{o(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},be=class extends A{static{o(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},we=class extends A{static{o(this,"UdfInsufficientCredits")}},Pe=class extends A{static{o(this,"UdfFunctionNotFoundError")}},_e=class extends A{static{o(this,"UdfFunctionDisabledError")}},Te=class extends A{static{o(this,"UdfRateLimitedError")}},Re=class extends A{static{o(this,"UdfExecutionError")}},Z=class extends A{static{o(this,"UdfTransportError")}},tn="alva:pbsv:update",nn="alva:udf:consent-request",rn="alva:udf:consent-response",sn="alva:udf:auth-required",on="alva:subscribe:propose",an="alva:subscribe:result",un="alva:subscribe:manage",cn="https://api-llm.prd.alva.ai",ln=300*1e3,De=null,L=null,Rt=cn,G=null,D=null,en=!1,Ue=new Map,Fe=new Map,Fi=o(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Li=o(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),St=o(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Li(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),Se=o(()=>De,"getViewerToken"),z=o(()=>!!Se(),"isAuthenticated"),Oi=o(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Gi=o(t=>{let e=new URLSearchParams(t.location.search),n=t;De=n.__ALVA_PBSV_BOOTSTRAP__||null,delete n.__ALVA_PBSV_BOOTSTRAP__,e.has("_pbsv")&&Oi(t),L=e.get("parent_origin"),Rt=(e.get("api_origin")||cn).replace(/\/$/,""),G=St(De)},"parseBootParams"),dn=o(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),Mi=o(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),$i=o(t=>{let e=t;return{...e,result:Mi(e.result)}},"normalizeInvokeResponse"),pn=o(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),kt=o((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=pn(t),r={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new fe(i,r);case"PBSV_INVALID":case"UNAUTHENTICATED":return new me(i,r);case"PBSV_PID_MISMATCH":return new Q(i,r);case"CONSENT_REQUIRED":return new ge(i,r);case"INSUFFICIENT_CREDITS":return new we(i,r);case"FUNCTION_NOT_FOUND":return new Pe(i,r);case"FUNCTION_DISABLED":return new _e(i,r);case"RESOURCE_EXHAUSTED":return new Te(i,r);case"EXECUTION_FAILED":return new Re(i,r);default:return new Z(i,r)}},"mapUdfErrorResponse"),ji=o(t=>{if(!D||!L||t.origin!==L||t.source!==D.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===tn){typeof e.token=="string"&&e.token.length>0&&(De=e.token,G=St(e.token));return}if(e.type===an){if(typeof e.request_id!="string")return;let i=Fe.get(e.request_id);if(!i)return;clearTimeout(i.timer),Fe.delete(e.request_id),i.resolve(Fi(e.status));return}if(e.type!==rn||typeof e.request_id!="string")return;let n=Ue.get(e.request_id);n&&(clearTimeout(n.timer),Ue.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),hn=o(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Bi=o(()=>{if(!G)return null;let t=Number(G);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),Wi=o(async(t,e)=>{if(!D||!L)return"denied";let n=L,i=hn();return new Promise(s=>{let r=setTimeout(()=>{Ue.delete(i),s("timeout")},ln);Ue.set(i,{resolve:s,timer:r}),D?.parent.postMessage({type:nn,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Qi=o(async t=>{if(!D||!L)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=L,s=hn();return new Promise(r=>{let a=setTimeout(()=>{Fe.delete(s),r("timeout")},ln);Fe.set(s,{resolve:r,timer:a}),D?.parent.postMessage({type:on,request_id:s,playbook_id:G,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Vi=o(()=>{!D||!L||D.parent.postMessage({type:un,playbook_id:G},L)},"manageSubscriptions"),fn={propose:Qi,manage:Vi},Hi=o(t=>{!D||!L||D.parent.postMessage({type:sn,function_name:t},L)},"requestAuthentication"),Et=o(async(t,e,n=!1)=>{let i=Se();if(!i)throw new J;if(!G)throw new Q("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Bi();if(!s)throw new Q("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let r;try{r=await fetch(`${Rt}/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 Z("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await dn(r);if(r.ok)return $i(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=pn(a),c=typeof u.playbook_id=="string"?u.playbook_id:G,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,p=await Wi(c,d);if(p==="granted")return Et(t,e,!0);throw p==="timeout"?new be:new ye}throw kt(a,r.status)},"call"),Ki=o(async()=>{let t=Se();if(!t)throw new J;if(!G)throw new Q("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${Rt}/api/v1/service/functions`);e.searchParams.set("playbook_id",G);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await dn(n);if(!n.ok)throw kt(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),Tt=o((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Yi=o(t=>{if(typeof t!="string")return t;let n=D?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),Xi=o((t,e)=>{if(!D)throw new Error("Playbook runtime is not installed.");let n=Yi(t),i=D.document.createElement("button"),s=e.label||e.functionName,r=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=z()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),z()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!z()){Hi(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=r,Tt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await Et(e.functionName,e.params??{});Tt(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){Tt(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=z()?s:a,z()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),mn={call:Et,list:Ki,getViewerToken:Se,isAuthenticated:z,renderButton:Xi,UdfError:A,UdfAuthRequiredError:J,UdfTokenExpiredError:fe,UdfTokenInvalidError:me,UdfPidMismatchError:Q,UdfConsentRequiredError:ge,UdfConsentDeniedError:ye,UdfConsentTimeoutError:be,UdfInsufficientCredits:we,UdfFunctionNotFoundError:Pe,UdfFunctionDisabledError:_e,UdfRateLimitedError:Te,UdfExecutionError:Re,UdfTransportError:Z},At=o(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||en)return;D=e,en=!0,Gi(e),e.addEventListener("message",ji);let n=e,i=n.alva||{};n.alva={...i,udf:mn,subscribe:fn}},"installPlaybookRuntime");var l=class extends Error{static{o(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},Le=class extends Error{static{o(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function gn(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}o(gn,"isArrayBuffer");var yn=1;function zi(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,r=0;if(n>=194&&n<=223)i=1,s=128,r=n&31;else if(n>=224&&n<=239)i=2,s=2048,r=n&15;else if(n>=240&&n<=244)i=3,s=65536,r=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;r=r<<6|u&63}if(r<s||r>1114111||r>=55296&&r<=57343)return!1;e+=i+1}return!0}o(zi,"isValidUtf8");var Oe=class{constructor(e){this.client=e}client;static{o(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(!gn(n)||!zi(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:yn}:{}}})}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:yn}:{}},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 bn="9007199254740991";function wn(t,e,n,i){let s=t.length+e,r=n.length+i;if(s!==r)return s>r;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}o(wn,"scaledIntegerGreater");function Ji(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 r=(n+i).replace(/^0+/,"")||"0";if(r==="0")return!1;let a=s-i.length;return a>=0?wn(r,a,bn,0):wn(r,0,bn,-a)}o(Ji,"numberOutsideSafeRange");function Zi(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(Ji(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++}}o(Zi,"validateJSONNumberTokens");function vt(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)=>vt(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,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(r.enumerable){if(!("value"in r))throw new TypeError(`${e} must not contain accessors`);vt(r.value,`${e}.${s}`,n)}}n.delete(t)}}o(vt,"assertPlainJSONData");function ke(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");vt(t,"args",new Set);let e=JSON.stringify(t);return Pn(e),e}o(ke,"serializeStructuredArgs");function Pn(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");Zi(t)}o(Pn,"validateSerializedArgs");function Ee(t,e,n){let i=Object.entries(t).filter(([s,r])=>r!==void 0&&(n===void 0||s!==e));return n!==void 0&&(Pn(n),i.push([e,n])),`{${i.map(([s,r])=>{let a=s===e&&n!==void 0?n:JSON.stringify(r);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}o(Ee,"objectWithRawJSONField");var Ge=class{constructor(e){this.client=e}client;static{o(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ke(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:Ee(i,"args",n)},timeoutMs:e.timeout_ms})}};var Me=class{constructor(e){this.client=e}client;static{o(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ke(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:Ee(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,ke(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:Ee(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 $e=class{constructor(e){this.client=e}client;static{o(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 je=class{constructor(e){this.client=e}client;static{o(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 We=class{constructor(e){this.client=e}client;static{o(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=Be(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=Be(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=Be(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=Be(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 Be(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}o(Be,"requireFeedID");var _n={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 U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(U,"record");function er(t){if(!U(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")}o(er,"validateXReadParams");function M(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${t} response`,502)}o(M,"invalidResponse");function Tn(t,e){if(!U(t))return M(e);if(t.errors!==void 0){if(!Array.isArray(t.errors))return M(e);if(t.errors.length>0){let n=t.errors.flatMap(r=>U(r)&&typeof r.message=="string"?[r.message]:[]),i=t.errors.map(r=>U(r)&&U(r.extensions)?r.extensions.code:void 0),s=typeof i[0]=="string"&&Object.hasOwn(_n,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR";throw new l(s,n.join("; ")||"X read failed",_n[s]??502,{errors:t.errors})}}return!U(t.data)||!U(t.data.viewer)?M(e):t.data.viewer[e]}o(Tn,"viewerField");function tr(t,e,n){if(!U(t)||!Array.isArray(t.edges)||!U(t.pageInfo))return M(e);let i=t.pageInfo;if(typeof i.startCursor!="string"||typeof i.endCursor!="string"||typeof i.hasNextPage!="boolean"||typeof i.hasPreviousPage!="boolean"||i.hasNextPage&&!i.endCursor)return M(e);for(let a of t.edges){if(!U(a)||typeof a.cursor!="string"||!a.cursor||!U(a.node))return M(e);let u=a.node;if(n.some(c=>typeof u[c]!="string")||!u.id)return M(e)}let s=t.edges[0],r=t.edges[t.edges.length-1];return i.startCursor!==(s?.cursor??"")||r&&i.endCursor!==r.cursor?M(e):{edges:t.edges,pageInfo:i,retrievedAt:new Date().toISOString()}}o(tr,"readPage");var ee=class{constructor(e){this.client=e}client;static{o(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=Tn(e,"xConnection");return!U(n)||["connected","canReadFollowing","canReadPosts"].some(i=>typeof n[i]!="boolean")?M("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,i){er(i),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:i.first??20,after:i.after}}});return tr(Tn(s,e),e,n.split(" "))}};function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(h,"record");function v(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}o(v,"isPositiveInt64");var te=`
|
|
1
|
+
"use strict";var AlvaToolkit=(()=>{var qe=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var qi=Object.prototype.hasOwnProperty;var o=(t,e)=>qe(t,"name",{value:e,configurable:!0});var Di=(t,e)=>{for(var n in e)qe(t,n,{get:e[n],enumerable:!0})},Ui=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ni(e))!qi.call(t,s)&&s!==n&&qe(t,s,{get:()=>e[s],enumerable:!(i=xi(e,s))||i.enumerable});return t};var Fi=t=>Ui(qe({},"__esModule",{value:!0}),t);var Eo={};Di(Eo,{AlertsResource:()=>ue,AlvaClient:()=>_t,AlvaError:()=>l,AutomationAlertDeliveryResource:()=>ve,AutomationResource:()=>re,CliUsageError:()=>Le,CompanyNewsResource:()=>he,FollowsResource:()=>ae,ForYouResource:()=>ie,MarketsResource:()=>ce,PBSV_UPDATE_MESSAGE:()=>nn,SUBSCRIBE_MANAGE_MESSAGE:()=>cn,SUBSCRIBE_PROPOSE_MESSAGE:()=>an,SUBSCRIBE_RESULT_MESSAGE:()=>un,SchedulesResource:()=>le,StewardResource:()=>de,ThesesResource:()=>oe,TradingPairsResource:()=>pe,UDF_AUTH_REQUIRED_MESSAGE:()=>on,UDF_CONSENT_REQUEST_MESSAGE:()=>rn,UDF_CONSENT_RESPONSE_MESSAGE:()=>sn,UdfAuthRequiredError:()=>J,UdfConsentDeniedError:()=>ye,UdfConsentRequiredError:()=>ge,UdfConsentTimeoutError:()=>be,UdfError:()=>A,UdfExecutionError:()=>Re,UdfFunctionDisabledError:()=>_e,UdfFunctionNotFoundError:()=>Pe,UdfInsufficientCredits:()=>we,UdfPidMismatchError:()=>Q,UdfRateLimitedError:()=>Te,UdfTokenExpiredError:()=>fe,UdfTokenInvalidError:()=>me,UdfTransportError:()=>Z,VERSION:()=>ko,XResource:()=>ee,getViewerToken:()=>Se,installPlaybookRuntime:()=>vt,mapUdfErrorResponse:()=>Et,playbookIdFromToken:()=>kt,subscribe:()=>mn,udf:()=>gn});var A=class extends Error{static{o(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}},J=class extends A{static{o(this,"UdfAuthRequiredError")}constructor(){super("Sign in to use this UDF.",{code:"AUTH_REQUIRED"})}},fe=class extends A{static{o(this,"UdfTokenExpiredError")}},me=class extends A{static{o(this,"UdfTokenInvalidError")}},Q=class extends A{static{o(this,"UdfPidMismatchError")}},ge=class extends A{static{o(this,"UdfConsentRequiredError")}},ye=class extends A{static{o(this,"UdfConsentDeniedError")}constructor(){super("UDF consent was denied.",{code:"CONSENT_DENIED"})}},be=class extends A{static{o(this,"UdfConsentTimeoutError")}constructor(){super("UDF consent timed out.",{code:"CONSENT_TIMEOUT"})}},we=class extends A{static{o(this,"UdfInsufficientCredits")}},Pe=class extends A{static{o(this,"UdfFunctionNotFoundError")}},_e=class extends A{static{o(this,"UdfFunctionDisabledError")}},Te=class extends A{static{o(this,"UdfRateLimitedError")}},Re=class extends A{static{o(this,"UdfExecutionError")}},Z=class extends A{static{o(this,"UdfTransportError")}},nn="alva:pbsv:update",rn="alva:udf:consent-request",sn="alva:udf:consent-response",on="alva:udf:auth-required",an="alva:subscribe:propose",un="alva:subscribe:result",cn="alva:subscribe:manage",ln="https://api-llm.prd.alva.ai",dn=300*1e3,De=null,L=null,St=ln,G=null,D=null,tn=!1,Ue=new Map,Fe=new Map,Li=o(t=>t==="subscribed"||t==="declined"||t==="timeout"?t:"error","normalizeProposalResult"),Oi=o(t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return atob(n)},"decodeBase64Url"),kt=o(t=>{if(!t)return null;let[,e]=t.split(".");if(!e)return null;try{let n=JSON.parse(Oi(e));if(typeof n.pid=="number")return String(n.pid);if(typeof n.pid=="string")return n.pid}catch{return null}return null},"playbookIdFromToken"),Se=o(()=>De,"getViewerToken"),z=o(()=>!!Se(),"isAuthenticated"),Gi=o(t=>{let e=new URL(t.location.href);e.searchParams.delete("_pbsv"),t.history.replaceState(null,"",e.pathname+e.search+e.hash)},"stripPbsvFromUrl"),Mi=o(t=>{let e=new URLSearchParams(t.location.search),n=t;De=n.__ALVA_PBSV_BOOTSTRAP__||null,delete n.__ALVA_PBSV_BOOTSTRAP__,e.has("_pbsv")&&Gi(t),L=e.get("parent_origin"),St=(e.get("api_origin")||ln).replace(/\/$/,""),G=kt(De)},"parseBootParams"),pn=o(async t=>{try{return await t.json()}catch{return{}}},"safeJson"),$i=o(t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},"parseResultPayload"),ji=o(t=>{let e=t;return{...e,result:$i(e.result)}},"normalizeInvokeResponse"),hn=o(t=>t.error?.metadata||t.details?.metadata||{},"errorMetadata"),Et=o((t,e)=>{let n=t.error?.code||"TRANSPORT",i=t.error?.message||n,s=hn(t),r={code:n,metadata:s,status:e};switch(n){case"PBSV_EXPIRED":return new fe(i,r);case"PBSV_INVALID":case"UNAUTHENTICATED":return new me(i,r);case"PBSV_PID_MISMATCH":return new Q(i,r);case"CONSENT_REQUIRED":return new ge(i,r);case"INSUFFICIENT_CREDITS":return new we(i,r);case"FUNCTION_NOT_FOUND":return new Pe(i,r);case"FUNCTION_DISABLED":return new _e(i,r);case"RESOURCE_EXHAUSTED":return new Te(i,r);case"EXECUTION_FAILED":return new Re(i,r);default:return new Z(i,r)}},"mapUdfErrorResponse"),Bi=o(t=>{if(!D||!L||t.origin!==L||t.source!==D.parent||!t.data||typeof t.data!="object")return;let e=t.data;if(e.type===nn){typeof e.token=="string"&&e.token.length>0&&(De=e.token,G=kt(e.token));return}if(e.type===un){if(typeof e.request_id!="string")return;let i=Fe.get(e.request_id);if(!i)return;clearTimeout(i.timer),Fe.delete(e.request_id),i.resolve(Li(e.status));return}if(e.type!==sn||typeof e.request_id!="string")return;let n=Ue.get(e.request_id);n&&(clearTimeout(n.timer),Ue.delete(e.request_id),n.resolve(e.granted===!0?"granted":"denied"))},"onMessage"),fn=o(()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,"randomRequestId"),Wi=o(()=>{if(!G)return null;let t=Number(G);return Number.isSafeInteger(t)?t:null},"playbookIdForInvoke"),Qi=o(async(t,e)=>{if(!D||!L)return"denied";let n=L,i=fn();return new Promise(s=>{let r=setTimeout(()=>{Ue.delete(i),s("timeout")},dn);Ue.set(i,{resolve:s,timer:r}),D?.parent.postMessage({type:rn,request_id:i,playbook_id:t,min_allowance:e},n)})},"requestConsent"),Vi=o(async t=>{if(!D||!L)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=L,s=fn();return new Promise(r=>{let a=setTimeout(()=>{Fe.delete(s),r("timeout")},dn);Fe.set(s,{resolve:r,timer:a}),D?.parent.postMessage({type:an,request_id:s,playbook_id:G,feed:{owner:e,name:n}},i)})},"proposeSubscribe"),Hi=o(()=>{!D||!L||D.parent.postMessage({type:cn,playbook_id:G},L)},"manageSubscriptions"),mn={propose:Vi,manage:Hi},Ki=o(t=>{!D||!L||D.parent.postMessage({type:on,function_name:t},L)},"requestAuthentication"),At=o(async(t,e,n=!1)=>{let i=Se();if(!i)throw new J;if(!G)throw new Q("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let s=Wi();if(!s)throw new Q("Invalid playbook id.",{code:"PBSV_PID_MISMATCH"});let r;try{r=await fetch(`${St}/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 Z("Network error while invoking UDF.",{code:"TRANSPORT"})}let a=await pn(r);if(r.ok)return ji(a);if(a.error?.code==="CONSENT_REQUIRED"&&!n){let u=hn(a),c=typeof u.playbook_id=="string"?u.playbook_id:G,d=typeof u.min_allowance_suggested=="number"?u.min_allowance_suggested:1,p=await Qi(c,d);if(p==="granted")return At(t,e,!0);throw p==="timeout"?new be:new ye}throw Et(a,r.status)},"call"),Yi=o(async()=>{let t=Se();if(!t)throw new J;if(!G)throw new Q("Missing playbook id.",{code:"PBSV_PID_MISMATCH"});let e=new URL(`${St}/api/v1/service/functions`);e.searchParams.set("playbook_id",G);let n=await fetch(e.toString(),{headers:{Authorization:`Bearer ${t}`,"X-Pbsv":"1"}}),i=await pn(n);if(!n.ok)throw Et(i,n.status);let s=i.functions;return Array.isArray(s)?s:[]},"list"),Rt=o((t,e,n)=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))},"dispatchButtonEvent"),Xi=o(t=>{if(typeof t!="string")return t;let n=D?.document?.querySelector(t);if(n&&"appendChild"in n)return n;throw new Error(`UDF button target not found: ${t}`)},"resolveButtonTarget"),zi=o((t,e)=>{if(!D)throw new Error("Playbook runtime is not installed.");let n=Xi(t),i=D.document.createElement("button"),s=e.label||e.functionName,r=e.loadingLabel||"Running...",a=e.disabledLabel||"Sign in to run";return i.type="button",i.className="alva-udf-button",i.textContent=z()?s:a,i.disabled=!1,i.setAttribute("data-function-name",e.functionName),z()||i.setAttribute("aria-disabled","true"),i.addEventListener("click",async()=>{if(!z()){Ki(e.functionName);return}if(!i.disabled){i.disabled=!0,i.textContent=r,Rt(i,"alva:udf-button:loading",{functionName:e.functionName});try{let u=await At(e.functionName,e.params??{});Rt(i,"alva:udf-button:result",{functionName:e.functionName,result:u})}catch(u){Rt(i,"alva:udf-button:error",{functionName:e.functionName,error:u})}finally{i.disabled=!1,i.textContent=z()?s:a,z()||i.setAttribute("aria-disabled","true")}}}),n.appendChild(i),i},"renderButton"),gn={call:At,list:Yi,getViewerToken:Se,isAuthenticated:z,renderButton:zi,UdfError:A,UdfAuthRequiredError:J,UdfTokenExpiredError:fe,UdfTokenInvalidError:me,UdfPidMismatchError:Q,UdfConsentRequiredError:ge,UdfConsentDeniedError:ye,UdfConsentTimeoutError:be,UdfInsufficientCredits:we,UdfFunctionNotFoundError:Pe,UdfFunctionDisabledError:_e,UdfRateLimitedError:Te,UdfExecutionError:Re,UdfTransportError:Z},vt=o(t=>{let e=t??(typeof window>"u"?void 0:window);if(!e||tn)return;D=e,tn=!0,Mi(e),e.addEventListener("message",Bi);let n=e,i=n.alva||{};n.alva={...i,udf:gn,subscribe:mn}},"installPlaybookRuntime");var l=class extends Error{static{o(this,"AlvaError")}code;status;details;constructor(e,n,i,s){super(n),this.name="AlvaError",this.code=e,this.status=i,this.details=s}},Le=class extends Error{static{o(this,"CliUsageError")}command;constructor(e,n){super(e),this.name="CliUsageError",this.command=n}};function yn(t){return Object.prototype.toString.call(t)==="[object ArrayBuffer]"}o(yn,"isArrayBuffer");var bn=1;function Ji(t){let e=0;for(;e<t.length;){let n=t[e];if(n<=127){e+=1;continue}let i=0,s=0,r=0;if(n>=194&&n<=223)i=1,s=128,r=n&31;else if(n>=224&&n<=239)i=2,s=2048,r=n&15;else if(n>=240&&n<=244)i=3,s=65536,r=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;r=r<<6|u&63}if(r<s||r>1114111||r>=55296&&r<=57343)return!1;e+=i+1}return!0}o(Ji,"isValidUtf8");var Oe=class{constructor(e){this.client=e}client;static{o(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(!yn(n)||!Ji(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:bn}:{}}})}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:bn}:{}},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 wn="9007199254740991";function Pn(t,e,n,i){let s=t.length+e,r=n.length+i;if(s!==r)return s>r;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}o(Pn,"scaledIntegerGreater");function Zi(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 r=(n+i).replace(/^0+/,"")||"0";if(r==="0")return!1;let a=s-i.length;return a>=0?Pn(r,a,wn,0):Pn(r,0,wn,-a)}o(Zi,"numberOutsideSafeRange");function er(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(Zi(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++}}o(er,"validateJSONNumberTokens");function It(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)=>It(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,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))if(r.enumerable){if(!("value"in r))throw new TypeError(`${e} must not contain accessors`);It(r.value,`${e}.${s}`,n)}}n.delete(t)}}o(It,"assertPlainJSONData");function ke(t){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("args must be a JSON object");It(t,"args",new Set);let e=JSON.stringify(t);return _n(e),e}o(ke,"serializeStructuredArgs");function _n(t){let e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("args must be a JSON object");er(t)}o(_n,"validateSerializedArgs");function Ee(t,e,n){let i=Object.entries(t).filter(([s,r])=>r!==void 0&&(n===void 0||s!==e));return n!==void 0&&(_n(n),i.push([e,n])),`{${i.map(([s,r])=>{let a=s===e&&n!==void 0?n:JSON.stringify(r);return`${JSON.stringify(s)}:${a}`}).join(",")}}`}o(Ee,"objectWithRawJSONField");var Ge=class{constructor(e){this.client=e}client;static{o(this,"RunResource")}async execute(e){return this.client._requireAuth(),e.args===void 0?this.request(e):this.request(e,ke(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:Ee(i,"args",n)},timeoutMs:e.timeout_ms})}};var Me=class{constructor(e){this.client=e}client;static{o(this,"DeployResource")}async create(e){return this.client._requireAuth(),e.args===void 0?this.createRequest(e):this.createRequest(e,ke(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:Ee(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,ke(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:Ee(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 $e=class{constructor(e){this.client=e}client;static{o(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 je=class{constructor(e){this.client=e}client;static{o(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 We=class{constructor(e){this.client=e}client;static{o(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=Be(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/stop`)}async resume(e){this.client._requireAuth();let n=Be(e.id);return this.client._request("POST",`/api/v1/feed/${encodeURIComponent(String(n))}/resume`)}async delete(e){this.client._requireAuth();let n=Be(e.id);return this.client._request("DELETE",`/api/v1/feed/${encodeURIComponent(String(n))}`)}async setVisibility(e){this.client._requireAuth();let n=Be(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 Be(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}o(Be,"requireFeedID");var Tn={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 U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(U,"record");function tr(t){if(!U(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")}o(tr,"validateXReadParams");function M(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid viewer.${t} response`,502)}o(M,"invalidResponse");function Rn(t,e){if(!U(t))return M(e);if(t.errors!==void 0){if(!Array.isArray(t.errors))return M(e);if(t.errors.length>0){let n=t.errors.flatMap(r=>U(r)&&typeof r.message=="string"?[r.message]:[]),i=t.errors.map(r=>U(r)&&U(r.extensions)?r.extensions.code:void 0),s=typeof i[0]=="string"&&Object.hasOwn(Tn,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR";throw new l(s,n.join("; ")||"X read failed",Tn[s]??502,{errors:t.errors})}}return!U(t.data)||!U(t.data.viewer)?M(e):t.data.viewer[e]}o(Rn,"viewerField");function nr(t,e,n){if(!U(t)||!Array.isArray(t.edges)||!U(t.pageInfo))return M(e);let i=t.pageInfo;if(typeof i.startCursor!="string"||typeof i.endCursor!="string"||typeof i.hasNextPage!="boolean"||typeof i.hasPreviousPage!="boolean"||i.hasNextPage&&!i.endCursor)return M(e);for(let a of t.edges){if(!U(a)||typeof a.cursor!="string"||!a.cursor||!U(a.node))return M(e);let u=a.node;if(n.some(c=>typeof u[c]!="string")||!u.id)return M(e)}let s=t.edges[0],r=t.edges[t.edges.length-1];return i.startCursor!==(s?.cursor??"")||r&&i.endCursor!==r.cursor?M(e):{edges:t.edges,pageInfo:i,retrievedAt:new Date().toISOString()}}o(nr,"readPage");var ee=class{constructor(e){this.client=e}client;static{o(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=Rn(e,"xConnection");return!U(n)||["connected","canReadFollowing","canReadPosts"].some(i=>typeof n[i]!="boolean")?M("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,i){tr(i),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:i.first??20,after:i.after}}});return nr(Rn(s,e),e,n.split(" "))}};function h(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(h,"record");function v(t){return typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}o(v,"isPositiveInt64");var te=`
|
|
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 Sn(t){return Array.isArray(t)&&t.every(v)}o(Sn,"positiveInt64List");function ir(t){return Array.isArray(t)&&t.every(e=>h(e)&&v(e.entityId)&&typeof e.stance=="string"&&e.stance.trim()!=="")}o(ir,"stanceList");function rr(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.id=="string"&&e.id.trim()!==""&&typeof e.ticker=="string"&&typeof e.name=="string")}o(rr,"entityList");function sr(t){return Array.isArray(t)&&t.every(e=>h(e)&&typeof e.type=="string"&&e.type.trim()!==""&&typeof e.coverUrl=="string"&&(e.url===null||typeof e.url=="string"))}o(sr,"mediaList");function or(t){return Array.isArray(t)&&t.every(e=>h(e)&&(e.title===null||typeof e.title=="string")&&typeof e.sourceKind=="string"&&typeof e.sourceContentId=="string"&&typeof e.publicUrl=="string"&&ar(e.sourceTimeMs)&&typeof e.locator=="string")}o(or,"sourceRefList");function ar(t){return t===null||typeof t=="number"&&Number.isFinite(t)}o(ar,"nullableMs");function ur(t){return h(t)&&v(t.versionId)&&v(t.materialVersionId)&&typeof t.publishedAtMs=="number"&&Number.isFinite(t.publishedAtMs)&&typeof t.changeKind=="string"&&t.changeKind.trim()!==""&&or(t.sourceRefs)}o(ur,"snapshot");function cr(t){return h(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)&&h(t.viewerState)&&(t.viewerState.following===null||typeof t.viewerState.following=="boolean")}o(cr,"publisher");function ne(t){if(!h(t))return!1;for(let e of["thesisId","playbookId","authorVersionId","materialVersionId"])if(!v(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!Sn(t.entityIds)||!Sn(t.categoryIds)||!ir(t.entityStances)||!rr(t.entities)||!sr(t.medias)||!cr(t.publisher)||!ur(t.snapshotRelease)?!1:t.signalFeed===null||h(t.signalFeed)&&v(t.signalFeed.id)}o(ne,"isThesisPublication");var lr=`
|
|
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 dr(t){if(!h(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 i=t[n];if(i!==void 0&&(typeof i!="string"||!i.trim()))throw new Error(`${n} must be a non-empty cursor`)}if(t.feedId!==void 0&&!v(t.feedId))throw new Error("feedId must be a positive decimal int64 string")}o(dr,"validateForYouListParams");function Ae(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid For You connection",502)}o(Ae,"invalidResponse");function pr(t){if(!h(t)||!Array.isArray(t.edges)||!h(t.pageInfo))return Ae();let e=t.pageInfo;if(typeof e.startCursor!="string"||typeof e.endCursor!="string"||typeof e.hasNextPage!="boolean"||typeof e.hasPreviousPage!="boolean")return Ae();for(let s of t.edges){if(!h(s)||typeof s.cursor!="string"||!s.cursor.trim()||!h(s.node))return Ae();let r=s.node;if(typeof r.id!="string"||!r.id.startsWith("FeedEntry:")||!v(r.id.slice(10))||!h(r.feed)||!v(r.feed.id)||!h(r.major)||typeof r.major.id!="string"||!v(r.major.feedId)||typeof r.title!="string"||typeof r.body!="string")return Ae()}let n=t.edges[0],i=t.edges[t.edges.length-1];return e.startCursor!==(n?.cursor??"")||e.endCursor!==(i?.cursor??"")||t.edges.length===0&&e.hasNextPage?Ae():t}o(pr,"connection");var hr=`
|
|
50
50
|
query ToolkitForYouTheses($input: ThesisRecommendationInput) {
|
|
51
51
|
viewer {
|
|
52
52
|
thesisRecommendations(input: $input) {
|
|
@@ -64,7 +64,7 @@ query ToolkitForYouTheses($input: ThesisRecommendationInput) {
|
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
-
`.trim();function
|
|
67
|
+
`.trim();function fr(t){if(!h(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")}o(fr,"validateForYouThesesParams");function kn(t,e){if(!h(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(i=>h(i)&&typeof i.message=="string"?[i.message]:[]);throw new l("GRAPHQL_ERROR",n.join("; ")||"GraphQL request failed",400,{errors:t.errors})}}if(!h(t.data)||!h(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]}o(kn,"graphqlViewerField");function Qe(){throw new l("GRAPHQL_INVALID_RESPONSE","GraphQL returned an invalid Thesis recommendation page",502)}o(Qe,"invalidPage");function mr(t){if(!h(t)||!Array.isArray(t.edges)||!h(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 Qe();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 Qe();for(let i of t.edges)if(!h(i)||typeof i.cursor!="string"||!i.cursor.trim()||!h(i.node)||typeof i.node.itemKey!="string"||!i.node.itemKey.trim()||!ne(i.node.publication))return Qe();let n=t.edges[0];return e.startCursor!==(n?.cursor??"")?Qe():t}o(mr,"recommendationPage");var ie=class{constructor(e){this.client=e}client;static{o(this,"ForYouResource")}async list(e={}){dr(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:lr,variables:{input:{first:e.first??20,after:e.after,newerThan:e.newerThan,feedId:e.feedId}}}});return pr(kn(n,"forYou"))}async theses(e={}){fr(e),this.client._requireAuth();let n=await this.client._request("POST","/query",{body:{query:hr,variables:{input:{first:e.first??10,after:e.after}}}}),i=kn(n,"thesisRecommendations");return mr(i)}};var gr=`
|
|
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(),yr=`
|
|
78
78
|
mutation ToolkitUpdateAutomationAlertDelivery(
|
|
79
79
|
$input: UpdateAutomationAlertDeliveryInput!
|
|
80
80
|
$includeAlvaChannels: Boolean!
|
|
@@ -89,31 +89,31 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
`.trim(),re=class{constructor(e){this.client=e;this.delivery=new ve(e)}client;static{o(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=yr(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ve(e.id);if(!br(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)}},ve=class{constructor(e){this.client=e}client;static{o(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ve(e.id),s=(await this.graphql(mr,{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=Ve(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 r=i?wr(e.alvaChannelIds??[]):void 0,u=(await this.graphql(gr,{input:{automationId:n,...i?{alvaChannelIds:r}:{},...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",Pr(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 yr(t){if(typeof t=="string")return Ve(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}o(yr,"requireAutomationID");function Ve(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}o(Ve,"requireAutomationIDString");function br(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}o(br,"hasAutomationUpdate");function wr(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}o(wr,"uniqueAlvaChannelIDs");function Pr(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"}o(Pr,"graphQLErrorMessage");var kn=["public","private","paid"];var He=class{constructor(e){this.client=e}client;static{o(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),r;for(;;){let a=await this.listByOwner({owner:i,cursor:r,limit:100}),u=a.items.find(c=>c.name===s);if(u)return u;if(!a.has_next||!a.next_cursor)return null;r=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=_r(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(r=>Tr(r,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!kn.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${kn.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function _r(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"}o(_r,"webOriginFromApiBase");function Tr(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,r=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:r,url:r?`${e}${r}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}o(Tr,"toAgentPlaybook");var Ke=class{constructor(e){this.client=e}client;static{o(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 Ye=class{constructor(e){this.client=e}client;static{o(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 En=[{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 An(t,e){return En.find(n=>n.skill===t&&n.file===e)}o(An,"getSkillEndpointMetadata");function It(t){return En.filter(e=>e.skill===t)}o(It,"listSkillEndpointMetadata");var Xe=class{constructor(e){this.client=e}client;static{o(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...vn(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 r=It(e.name);return{...s,...vn(e.name),...r.length>0?{endpoint_metadata:r}:{}}}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 r=An(e.name,e.file);return{...s,...r?{metadata:r}:{}}}};function vn(t){let e=It(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}o(vn,"metadataSummaryForSkill");function In(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}}o(In,"normalizePlaybookSkillSummary");function Cn(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]}}o(Cn,"parsePlaybookSkillId");var ze=class{constructor(e){this.client=e}client;static{o(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(In)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=Cn(e),s=encodeURIComponent(n),r=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${s}/${r}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...In(u),files:u.files??[]}}async file(e,n){let{username:i,name:s}=Cn(e),r=encodeURIComponent(i),a=encodeURIComponent(s),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${r}/${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 Je=class{constructor(e){this.client=e}client;static{o(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 Ze=class{constructor(e){this.client=e}client;static{o(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var et=class{constructor(e){this.client=e}client;static{o(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 tt=class{constructor(e){this.client=e}client;static{o(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var nt=class{constructor(e){this.client=e}client;static{o(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 it=class{constructor(e){this.client=e}client;static{o(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 rt=class{constructor(e){this.client=e}client;static{o(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 st=class{constructor(e){this.client=e}client;static{o(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:Rr(e)})}};function Rr(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}o(Rr,"buildQuery");var ot=class{constructor(e){this.client=e}client;static{o(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 at=class{constructor(e){this.client=e}client;static{o(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 qn="pageInfo { endCursor hasNextPage }",Dn="__typename id slug displayName bio",Sr="__typename id username displayName bio",Un="__typename id ticker name kind assetClass venue { id name }",Fn=`theses(input: $input) {
|
|
92
|
+
`.trim(),re=class{constructor(e){this.client=e;this.delivery=new ve(e)}client;static{o(this,"AutomationResource")}delivery;list(e={}){return this.client.feed.list(e)}async inspect(e){this.client._requireAuth();let n=br(e.id);return this.client._request("GET",`/api/v1/automation/${encodeURIComponent(String(n))}`)}async update(e){this.client._requireAuth();let n=Ve(e.id);if(!wr(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)}},ve=class{constructor(e){this.client=e}client;static{o(this,"AutomationAlertDeliveryResource")}async get(e){this.client._requireAuth();let n=Ve(e.id),s=(await this.graphql(gr,{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=Ve(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 r=i?Pr(e.alvaChannelIds??[]):void 0,u=(await this.graphql(yr,{input:{automationId:n,...i?{alvaChannelIds:r}:{},...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",_r(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 br(t){if(typeof t=="string")return Ve(t);if(!Number.isSafeInteger(t)||t<=0)throw new Error("automation id must be a positive integer");return t}o(br,"requireAutomationID");function Ve(t){if(!/^[1-9]\d*$/.test(t))throw new Error("automation id must be a positive integer string");return t}o(Ve,"requireAutomationIDString");function wr(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}o(wr,"hasAutomationUpdate");function Pr(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}o(Pr,"uniqueAlvaChannelIDs");function _r(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"}o(_r,"graphQLErrorMessage");function He(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"}o(He,"webOriginFromApiBase");var En=["public","private","paid"];var Ke=class{constructor(e){this.client=e}client;static{o(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),r;for(;;){let a=await this.listByOwner({owner:i,cursor:r,limit:100}),u=a.items.find(c=>c.name===s);if(u)return u;if(!a.has_next||!a.next_cursor)return null;r=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=He(this.client.baseUrl);return{playbooks:(i.playbooks??[]).map(r=>Tr(r,s)),has_next:i.has_next??!1}}async setVisibility(e){if(!En.includes(e.visibility))throw new l("INVALID_ARGUMENT",`Invalid visibility "${e.visibility}". Expected one of: ${En.join(", ")}.`,400);return this.client._requireAuth(),await this.client._request("POST",`/api/v1/playbook/${encodeURIComponent(e.name)}/visibility`,{body:{visibility:e.visibility}})}};function Tr(t,e){let n=t.creator?.name??"",i=t.name??"",s=n&&i?`${n}/${i}`:i,r=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:r,url:r?`${e}${r}`:"",...t.readme?{readme:t.readme}:{},cursor:t.cursor??""}}o(Tr,"toAgentPlaybook");var Ye=class{constructor(e){this.client=e}client;static{o(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 Xe=class{constructor(e){this.client=e}client;static{o(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 An=[{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 vn(t,e){return An.find(n=>n.skill===t&&n.file===e)}o(vn,"getSkillEndpointMetadata");function Ct(t){return An.filter(e=>e.skill===t)}o(Ct,"listSkillEndpointMetadata");var ze=class{constructor(e){this.client=e}client;static{o(this,"DataSkillsResource")}async list(){return{skills:((await this.client._request("GET","/api/v1/skills",{baseUrl:this.client.arraysBaseUrl,noAuth:!0})).data??[]).map(n=>({...n,...In(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 r=Ct(e.name);return{...s,...In(e.name),...r.length>0?{endpoint_metadata:r}:{}}}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 r=vn(e.name,e.file);return{...s,...r?{metadata:r}:{}}}};function In(t){let e=Ct(t).length;return e===0?{}:{metadata:{endpoint_count:e}}}o(In,"metadataSummaryForSkill");function Cn(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}}o(Cn,"normalizePlaybookSkillSummary");function xn(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]}}o(xn,"parsePlaybookSkillId");var Je=class{constructor(e){this.client=e}client;static{o(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(Cn)}}async tags(){return{tags:(await this.client._request("GET","/api/v1/skills/tags")).data??[]}}async get(e){let{username:n,name:i}=xn(e),s=encodeURIComponent(n),r=encodeURIComponent(i),u=(await this.client._request("GET",`/api/v1/skills/${s}/${r}`)).data?.[0];if(!u)throw new l("NOT_FOUND",`empty playbook skills get response for ${e}`,0);return{...Cn(u),files:u.files??[]}}async file(e,n){let{username:i,name:s}=xn(e),r=encodeURIComponent(i),a=encodeURIComponent(s),u=n.split("/").map(encodeURIComponent).join("/"),d=(await this.client._request("GET",`/api/v1/skills/${r}/${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 Ze=class{constructor(e){this.client=e}client;static{o(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 et=class{constructor(e){this.client=e}client;static{o(this,"RemixResource")}async save(e){this.client._requireAuth(),await this.client._request("POST","/api/v1/remix",{body:{child:e.child,parents:e.parents}})}};var tt=class{constructor(e){this.client=e}client;static{o(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 nt=class{constructor(e){this.client=e}client;static{o(this,"UserResource")}async me(){return this.client._requireAuth(),this.client._request("GET","/api/v1/me")}};var it=class{constructor(e){this.client=e}client;static{o(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 rt=class{constructor(e){this.client=e}client;static{o(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 st=class{constructor(e){this.client=e}client;static{o(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 ot=class{constructor(e){this.client=e}client;static{o(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:Rr(e)})}};function Rr(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}o(Rr,"buildQuery");var at=class{constructor(e){this.client=e}client;static{o(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 ut=class{constructor(e){this.client=e}client;static{o(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 Dn="pageInfo { endCursor hasNextPage }",Un="__typename id slug displayName bio",Sr="__typename id username displayName bio",Fn="__typename id ticker name kind assetClass venue { id name }",Ln=`theses(input: $input) {
|
|
93
93
|
edges { cursor node { id latestRelease { thesisPublication { ${te} } } } }
|
|
94
|
-
${
|
|
94
|
+
${Dn}
|
|
95
95
|
}`,kr=`query ToolkitPersonTheses($slug: String!, $input: ProfileThesisConnectionInput) {
|
|
96
|
-
scope: person(slug: $slug) { ${
|
|
96
|
+
scope: person(slug: $slug) { ${Un} ${Ln} }
|
|
97
97
|
}`,Er=`query ToolkitUserTheses($username: String!, $input: ProfileThesisConnectionInput) {
|
|
98
|
-
scope: publicUser(username: $username) { ${Sr} ${
|
|
98
|
+
scope: publicUser(username: $username) { ${Sr} ${Ln} }
|
|
99
99
|
}`,Ar=`query ToolkitEntityTheses($id: ID!, $input: EntityThesisConnectionInput) {
|
|
100
|
-
market { scope: entity(input: { id: $id }) { ${
|
|
101
|
-
theses(input: $input) { edges { cursor node { ${te} } } ${
|
|
100
|
+
market { scope: entity(input: { id: $id }) { ${Fn}
|
|
101
|
+
theses(input: $input) { edges { cursor node { ${te} } } ${Dn} }
|
|
102
102
|
} }
|
|
103
103
|
}`,vr=`query ToolkitThesisPeople($query: String!) {
|
|
104
104
|
search: people(input: { query: $query, first: 50 }) {
|
|
105
|
-
edges { node { ${
|
|
105
|
+
edges { node { ${Un} } } pageInfo { hasNextPage }
|
|
106
106
|
}
|
|
107
107
|
}`,Ir=`query ToolkitThesisEntities($query: String!) {
|
|
108
108
|
market { search: entities(input: { query: $query, first: 50, byPrefix: false }) {
|
|
109
|
-
edges { node { ${
|
|
109
|
+
edges { node { ${Fn} } } pageInfo { hasNextPage }
|
|
110
110
|
} }
|
|
111
111
|
}`,Cr=`query ToolkitRelatedTheses($id: ID!, $input: RelatedThesisInput) {
|
|
112
112
|
node(id: $id) { ... on Playbook { relatedTheses(input: $input) {
|
|
113
113
|
state nextCursor
|
|
114
114
|
edges { cursor node { itemKey score publication { ${te} } } }
|
|
115
115
|
} } }
|
|
116
|
-
}`,xr=["person","personName","user","ticker","entityId"];function
|
|
116
|
+
}`,xr=["person","personName","user","ticker","entityId"];function On(t){if(!h(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&&!x(t.cursor))throw F("cursor must be non-empty")}o(On,"validateThesisPageParams");function Nr(t){On(t);let e=xr.filter(n=>t[n]!==void 0);if(e.length!==1)throw F("Choose exactly one of person, personName, user, ticker or entityId");if(!x(t[e[0]]))throw F(`${e[0]} must be non-empty`);if(t.entityId!==void 0&&!v(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")}o(Nr,"validateListThesesParams");async function Gn(t,e){Nr(e),t._requireAuth();let n={first:e.first??10,after:e.cursor},i=e.ticker===void 0?e.entityId:(await qn(t,Ir,e.ticker,"Entity")).id;if(i!==void 0){let u=await K(t,Ar,{id:i,input:n});if(!h(u.market))throw w();return Nn(u.market.scope,c=>ne(c)?{playbookId:c.playbookId,publication:c}:void 0)}let s={...n,status:e.status},r=e.personName===void 0?e.person:(await qn(t,vr,e.personName,"Person")).slug,a=r===void 0?await K(t,Er,{username:e.user,input:s}):await K(t,kr,{slug:r,input:s});return Nn(a.scope,u=>{if(!v(u.id))return;let c=u.latestRelease;if(c===null)return{playbookId:u.id,publication:null};if(!h(c))return;let d=c.thesisPublication;if(!(d!==null&&!ne(d)))return{playbookId:u.id,publication:d}})}o(Gn,"listTheses");async function Mn(t,e,n={}){if(On(n),!v(e))throw F("id must be an internal positive int64 Playbook ID");t._requireAuth();let i=await K(t,Cr,{id:`Playbook:${e}`,input:{first:n.first??10,after:n.cursor}});if(i.node===null)throw Ie();if(!h(i.node))throw w();let s=i.node.relatedTheses;if(!h(s)||!["GENERATING","READY","FAILED"].includes(s.state)||s.nextCursor!==null&&!x(s.nextCursor))throw w();for(let r of jn(s))if(!x(r.node.itemKey)||typeof r.node.score!="number"||!ne(r.node.publication))throw w();return{state:s.state,edges:s.edges,nextCursor:s.nextCursor}}o(Mn,"relatedTheses");function Nn(t,e){if(t===null)throw Ie();let n=$n(t);if(!h(t)||!h(t.theses))throw w();let i=t.theses,s=jn(i).map(r=>{let a=e(r.node);if(a===void 0)throw w();return{cursor:r.cursor,node:a}});return{scope:n,edges:s,nextCursor:qr(i)}}o(Nn,"thesisPage");async function qn(t,e,n,i){let s=await K(t,e,{query:n}),r=h(s.market)?s.market.search:s.search;if(!h(r)||!Array.isArray(r.edges)||!h(r.pageInfo))throw w();let a=r.edges.map(c=>$n(h(c)?c.node:void 0));if(!a.every(c=>c.__typename===i))throw w();let u=r.pageInfo.hasNextPage===!0;if(a.length===1&&!u)return a[0];throw a.length===0&&!u?Ie():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})}o(qn,"resolveUnique");function $n(t){if(!h(t)||!x(t.id))throw w();if(t.__typename==="Entity"){if(!["ticker","name","kind","assetClass"].every(n=>typeof t[n]=="string")||t.venue!==null&&(!h(t.venue)||!x(t.venue.id)||typeof t.venue.name!="string"))throw w()}else if(typeof t.displayName!="string"||typeof t.bio!="string"||!(t.__typename==="Person"&&x(t.slug)||t.__typename==="PublicUser"&&x(t.username)))throw w();let e={...t};return delete e.theses,e}o($n,"readScope");function jn(t){if(!Array.isArray(t.edges)||!t.edges.every(e=>h(e)&&x(e.cursor)&&h(e.node)))throw w();return t.edges}o(jn,"edges");function qr(t){let e=t.pageInfo;if(!h(e)||typeof e.hasNextPage!="boolean"||e.hasNextPage&&!x(e.endCursor))throw w();return e.hasNextPage?e.endCursor:null}o(qr,"nextCursor");var Dr=`query ToolkitThesisReturn($id: ID!, $detail: Boolean!) {
|
|
117
117
|
node(id: $id) { ... on Playbook { latestRelease { thesisPublication {
|
|
118
118
|
returnTracking
|
|
119
119
|
thesisReturn(detail: $detail) {
|
|
@@ -123,11 +123,11 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
123
123
|
allocation { holdings { entityId symbol direction weight } cash }
|
|
124
124
|
}
|
|
125
125
|
} } } }
|
|
126
|
-
}`;async function
|
|
126
|
+
}`;async function Bn(t,e,n={}){if(!v(e))throw F("id must be an internal positive int64 Playbook ID");if(n.detail!==void 0&&typeof n.detail!="boolean")throw F("detail must be a boolean");t._requireAuth();let i=await K(t,Dr,{id:`Playbook:${e}`,detail:n.detail??!1});if(i.node===null)throw Ie();if(!h(i.node))throw w();let s=i.node.latestRelease;if(s==null)return{playbookId:e,returnTracking:null,thesisReturn:null};if(!h(s))throw w();let r=s.thesisPublication;if(r===null)return{playbookId:e,returnTracking:null,thesisReturn:null};if(!h(r))throw w();let a=r.returnTracking;if(a!==null&&!["UNSET","ON","OFF"].includes(a))throw w();let u=r.thesisReturn;if(u!==null&&!Fr(u))throw w();return{playbookId:e,returnTracking:a,thesisReturn:u}}o(Bn,"thesisReturn");var Ur=`query ToolkitThesisWatchpoints($id: ID!) {
|
|
127
127
|
node(id: $id) { ... on Playbook { latestRelease { thesisPublication {
|
|
128
128
|
watchpoints { label text origin }
|
|
129
129
|
} } } }
|
|
130
|
-
}`;async function
|
|
130
|
+
}`;async function Wn(t,e){if(!v(e))throw F("id must be an internal positive int64 Playbook ID");t._requireAuth();let n=await K(t,Ur,{id:`Playbook:${e}`});if(n.node===null)throw Ie();if(!h(n.node))throw w();let i=n.node.latestRelease;if(i==null)return{playbookId:e,watchpoints:[]};if(!h(i))throw w();let s=i.thesisPublication;if(s===null)return{playbookId:e,watchpoints:[]};if(!h(s)||!Array.isArray(s.watchpoints))throw w();let r=s.watchpoints.map(a=>{if(!h(a)||!x(a.label)||!x(a.text)||!["stated","inferred","agent"].includes(a.origin))throw w();return{label:a.label,text:a.text,origin:a.origin}});return{playbookId:e,watchpoints:r}}o(Wn,"thesisWatchpoints");function Fr(t){return!h(t)||typeof t.live!="boolean"||typeof t.value!="number"||typeof t.stale!="boolean"||typeof t.computedAtMs!="number"||!Array.isArray(t.updates)||t.allocation!==null&&!Lr(t.allocation)?!1:t.updates.every(e=>h(e)&&x(e.authorVersionId)&&typeof e.publishedAtMs=="number"&&typeof e.startValue=="number"&&Array.isArray(e.positions)&&e.positions.every(n=>h(n)&&x(n.symbol)&&["BULLISH","BEARISH"].includes(n.direction)&&["PENDING","NEXT_UPDATE","LATEST"].includes(n.end)&&typeof n.positionReturn=="number"&&typeof n.weight=="number"))}o(Fr,"validThesisReturn");function Lr(t){return h(t)&&typeof t.cash=="number"&&Array.isArray(t.holdings)&&t.holdings.every(e=>h(e)&&x(e.entityId)&&x(e.symbol)&&["BULLISH","BEARISH"].includes(e.direction)&&typeof e.weight=="number")}o(Lr,"validAllocation");async function K(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!h(i))throw w();if(i.errors!==void 0){if(!Array.isArray(i.errors))throw w();if(i.errors.length){let s=i.errors.flatMap(c=>h(c)&&typeof c.message=="string"?[c.message]:[]),r=new Set(i.errors.map(c=>h(c)&&h(c.extensions)?c.extensions.code:void 0)),[a]=r,u=r.size===1&&typeof a=="string"?Or.get(a):void 0;throw new l(u===void 0?"GRAPHQL_ERROR":String(a),s.join("; ")||"GraphQL request failed",u??400,{errors:i.errors})}}if(!h(i.data))throw w();return i.data}o(K,"graphql");var Or=new Map([["NOT_FOUND",404],["PERMISSION_DENIED",403],["UNAUTHENTICATED",401]]);function x(t){return typeof t=="string"&&t.trim().length>0}o(x,"nonempty");function F(t){return new l("INVALID_ARGUMENT",t,400)}o(F,"argument");function w(){return new l("GRAPHQL_INVALID_RESPONSE","Invalid Thesis read response",502)}o(w,"invalid");function Ie(){return new l("NOT_FOUND","No visible matching identity or Thesis found",404)}o(Ie,"notFound");var Qn=["fundamentals","macro","technicals","commentary"],Vn=["all","notable","major"],Gr=`mutation SetThesisStarred($input: SetThesisStarredInput!) {
|
|
131
131
|
setThesisStarred(input: $input) {
|
|
132
132
|
thesisId
|
|
133
133
|
stats { starCount }
|
|
@@ -137,12 +137,12 @@ mutation ToolkitUpdateAutomationAlertDelivery(
|
|
|
137
137
|
setThesisSignalEnabled(input: $input) {
|
|
138
138
|
publication { playbookId authorVersionId archived researchPaused }
|
|
139
139
|
}
|
|
140
|
-
}`,$r=9223372036854775807n,jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Br=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,
|
|
140
|
+
}`,$r=9223372036854775807n,jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Br=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,Yn=new TextEncoder,oe=class{constructor(e){this.client=e}client;static{o(this,"ThesesResource")}list(e){return Gn(this.client,e)}related(e,n={}){return Mn(this.client,e,n)}async assetCandidates(e,n={}){this.client._requireAuth();let s={text:xe(e),selectedEntityIds:Ot(n.entityIds??[],"entityIds")};if(n.thesisId!==void 0&&(s.thesisId=I(n.thesisId,"thesisId")),n.discover!==void 0){if(typeof n.discover!="boolean")throw m("discover must be a boolean");s.discover=n.discover}let r=await this.client._request("POST","/query",{body:{query:`query ThesisAssetCandidates($input: ThesisAssetCandidatesInput!) {
|
|
141
141
|
viewer { thesisAssetCandidates(input: $input) {
|
|
142
142
|
mentions { quote ticker resolution stance candidates { entityId ticker name kind } }
|
|
143
143
|
returnPreview { tracking askSwitch directions { entityId direction } keptEntityIds lastLegRemoved }
|
|
144
144
|
} }
|
|
145
|
-
}`,variables:{input:s}}});if(Array.isArray(r?.errors)&&r.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:r.errors});let a=r?.data,u=g(a)?a.viewer:void 0,c=g(u)?u.thesisAssetCandidates:void 0;if(!g(c)||!Array.isArray(c.mentions))throw f("asset candidates response must contain mentions");return{mentions:c.mentions.map((p,P)=>{if(!g(p)||typeof p.quote!="string"||typeof p.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(p.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(p.stance)||!Array.isArray(p.candidates))throw f(`asset mention ${P} is invalid`);let _=p.candidates.map(b=>{if(!g(b)||typeof b.ticker!="string"||typeof b.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(b.kind))throw f(`asset mention ${P} has invalid candidate`);return{entityId:C(b.entityId,`asset mention ${P} candidate.entityId`),ticker:b.ticker,name:b.name,kind:b.kind}});return{...p,candidates:_}}),returnPreview:Kr(c.returnPreview)}}thesisReturn(e,n={}){return jn(this.client,e,n)}watchpoints(e){return Bn(this.client,e)}async create(e){this.client._requireAuth();let n=Wr(e),i=se(await this.client._request("POST","/api/v1/theses",{body:n}));return Vn(n.entity_stances,i.thesis.entity_stances),i}async get(e){this.client._requireAuth();let n=I(e,"id"),i=Xr(await this.client._request("GET",`/api/v1/theses/${n}`));if(i.thesis.id!==n)throw f("get response must match the requested thesis");return i}async getVersion(e,n){this.client._requireAuth();let i=I(e,"id"),s=I(n,"author_version_id"),r=se(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(r.thesis.id!==i||r.thesis.author_version_id!==s)throw f("version response must match the requested thesis and author version");return r}async listUpdates(e,n={}){this.client._requireAuth();let i=I(e,"id"),s=n.first??10;if(!Number.isInteger(s)||s<1||s>100)throw m("first must be between 1 and 100");if(n.cursor!==void 0&&typeof n.cursor!="string")throw m("cursor must be a string");let r=await this.client._request("GET",`/api/v1/theses/${i}/versions`,{query:{first:s,cursor:n.cursor,updates_only:!0}});if(!g(r)||!Array.isArray(r.versions)||typeof r.next_cursor!="string")throw f("invalid Update list");let a=r.versions.map(Ut);if(a.some(u=>u.id!==i))throw f("Update list must match requested Thesis");return{versions:a,next_cursor:r.next_cursor}}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw m("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw m("cursor must be a string");return zr(await this.client._request("GET",`/api/v1/theses/${I(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Yr(n),s=I(e,"id"),r=se(await this.client._request("PUT",`/api/v1/theses/${s}`,{body:i}));if(r.thesis.id!==s)throw f("update response must match the requested thesis");return Vn(i.entity_stances,r.thesis.entity_stances),r}async setArchived(e,n){if(this.client._requireAuth(),!g(n))throw m("params is required");let i=I(e,"id"),s=Ft(n.request_id);if(typeof n.archived!="boolean")throw m("archived must be a boolean");n.note!==void 0&&$(n.note,"note");let r=await this.get(i);if(r.thesis.archived===n.archived&&n.note===void 0)return{thesis:r.thesis};if(!rs(r.thesis.entity_ids,r.thesis.entity_stances))throw f("archive requires one entity_stance for every Thesis entity");let a=await this.update(i,{request_id:s,expected_author_version_id:r.thesis.author_version_id,body:r.thesis.body,title:r.thesis.title,entity_ids:r.thesis.entity_ids,entity_stances:r.thesis.entity_stances?.map(({entity_id:u,stance:c})=>({entity_id:u,stance:c})),visibility:r.thesis.visibility,archived:n.archived,medias:r.thesis.medias,note:n.note});if(a.thesis.id!==i||a.thesis.archived!==n.archived)throw f("archive response must match the requested state");return a}async setStarred(e,n){this.client._requireAuth();let i=I(e,"id");if(typeof n!="boolean")throw m("isStarred must be a boolean");let r=(await Hn(this.client,Gr,{input:{thesisId:i,isStarred:n}})).setThesisStarred;if(!g(r)||!g(r.stats)||!g(r.viewerState))throw f("star response must contain stats and viewerState");let a=C(r.thesisId,"thesisId");if(a!==i)throw f("star response must match the requested thesis");let u=r.stats.starCount;if(typeof u!="number"||!Number.isInteger(u)||u<0)throw f("star response must contain a nonnegative star count");let c=B(r.viewerState.isStarred,"viewerState.isStarred");if(c!==n)throw f("star response did not apply the requested state");return{thesis_id:a,star_count:u,is_starred:c}}async getSignalPreferences(e){if(this.client._requireAuth(),e===void 0)return Ct(await this.client._request("GET","/api/v1/theses/signal-preferences"),null);let n=I(e,"id");return Ct(await this.client._request("GET",`/api/v1/theses/${n}/signal-preferences`),n)}async setSignalPreferences(e,n){this.client._requireAuth();let i=I(e,"id"),s=Dt(n);return Ct(await this.client._request("PUT",`/api/v1/theses/${i}/signal-preferences`,{body:{signal_preferences:s}}),i)}async setSignalEnabled(e,n){this.client._requireAuth();let i=I(e,"id");if(typeof n!="boolean")throw m("enabled must be a boolean");let r=(await Hn(this.client,Mr,{input:{thesisId:i,enabled:n}})).setThesisSignalEnabled;if(!g(r)||!g(r.publication))throw f("Signal response must contain publication");let a=r.publication,u=C(a.playbookId,"publication.playbookId");if(u!==i)throw f("Signal response must match the requested thesis");let c=B(a.researchPaused,"publication.researchPaused");if(c===n)throw f("Signal response did not apply the requested state");return{thesis_id:u,author_version_id:C(a.authorVersionId,"publication.authorVersionId"),archived:B(a.archived,"publication.archived"),research_paused:c,enabled:!c}}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw m("params is required");let i=I(e,"id"),s=Zn(n.visibility),r=se(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(r.thesis.id!==i||r.thesis.visibility!==s)throw f("visibility response must match the requested thesis and visibility");return r}async rewrite(e){this.client._requireAuth();let n=xe(e.body),i=e.mode===void 0?"reformat":Zr(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 f("rewrite response must contain a string body");return{body:ei(s.body)}}};function Wr(t){let e={request_id:Ft(t.request_id),body:xe(t.body),title:Ot(t.title??""),entity_ids:Lt(t.entity_ids??[],"entity_ids"),visibility:Zn(t.visibility??"public")};if(t.images!==void 0){if(!Array.isArray(t.images)||t.images.length>20)throw m("images must contain at most 20 URLs");if(t.images.length&&e.visibility!=="public")throw m("image publication currently requires public visibility");e.medias=t.images.map(n=>{if(!qt(n)||!n.startsWith("https://"))throw m("images must contain HTTPS URLs returned by the upload tool");return{type:"image",cover_url:n,url:n}})}return t.tickers!==void 0&&(e.tickers=Jr(t.tickers)),t.track_return!==void 0&&(e.track_return=Yn(t.track_return)),t.signal_preferences!==void 0&&(e.signal_preferences=Dt(t.signal_preferences)),t.entity_stances!==void 0&&(e.entity_stances=Xn(t.entity_stances,e.entity_ids)),e}o(Wr,"createBody");function Dt(t){if(!g(t)||!Array.isArray(t.kinds))throw m("signal_preferences must have kinds and min_importance");let e=[...new Set(t.kinds)];if(e.length===0||!e.every(n=>Wn.includes(n)))throw m(`signal kinds must be one or more of ${Wn.join(", ")}`);if(!Qn.includes(t.min_importance))throw m(`min_importance must be ${Qn.join(", ")}`);return{kinds:e,min_importance:t.min_importance}}o(Dt,"requireSignalPreferences");function Ct(t,e){if(!g(t)||t.thesis_id!==e)throw f("Signal setting response must name the requested thesis");try{return{thesis_id:e,preferences:Dt(t.signal_preferences)}}catch{throw f("response contains an unknown Signal setting")}}o(Ct,"signalPreferencesResponse");var Nt=["unknown","bullish","bearish","none"],Qr=["UNKNOWN","BULLISH","BEARISH","NONE"],Vr=["UNSET","ON","OFF"];function Yn(t){if(typeof t!="boolean")throw m("track_return must be a boolean");return t}o(Yn,"requireTrackReturn");function Hr(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);return t.map((n,i)=>{if(!g(n)||!Qr.includes(n.direction))throw f(`${e}[${i}] is invalid`);return{entityId:C(n.entityId,`${e}[${i}].entityId`),direction:n.direction}})}o(Hr,"selectedDirections");function Kr(t){if(t==null)return null;if(!g(t)||!Vr.includes(t.tracking)||typeof t.askSwitch!="boolean"||typeof t.lastLegRemoved!="boolean"||!Array.isArray(t.keptEntityIds))throw f("returnPreview is invalid");return{tracking:t.tracking,askSwitch:t.askSwitch,directions:Hr(t.directions,"returnPreview.directions"),keptEntityIds:t.keptEntityIds.map((e,n)=>C(e,`returnPreview.keptEntityIds[${n}]`)),lastLegRemoved:t.lastLegRemoved}}o(Kr,"returnPreview");function Xn(t,e){if(!Array.isArray(t)||t.length>Ce)throw m("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,r)=>{if(!g(s))throw m(`entity_stances[${r}] must be an object`);let a=I(s.entity_id,`entity_stances[${r}].entity_id`);if(!n.has(a)||i.has(a))throw m("entity stance must reference one unique entity_id");if(i.add(a),!Nt.includes(s.stance))throw m(`entity_stances[${r}].stance is invalid`);let u={entity_id:a,stance:s.stance};if(s.weight!==void 0){if(!zn(s.weight))throw m(`entity_stances[${r}].weight must be a fraction in (0, 1] with at most four decimals`);if(u.stance!=="bullish"&&u.stance!=="bearish")throw m(`entity_stances[${r}].weight needs a bullish or bearish stance`);u.weight=s.weight}return u})}o(Xn,"requireEntityStances");function zn(t){if(typeof t!="number"||!Number.isFinite(t))return!1;let e=Math.round(t*1e4);return e>=1&&e<=1e4&&Math.abs(t*1e4-e)<=1e-6}o(zn,"validWeight");function Vn(t,e){if(!Array.isArray(t))return;let n=new Map;for(let i of e??[])i.weight!==void 0&&n.set(i.entity_id,i.weight);for(let i of t){if(i.weight===void 0)continue;let s=n.get(i.entity_id);if(s===void 0||Math.abs(s-i.weight)>1e-9)throw f("the Update was published without the weights sent: the server predates weights")}}o(Vn,"requireKeptWeights");function Yr(t){let e={request_id:Ft(t.request_id),expected_author_version_id:I(t.expected_author_version_id,"expected_author_version_id"),body:xe(t.body),title:Ot(t.title??""),entity_ids:Lt(t.entity_ids??[],"entity_ids"),visibility:Jn(t.visibility)};if(t.medias!==void 0){if(!Array.isArray(t.medias)||t.medias.length>20)throw m("medias must be an array of at most 20 items");if(!t.medias.every(ti))throw m("medias contains invalid media");e.medias=t.medias}if(t.archived!==void 0){if(typeof t.archived!="boolean")throw m("archived must be a boolean");e.archived=t.archived}return t.note!==void 0&&(e.note=$(t.note,"note")),t.track_return!==void 0&&(e.track_return=Yn(t.track_return)),t.entity_stances!==void 0&&(e.entity_stances=Xn(t.entity_stances,e.entity_ids)),e}o(Yr,"updateBody");function Ut(t){return se({thesis:t}).thesis}o(Ut,"parseThesisREST");function se(t){if(!g(t)||!g(t.thesis))throw f("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:is(e.title),body:ei(e.body),entity_ids:es(e.entity_ids,"thesis.entity_ids"),visibility:ns(e.visibility),closed:B(e.closed,"thesis.closed"),archived:B(e.archived,"thesis.archived"),closing_note:ts(e.closing_note),author_kind:T(e.author_kind,"thesis.author_kind"),author_ref:T(e.author_ref,"thesis.author_ref")};if(e.medias!==void 0){if(!Array.isArray(e.medias)||e.medias.length>20)throw f("thesis.medias must contain at most 20 items");n.medias=e.medias.map(i=>{if(!ti(i))throw f("thesis.medias contains invalid media");return{type:i.type,cover_url:i.cover_url,...i.url===void 0?{}:{url:i.url}}})}if(e.version_archived!==void 0&&(n.version_archived=B(e.version_archived,"thesis.version_archived")),e.note!==void 0&&(n.note=T(e.note,"thesis.note")),e.change_kind!==void 0&&(n.change_kind=T(e.change_kind,"thesis.change_kind")),e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw f("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!g(i))throw f("thesis.entity_stances contains invalid entry");let s=C(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))throw f("entity stance must reference a thesis entity");if(!Nt.includes(i.stance))throw f("thesis.entity_stances contains invalid stance");let r={entity_id:s,stance:i.stance};if(i.direction!==void 0){if(!Nt.includes(i.direction))throw f("thesis.entity_stances contains invalid direction");r.direction=i.direction}if(i.weight!==void 0){if(!zn(i.weight))throw f("thesis.entity_stances contains invalid weight");r.weight=i.weight}return r})}return{thesis:n}}o(se,"thesisResponse");function Xr(t){let e=se(t);if(!g(t)||!g(t.author))throw f("response must contain author");let n=t.author,i={id:C(n.id,"author.id"),kind:T(n.kind,"author.kind"),display_name:T(n.display_name,"author.display_name"),avatar_url:T(n.avatar_url,"author.avatar_url"),username:T(n.username,"author.username")};if(!Array.isArray(t.entities))throw f("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw f("entities must match thesis.entity_ids");let s=t.entities.map((r,a)=>{if(!g(r))throw f(`entities[${a}] must be an object`);let u={id:C(r.id,`entities[${a}].id`),ticker:T(r.ticker,`entities[${a}].ticker`),name:T(r.name,`entities[${a}].name`),icon_url:T(r.icon_url,`entities[${a}].icon_url`),kind:T(r.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw f("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:i,entities:s}}o(Xr,"thesisGetResponse");function zr(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw f("invalid Signal history response");let i=t.research,s={state:T(i.state,"research.state"),pending_work:ut(i.pending_work,"research.pending_work"),read_complete:B(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=ut(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=ut(i.last_completed_ms,"research.last_completed_ms"));let r=t.entries.map(u=>{if(!g(u)||!g(u.signal)||!g(u.signal.source))throw f("entry must include a Signal and source");let c=u.signal,d=c.source,p=C(c.thesis_id,"signal.thesis_id");if(p!==e)throw f("Signal belongs to another Thesis");let P=xt(u.cursor,"entry.cursor"),_={title:T(d.title,"source.title")};d.url!==void 0&&(_.url=T(d.url,"source.url")),d.published_at_ms!==void 0&&(_.published_at_ms=ut(d.published_at_ms,"source.published_at_ms"));let b={id:C(c.id,"signal.id"),thesis_id:p,author_version_id:C(c.author_version_id,"signal.author_version_id"),statement_snapshot:xt(c.statement_snapshot,"signal.statement_snapshot"),stance:T(c.stance,"signal.stance"),explanation:T(c.explanation,"signal.explanation"),information_kind:T(c.information_kind,"signal.information_kind"),source:_};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw f("invalid evidence excerpt");b.evidence_excerpt={text:xt(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:B(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:B(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:C(u.feed_entry_id,"feed_entry_id"),cursor:P,signal:b}}),a=T(t.next_cursor,"next_cursor");if(a&&a!==r[r.length-1]?.cursor)throw f("next_cursor must match the final entry");return{research:s,entries:r,next_cursor:a}}o(zr,"thesisSignalsResponse");function ut(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw f(e+" must be a nonnegative safe integer");return t}o(ut,"responseNonnegativeInteger");function xt(t,e){let n=T(t,e);if(!n.trim())throw f(e+" must be nonempty");return n}o(xt,"responseNonemptyText");function Ft(t){if(!jr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw m("request_id must be a non-zero RFC 4122 UUID");return t}o(Ft,"requireRequestID");function I(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw m(`${e} must be a positive int64 decimal string`);if(BigInt(t)>$r)throw m(`${e} must be a positive int64 decimal string`);return t}o(I,"requireID");var Ce=100;function Lt(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>Ce)throw m(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}o(Lt,"requireIDs");function Jr(t){if(!Array.isArray(t))throw m("tickers must be an array");if(t.length>100)throw m("tickers must contain at most 100 values");return t.map((e,n)=>{let i=$(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw m(`tickers[${n}] must be non-empty`);return i})}o(Jr,"requireTickers");function xe(t){let e=$(t,"body");if(e.trim().length===0)throw m("body must not be blank");if(Kn.encode(e).byteLength>65536)throw m("body must be at most 65536 UTF-8 bytes");return e}o(xe,"requireBody");function Ot(t){let e=$(t,"title");if(Kn.encode(e).byteLength>500)throw m("title must be at most 500 UTF-8 bytes");return e}o(Ot,"requireTitle");function Jn(t){let e=$(t,"visibility");if(e!=="public"&&e!=="private"&&e!=="paid")throw m("visibility must be public, private or paid");return e}o(Jn,"requireVisibility");function Zn(t){let e=$(t,"visibility");if(e!=="public"&&e!=="private")throw m("visibility must be public or private");return e}o(Zn,"requirePublicVisibility");function Zr(t){let e=$(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw m("mode must be reformat, shorten, or enrich")}o(Zr,"requireRewriteMode");function $(t,e){if(typeof t!="string")throw m(`${e} must be a string`);if(Br.test(t))throw m(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw m(`${e} must not contain NUL`);return t}o($,"requireText");function C(t,e){if(typeof t=="number")throw f(`${e} must be a decimal string; numeric IDs are unsafe`);try{return I(t,e)}catch{throw f(`${e} must be a positive int64 decimal string`)}}o(C,"responseID");function es(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);if(t.length>Ce)throw f(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>C(n,`${e}[${i}]`))}o(es,"responseIDs");function T(t,e){try{return $(t,e)}catch{throw f(`${e} must be valid text`)}}o(T,"responseText");function ts(t){try{return $(t,"note")}catch{throw f("thesis.closing_note must be valid text")}}o(ts,"responseClosingNote");function B(t,e){if(typeof t!="boolean")throw f(`${e} must be boolean`);return t}o(B,"responseBoolean");function ns(t){try{return Jn(t)}catch{throw f("thesis.visibility must be public, private or paid")}}o(ns,"responseVisibility");function ei(t){try{return xe(t)}catch{throw f("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}o(ei,"responseBody");function is(t){try{return Ot(t)}catch{throw f("response title must be valid text at most 500 UTF-8 bytes")}}o(is,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(g,"isRecord");function rs(t,e){if(t.length===0)return!e||e.length===0;if(!e||e.length!==t.length)return!1;let n=new Set(t),i=new Set;return e.every(s=>n.has(s.entity_id)&&!i.has(s.entity_id)&&i.add(s.entity_id))}o(rs,"completeEntityStances");function m(t){return new l("INVALID_ARGUMENT",t,400)}o(m,"invalidArgument");function f(t){return new l("INVALID_RESPONSE",t,502)}o(f,"invalidResponse");function ti(t){return g(t)&&["image","price_chart","audio","video"].includes(t.type)&&qt(t.cover_url)&&(t.url==null||qt(t.url))}o(ti,"validMedia");function qt(t){if(typeof t!="string"||t.length>2048||/[\s\u0000]/.test(t))return!1;try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!!e.hostname&&!e.username&&!e.password}catch{return!1}}o(qt,"validMediaURL");async function Hn(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!g(i))throw f("GraphQL response must be an object");if(i.errors!==void 0){if(!Array.isArray(i.errors))throw f("GraphQL errors must be an array");if(i.errors.length>0){let s=i.errors.flatMap(d=>g(d)&&typeof d.message=="string"?[d.message]:[]),r=new Set(i.errors.map(d=>g(d)&&g(d.extensions)?d.extensions.code:void 0)),[a]=r,u=r.size===1&&(a==="NOT_FOUND"||a==="PERMISSION_DENIED"||a==="UNAUTHENTICATED")?a:void 0,c=u==="NOT_FOUND"?404:u==="PERMISSION_DENIED"?403:u==="UNAUTHENTICATED"?401:400;throw new l(u??"GRAPHQL_ERROR",s.join("; ")||"GraphQL request failed",c,{errors:i.errors})}}if(!g(i.data))throw f("GraphQL response must contain data");return i.data}o(Hn,"thesisGraphql");var ni=50,ii=40,ss=100,hi=50,os=100,ri=2048,si=200,as=5,us=["STOCK","ETF","CRYPTO"],cs=["USER","PERSON"],ls=new Set(["NOT_FOUND","FAILED_PRECONDITION"]),fi={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},oi="id ticker name kind",Gt="__typename id displayName followersCount viewerState { following } ... on PublicUser { username } ... on Person { slug xHandle }";function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(y,"record");function k(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid ${t} response`,502)}o(k,"invalidResponse");function mi(t){if(!y(t)||t.errors===void 0)return;if(!Array.isArray(t.errors))return k("GraphQL");if(t.errors.length===0)return;let e=t.errors,n=e.flatMap(r=>y(r)&&typeof r.message=="string"?[r.message]:[]),i=e.map(r=>y(r)&&y(r.extensions)?r.extensions.code:void 0);return{code:typeof i[0]=="string"&&Object.hasOwn(fi,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR",message:n.join("; ")||"Request failed",errors:e}}o(mi,"graphQLFailure");function gi(t){throw new l(t.code,t.message,fi[t.code]??502,{errors:t.errors})}o(gi,"throwFailure");function ct(t,e){let n=mi(t);return n&&gi(n),!y(t)||!y(t.data)?k(e):t.data}o(ct,"responseData");function ai(t,e){let n=ct(t,e);return y(n.viewer)?n.viewer[e]:k(e)}o(ai,"viewerField");function W(t,e){return typeof t!="string"||!t?k(e):t}o(W,"requireString");function ui(t,e){return!y(t)||typeof t.hasNextPage!="boolean"||t.endCursor!==null&&t.endCursor!==void 0&&typeof t.endCursor!="string"||t.hasNextPage&&!t.endCursor?k(e):{endCursor:typeof t.endCursor=="string"?t.endCursor:"",hasNextPage:t.hasNextPage}}o(ui,"pageInfo");function ci(t,e){if(!y(t)||!y(t.viewerState))return k(e);let n=t.viewerState.following;if(typeof t.followersCount!="number"||typeof t.displayName!="string"||n!==null&&typeof n!="boolean")return k(e);let i={id:W(t.id,e),displayName:t.displayName,followersCount:t.followersCount,following:n??null};return t.__typename==="PublicUser"?{kind:"USER",...i,username:W(t.username,e)}:t.__typename==="Person"?t.xHandle!==null&&t.xHandle!==void 0&&typeof t.xHandle!="string"?k(e):{kind:"PERSON",...i,slug:W(t.slug,e),xHandle:t.xHandle??null}:k(e)}o(ci,"normalizeProfile");function lt(t,e,n="first"){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>e)throw new Error(`${n} must be an integer between 1 and ${e}`);return t}}o(lt,"boundedFirst");function li(t){if(t!==void 0){if(typeof t!="string"||!t.trim()||t.length>4096)throw new Error("after must be a non-empty cursor of at most 4096 characters");return t}}o(li,"optionalCursor");function $t(t,e){if(!(t===void 0&&!e)){if(typeof t!="string"||!cs.includes(t))throw new Error("kind must be USER or PERSON");return t}}o($t,"profileKind");function di(t){if(t!==void 0){if(typeof t!="string"||!us.includes(t))throw new Error("kind must be STOCK, ETF, or CRYPTO");return t}}o(di,"tickerKind");function ds(t){if(!y(t)||!Array.isArray(t.tickers))throw new Error("tickers must be a list of ticker symbols");let e=di(t.kind),n=[];for(let i of t.tickers){let s=typeof i=="string"?{ticker:i}:i;if(!y(s)||typeof s.ticker!="string")throw new Error("tickers must be symbols or {ticker, kind} specs");let r=s.ticker.trim().toUpperCase();if(!r||/\s/.test(r)||r.length>ii)throw new Error(`ticker '${s.ticker}' must be a non-empty symbol of at most ${ii} characters`);let a=di(s.kind)??e;n.some(u=>u.ticker===r&&u.kind===a)||n.push(a===void 0?{ticker:r}:{ticker:r,kind:a})}if(n.length===0||n.length>ni)throw new Error(`tickers must contain between 1 and ${ni} symbols`);return{tickers:n}}o(ds,"normalizeWatchlistTickersParams");function ps(t){if(!y(t))throw new Error("profile reference must be an object");let e=$t(t.kind,!0);if(typeof t.id!="string"||!/^[1-9]\d{0,18}$/.test(t.id))throw new Error("id must be a positive decimal profile id");return{kind:e,id:t.id}}o(ps,"validateProfileRef");function hs(t){if(!y(t)||typeof t.query!="string")throw new Error("query is required");let e=t.query.trim();if(!e||e.length>si)throw new Error(`query must be non-empty and at most ${si} characters`);return{query:e,kind:$t(t.kind,!1),first:lt(t.first,hi)}}o(hs,"validateSearchProfilesParams");function pi(t,e,n,i){return e===void 0?{ok:!1,unresolved:{input:t,code:n,message:i}}:{ok:!1,unresolved:{input:t,kind:e,code:n,message:n==="NOT_FOUND"?`no ${e} entity found for ticker ${t}; it may exist as another kind (retry with a different :kind suffix or none)`:i}}}o(pi,"unresolvedTicker");var ae=class{constructor(e){this.client=e}client;static{o(this,"FollowsResource")}async addToWatchlist(e){let{changed:n,unchanged:i,unresolved:s}=await this.changeWatchlist(e,"add");return{added:n,unchanged:i,unresolved:s}}async removeFromWatchlist(e){let{changed:n,unchanged:i,unresolved:s}=await this.changeWatchlist(e,"remove");return{removed:n,unchanged:i,unresolved:s}}async watchlist(e={}){let n=lt(e.first,ss),i=li(e.after);this.client._requireAuth();let s=await this.client._request("POST","/query",{body:{query:`query ToolkitWatchlist($input: MarketWatchlistConnectionInput) { viewer { marketWatchlist(input: $input) { totalCount edges { cursor followedAtMs node { ${oi} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{first:n??20,after:i}}}}),r="viewer.marketWatchlist",a=ai(s,"marketWatchlist");if(!y(a)||typeof a.totalCount!="number"||!Array.isArray(a.edges))return k(r);let u=a.edges.map(c=>!y(c)||!y(c.node)||typeof c.followedAtMs!="number"?k(r):{entityId:W(c.node.id,r),ticker:W(c.node.ticker,r),name:typeof c.node.name=="string"?c.node.name:"",kind:W(c.node.kind,r),addedAtMs:c.followedAtMs});return{totalCount:a.totalCount,tickers:u,pageInfo:ui(a.pageInfo,r)}}async searchProfiles(e){let{query:n,kind:i,first:s}=hs(e);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitSearchProfiles($input: PublicProfileConnectionInput) { profiles(input: $input) { edges { node { ${Gt} } } pageInfo { endCursor hasNextPage } } }`,variables:{input:{query:n,kind:i,first:s??10}}}});return this.profilesPage(ct(r,"profiles").profiles,"profiles")}async profiles(e={}){let n=$t(e.kind,!1),i=lt(e.first,hi),s=li(e.after);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitFollowedProfiles($input: FollowingProfileConnectionInput) { viewer { followingProfiles(input: $input) { edges { node { ${Gt} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{kind:n,first:i??20,after:s}}}});return this.profilesPage(ai(r,"followingProfiles"),"viewer.followingProfiles")}async theses(e={}){let n=lt(e.first,os),i=e.cursor;if(i!==void 0&&(typeof i!="string"||!i.trim()||i.length>ri))throw new Error(`cursor must be a non-empty cursor of at most ${ri} characters`);this.client._requireAuth();let s={};return n!==void 0&&(s.first=String(n)),i!==void 0&&(s.cursor=i),fs(await this.client._request("GET","/api/v1/me/following/theses",{query:s}))}async followProfile(e){return this.changeProfile(e,"followProfile")}async unfollowProfile(e){return this.changeProfile(e,"unfollowProfile")}profilesPage(e,n){return!y(e)||!Array.isArray(e.edges)?k(n):{profiles:e.edges.map(i=>y(i)?ci(i.node,n):k(n)),pageInfo:ui(e.pageInfo,n)}}async changeProfile(e,n){let i=ps(e);this.client._requireAuth();let s=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeProfileFollow($input: PublicProfileRefInput!) { ${n}(input: $input) { following target { ${Gt} } } }`,variables:{input:i}}}),r=ct(s,n)[n];return!y(r)||typeof r.following!="boolean"?k(n):{following:r.following,profile:r.target===null||r.target===void 0?null:ci(r.target,n)}}async changeWatchlist(e,n){let{tickers:i}=ds(e);this.client._requireAuth();let s=await this.lookupTickers(i),r=[],a=[],u=[],c=new Map,d=[];for(let p of s){if(!p.ok){u.push(p.unresolved);continue}let P=c.get(p.ticker.entityId);if(P){P.push(p.ticker);continue}let _=n==="add"?!p.inWatchlist:p.inWatchlist,b=_?r:a;b.push(p.ticker),c.set(p.ticker.entityId,b),(_||n==="remove")&&d.push(p.ticker.entityId)}if(d.length>0){let p=n==="add"?"followTickers":"unfollowTickers",P=n==="add"?"FollowTickersInput":"UnfollowTickersInput",_=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeWatchlist($input: ${P}!) { ${p}(input: $input) { entities { id } } }`,variables:{input:{entityIds:d}}}}),b=ct(_,p)[p];if(!y(b)||!Array.isArray(b.entities))return k(p)}return{changed:r,unchanged:a,unresolved:u}}async lookupTickers(e){let n=new Array(e.length),i=0,s=o(async()=>{for(;i<e.length;){let r=i++,{ticker:a,kind:u}=e[r];n[r]=await this.lookupTicker(a,u)}},"worker");return await Promise.all(Array.from({length:Math.min(as,e.length)},s)),n}async lookupTicker(e,n){let i=await this.client._request("POST","/query",{body:{query:`query ToolkitTickerLookup($input: MarketEntityLookupInput!) { market { entity(input: $input) { ${oi} viewerState { isFollowed } } } }`,variables:{input:{ticker:e,kind:n}}}}),s=mi(i);if(s){if(ls.has(s.code))return pi(e,n,s.code,s.message);gi(s)}let r="market.entity";if(!y(i)||!y(i.data)||!y(i.data.market))return k(r);let a=i.data.market.entity;if(a==null)return pi(e,n,"NOT_FOUND",`no entity found for ticker: ${e}`);if(!y(a))return k(r);let u=a.viewerState;if(u==null)throw new l("PERMISSION_DENIED","This credential cannot read the user's watchlist",403);return!y(u)||typeof u.isFollowed!="boolean"?k(r):{ok:!0,inWatchlist:u.isFollowed,ticker:{input:e,entityId:W(a.id,r),ticker:W(a.ticker,r),name:typeof a.name=="string"?a.name:"",kind:W(a.kind,r)}}}};function Mt(t){return new l("INVALID_RESPONSE",t,502)}o(Mt,"invalidFollowingTheses");function fs(t){if(!y(t)||!Array.isArray(t.items)||typeof t.next_cursor!="string"||!t.next_cursor||typeof t.has_more!="boolean")throw Mt("invalid following theses page");return{items:t.items.map(e=>{if(!y(e))throw Mt("invalid following theses item");return{thesis:Ut(e.thesis),author:ms(e.author)}}),next_cursor:t.next_cursor,has_more:t.has_more}}o(fs,"followingThesesPage");function ms(t){if(t===null)return null;if(!y(t)||t.kind!=="user"||typeof t.username!="string"||typeof t.display_name!="string")throw Mt("invalid following theses author");return{kind:t.kind,username:t.username,display_name:t.display_name}}o(ms,"followingThesisAuthor");var ue=class{constructor(e){this.client=e}client;static{o(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 dt=class{constructor(e){this.client=e}client;static{o(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:yi(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:yi(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 yi(t){return`{"session_id":${bi(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${bi(t.target_id)}}`}o(yi,"mutationBody");function bi(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}o(bi,"idLiteral");var pt=class{constructor(e){this.client=e}client;static{o(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var ht=class{constructor(e){this.client=e}client;static{o(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:ys(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 jt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>jt(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:gs(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 jt(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=wi(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=wi(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}o(jt,"normalizeAllowance");function gs(t){let e=jt(t);if(!e)throw new Error("allowance response missing allowance");return e}o(gs,"requireAllowance");function wi(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 r=Date.parse(t);return Number.isNaN(r)?void 0:r}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)}o(wi,"timestampMs");function ys(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}o(ys,"parseResultPayload");var bs=`
|
|
145
|
+
}`,variables:{input:s}}});if(Array.isArray(r?.errors)&&r.errors.length>0)throw new l("GRAPHQL_ERROR","Asset extraction failed",400,{errors:r.errors});let a=r?.data,u=g(a)?a.viewer:void 0,c=g(u)?u.thesisAssetCandidates:void 0;if(!g(c)||!Array.isArray(c.mentions))throw f("asset candidates response must contain mentions");return{mentions:c.mentions.map((p,P)=>{if(!g(p)||typeof p.quote!="string"||typeof p.ticker!="string"||!["RESOLVED","AMBIGUOUS","UNRESOLVED"].includes(p.resolution)||!["UNKNOWN","BULLISH","BEARISH"].includes(p.stance)||!Array.isArray(p.candidates))throw f(`asset mention ${P} is invalid`);let _=p.candidates.map(b=>{if(!g(b)||typeof b.ticker!="string"||typeof b.name!="string"||!["STOCK","ETF","CRYPTO","INDEX"].includes(b.kind))throw f(`asset mention ${P} has invalid candidate`);return{entityId:C(b.entityId,`asset mention ${P} candidate.entityId`),ticker:b.ticker,name:b.name,kind:b.kind}});return{...p,candidates:_}}),returnPreview:Kr(c.returnPreview)}}thesisReturn(e,n={}){return Bn(this.client,e,n)}watchpoints(e){return Wn(this.client,e)}async create(e){this.client._requireAuth();let n=Wr(e),i=se(await this.client._request("POST","/api/v1/theses",{body:n}));Hn(n.entity_stances,i.thesis.entity_stances);let s=He(this.client.baseUrl);return{...i,url:`${s}/thesis/${i.thesis.id}`}}async get(e){this.client._requireAuth();let n=I(e,"id"),i=Xr(await this.client._request("GET",`/api/v1/theses/${n}`));if(i.thesis.id!==n)throw f("get response must match the requested thesis");return i}async getVersion(e,n){this.client._requireAuth();let i=I(e,"id"),s=I(n,"author_version_id"),r=se(await this.client._request("GET",`/api/v1/theses/${i}/versions/${s}`));if(r.thesis.id!==i||r.thesis.author_version_id!==s)throw f("version response must match the requested thesis and author version");return r}async listUpdates(e,n={}){this.client._requireAuth();let i=I(e,"id"),s=n.first??10;if(!Number.isInteger(s)||s<1||s>100)throw m("first must be between 1 and 100");if(n.cursor!==void 0&&typeof n.cursor!="string")throw m("cursor must be a string");let r=await this.client._request("GET",`/api/v1/theses/${i}/versions`,{query:{first:s,cursor:n.cursor,updates_only:!0}});if(!g(r)||!Array.isArray(r.versions)||typeof r.next_cursor!="string")throw f("invalid Update list");let a=r.versions.map(Ft);if(a.some(u=>u.id!==i))throw f("Update list must match requested Thesis");return{versions:a,next_cursor:r.next_cursor}}async signals(e,n={}){this.client._requireAuth();let i=n.first??20;if(!Number.isInteger(i)||i<1||i>50)throw m("first must be an integer between 1 and 50");if(n.cursor!==void 0&&typeof n.cursor!="string")throw m("cursor must be a string");return zr(await this.client._request("GET",`/api/v1/theses/${I(e,"id")}/signals`,{query:{first:i,...n.cursor===void 0?{}:{cursor:n.cursor}}}),e,i)}async update(e,n){this.client._requireAuth();let i=Yr(n),s=I(e,"id"),r=se(await this.client._request("PUT",`/api/v1/theses/${s}`,{body:i}));if(r.thesis.id!==s)throw f("update response must match the requested thesis");return Hn(i.entity_stances,r.thesis.entity_stances),r}async setArchived(e,n){if(this.client._requireAuth(),!g(n))throw m("params is required");let i=I(e,"id"),s=Lt(n.request_id);if(typeof n.archived!="boolean")throw m("archived must be a boolean");n.note!==void 0&&$(n.note,"note");let r=await this.get(i);if(r.thesis.archived===n.archived&&n.note===void 0)return{thesis:r.thesis};if(!rs(r.thesis.entity_ids,r.thesis.entity_stances))throw f("archive requires one entity_stance for every Thesis entity");let a=await this.update(i,{request_id:s,expected_author_version_id:r.thesis.author_version_id,body:r.thesis.body,title:r.thesis.title,entity_ids:r.thesis.entity_ids,entity_stances:r.thesis.entity_stances?.map(({entity_id:u,stance:c})=>({entity_id:u,stance:c})),visibility:r.thesis.visibility,archived:n.archived,medias:r.thesis.medias,note:n.note});if(a.thesis.id!==i||a.thesis.archived!==n.archived)throw f("archive response must match the requested state");return a}async setStarred(e,n){this.client._requireAuth();let i=I(e,"id");if(typeof n!="boolean")throw m("isStarred must be a boolean");let r=(await Kn(this.client,Gr,{input:{thesisId:i,isStarred:n}})).setThesisStarred;if(!g(r)||!g(r.stats)||!g(r.viewerState))throw f("star response must contain stats and viewerState");let a=C(r.thesisId,"thesisId");if(a!==i)throw f("star response must match the requested thesis");let u=r.stats.starCount;if(typeof u!="number"||!Number.isInteger(u)||u<0)throw f("star response must contain a nonnegative star count");let c=B(r.viewerState.isStarred,"viewerState.isStarred");if(c!==n)throw f("star response did not apply the requested state");return{thesis_id:a,star_count:u,is_starred:c}}async getSignalPreferences(e){if(this.client._requireAuth(),e===void 0)return xt(await this.client._request("GET","/api/v1/theses/signal-preferences"),null);let n=I(e,"id");return xt(await this.client._request("GET",`/api/v1/theses/${n}/signal-preferences`),n)}async setSignalPreferences(e,n){this.client._requireAuth();let i=I(e,"id"),s=Ut(n);return xt(await this.client._request("PUT",`/api/v1/theses/${i}/signal-preferences`,{body:{signal_preferences:s}}),i)}async setSignalEnabled(e,n){this.client._requireAuth();let i=I(e,"id");if(typeof n!="boolean")throw m("enabled must be a boolean");let r=(await Kn(this.client,Mr,{input:{thesisId:i,enabled:n}})).setThesisSignalEnabled;if(!g(r)||!g(r.publication))throw f("Signal response must contain publication");let a=r.publication,u=C(a.playbookId,"publication.playbookId");if(u!==i)throw f("Signal response must match the requested thesis");let c=B(a.researchPaused,"publication.researchPaused");if(c===n)throw f("Signal response did not apply the requested state");return{thesis_id:u,author_version_id:C(a.authorVersionId,"publication.authorVersionId"),archived:B(a.archived,"publication.archived"),research_paused:c,enabled:!c}}async setVisibility(e,n){if(this.client._requireAuth(),!n)throw m("params is required");let i=I(e,"id"),s=ei(n.visibility),r=se(await this.client._request("POST",`/api/v1/theses/${i}/visibility`,{body:{visibility:s}}));if(r.thesis.id!==i||r.thesis.visibility!==s)throw f("visibility response must match the requested thesis and visibility");return r}async rewrite(e){this.client._requireAuth();let n=xe(e.body),i=e.mode===void 0?"reformat":Zr(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 f("rewrite response must contain a string body");return{body:ti(s.body)}}};function Wr(t){let e={request_id:Lt(t.request_id),body:xe(t.body),title:Gt(t.title??""),entity_ids:Ot(t.entity_ids??[],"entity_ids"),visibility:ei(t.visibility??"public")};if(t.images!==void 0){if(!Array.isArray(t.images)||t.images.length>20)throw m("images must contain at most 20 URLs");if(t.images.length&&e.visibility!=="public")throw m("image publication currently requires public visibility");e.medias=t.images.map(n=>{if(!Dt(n)||!n.startsWith("https://"))throw m("images must contain HTTPS URLs returned by the upload tool");return{type:"image",cover_url:n,url:n}})}return t.tickers!==void 0&&(e.tickers=Jr(t.tickers)),t.track_return!==void 0&&(e.track_return=Xn(t.track_return)),t.signal_preferences!==void 0&&(e.signal_preferences=Ut(t.signal_preferences)),t.entity_stances!==void 0&&(e.entity_stances=zn(t.entity_stances,e.entity_ids)),e}o(Wr,"createBody");function Ut(t){if(!g(t)||!Array.isArray(t.kinds))throw m("signal_preferences must have kinds and min_importance");let e=[...new Set(t.kinds)];if(e.length===0||!e.every(n=>Qn.includes(n)))throw m(`signal kinds must be one or more of ${Qn.join(", ")}`);if(!Vn.includes(t.min_importance))throw m(`min_importance must be ${Vn.join(", ")}`);return{kinds:e,min_importance:t.min_importance}}o(Ut,"requireSignalPreferences");function xt(t,e){if(!g(t)||t.thesis_id!==e)throw f("Signal setting response must name the requested thesis");try{return{thesis_id:e,preferences:Ut(t.signal_preferences)}}catch{throw f("response contains an unknown Signal setting")}}o(xt,"signalPreferencesResponse");var qt=["unknown","bullish","bearish","none"],Qr=["UNKNOWN","BULLISH","BEARISH","NONE"],Vr=["UNSET","ON","OFF"];function Xn(t){if(typeof t!="boolean")throw m("track_return must be a boolean");return t}o(Xn,"requireTrackReturn");function Hr(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);return t.map((n,i)=>{if(!g(n)||!Qr.includes(n.direction))throw f(`${e}[${i}] is invalid`);return{entityId:C(n.entityId,`${e}[${i}].entityId`),direction:n.direction}})}o(Hr,"selectedDirections");function Kr(t){if(t==null)return null;if(!g(t)||!Vr.includes(t.tracking)||typeof t.askSwitch!="boolean"||typeof t.lastLegRemoved!="boolean"||!Array.isArray(t.keptEntityIds))throw f("returnPreview is invalid");return{tracking:t.tracking,askSwitch:t.askSwitch,directions:Hr(t.directions,"returnPreview.directions"),keptEntityIds:t.keptEntityIds.map((e,n)=>C(e,`returnPreview.keptEntityIds[${n}]`)),lastLegRemoved:t.lastLegRemoved}}o(Kr,"returnPreview");function zn(t,e){if(!Array.isArray(t)||t.length>Ce)throw m("entity_stances must contain at most 100 values");let n=new Set(e),i=new Set;return t.map((s,r)=>{if(!g(s))throw m(`entity_stances[${r}] must be an object`);let a=I(s.entity_id,`entity_stances[${r}].entity_id`);if(!n.has(a)||i.has(a))throw m("entity stance must reference one unique entity_id");if(i.add(a),!qt.includes(s.stance))throw m(`entity_stances[${r}].stance is invalid`);let u={entity_id:a,stance:s.stance};if(s.weight!==void 0){if(!Jn(s.weight))throw m(`entity_stances[${r}].weight must be a fraction in (0, 1] with at most four decimals`);if(u.stance!=="bullish"&&u.stance!=="bearish")throw m(`entity_stances[${r}].weight needs a bullish or bearish stance`);u.weight=s.weight}return u})}o(zn,"requireEntityStances");function Jn(t){if(typeof t!="number"||!Number.isFinite(t))return!1;let e=Math.round(t*1e4);return e>=1&&e<=1e4&&Math.abs(t*1e4-e)<=1e-6}o(Jn,"validWeight");function Hn(t,e){if(!Array.isArray(t))return;let n=new Map;for(let i of e??[])i.weight!==void 0&&n.set(i.entity_id,i.weight);for(let i of t){if(i.weight===void 0)continue;let s=n.get(i.entity_id);if(s===void 0||Math.abs(s-i.weight)>1e-9)throw f("the Update was published without the weights sent: the server predates weights")}}o(Hn,"requireKeptWeights");function Yr(t){let e={request_id:Lt(t.request_id),expected_author_version_id:I(t.expected_author_version_id,"expected_author_version_id"),body:xe(t.body),title:Gt(t.title??""),entity_ids:Ot(t.entity_ids??[],"entity_ids"),visibility:Zn(t.visibility)};if(t.medias!==void 0){if(!Array.isArray(t.medias)||t.medias.length>20)throw m("medias must be an array of at most 20 items");if(!t.medias.every(ni))throw m("medias contains invalid media");e.medias=t.medias}if(t.archived!==void 0){if(typeof t.archived!="boolean")throw m("archived must be a boolean");e.archived=t.archived}return t.note!==void 0&&(e.note=$(t.note,"note")),t.track_return!==void 0&&(e.track_return=Xn(t.track_return)),t.entity_stances!==void 0&&(e.entity_stances=zn(t.entity_stances,e.entity_ids)),e}o(Yr,"updateBody");function Ft(t){return se({thesis:t}).thesis}o(Ft,"parseThesisREST");function se(t){if(!g(t)||!g(t.thesis))throw f("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:is(e.title),body:ti(e.body),entity_ids:es(e.entity_ids,"thesis.entity_ids"),visibility:ns(e.visibility),closed:B(e.closed,"thesis.closed"),archived:B(e.archived,"thesis.archived"),closing_note:ts(e.closing_note),author_kind:T(e.author_kind,"thesis.author_kind"),author_ref:T(e.author_ref,"thesis.author_ref")};if(e.medias!==void 0){if(!Array.isArray(e.medias)||e.medias.length>20)throw f("thesis.medias must contain at most 20 items");n.medias=e.medias.map(i=>{if(!ni(i))throw f("thesis.medias contains invalid media");return{type:i.type,cover_url:i.cover_url,...i.url===void 0?{}:{url:i.url}}})}if(e.version_archived!==void 0&&(n.version_archived=B(e.version_archived,"thesis.version_archived")),e.note!==void 0&&(n.note=T(e.note,"thesis.note")),e.change_kind!==void 0&&(n.change_kind=T(e.change_kind,"thesis.change_kind")),e.entity_stances!==void 0){if(!Array.isArray(e.entity_stances))throw f("thesis.entity_stances must be an array");n.entity_stances=e.entity_stances.map(i=>{if(!g(i))throw f("thesis.entity_stances contains invalid entry");let s=C(i.entity_id,"entity_stances.entity_id");if(!n.entity_ids.includes(s))throw f("entity stance must reference a thesis entity");if(!qt.includes(i.stance))throw f("thesis.entity_stances contains invalid stance");let r={entity_id:s,stance:i.stance};if(i.direction!==void 0){if(!qt.includes(i.direction))throw f("thesis.entity_stances contains invalid direction");r.direction=i.direction}if(i.weight!==void 0){if(!Jn(i.weight))throw f("thesis.entity_stances contains invalid weight");r.weight=i.weight}return r})}return{thesis:n}}o(se,"thesisResponse");function Xr(t){let e=se(t);if(!g(t)||!g(t.author))throw f("response must contain author");let n=t.author,i={id:C(n.id,"author.id"),kind:T(n.kind,"author.kind"),display_name:T(n.display_name,"author.display_name"),avatar_url:T(n.avatar_url,"author.avatar_url"),username:T(n.username,"author.username")};if(!Array.isArray(t.entities))throw f("response must contain entities");if(t.entities.length!==e.thesis.entity_ids.length)throw f("entities must match thesis.entity_ids");let s=t.entities.map((r,a)=>{if(!g(r))throw f(`entities[${a}] must be an object`);let u={id:C(r.id,`entities[${a}].id`),ticker:T(r.ticker,`entities[${a}].ticker`),name:T(r.name,`entities[${a}].name`),icon_url:T(r.icon_url,`entities[${a}].icon_url`),kind:T(r.kind,`entities[${a}].kind`)};if(u.id!==e.thesis.entity_ids[a])throw f("entities must preserve thesis.entity_ids order");return u});return{thesis:e.thesis,author:i,entities:s}}o(Xr,"thesisGetResponse");function zr(t,e,n){if(!g(t)||!g(t.research)||!Array.isArray(t.entries)||t.entries.length>n)throw f("invalid Signal history response");let i=t.research,s={state:T(i.state,"research.state"),pending_work:ct(i.pending_work,"research.pending_work"),read_complete:B(i.read_complete,"research.read_complete")};i.last_attempt_ms!==void 0&&(s.last_attempt_ms=ct(i.last_attempt_ms,"research.last_attempt_ms")),i.last_completed_ms!==void 0&&(s.last_completed_ms=ct(i.last_completed_ms,"research.last_completed_ms"));let r=t.entries.map(u=>{if(!g(u)||!g(u.signal)||!g(u.signal.source))throw f("entry must include a Signal and source");let c=u.signal,d=c.source,p=C(c.thesis_id,"signal.thesis_id");if(p!==e)throw f("Signal belongs to another Thesis");let P=Nt(u.cursor,"entry.cursor"),_={title:T(d.title,"source.title")};d.url!==void 0&&(_.url=T(d.url,"source.url")),d.published_at_ms!==void 0&&(_.published_at_ms=ct(d.published_at_ms,"source.published_at_ms"));let b={id:C(c.id,"signal.id"),thesis_id:p,author_version_id:C(c.author_version_id,"signal.author_version_id"),statement_snapshot:Nt(c.statement_snapshot,"signal.statement_snapshot"),stance:T(c.stance,"signal.stance"),explanation:T(c.explanation,"signal.explanation"),information_kind:T(c.information_kind,"signal.information_kind"),source:_};if(c.evidence_excerpt!==void 0){if(!g(c.evidence_excerpt))throw f("invalid evidence excerpt");b.evidence_excerpt={text:Nt(c.evidence_excerpt.text,"evidence_excerpt.text"),omitted_before:B(c.evidence_excerpt.omitted_before,"evidence_excerpt.omitted_before"),omitted_after:B(c.evidence_excerpt.omitted_after,"evidence_excerpt.omitted_after")}}return{feed_entry_id:C(u.feed_entry_id,"feed_entry_id"),cursor:P,signal:b}}),a=T(t.next_cursor,"next_cursor");if(a&&a!==r[r.length-1]?.cursor)throw f("next_cursor must match the final entry");return{research:s,entries:r,next_cursor:a}}o(zr,"thesisSignalsResponse");function ct(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw f(e+" must be a nonnegative safe integer");return t}o(ct,"responseNonnegativeInteger");function Nt(t,e){let n=T(t,e);if(!n.trim())throw f(e+" must be nonempty");return n}o(Nt,"responseNonemptyText");function Lt(t){if(!jr.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/i.test(t))throw m("request_id must be a non-zero RFC 4122 UUID");return t}o(Lt,"requireRequestID");function I(t,e){if(typeof t!="string"||!/^[1-9]\d*$/.test(t))throw m(`${e} must be a positive int64 decimal string`);if(BigInt(t)>$r)throw m(`${e} must be a positive int64 decimal string`);return t}o(I,"requireID");var Ce=100;function Ot(t,e){if(!Array.isArray(t))throw m(`${e} must be an array`);if(t.length>Ce)throw m(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>I(n,`${e}[${i}]`))}o(Ot,"requireIDs");function Jr(t){if(!Array.isArray(t))throw m("tickers must be an array");if(t.length>100)throw m("tickers must contain at most 100 values");return t.map((e,n)=>{let i=$(e,`tickers[${n}]`);if(i.trim()===""||i.includes("\0"))throw m(`tickers[${n}] must be non-empty`);return i})}o(Jr,"requireTickers");function xe(t){let e=$(t,"body");if(e.trim().length===0)throw m("body must not be blank");if(Yn.encode(e).byteLength>65536)throw m("body must be at most 65536 UTF-8 bytes");return e}o(xe,"requireBody");function Gt(t){let e=$(t,"title");if(Yn.encode(e).byteLength>500)throw m("title must be at most 500 UTF-8 bytes");return e}o(Gt,"requireTitle");function Zn(t){let e=$(t,"visibility");if(e!=="public"&&e!=="private"&&e!=="paid")throw m("visibility must be public, private or paid");return e}o(Zn,"requireVisibility");function ei(t){let e=$(t,"visibility");if(e!=="public"&&e!=="private")throw m("visibility must be public or private");return e}o(ei,"requirePublicVisibility");function Zr(t){let e=$(t,"mode");if(e==="reformat"||e==="shorten"||e==="enrich")return e;throw m("mode must be reformat, shorten, or enrich")}o(Zr,"requireRewriteMode");function $(t,e){if(typeof t!="string")throw m(`${e} must be a string`);if(Br.test(t))throw m(`${e} contains invalid Unicode`);if((e==="body"||e==="title"||e==="note")&&t.includes("\0"))throw m(`${e} must not contain NUL`);return t}o($,"requireText");function C(t,e){if(typeof t=="number")throw f(`${e} must be a decimal string; numeric IDs are unsafe`);try{return I(t,e)}catch{throw f(`${e} must be a positive int64 decimal string`)}}o(C,"responseID");function es(t,e){if(!Array.isArray(t))throw f(`${e} must be an array`);if(t.length>Ce)throw f(`${e} must contain at most ${Ce} IDs`);return t.map((n,i)=>C(n,`${e}[${i}]`))}o(es,"responseIDs");function T(t,e){try{return $(t,e)}catch{throw f(`${e} must be valid text`)}}o(T,"responseText");function ts(t){try{return $(t,"note")}catch{throw f("thesis.closing_note must be valid text")}}o(ts,"responseClosingNote");function B(t,e){if(typeof t!="boolean")throw f(`${e} must be boolean`);return t}o(B,"responseBoolean");function ns(t){try{return Zn(t)}catch{throw f("thesis.visibility must be public, private or paid")}}o(ns,"responseVisibility");function ti(t){try{return xe(t)}catch{throw f("response body must be nonblank valid text at most 65536 UTF-8 bytes")}}o(ti,"responseBody");function is(t){try{return Gt(t)}catch{throw f("response title must be valid text at most 500 UTF-8 bytes")}}o(is,"responseTitle");function g(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(g,"isRecord");function rs(t,e){if(t.length===0)return!e||e.length===0;if(!e||e.length!==t.length)return!1;let n=new Set(t),i=new Set;return e.every(s=>n.has(s.entity_id)&&!i.has(s.entity_id)&&i.add(s.entity_id))}o(rs,"completeEntityStances");function m(t){return new l("INVALID_ARGUMENT",t,400)}o(m,"invalidArgument");function f(t){return new l("INVALID_RESPONSE",t,502)}o(f,"invalidResponse");function ni(t){return g(t)&&["image","price_chart","audio","video"].includes(t.type)&&Dt(t.cover_url)&&(t.url==null||Dt(t.url))}o(ni,"validMedia");function Dt(t){if(typeof t!="string"||t.length>2048||/[\s\u0000]/.test(t))return!1;try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!!e.hostname&&!e.username&&!e.password}catch{return!1}}o(Dt,"validMediaURL");async function Kn(t,e,n){let i=await t._request("POST","/query",{body:{query:e,variables:n}});if(!g(i))throw f("GraphQL response must be an object");if(i.errors!==void 0){if(!Array.isArray(i.errors))throw f("GraphQL errors must be an array");if(i.errors.length>0){let s=i.errors.flatMap(d=>g(d)&&typeof d.message=="string"?[d.message]:[]),r=new Set(i.errors.map(d=>g(d)&&g(d.extensions)?d.extensions.code:void 0)),[a]=r,u=r.size===1&&(a==="NOT_FOUND"||a==="PERMISSION_DENIED"||a==="UNAUTHENTICATED")?a:void 0,c=u==="NOT_FOUND"?404:u==="PERMISSION_DENIED"?403:u==="UNAUTHENTICATED"?401:400;throw new l(u??"GRAPHQL_ERROR",s.join("; ")||"GraphQL request failed",c,{errors:i.errors})}}if(!g(i.data))throw f("GraphQL response must contain data");return i.data}o(Kn,"thesisGraphql");var ii=50,ri=40,ss=100,fi=50,os=100,si=2048,oi=200,as=5,us=["STOCK","ETF","CRYPTO"],cs=["USER","PERSON"],ls=new Set(["NOT_FOUND","FAILED_PRECONDITION"]),mi={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},ai="id ticker name kind",Mt="__typename id displayName followersCount viewerState { following } ... on PublicUser { username } ... on Person { slug xHandle }";function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(y,"record");function k(t){throw new l("GRAPHQL_INVALID_RESPONSE",`GraphQL returned an invalid ${t} response`,502)}o(k,"invalidResponse");function gi(t){if(!y(t)||t.errors===void 0)return;if(!Array.isArray(t.errors))return k("GraphQL");if(t.errors.length===0)return;let e=t.errors,n=e.flatMap(r=>y(r)&&typeof r.message=="string"?[r.message]:[]),i=e.map(r=>y(r)&&y(r.extensions)?r.extensions.code:void 0);return{code:typeof i[0]=="string"&&Object.hasOwn(mi,i[0])&&i.every(r=>r===i[0])?i[0]:"GRAPHQL_ERROR",message:n.join("; ")||"Request failed",errors:e}}o(gi,"graphQLFailure");function yi(t){throw new l(t.code,t.message,mi[t.code]??502,{errors:t.errors})}o(yi,"throwFailure");function lt(t,e){let n=gi(t);return n&&yi(n),!y(t)||!y(t.data)?k(e):t.data}o(lt,"responseData");function ui(t,e){let n=lt(t,e);return y(n.viewer)?n.viewer[e]:k(e)}o(ui,"viewerField");function W(t,e){return typeof t!="string"||!t?k(e):t}o(W,"requireString");function ci(t,e){return!y(t)||typeof t.hasNextPage!="boolean"||t.endCursor!==null&&t.endCursor!==void 0&&typeof t.endCursor!="string"||t.hasNextPage&&!t.endCursor?k(e):{endCursor:typeof t.endCursor=="string"?t.endCursor:"",hasNextPage:t.hasNextPage}}o(ci,"pageInfo");function li(t,e){if(!y(t)||!y(t.viewerState))return k(e);let n=t.viewerState.following;if(typeof t.followersCount!="number"||typeof t.displayName!="string"||n!==null&&typeof n!="boolean")return k(e);let i={id:W(t.id,e),displayName:t.displayName,followersCount:t.followersCount,following:n??null};return t.__typename==="PublicUser"?{kind:"USER",...i,username:W(t.username,e)}:t.__typename==="Person"?t.xHandle!==null&&t.xHandle!==void 0&&typeof t.xHandle!="string"?k(e):{kind:"PERSON",...i,slug:W(t.slug,e),xHandle:t.xHandle??null}:k(e)}o(li,"normalizeProfile");function dt(t,e,n="first"){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>e)throw new Error(`${n} must be an integer between 1 and ${e}`);return t}}o(dt,"boundedFirst");function di(t){if(t!==void 0){if(typeof t!="string"||!t.trim()||t.length>4096)throw new Error("after must be a non-empty cursor of at most 4096 characters");return t}}o(di,"optionalCursor");function jt(t,e){if(!(t===void 0&&!e)){if(typeof t!="string"||!cs.includes(t))throw new Error("kind must be USER or PERSON");return t}}o(jt,"profileKind");function pi(t){if(t!==void 0){if(typeof t!="string"||!us.includes(t))throw new Error("kind must be STOCK, ETF, or CRYPTO");return t}}o(pi,"tickerKind");function ds(t){if(!y(t)||!Array.isArray(t.tickers))throw new Error("tickers must be a list of ticker symbols");let e=pi(t.kind),n=[];for(let i of t.tickers){let s=typeof i=="string"?{ticker:i}:i;if(!y(s)||typeof s.ticker!="string")throw new Error("tickers must be symbols or {ticker, kind} specs");let r=s.ticker.trim().toUpperCase();if(!r||/\s/.test(r)||r.length>ri)throw new Error(`ticker '${s.ticker}' must be a non-empty symbol of at most ${ri} characters`);let a=pi(s.kind)??e;n.some(u=>u.ticker===r&&u.kind===a)||n.push(a===void 0?{ticker:r}:{ticker:r,kind:a})}if(n.length===0||n.length>ii)throw new Error(`tickers must contain between 1 and ${ii} symbols`);return{tickers:n}}o(ds,"normalizeWatchlistTickersParams");function ps(t){if(!y(t))throw new Error("profile reference must be an object");let e=jt(t.kind,!0);if(typeof t.id!="string"||!/^[1-9]\d{0,18}$/.test(t.id))throw new Error("id must be a positive decimal profile id");return{kind:e,id:t.id}}o(ps,"validateProfileRef");function hs(t){if(!y(t)||typeof t.query!="string")throw new Error("query is required");let e=t.query.trim();if(!e||e.length>oi)throw new Error(`query must be non-empty and at most ${oi} characters`);return{query:e,kind:jt(t.kind,!1),first:dt(t.first,fi)}}o(hs,"validateSearchProfilesParams");function hi(t,e,n,i){return e===void 0?{ok:!1,unresolved:{input:t,code:n,message:i}}:{ok:!1,unresolved:{input:t,kind:e,code:n,message:n==="NOT_FOUND"?`no ${e} entity found for ticker ${t}; it may exist as another kind (retry with a different :kind suffix or none)`:i}}}o(hi,"unresolvedTicker");var ae=class{constructor(e){this.client=e}client;static{o(this,"FollowsResource")}async addToWatchlist(e){let{changed:n,unchanged:i,unresolved:s}=await this.changeWatchlist(e,"add");return{added:n,unchanged:i,unresolved:s}}async removeFromWatchlist(e){let{changed:n,unchanged:i,unresolved:s}=await this.changeWatchlist(e,"remove");return{removed:n,unchanged:i,unresolved:s}}async watchlist(e={}){let n=dt(e.first,ss),i=di(e.after);this.client._requireAuth();let s=await this.client._request("POST","/query",{body:{query:`query ToolkitWatchlist($input: MarketWatchlistConnectionInput) { viewer { marketWatchlist(input: $input) { totalCount edges { cursor followedAtMs node { ${ai} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{first:n??20,after:i}}}}),r="viewer.marketWatchlist",a=ui(s,"marketWatchlist");if(!y(a)||typeof a.totalCount!="number"||!Array.isArray(a.edges))return k(r);let u=a.edges.map(c=>!y(c)||!y(c.node)||typeof c.followedAtMs!="number"?k(r):{entityId:W(c.node.id,r),ticker:W(c.node.ticker,r),name:typeof c.node.name=="string"?c.node.name:"",kind:W(c.node.kind,r),addedAtMs:c.followedAtMs});return{totalCount:a.totalCount,tickers:u,pageInfo:ci(a.pageInfo,r)}}async searchProfiles(e){let{query:n,kind:i,first:s}=hs(e);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitSearchProfiles($input: PublicProfileConnectionInput) { profiles(input: $input) { edges { node { ${Mt} } } pageInfo { endCursor hasNextPage } } }`,variables:{input:{query:n,kind:i,first:s??10}}}});return this.profilesPage(lt(r,"profiles").profiles,"profiles")}async profiles(e={}){let n=jt(e.kind,!1),i=dt(e.first,fi),s=di(e.after);this.client._requireAuth();let r=await this.client._request("POST","/query",{body:{query:`query ToolkitFollowedProfiles($input: FollowingProfileConnectionInput) { viewer { followingProfiles(input: $input) { edges { node { ${Mt} } } pageInfo { endCursor hasNextPage } } } }`,variables:{input:{kind:n,first:i??20,after:s}}}});return this.profilesPage(ui(r,"followingProfiles"),"viewer.followingProfiles")}async theses(e={}){let n=dt(e.first,os),i=e.cursor;if(i!==void 0&&(typeof i!="string"||!i.trim()||i.length>si))throw new Error(`cursor must be a non-empty cursor of at most ${si} characters`);this.client._requireAuth();let s={};return n!==void 0&&(s.first=String(n)),i!==void 0&&(s.cursor=i),fs(await this.client._request("GET","/api/v1/me/following/theses",{query:s}))}async followProfile(e){return this.changeProfile(e,"followProfile")}async unfollowProfile(e){return this.changeProfile(e,"unfollowProfile")}profilesPage(e,n){return!y(e)||!Array.isArray(e.edges)?k(n):{profiles:e.edges.map(i=>y(i)?li(i.node,n):k(n)),pageInfo:ci(e.pageInfo,n)}}async changeProfile(e,n){let i=ps(e);this.client._requireAuth();let s=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeProfileFollow($input: PublicProfileRefInput!) { ${n}(input: $input) { following target { ${Mt} } } }`,variables:{input:i}}}),r=lt(s,n)[n];return!y(r)||typeof r.following!="boolean"?k(n):{following:r.following,profile:r.target===null||r.target===void 0?null:li(r.target,n)}}async changeWatchlist(e,n){let{tickers:i}=ds(e);this.client._requireAuth();let s=await this.lookupTickers(i),r=[],a=[],u=[],c=new Map,d=[];for(let p of s){if(!p.ok){u.push(p.unresolved);continue}let P=c.get(p.ticker.entityId);if(P){P.push(p.ticker);continue}let _=n==="add"?!p.inWatchlist:p.inWatchlist,b=_?r:a;b.push(p.ticker),c.set(p.ticker.entityId,b),(_||n==="remove")&&d.push(p.ticker.entityId)}if(d.length>0){let p=n==="add"?"followTickers":"unfollowTickers",P=n==="add"?"FollowTickersInput":"UnfollowTickersInput",_=await this.client._request("POST","/query",{body:{query:`mutation ToolkitChangeWatchlist($input: ${P}!) { ${p}(input: $input) { entities { id } } }`,variables:{input:{entityIds:d}}}}),b=lt(_,p)[p];if(!y(b)||!Array.isArray(b.entities))return k(p)}return{changed:r,unchanged:a,unresolved:u}}async lookupTickers(e){let n=new Array(e.length),i=0,s=o(async()=>{for(;i<e.length;){let r=i++,{ticker:a,kind:u}=e[r];n[r]=await this.lookupTicker(a,u)}},"worker");return await Promise.all(Array.from({length:Math.min(as,e.length)},s)),n}async lookupTicker(e,n){let i=await this.client._request("POST","/query",{body:{query:`query ToolkitTickerLookup($input: MarketEntityLookupInput!) { market { entity(input: $input) { ${ai} viewerState { isFollowed } } } }`,variables:{input:{ticker:e,kind:n}}}}),s=gi(i);if(s){if(ls.has(s.code))return hi(e,n,s.code,s.message);yi(s)}let r="market.entity";if(!y(i)||!y(i.data)||!y(i.data.market))return k(r);let a=i.data.market.entity;if(a==null)return hi(e,n,"NOT_FOUND",`no entity found for ticker: ${e}`);if(!y(a))return k(r);let u=a.viewerState;if(u==null)throw new l("PERMISSION_DENIED","This credential cannot read the user's watchlist",403);return!y(u)||typeof u.isFollowed!="boolean"?k(r):{ok:!0,inWatchlist:u.isFollowed,ticker:{input:e,entityId:W(a.id,r),ticker:W(a.ticker,r),name:typeof a.name=="string"?a.name:"",kind:W(a.kind,r)}}}};function $t(t){return new l("INVALID_RESPONSE",t,502)}o($t,"invalidFollowingTheses");function fs(t){if(!y(t)||!Array.isArray(t.items)||typeof t.next_cursor!="string"||!t.next_cursor||typeof t.has_more!="boolean")throw $t("invalid following theses page");return{items:t.items.map(e=>{if(!y(e))throw $t("invalid following theses item");return{thesis:Ft(e.thesis),author:ms(e.author)}}),next_cursor:t.next_cursor,has_more:t.has_more}}o(fs,"followingThesesPage");function ms(t){if(t===null)return null;if(!y(t)||t.kind!=="user"||typeof t.username!="string"||typeof t.display_name!="string")throw $t("invalid following theses author");return{kind:t.kind,username:t.username,display_name:t.display_name}}o(ms,"followingThesisAuthor");var ue=class{constructor(e){this.client=e}client;static{o(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 pt=class{constructor(e){this.client=e}client;static{o(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:bi(e)})}async unsubscribe(e){return this.client._requireAuth(),this.client._request("DELETE","/api/v1/channel/group-subscriptions",{jsonBody:bi(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 bi(t){return`{"session_id":${wi(t.session_id)},"target_type":${JSON.stringify(t.target_type)},"target_id":${wi(t.target_id)}}`}o(bi,"mutationBody");function wi(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}o(wi,"idLiteral");var ht=class{constructor(e){this.client=e}client;static{o(this,"FeedbackResource")}async submit(e){return this.client._requireAuth(),this.client._request("POST","/api/v1/feedback",{body:e})}};var ft=class{constructor(e){this.client=e}client;static{o(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:ys(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 Bt(n.allowance)}async listAllowances(){return this.client._requireAuth(),{allowances:((await this.client._request("GET","/api/v1/service/allowances")).allowances??[]).map(n=>Bt(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:gs(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 Bt(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=Pi(t.created_at_ms??t.createdAtMs??t.created_at??t.createdAt),i=Pi(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}o(Bt,"normalizeAllowance");function gs(t){let e=Bt(t);if(!e)throw new Error("allowance response missing allowance");return e}o(gs,"requireAllowance");function Pi(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 r=Date.parse(t);return Number.isNaN(r)?void 0:r}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)}o(Pi,"timestampMs");function ys(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}}o(ys,"parseResultPayload");var bs=`
|
|
146
146
|
query ToolkitCreditWallet {
|
|
147
147
|
viewer {
|
|
148
148
|
creditWallet {
|
|
@@ -184,7 +184,7 @@ query ToolkitCreditWalletItems($input: CreditWalletItemConnectionInput!) {
|
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
186
|
}
|
|
187
|
-
`.trim();function Ps(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"}o(Ps,"graphQLErrorMessage");var
|
|
187
|
+
`.trim();function Ps(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"}o(Ps,"graphQLErrorMessage");var mt=class{constructor(e){this.client=e}client;static{o(this,"CreditsResource")}async wallet(){this.client._requireAuth();let n=(await this.graphql(bs)).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 i=(await this.graphql(ws,{input:{startAtMs:e.startAtMs,endAtMs:e.endAtMs,sessionId:e.sessionId,first:e.first,after:e.after}})).viewer?.creditWallet;if(!i)throw new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include viewer.creditWallet.items",502);return i}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Ps(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}};var _s=["Q1","Q2","Q3","Q4"],Ts=["latest-completed","next-confirmed"],Rs=`
|
|
188
188
|
query ToolkitCompanyNarrative($ticker: String!) {
|
|
189
189
|
market {
|
|
190
190
|
entity(input: { ticker: $ticker, kind: STOCK }) {
|
|
@@ -311,7 +311,7 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
311
311
|
}
|
|
312
312
|
}
|
|
313
313
|
}
|
|
314
|
-
`.trim();function Es(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"}o(Es,"graphQLErrorMessage");function
|
|
314
|
+
`.trim();function Es(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"}o(Es,"graphQLErrorMessage");function Wt(t){let e=t.trim().toUpperCase();if(!e)throw new l("INVALID_ARGUMENT","ticker is required",400);return e}o(Wt,"normalizedTicker");var ce=class{constructor(e){this.client=e}client;static{o(this,"MarketsResource")}async narrative(e){this.client._requireAuth();let n=Wt(e),s=(await this.graphql(Rs,{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=Wt(e),s=(await this.graphql(Ss,{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=Wt(e.ticker),i=e.event,s=e.fiscalYear,r=e.fiscalQuarter;if(i!==void 0&&(s!==void 0||r!==void 0))throw new l("INVALID_ARGUMENT","event cannot be combined with fiscalYear or fiscalQuarter",400);if(s===void 0!=(r===void 0))throw new l("INVALID_ARGUMENT","fiscalYear and fiscalQuarter must be provided together",400);if(i!==void 0&&!Ts.includes(i))throw new l("INVALID_ARGUMENT",`Unknown earnings event selector: ${i}`,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(r!==void 0&&!_s.includes(r))throw new l("INVALID_ARGUMENT","fiscalQuarter must be Q1, Q2, Q3, or Q4",400);let u,c;if(s!==void 0&&r!==void 0)u=s,c=r;else{let P=i??"latest-completed",_=await this.earningsPeriods(n),b=this.selectPeriod(_,P,n);u=b.fiscalYear,c=b.fiscalQuarter}let p=(await this.graphql(ks,{ticker:n,input:{fiscalYear:u,fiscalQuarter:c}})).market?.entity;if(!p)throw this.notFound(n);if(!p.earnings)throw new l("MARKETS_EARNINGS_NOT_COVERED",`No earnings content is available for ${p.ticker} FY${u} ${c}`,404,{ticker:p.ticker,fiscalYear:u,fiscalQuarter:c});return{ticker:p.ticker,...p.earnings}}selectPeriod(e,n,i){if(n==="latest-completed"){let s=e.periods.filter(r=>r.status==="COMPLETED").sort((r,a)=>a.earningsDate.localeCompare(r.earningsDate));if(s.length>0)return s[0]}else{let s=e.periods.filter(r=>r.status==="UPCOMING").sort((r,a)=>r.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 ${i}`,404,{ticker:i,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 i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(i.errors&&i.errors.length>0)throw new l("GRAPHQL_ERROR",Es(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}};var gt=`
|
|
315
315
|
id
|
|
316
316
|
name
|
|
317
317
|
rule { kind atMs everyIntervalSeconds cronExpression cronTimezone }
|
|
@@ -328,32 +328,32 @@ query ToolkitCompanyEarnings($ticker: String!, $input: CompanyEarningsInput) {
|
|
|
328
328
|
query ToolkitListAgentSchedules($channelId: ID!, $after: String) {
|
|
329
329
|
viewer { channel(id: $channelId) {
|
|
330
330
|
schedules(input: { first: 64, after: $after }) {
|
|
331
|
-
edges { node { channel { id } ${
|
|
331
|
+
edges { node { channel { id } ${gt} } }
|
|
332
332
|
pageInfo { hasNextPage endCursor }
|
|
333
333
|
}
|
|
334
334
|
} }
|
|
335
335
|
}`.trim(),vs=`
|
|
336
336
|
mutation ToolkitUpdateAgentSchedule($input: UpdateChannelScheduleInput!) {
|
|
337
337
|
updateChannelSchedule(input: $input) {
|
|
338
|
-
schedule { channel { id } ${
|
|
338
|
+
schedule { channel { id } ${gt} }
|
|
339
339
|
deleted
|
|
340
340
|
}
|
|
341
341
|
}`.trim(),Is=`
|
|
342
342
|
query ToolkitListSessionSchedules($inboxPath: String!, $after: String) {
|
|
343
343
|
viewer { sessionSchedules(inboxPath: $inboxPath, input: { first: 64, after: $after }) {
|
|
344
|
-
edges { node { ${
|
|
344
|
+
edges { node { ${gt} } }
|
|
345
345
|
pageInfo { hasNextPage endCursor }
|
|
346
346
|
} }
|
|
347
347
|
}`.trim(),Cs=`
|
|
348
348
|
mutation ToolkitUpdateSessionSchedule($input: UpdateSessionScheduleInput!) {
|
|
349
349
|
updateSessionSchedule(input: $input) {
|
|
350
|
-
schedule { ${
|
|
350
|
+
schedule { ${gt} }
|
|
351
351
|
deleted
|
|
352
352
|
}
|
|
353
353
|
}`.trim(),xs=`
|
|
354
354
|
query ToolkitAgentChannel {
|
|
355
355
|
viewer { channels { id kind } }
|
|
356
|
-
}`.trim(),Ns=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,qs=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Ds=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Us=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Fs={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},le=class{constructor(e){this.client=e}client;static{o(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=
|
|
356
|
+
}`.trim(),Ns=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,qs=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+-](\d{2}):(\d{2}))$/i,Ds=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-](\d{2}):(\d{2}))$/i,Us=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/,Fs={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},le=class{constructor(e){this.client=e}client;static{o(this,"SchedulesResource")}async list(e){this.client._requireAuth();let n=Vt(e),i="inboxPath"in n,s=[],r=null,a=new Set;for(;;){let u=await this.graphql(i?Is:As,{...n,after:r}),c=i?u.viewer?.sessionSchedules:u.viewer?.channel?.schedules;if(!c?.edges)throw Ti();for(let p of c.edges){if(!p?.node)throw N();s.push(Qt(p.node))}if(c.pageInfo?.hasNextPage!==!0)return s;let d=c.pageInfo.endCursor;if(!d||a.has(d))throw N();a.add(d),r=d}}async put(e){this.client._requireAuth();let n={...Vt(e),name:Ri(e.name),definition:{...Ls(e.rule,e.bounds),message:{text:$s(e.text)}}},i=(await this.update(n))?.schedule;if(!i)throw N();return Qt(i)}pause(e){return this.manage("PAUSED",e)}resume(e){return this.manage("ACTIVE",e)}async delete(e){if(this.client._requireAuth(),(await this.update({..._i(e),lifecycle:"REMOVED"}))?.deleted!==!0)throw N()}async agentChannelId(){this.client._requireAuth();let n=(await this.graphql(xs)).viewer?.channels?.find(i=>i.kind==="AGENT")?.id;if(!n)throw Ti();return n}async manage(e,n){this.client._requireAuth();let i=(await this.update({..._i(n),lifecycle:e}))?.schedule;if(!i)throw N();return Qt(i)}async update(e){let n="inboxPath"in e,i=await this.graphql(n?Cs:vs,{input:e});return n?i.updateSessionSchedule:i.updateChannelSchedule}async graphql(e,n){let i=await this.client._request("POST","/query",{body:n===void 0?{query:e}:{query:e,variables:n}});if(i.errors?.length){let s=i.errors.map(d=>d.extensions?.code),a=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,u=a?Fs[a]:void 0,c=a!==void 0&&u!==void 0?a:"GRAPHQL_ERROR";throw new l(c,i.errors.map(d=>d.message).filter(d=>typeof d=="string").join("; ")||"GraphQL request failed",u??502,{errors:i.errors})}if(!i.data)throw N();return i.data}};function Ls(t,e){let n=Os(e);switch(t.kind){case"after":if(n)throw R("after does not accept recurring bounds");let i=Date.now()+Si(t.duration,1),s=Math.ceil(i/1e3)*1e3;if(!Number.isSafeInteger(s)||Number.isNaN(new Date(s).getTime()))throw R("after is out of range");return{rule:{kind:"AT",atMs:s}};case"at":if(n)throw R("at does not accept recurring bounds");return{rule:{kind:"AT",atMs:Ht(t.timestamp)}};case"every":return{rule:{kind:"EVERY",everyIntervalSeconds:js(t.interval)},...n?{bounds:n}:{}};case"cron":if(!t.expression.trim()||!t.timezone.trim())throw R("cron expression and timezone are required");return{rule:{kind:"CRON",cronExpression:t.expression,cronTimezone:t.timezone},...n?{bounds:n}:{}}}}o(Ls,"ruleInput");function Os(t){if(!t)return;let e={};if(t.startsAt!==void 0&&(e.startsAtMs=Ht(t.startsAt)),t.until!==void 0&&(e.untilMs=Ht(t.until)),t.maxOccurrences!==void 0){if(!Number.isSafeInteger(t.maxOccurrences)||t.maxOccurrences<=0)throw R("maxOccurrences must be a positive safe integer");e.maxOccurrences=t.maxOccurrences}return Object.keys(e).length>0?e:void 0}o(Os,"boundsInput");function Qt(t){let n={ACTIVE:"active",PAUSED:"paused",COMPLETED:"completed",FAILED:"failed"}[t.status];if(!n)throw N();let i=t.bounds??{},s=t.message??{},r={name:t.name,rule:Gs(t.rule),bounds:{...i.startsAtMs!=null?{startsAt:Y(i.startsAtMs,!0)}:{},...i.untilMs!=null?{until:Y(i.untilMs,!0)}:{},...i.maxOccurrences!=null?{maxOccurrences:Kt(i.maxOccurrences,"maxOccurrences")}:{}},text:s.text??"",status:n,occurrencesUsed:Kt(t.occurrencesUsed,"occurrencesUsed"),...t.nextFireAtMs!=null?{nextFireAt:Y(t.nextFireAtMs,!0)}:{},createdAt:Y(t.createdAtMs),updatedAt:Y(t.updatedAtMs)};if(n==="failed"){if(!t.failureCode)throw N();let u={TARGET_INVALID:"target_invalid",DELIVERY_EXHAUSTED:"delivery_exhausted",PAYLOAD_CONFLICT:"payload_conflict"}[t.failureCode];if(!u)throw N();r.failure={code:u,...t.failureAtMs!=null?{at:Y(t.failureAtMs)}:{}}}return r}o(Qt,"fromWireSchedule");function Gs(t){switch(t.kind){case"AT":if(t.atMs==null)throw N();return{kind:"at",timestamp:Y(t.atMs,!0)};case"EVERY":if(t.everyIntervalSeconds==null)throw N();return{kind:"every",interval:`PT${Kt(t.everyIntervalSeconds,"interval")}S`};case"CRON":if(!t.cronExpression||!t.cronTimezone)throw N();return{kind:"cron",expression:t.cronExpression,timezone:t.cronTimezone}}throw N()}o(Gs,"fromWireRule");function _i(t){return{...Vt(t),name:Ri(t.name)}}o(_i,"managementInput");function Vt(t){if(t.channelId!==void 0==(t.inboxPath!==void 0))throw R("exactly one of channelId or inboxPath is required");if(t.channelId!==void 0)return{channelId:Ms(t.channelId)};let e=t.inboxPath,n=typeof e=="string"?ki(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 R("inboxPath must be a canonical absolute ALFS Inbox path");let i=e.endsWith(".inbox.jsonl")?e.slice(0,-12)+".jsonl":e.endsWith(".inbox")&&!e.endsWith(".jsonl.inbox")?e.slice(0,-6):void 0;if(i===void 0||/\.inbox(?:\.jsonl)?$/.test(i)||/\.lock(?:\.recovery|\.heartbeat-[^/]+|\.stale-[^/]+)?$/.test(i)||i.endsWith("/.jsonl"))throw R("inboxPath must identify a standard Session Inbox sidecar");return{inboxPath:e}}o(Vt,"targetInput");function Ms(t){if(typeof t=="number"&&(!Number.isSafeInteger(t)||t<=0))throw R("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 R("channelId must be a positive integer");return e}o(Ms,"channelID");function Ri(t){if(!Ns.test(t))throw R("name must be 1-63 lowercase alphanumeric characters or hyphens");return t}o(Ri,"requireName");function $s(t){let e=ki(t);if(e===void 0||!t.trim()||e>16*1024)throw R("text must be 1..16384 UTF-8 bytes");return t}o($s,"requireText");function js(t){let e=Si(t,60);if(e%1e3!==0)throw R("duration must resolve to whole seconds");return e/1e3}o(js,"durationSeconds");function Si(t,e){let n=Us.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 R("duration must be a positive ISO 8601 day/time duration");let[i,s,r,a]=n.slice(1,5).map(d=>BigInt(d??"0")),u=((i*24n+s)*60n+r)*60n+a;if(u<BigInt(e))throw R(`duration must be at least ${e} whole seconds`);let c=Number(u*1000n);if(!Number.isSafeInteger(c))throw R("duration is out of range");return c}o(Si,"durationMilliseconds");function Ht(t,e=!1){let n=(e?Ds:qs).exec(t);if(!n)throw R("timestamp must be RFC3339 with a timezone");let[i,s,r,a,u,c]=n.slice(1,7).map(Number),d=Number(n[8]??0),p=Number(n[9]??0),P=new Date(Date.UTC(i,s,0)).getUTCDate(),_=Date.parse(t);if(!Number.isFinite(_)||i<1||i>9999||s<1||s>12||r<1||r>P||a>23||u>59||c>59||d>23||p>59)throw R("timestamp must be RFC3339 with a timezone");return _}o(Ht,"timestampMilliseconds");function Y(t,e=!1){if(!Number.isSafeInteger(t)||e&&t%1e3!==0)throw N();let n=new Date(t);if(Number.isNaN(n.getTime()))throw N();return n.toISOString()}o(Y,"timestampString");function Kt(t,e){let n=Number(t);if(!Number.isSafeInteger(n)||n<0)throw R(`${e} exceeds JavaScript safe integer range`);return n}o(Kt,"safeInteger");function R(t){return new l("INVALID_ARGUMENT",t,400)}o(R,"invalid");function ki(t){let e=new TextEncoder().encode(t);return new TextDecoder("utf-8",{fatal:!0}).decode(e)===t?e.byteLength:void 0}o(ki,"utf8Size");function Ti(){return new l("NOT_FOUND","channel schedule target not found",404)}o(Ti,"scheduleNotFound");function N(){return new l("GRAPHQL_EMPTY_RESPONSE","GraphQL response did not include a valid schedule",502)}o(N,"scheduleEmptyResponse");var Bs={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},Ws=`
|
|
357
357
|
mutation ToolkitStewardDecide($input: UpdateStewardDeliveryInput!) {
|
|
358
358
|
updateStewardDelivery(input: $input) { delivery { deliveryId state } }
|
|
359
359
|
}`.trim(),Qs=`
|
|
@@ -378,13 +378,13 @@ query ToolkitStewardPending($inboxPath: String!, $input: StewardDigestPendingInp
|
|
|
378
378
|
}`.trim(),Ks=`
|
|
379
379
|
mutation ToolkitStewardBriefed($input: CompleteStewardBriefInput!) {
|
|
380
380
|
completeStewardBrief(input: $input) { ok }
|
|
381
|
-
}`.trim(),
|
|
381
|
+
}`.trim(),Ai=`
|
|
382
382
|
digestRunId state scheduleId scheduleVersion occurrenceIndex
|
|
383
383
|
windowSinceMs windowUntilMs scanCompletedAtMs bodySha256 coverageSha256
|
|
384
384
|
channelMessageId attempts lastError startedAtMs completedAtMs sendUncertainAtMs
|
|
385
385
|
`.trim(),Ys=`
|
|
386
386
|
query ToolkitStewardDigestRun($inboxPath: String!, $digestRunId: String!) {
|
|
387
|
-
viewer { stewardDigestRun(inboxPath: $inboxPath, digestRunId: $digestRunId) { ${
|
|
387
|
+
viewer { stewardDigestRun(inboxPath: $inboxPath, digestRunId: $digestRunId) { ${Ai} } }
|
|
388
388
|
}`.trim(),Xs=`
|
|
389
389
|
query ToolkitStewardDigestRunPending($inboxPath: String!, $digestRunId: String!, $input: StewardDigestRunPendingInput) {
|
|
390
390
|
viewer {
|
|
@@ -397,10 +397,10 @@ query ToolkitStewardDigestRunPending($inboxPath: String!, $digestRunId: String!,
|
|
|
397
397
|
}
|
|
398
398
|
}`.trim(),zs=`
|
|
399
399
|
mutation ToolkitStewardPublishDailyBrief($input: PublishStewardDailyBriefInput!) {
|
|
400
|
-
publishStewardDailyBrief(input: $input) { run { ${
|
|
401
|
-
}`.trim(),Js=new Set(["immediate","digest","suppress"]),Zs=/^[1-9][0-9]{0,18}$/,eo=100,to=1e4,no=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,io=3,ro=new Set(["NETWORK_ERROR","NETWORK_TIMEOUT","UNAVAILABLE","DEADLINE_EXCEEDED"]),so=new Set([502,503,504]);function q(t){return new l("INVALID_ARGUMENT",t,400)}o(q,"invalid");function V(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw q("steward commands require the steward Session Inbox path");return t.inboxPath}o(V,"requireInboxPath");function Yt(t,e="delivery id"){if(!Zs.test(t))throw q(`${e} must be a positive integer`);return t}o(Yt,"requireDeliveryId");function Xt(t){let e=new Set;for(let n of t){if(Yt(n),e.has(n))throw q(`duplicate delivery id ${n}`);e.add(n)}return[...e]}o(Xt,"normalizeDeliveryIds");function oo(t){if(t.length===0)throw q("at least one delivery id is required");return Xt(t)}o(oo,"requireDeliveryIds");function ao(t){if(!Js.has(t))throw q("decision must be one of immediate, digest, suppress");return t}o(ao,"requireDecision");function uo(){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 i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.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)}`}o(uo,"generateRequestId");function ki(t){if(t===void 0)return uo();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 q("request id must be a UUID");return t}o(ki,"requireRequestId");function Kt(t){if(!no.test(t))throw q("digest run id must be a UUID");return t.toLowerCase()}o(Kt,"requireDigestRunId");function co(t){return t instanceof l&&(ro.has(t.code)||so.has(t.status))}o(co,"isTransientStewardError");function E(){return new l("EMPTY_RESPONSE","steward response was empty",502)}o(E,"emptyResponse");var de=class{constructor(e){this.client=e}client;static{o(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw q("a decision reason is required");let s=(await this.graphql(Ws,{input:{inboxPath:V(e),deliveryId:Yt(e.deliveryId),decision:{decision:ao(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw E();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(Qs,{input:{inboxPath:V(e),deliveryId:Yt(e.deliveryId),forward:{requestId:ki(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw E();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw q("a message body is required");let i=(await this.graphql(Vs,{input:{inboxPath:V(e),requestId:ki(e.requestId),body:e.body,deliveryIds:Xt(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw E();return i}async pending(e){if(e.after!==void 0)return this.pendingPage(e);let n=[],i=new Set,s=new Set,r,a,u;do{let c=await this.pendingPageWithRetry({...e,after:r,sinceMs:r===void 0?e.sinceMs:void 0,untilMs:r===void 0?e.untilMs:void 0});if(a===void 0)a=c.windowSinceMs,u=c.windowUntilMs;else if(c.windowSinceMs!==a||c.windowUntilMs!==u)throw new l("ABORTED","steward pending window changed during pagination",409);for(let d of c.items)i.has(d.deliveryId)||(i.add(d.deliveryId),n.push(d));if(r=c.nextCursor??void 0,r!==void 0){if(s.has(r))throw new l("INTERNAL","steward pending pagination loop detected",500);s.add(r)}}while(r!==void 0);if(a===void 0||u===void 0)throw E();return{items:n,windowSinceMs:a,windowUntilMs:u}}async pendingPage(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw q("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[_,b]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(b!==void 0&&(!Number.isSafeInteger(b)||b<=0))throw q(`${_} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw q("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let r=(await this.graphql(Hs,{inboxPath:V(e),input:i})).viewer?.stewardDigestPending;if(!r||!Array.isArray(r.edges))throw E();let a=r.windowSinceMs??0,u=r.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw E();let c=r.edges.map(_=>_.node),d=r.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();let p=d.endCursor;if(p!=null&&typeof p!="string"||d.hasNextPage&&!p)throw E();let P=d.hasNextPage?p:null;return{items:c,nextCursor:P,windowSinceMs:a,windowUntilMs:u}}async pendingPageWithRetry(e){for(let n=1;n<io;n+=1)try{return await this.pendingPage(e)}catch(i){if(!co(i))throw i}return this.pendingPage(e)}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw q("a digest run id is required");let i=V(e),s=oo(e.deliveryIds);if(s.length>eo)throw q("legacy briefed accepts at most 100 delivery ids");if((await this.graphql(Ks,{input:{inboxPath:i,deliveryIds:s,digestRunId:n}})).completeStewardBrief?.ok!==!0)throw E();return{ok:!0}}async digestRun(e){this.client._requireAuth();let i=(await this.graphql(Ys,{inboxPath:V(e),digestRunId:Kt(e.digestRunId)})).viewer?.stewardDigestRun;if(!i)throw E();return i}async digestRunPending(e){this.client._requireAuth();let n=V(e),i=Kt(e.digestRunId),s=[],r=new Set,a;for(;;){let c=(await this.graphql(Xs,{inboxPath:n,digestRunId:i,input:{first:100,...a===void 0?{}:{after:a}}})).viewer?.stewardDigestRunPending;if(!c||!Array.isArray(c.edges))throw E();let d=c.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();for(let P of c.edges){if(!P?.node)throw E();s.push(P.node)}if(!d.hasNextPage)break;let p=d.endCursor;if(typeof p!="string"||p===""||r.has(p))throw E();r.add(p),a=p}return s}async sendDigestRun(e){this.client._requireAuth();let n=Xt(e.deliveryIds??[]);if(n.length>to)throw q("durable Daily Brief accepts at most 10000 delivery ids");if(e.body!==void 0&&e.body.trim()==="")throw q("a message body must be non-blank when provided");let s=(await this.graphql(zs,{input:{inboxPath:V(e),digestRunId:Kt(e.digestRunId),deliveryIds:n,...e.body===void 0?{}:{body:e.body}}})).publishStewardDailyBrief?.run;if(!s)throw E();return s}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw E();if(i.errors?.length){let s=i.errors.map(u=>u.extensions?.code),r=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=r?Bs[r]:void 0;throw new l(r!==void 0&&a!==void 0?r:"GRAPHQL_ERROR",i.errors.map(u=>u.message).filter(u=>typeof u=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw E();return i.data}};function H(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(H,"isRecord");function S(t){return typeof t=="string"&&t.trim()!==""?t:void 0}o(S,"stringValue");function gt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}o(gt,"numberValue");function bt(t){return t===void 0?void 0:t.trim().toUpperCase()}o(bt,"upper");function vi(t){return t.split("_")}o(vi,"pairParts");function lo(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":vi(e)[1]?.toLowerCase()??""}o(lo,"inferInstrumentType");function po(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}o(po,"inferUnderlyingType");function Ai(t,e){let n=S(t.trading_pair)??S(t.tradingPair)??S(t.symbol);if(n===void 0)return;let i=S(t.type),s=vi(n),r=S(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=S(t.market)??S(t.exchange)??s[0]??"",u=S(t.quote)??s[s.length-1]??"",c=S(t.instrument_type)??S(t.instrumentType)??lo(i,n),d=S(t.underlying_type)??S(t.underlyingType)??po(i);return{symbol:r,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...i===void 0?{}:{type:i},...S(t.description)===void 0?{}:{description:S(t.description)},...gt(t.fee_rate)===void 0?gt(t.feeRate)===void 0?{}:{feeRate:gt(t.feeRate)}:{feeRate:gt(t.fee_rate)},...S(t.symbol_icon_url)===void 0?S(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:S(t.symbolIconUrl)}:{symbolIconUrl:S(t.symbol_icon_url)}}}o(Ai,"normalizeCandidate");function ho(t){if(!H(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>H(s)?[Ai(s)].filter(r=>r!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!H(s))continue;let r=S(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!H(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!H(c))continue;let d=Ai({...c,instrument_type:c.instrument_type??u.instrument_type},r);d!==void 0&&i.push(d)}}}return i}o(ho,"flattenResponse");function fo(t,e){let n=e.trim();return t.tradingPair===n?!0:bt(t.symbol)===bt(n)}o(fo,"matchesQuery");function yt(t,e){return e===void 0||bt(t)===bt(e)}o(yt,"matchesFilter");function mo(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}o(mo,"dedupe");function go(t){let e=H(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}}o(go,"resolveFilters");function yo(t,e){let n=t.split("_"),i=n[0],s=n[1],r=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!r||!a?{symbol:t,...e}:{symbol:r,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}o(yo,"pairSearchParams");var pe=class{constructor(e){this.client=e}client;static{o(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=H(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),r=mo(ho(s)).filter(u=>fo(u,i)).filter(u=>yt(u.market,e.market)).filter(u=>yt(u.instrumentType,e.instrumentType)).filter(u=>yt(u.underlyingType,e.underlyingType)).filter(u=>yt(u.quote,e.quote)),a=e.limit;return a!==void 0&&r.length>a?{query:i,candidates:r.slice(0,a),truncated:!0}:{query:i,candidates:r}}async resolve(e){let n=H(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=go(e),r=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:yo(i,s),a=await this.search(r),u=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);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 "${i??r.symbol}"`:`multiple canonical trading pairs matched "${r.symbol}"`,u.length===0?404:409,{query:i??r.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var bo=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
|
|
400
|
+
publishStewardDailyBrief(input: $input) { run { ${Ai} } }
|
|
401
|
+
}`.trim(),Js=new Set(["immediate","digest","suppress"]),Zs=/^[1-9][0-9]{0,18}$/,eo=100,to=1e4,no=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,io=3,ro=new Set(["NETWORK_ERROR","NETWORK_TIMEOUT","UNAVAILABLE","DEADLINE_EXCEEDED"]),so=new Set([502,503,504]);function q(t){return new l("INVALID_ARGUMENT",t,400)}o(q,"invalid");function V(t){if(!t||typeof t.inboxPath!="string"||t.inboxPath==="")throw q("steward commands require the steward Session Inbox path");return t.inboxPath}o(V,"requireInboxPath");function Xt(t,e="delivery id"){if(!Zs.test(t))throw q(`${e} must be a positive integer`);return t}o(Xt,"requireDeliveryId");function zt(t){let e=new Set;for(let n of t){if(Xt(n),e.has(n))throw q(`duplicate delivery id ${n}`);e.add(n)}return[...e]}o(zt,"normalizeDeliveryIds");function oo(t){if(t.length===0)throw q("at least one delivery id is required");return zt(t)}o(oo,"requireDeliveryIds");function ao(t){if(!Js.has(t))throw q("decision must be one of immediate, digest, suppress");return t}o(ao,"requireDecision");function uo(){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 i=0;i<e.length;i+=1)e[i]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,i=>i.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)}`}o(uo,"generateRequestId");function Ei(t){if(t===void 0)return uo();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 q("request id must be a UUID");return t}o(Ei,"requireRequestId");function Yt(t){if(!no.test(t))throw q("digest run id must be a UUID");return t.toLowerCase()}o(Yt,"requireDigestRunId");function co(t){return t instanceof l&&(ro.has(t.code)||so.has(t.status))}o(co,"isTransientStewardError");function E(){return new l("EMPTY_RESPONSE","steward response was empty",502)}o(E,"emptyResponse");var de=class{constructor(e){this.client=e}client;static{o(this,"StewardResource")}async decide(e){this.client._requireAuth();let n=e.reason?.trim();if(!n)throw q("a decision reason is required");let s=(await this.graphql(Ws,{input:{inboxPath:V(e),deliveryId:Xt(e.deliveryId),decision:{decision:ao(e.decision).toUpperCase(),reason:n}}})).updateStewardDelivery?.delivery;if(!s)throw E();return{state:s.state}}async forward(e){this.client._requireAuth();let i=(await this.graphql(Qs,{input:{inboxPath:V(e),deliveryId:Xt(e.deliveryId),forward:{requestId:Ei(e.requestId)}}})).updateStewardDelivery?.delivery;if(!i||!i.channelMessageId)throw E();return{channelMessageId:i.channelMessageId,state:i.state}}async send(e){if(this.client._requireAuth(),typeof e.body!="string"||e.body.trim()==="")throw q("a message body is required");let i=(await this.graphql(Vs,{input:{inboxPath:V(e),requestId:Ei(e.requestId),body:e.body,deliveryIds:zt(e.deliveryIds??[])}})).postStewardMessage?.message;if(!i)throw E();return i}async pending(e){if(e.after!==void 0)return this.pendingPage(e);let n=[],i=new Set,s=new Set,r,a,u;do{let c=await this.pendingPageWithRetry({...e,after:r,sinceMs:r===void 0?e.sinceMs:void 0,untilMs:r===void 0?e.untilMs:void 0});if(a===void 0)a=c.windowSinceMs,u=c.windowUntilMs;else if(c.windowSinceMs!==a||c.windowUntilMs!==u)throw new l("ABORTED","steward pending window changed during pagination",409);for(let d of c.items)i.has(d.deliveryId)||(i.add(d.deliveryId),n.push(d));if(r=c.nextCursor??void 0,r!==void 0){if(s.has(r))throw new l("INTERNAL","steward pending pagination loop detected",500);s.add(r)}}while(r!==void 0);if(a===void 0||u===void 0)throw E();return{items:n,windowSinceMs:a,windowUntilMs:u}}async pendingPage(e){this.client._requireAuth();let n=e.first??50;if(!Number.isInteger(n)||n<1||n>100)throw q("first must be an integer between 1 and 100");let i={first:n};if(e.after!==void 0&&e.after!=="")i.after=e.after;else{for(let[_,b]of[["sinceMs",e.sinceMs],["untilMs",e.untilMs]])if(b!==void 0&&(!Number.isSafeInteger(b)||b<=0))throw q(`${_} must be a positive safe integer timestamp`);if(e.sinceMs!==void 0&&e.untilMs!==void 0&&e.untilMs<=e.sinceMs)throw q("untilMs must be after sinceMs");e.sinceMs!==void 0&&(i.sinceMs=e.sinceMs),e.untilMs!==void 0&&(i.untilMs=e.untilMs)}let r=(await this.graphql(Hs,{inboxPath:V(e),input:i})).viewer?.stewardDigestPending;if(!r||!Array.isArray(r.edges))throw E();let a=r.windowSinceMs??0,u=r.windowUntilMs??0;if(!Number.isSafeInteger(a)||!Number.isSafeInteger(u)||a<=0||u<=a)throw E();let c=r.edges.map(_=>_.node),d=r.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();let p=d.endCursor;if(p!=null&&typeof p!="string"||d.hasNextPage&&!p)throw E();let P=d.hasNextPage?p:null;return{items:c,nextCursor:P,windowSinceMs:a,windowUntilMs:u}}async pendingPageWithRetry(e){for(let n=1;n<io;n+=1)try{return await this.pendingPage(e)}catch(i){if(!co(i))throw i}return this.pendingPage(e)}async briefed(e){this.client._requireAuth();let n=e.digestRunId?.trim();if(!n)throw q("a digest run id is required");let i=V(e),s=oo(e.deliveryIds);if(s.length>eo)throw q("legacy briefed accepts at most 100 delivery ids");if((await this.graphql(Ks,{input:{inboxPath:i,deliveryIds:s,digestRunId:n}})).completeStewardBrief?.ok!==!0)throw E();return{ok:!0}}async digestRun(e){this.client._requireAuth();let i=(await this.graphql(Ys,{inboxPath:V(e),digestRunId:Yt(e.digestRunId)})).viewer?.stewardDigestRun;if(!i)throw E();return i}async digestRunPending(e){this.client._requireAuth();let n=V(e),i=Yt(e.digestRunId),s=[],r=new Set,a;for(;;){let c=(await this.graphql(Xs,{inboxPath:n,digestRunId:i,input:{first:100,...a===void 0?{}:{after:a}}})).viewer?.stewardDigestRunPending;if(!c||!Array.isArray(c.edges))throw E();let d=c.pageInfo;if(!d||typeof d.hasNextPage!="boolean")throw E();for(let P of c.edges){if(!P?.node)throw E();s.push(P.node)}if(!d.hasNextPage)break;let p=d.endCursor;if(typeof p!="string"||p===""||r.has(p))throw E();r.add(p),a=p}return s}async sendDigestRun(e){this.client._requireAuth();let n=zt(e.deliveryIds??[]);if(n.length>to)throw q("durable Daily Brief accepts at most 10000 delivery ids");if(e.body!==void 0&&e.body.trim()==="")throw q("a message body must be non-blank when provided");let s=(await this.graphql(zs,{input:{inboxPath:V(e),digestRunId:Yt(e.digestRunId),deliveryIds:n,...e.body===void 0?{}:{body:e.body}}})).publishStewardDailyBrief?.run;if(!s)throw E();return s}async graphql(e,n){let i=await this.client._request("POST","/query",{body:{query:e,variables:n}});if(!i||typeof i!="object")throw E();if(i.errors?.length){let s=i.errors.map(u=>u.extensions?.code),r=new Set(s).size===1&&typeof s[0]=="string"?s[0]:void 0,a=r?Bs[r]:void 0;throw new l(r!==void 0&&a!==void 0?r:"GRAPHQL_ERROR",i.errors.map(u=>u.message).filter(u=>typeof u=="string").join("; ")||"GraphQL request failed",a??502,{errors:i.errors})}if(!i.data)throw E();return i.data}};function H(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(H,"isRecord");function S(t){return typeof t=="string"&&t.trim()!==""?t:void 0}o(S,"stringValue");function yt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}o(yt,"numberValue");function wt(t){return t===void 0?void 0:t.trim().toUpperCase()}o(wt,"upper");function Ii(t){return t.split("_")}o(Ii,"pairParts");function lo(t,e){let n=t?.toLowerCase();return n?.includes("spot")?"spot":n?.includes("perp")?"perp":n?.includes("option")?"option":Ii(e)[1]?.toLowerCase()??""}o(lo,"inferInstrumentType");function po(t){if(t===void 0)return;let e=t.split("-")[0]?.trim().toLowerCase();return e&&e!==t.toLowerCase()?e:void 0}o(po,"inferUnderlyingType");function vi(t,e){let n=S(t.trading_pair)??S(t.tradingPair)??S(t.symbol);if(n===void 0)return;let i=S(t.type),s=Ii(n),r=S(t.base)??e??(s.length>=4?s.slice(2,-1).join("_"):s.length===3?s[2]:n),a=S(t.market)??S(t.exchange)??s[0]??"",u=S(t.quote)??s[s.length-1]??"",c=S(t.instrument_type)??S(t.instrumentType)??lo(i,n),d=S(t.underlying_type)??S(t.underlyingType)??po(i);return{symbol:r,tradingPair:n,market:a,instrumentType:c,...d===void 0?{}:{underlyingType:d},quote:u,...i===void 0?{}:{type:i},...S(t.description)===void 0?{}:{description:S(t.description)},...yt(t.fee_rate)===void 0?yt(t.feeRate)===void 0?{}:{feeRate:yt(t.feeRate)}:{feeRate:yt(t.fee_rate)},...S(t.symbol_icon_url)===void 0?S(t.symbolIconUrl)===void 0?{}:{symbolIconUrl:S(t.symbolIconUrl)}:{symbolIconUrl:S(t.symbol_icon_url)}}}o(vi,"normalizeCandidate");function ho(t){if(!H(t))return[];let e=t.trading_pairs;if(Array.isArray(e))return e.flatMap(s=>H(s)?[vi(s)].filter(r=>r!==void 0):[]);let n=t.data;if(!Array.isArray(n))return[];let i=[];for(let s of n){if(!H(s))continue;let r=S(s.symbol),a=s.trading_pairs;if(Array.isArray(a)){for(let u of a)if(!(!H(u)||!Array.isArray(u.pairs)))for(let c of u.pairs){if(!H(c))continue;let d=vi({...c,instrument_type:c.instrument_type??u.instrument_type},r);d!==void 0&&i.push(d)}}}return i}o(ho,"flattenResponse");function fo(t,e){let n=e.trim();return t.tradingPair===n?!0:wt(t.symbol)===wt(n)}o(fo,"matchesQuery");function bt(t,e){return e===void 0||wt(t)===wt(e)}o(bt,"matchesFilter");function mo(t){let e=new Set;return t.filter(n=>e.has(n.tradingPair)?!1:(e.add(n.tradingPair),!0))}o(mo,"dedupe");function go(t){let e=H(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}}o(go,"resolveFilters");function yo(t,e){let n=t.split("_"),i=n[0],s=n[1],r=n.length>=4?n.slice(2,-1).join("_"):n.length===3?n[2]:void 0,a=n.at(-1);return!i||!s||!r||!a?{symbol:t,...e}:{symbol:r,market:e.market??i,instrumentType:e.instrumentType??s,underlyingType:e.underlyingType,quote:e.quote??a}}o(yo,"pairSearchParams");var pe=class{constructor(e){this.client=e}client;static{o(this,"TradingPairsResource")}async search(e){this.client._requireAuth();let n=H(e)?e.symbol:void 0,i=typeof n=="string"?n.trim():"";if(!i)throw new l("INVALID_ARGUMENT","symbol is required",400);let s=await this.client._request("GET","/api/v1/trading-pairs/search",{query:{q:i,strict:!0}}),r=mo(ho(s)).filter(u=>fo(u,i)).filter(u=>bt(u.market,e.market)).filter(u=>bt(u.instrumentType,e.instrumentType)).filter(u=>bt(u.underlyingType,e.underlyingType)).filter(u=>bt(u.quote,e.quote)),a=e.limit;return a!==void 0&&r.length>a?{query:i,candidates:r.slice(0,a),truncated:!0}:{query:i,candidates:r}}async resolve(e){let n=H(e)?e:{},i=typeof n.pair=="string"?n.pair.trim():void 0,s=go(e),r=i===void 0?{symbol:typeof n.symbol=="string"?n.symbol:"",...s}:yo(i,s),a=await this.search(r),u=i===void 0?a.candidates:a.candidates.filter(c=>c.tradingPair===i);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 "${i??r.symbol}"`:`multiple canonical trading pairs matched "${r.symbol}"`,u.length===0?404:409,{query:i??r.symbol,candidateCount:u.length,candidates:u.slice(0,50),...u.length>50?{truncated:!0}:{}});return u[0]}};var bo=`mutation CreateCompanyNews($input: CompanyNewsFeedInput!) {
|
|
402
402
|
companyNews {
|
|
403
403
|
createFeed(input: $input) { id producer { id } }
|
|
404
404
|
}
|
|
405
|
-
}`,wo={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 Po(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 i=t[e];if(i!==void 0&&(!Number.isInteger(i)||i<0||i>n))throw new l("INVALID_ARGUMENT",`${e} must be an integer from 0 to ${n} (0 selects the default)`,400)}}o(Po,"validateCompanyNewsCreateParams");var he=class{constructor(e){this.client=e}client;static{o(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),Po(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}},i=await this.client._request("POST","/query",{body:{query:bo,variables:{input:n}}});if(Array.isArray(i?.errors)&&i.errors.length>0){let a=i.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,i.errors.map(c=>c?.message).filter(Boolean).join("; ")||"Company News creation failed",wo[u]??502,{errors:i.errors})}let s=i?.data?.companyNews?.createFeed,r={feed_id:s?.id,cronjob_id:s?.producer?.id};if(typeof r!="object"||r===null||!("feed_id"in r)||!
|
|
405
|
+
}`,wo={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 Po(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 i=t[e];if(i!==void 0&&(!Number.isInteger(i)||i<0||i>n))throw new l("INVALID_ARGUMENT",`${e} must be an integer from 0 to ${n} (0 selects the default)`,400)}}o(Po,"validateCompanyNewsCreateParams");var he=class{constructor(e){this.client=e}client;static{o(this,"CompanyNewsResource")}async create(e){this.client._requireAuth(),Po(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}},i=await this.client._request("POST","/query",{body:{query:bo,variables:{input:n}}});if(Array.isArray(i?.errors)&&i.errors.length>0){let a=i.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,i.errors.map(c=>c?.message).filter(Boolean).join("; ")||"Company News creation failed",wo[u]??502,{errors:i.errors})}let s=i?.data?.companyNews?.createFeed,r={feed_id:s?.id,cronjob_id:s?.producer?.id};if(typeof r!="object"||r===null||!("feed_id"in r)||!Ci(r.feed_id)||!("cronjob_id"in r)||!Ci(r.cronjob_id))throw new l("INVALID_RESPONSE","company news response must contain decimal int64 feed_id and cronjob_id strings",502);return{feed_id:r.feed_id,cronjob_id:r.cronjob_id}}};function Ci(t){return typeof t=="string"&&t.trim()===t&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n}o(Ci,"validID");var _o="https://api-llm.prd.alva.ai",To="https://data-tools.prd.space.id";function Jt(t){return typeof t=="object"&&t!==null}o(Jt,"isRecord");function Pt(t,e){if(!Jt(t))return;let n=t[e];return typeof n=="string"&&n?n:void 0}o(Pt,"stringField");function Ro(t){if(t==null)return{};let e={};if(t instanceof Error){t.name&&(e.name=t.name),t.message&&(e.message=t.message);let i=Pt(t,"code");i&&(e.code=i)}else if(Jt(t)){let i=Pt(t,"code"),s=Pt(t,"name"),r=Pt(t,"message");i&&(e.code=i),s&&(e.name=s),r&&(e.message=r)}else e.message=String(t);let n=[e.code,e.name,e.message].filter(i=>!!i);return{message:n.length>0?n.join(": "):void 0,details:Object.keys(e).length>0?e:void 0}}o(Ro,"describeCause");function So(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:i,details:s}=Ro(Jt(t)?t.cause:void 0);return s&&(n.cause=s),{message:i?`${e}; cause: ${i}`:e,details:n}}o(So,"describeFetchFailure");var _t=class{static{o(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;_follows;_alerts;_channelGroupSubscriptions;_feedback;_functions;_credits;_markets;_schedules;_steward;_tradingPairs;_theses;_companyNews;constructor(e){this.baseUrl=e.baseUrl??_o,this.arraysBaseUrl=e.arraysBaseUrl??To,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 Oe(this)}get run(){return this._run??=new Ge(this)}get deploy(){return this._deploy??=new Me(this)}get serviceAccount(){return this._serviceAccount??=new $e(this)}get release(){return this._release??=new je(this)}get feed(){return this._feed??=new We(this)}get automation(){return this._automation??=new re(this)}get playbooks(){return this._playbooks??=new Ke(this)}get secrets(){return this._secrets??=new Ye(this)}get sdk(){return this._sdk??=new Xe(this)}get dataSkills(){return this._dataSkills??=new ze(this)}get playbookSkills(){return this._playbookSkills??=new Je(this)}get comments(){return this._comments??=new Ze(this)}get remix(){return this._remix??=new et(this)}get screenshot(){return this._screenshot??=new tt(this)}get user(){return this._user??=new nt(this)}get trading(){return this._trading??=new it(this)}get portfolio(){return this._portfolio??=new rt(this)}get arraysJwt(){return this._arraysJwt??=new st(this)}get notifications(){return this._notifications??=new ot(this)}get notificationPreferences(){return this._notificationPreferences??=new at(this)}get subscriptions(){return this._subscriptions??=new ut(this)}get follows(){return this._follows??=new ae(this)}get alerts(){return this._alerts??=new ue(this)}get channelGroupSubscriptions(){return this._channelGroupSubscriptions??=new pt(this)}get feedback(){return this._feedback??=new ht(this)}get functions(){return this._functions??=new ft(this)}get credits(){return this._credits??=new mt(this)}get markets(){return this._markets??=new ce(this)}get tradingPairs(){return this._tradingPairs??=new pe(this)}get schedules(){return this._schedules??=new le(this)}get steward(){return this._steward??=new de(this)}get theses(){return this._theses??=new oe(this)}get companyNews(){return this._companyNews??=new he(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 ee(this)}get forYou(){return this._forYou??=new ie(this)}async _request(e,n,i){let r=`${i?.baseUrl??this.baseUrl}${n}`;if(i?.query){let O=new URLSearchParams;for(let[j,Tt]of Object.entries(i.query))Tt!=null&&O.set(j,String(Tt));let X=O.toString();X&&(r+=`?${X}`)}let a={};i?.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&&!i?.noAuth&&(a["X-Alva-Origin-Session-Id"]=this.originSessionId);let u;i?.rawBody!==void 0?(a["Content-Type"]="application/octet-stream",u=i.rawBody):i?.jsonBody!==void 0?(a["Content-Type"]="application/json",u=i.jsonBody):i?.body!==void 0&&(a["Content-Type"]="application/json",u=JSON.stringify(i.body));let c,d=i?.timeoutMs,p=i?.signal??this.signal;if(p?.aborted)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});let P=d!==void 0?new AbortController:void 0,_=!1,b,Ne;P&&d!==void 0&&(p&&(Ne=o(()=>P.abort(p.reason),"abortListener"),p.addEventListener("abort",Ne,{once:!0})),b=setTimeout(()=>{_=!0,P.abort(new Error(`Request timed out after ${d}ms while calling ${e} ${n}`))},d));let Zt={method:e,headers:a,body:u,signal:P?.signal??p};d!==void 0&&(Zt.timeout=d);try{c=await fetch(r,Zt)}catch(O){if(p?.aborted&&!_)throw new l("NETWORK_ABORTED",`Request aborted while calling ${e} ${n}`,0,{method:e,path:n});if(_)throw new l("NETWORK_TIMEOUT",`Request timed out after ${d}ms while calling ${e} ${n}`,0,{method:e,path:n,timeout_ms:d});let X=So(O);throw new l("NETWORK_ERROR",X.message,0,{method:e,path:n,...X.details})}finally{Ne&&p&&p.removeEventListener("abort",Ne),b!==void 0&&clearTimeout(b)}if(!c.ok){let O="";try{O=await Promise.resolve(c.text())}catch{O=""}if((c.headers.get("content-type")??"").includes("application/json")&&O)try{let j=JSON.parse(O);if(j.error)throw new l(j.error.code??"UNKNOWN",j.error.message??`HTTP ${c.status}`,c.status,j.details)}catch(j){if(j instanceof l)throw j}throw new l("UNKNOWN",`HTTP ${c.status}: ${O.slice(0,200)}`,c.status)}if(c.status===204)return;let en=(c.headers.get("content-type")??"").toLowerCase();return en.includes("application/json")||en.includes("+json")?c.json():c.arrayBuffer()}};var ko="0.38.0-beta.2";vt();return Fi(Eo);})();
|
|
406
406
|
//# sourceMappingURL=browser.global.js.map
|