@trayai/helix-sdk 0.83.0 → 0.84.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,14 @@ general availability, minor versions may include breaking changes.
|
|
|
9
9
|
The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
|
|
10
10
|
released together and share a version — install matching versions.
|
|
11
11
|
|
|
12
|
+
## 0.83.0
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- Internal configuration update pointing the Tray dashboard host at
|
|
17
|
+
`app.helix.tray.ai`, surfaced by the Helix CLI's post-deploy dashboard link. No
|
|
18
|
+
changes to the SDK's public API.
|
|
19
|
+
|
|
12
20
|
## 0.80.0
|
|
13
21
|
|
|
14
22
|
### Changed
|
package/dist/broker/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n,o as s,p as i,q as a}from"../chunk-
|
|
1
|
+
import{n,o as s,p as i,q as a}from"../chunk-H4L4UWIK.js";import p from"ky";var d=6e4;async function l(e){let u=n({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),k=s(e.env),r=await p.post(`${k}/broker/http/dev`,{json:u,headers:{Authorization:`Bearer ${e.devToken}`,Accept:"application/json"},throwHttpErrors:!1,timeout:e.timeoutMs??d}),t;if((r.headers.get("content-type")??"").includes("application/json")?t=await r.json():t=await r.text(),r.status<200||r.status>=300)return{kind:"brokerError",brokerStatus:r.status,body:t};let o=i.safeParse(t);return o.success?{kind:"upstream",upstream:a(o.data)}:{kind:"brokerError",brokerStatus:r.status,body:t}}export{l as callBrokerDev};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as D,l as c,n as z,o as oe,p as Qe,q as Ze}from"./chunk-
|
|
1
|
+
import{d as D,l as c,n as z,o as oe,p as Qe,q as Ze}from"./chunk-H4L4UWIK.js";var R="X-Helix-Project-Execution-Token",F="X-Tray-Token",pr={mode:"dev",deploymentId:null},Pe={...pr},O={};function mo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(O.internalJwt=t),"helixExecutionJwt"in e&&(O.helixExecutionJwt=r),"devToken"in e&&(O.devToken=n),Pe={...Pe,...o}}function w(){return Pe}function _(){return O.internalJwt}function T(){return O.helixExecutionJwt}function et(){return O.devToken}var go="tray-config-bridge",ie=null;function yo(e){ie=e}function b(){if(!ie)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ie}function ho(){ie=null}import{AsyncLocalStorage as St}from"async_hooks";import{trace as kr,SpanKind as Ir,SpanStatusCode as Ie}from"@opentelemetry/api";import{ExportResultCode as Ar,W3CTraceContextPropagator as Dr}from"@opentelemetry/core";import{NodeTracerProvider as Or,SimpleSpanProcessor as Fr,BatchSpanProcessor as _r}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as gr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as yr}from"@opentelemetry/exporter-logs-otlp-proto";function Ce(e){return D(e).hosts.ingest}function hr(){return T()??""}function tt(){return{[R]:hr()}}function rt(){let e=Ce(b().env);return new gr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(tt())})}function nt(){let e=Ce(b().env);return new yr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(tt())})}import{logs as st,SeverityNumber as se}from"@opentelemetry/api-logs";import{LoggerProvider as Sr,BatchLogRecordProcessor as Er}from"@opentelemetry/sdk-logs";function J(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function wr(e){return new TextEncoder().encode(e).length}var ot="\u2026[truncated]",br=wr(ot),q=4096;function k(e,t=q){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-br);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+ot}function g(e,t=q){return k(J(e),t)}var xr="@trayai/helix-sdk",Y,it={debug:{number:se.DEBUG,text:"DEBUG"},info:{number:se.INFO,text:"INFO"},warn:{number:se.WARN,text:"WARN"},error:{number:se.ERROR,text:"ERROR"}};function vr(){return w().mode==="lambda"?[new Er({exporter:nt()})]:[]}function at(){if(Y!==void 0)return;let e=vr();e.length!==0&&(Y=new Sr({processors:e}),st.setGlobalLoggerProvider(Y))}function Rr(e,t,r){let n=it[e]??it.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function ct(e,t,r){st.getLogger(xr).emit(Rr(e,t,r))}async function lt(e=2e3){if(Y===void 0)return;let t;try{await Promise.race([Y.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
|
|
2
2
|
`)}finally{t!==void 0&&clearTimeout(t)}}function ke(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Tr(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function S(e,t){return Tr()?`\x1B[${e}m${t}\x1B[0m`:t}var Pr=5,Cr={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},ut="32",dt="31",ae="2",ft="1";function ce(e){return S(Cr[e]??"0",e.padEnd(Pr))}function mt(e,t){return`${ce("FN")} ${S(ft,`${e} ${t}`.trim())}`}function pt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${S(ae,n)} `:""}${ce(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${S(ae,J(r))}`),s}function gt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function yt(e){return`${ce("AUTH")} ${e}`}function ht(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=S(o==="error"?dt:ut,i);return`${ce("API")} ${e} ${t} \u2192 ${s} ${S(ae,`${n}ms`)}`}function wt(e,t,r){let n=t?dt:ut,o=S(n,"\u25CF"),i=S(n,t?"error":"success");return`${o} ${S(ft,e)} ${i} ${S(ae,`${r}ms`)}`}function B(e){try{process.stdout.write(e+`
|
|
3
3
|
`)}catch{}}var Et=new St,Br=new St;function E(e){let t=Br.getStore();t&&(t[e]=!0)}var Lr=/^[0-9a-f]{32}$/;function Nr(e){let t=e.replace(/-/g,"").toLowerCase();return Lr.test(t)?t:null}var jr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},L=new Map;function xt(e,t,r){let n=L.get(e);n?n[t]=r:L.set(e,{[t]:r})}function v(e,t,r){e.setAttribute(t,g(r))}var X;function bt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function Mr(e){return Math.round(e[0]*1e3+e[1]/1e6)}function vt(e){try{process.stdout.write(J(e)+`
|
|
4
4
|
`)}catch{}}var Ae=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=L.get(o),s={...n.attributes};if(i!==void 0){for(let[u,f]of Object.entries(i))typeof f=="string"?s[u]=k(f):typeof f=="object"&&f!==null?s[u]=g(f):s[u]=f;L.delete(o)}let a=Et.getStore(),l=a?Nr(a):null;vt({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:bt(n.startTime),endTimeUnixNano:bt(n.endTime),attributes:s,status:{code:jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:k(n.status.message)}:{}}})}r({code:Ar.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},De=class{onStart(t,r){}onEnd(t){L.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Oe=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&B(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var b=new Set(["production"]),i=new Map,m={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};i.set(m.name,m);var v=["api","broker","ingest","weaver","app","projectHost","dashboard"],y=["auth"],h=["storePrefix","appUrl","cookieName","cookieDomain"];function w(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let r of v)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string`);for(let r of y){let n=e.hosts[r];if(n!==void 0&&(typeof n!="string"||!n))throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string when set`)}for(let r of h)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`EnvironmentProfile.login.${r} must be a non-empty string`)}function x(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&v.every(n=>e.hosts[n]===r.hosts[n])&&y.every(n=>e.hosts[n]===r.hosts[n])&&h.every(n=>e.login[n]===r.login[n])}function j(e){w(e);let r=i.get(e.name);if(r){if(x(r,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let n of i.values())if(n.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${n.name}"`);i.set(e.name,e)}function S(e){return i.has(e)}function A(e){return i.get(e)}function _(e){let r=i.get(e);if(!r)throw new Error(`Unknown environment: ${e}`);return r}function F(){return[...i.keys()]}function T(){return[...i.values()].map(e=>e.exposedName)}function R(e){for(let r of i.values())if(r.exposedName===e)return r.name}var g=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function N(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[g];return}let n=e.trim(),o=R(n);if(o){r[g]=o;return}if(S(n)){r[g]=n;return}throw new Error(`Unknown environment: ${n}`)}function H(){return globalThis[g]}function V(){return[...i.values()].filter(e=>!b.has(e.name))}function L(){N(void 0),i.clear(),i.set(m.name,{...m,hosts:{...m.hosts},login:{...m.login}})}var f=class e extends Error{detail;constructor(r){super(P(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,o){return new e({kind:"broker_error",status:r,message:n,body:o})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,o){return new e({kind:"kv_call_failed",status:r,message:n,body:o})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,o){return new e({kind:"files_call_failed",status:r,message:n,body:o})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function O(e){return e instanceof f}function P(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}var B=new Set(["proxy-authorization","x-tray-token"]);function q(e){let r=e.toLowerCase();return B.has(r)||r.startsWith("x-tray-internal-")}function $(e){let r;return e instanceof Headers?r=Array.from(e.entries()):Array.isArray(e)?r=e:r=Object.entries(e),r.filter(([n])=>!q(n)).map(([n,o])=>({name:n,value:o}))}function I(e){return typeof e=="string"?"string":e instanceof Blob?"Blob":e instanceof FormData?"FormData":e instanceof ArrayBuffer?"ArrayBuffer":e instanceof Uint8Array?"Uint8Array":typeof ReadableStream<"u"&&e instanceof ReadableStream?"ReadableStream":null}function z(e){let r=new URL(e.url);if(r.protocol!=="https:")throw f.unsupportedScheme(r.protocol.replace(/:$/,""));let n=e.body!==void 0&&e.body!==null?I(e.body):null;if(n!==null)throw f.unsupportedBodyType(n);let o=r.host,a=r.pathname,s=[];for(let[c,d]of r.searchParams.entries())s.push({name:c,value:d});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[c,d]of e.query.entries())s.push({name:c,value:d});else for(let[c,d]of Object.entries(e.query))if(Array.isArray(d))for(let E of d)s.push({name:c,value:E});else s.push({name:c,value:d});let l=e.headers!==void 0?$(e.headers):[],u=e.body!==void 0&&e.body!==null?{host:o,method:e.method,path:a,body:e.body,headers:l,queryParams:s}:{host:o,method:e.method,path:a,headers:l,queryParams:s};return{authenticationId:e.authenticationId,httpRequest:u}}function M(e){return _(e).hosts.broker}import{z as t}from"zod";var k=t.object({name:t.string(),value:t.string()}),D=t.object({host:t.string(),method:t.string(),path:t.string().startsWith("/"),body:t.record(t.unknown()).optional(),headers:t.array(k),queryParams:t.array(k)}),J=t.object({authenticationId:t.string().uuid(),httpRequest:D}),X=t.object({httpResponse:t.object({status:t.number(),body:t.unknown().optional(),headers:t.array(k)})});function ee(e){let{status:r,body:n,headers:o}=e.httpResponse,a={};for(let{name:s,value:l}of o){let p=s.toLowerCase(),u=a[p];u===void 0?a[p]=l:Array.isArray(u)?u.push(l):a[p]=[u,l]}return{status:r,body:n,headers:a}}export{j as a,S as b,A as c,_ as d,F as e,T as f,R as g,N as h,H as i,V as j,L as k,f as l,O as m,z as n,M as o,X as p,ee as q};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as B,b as me}from"./chunk-L6J5L3JQ.js";import{A as Ce,B as ve,b as T,g as U,h as I,i as N,j as C,k as q,l as M,m as $,n as Z,o as ge,p as K,q as z,r as G,s as J,t as Q,x as X,y as he,z as ye}from"./chunk-OFYGDNQP.js";import{b as H,e as A,i as W,l as g,m as V}from"./chunk-4ZB2OBBJ.js";import{randomUUID as _e}from"crypto";import{SpanStatusCode as ne,SpanKind as Re}from"@opentelemetry/api";import{defineEventHandler as Pe,getMethod as Le,getRequestURL as Fe,getHeaders as se,getHeader as oe}from"h3";import{readBody as we,getQuery as Ee,getRouterParams as ke}from"h3";async function Y(e,t){let r=await Se(e),n=Ee(e),o=ke(e)??{},s={...n,...r,...o};return t?xe(s,t):s}async function Se(e){try{let t=await we(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function xe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var v=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function ee(e){return t=>{e.node.res.statusCode=t}}function te(){return(e,t)=>{throw new v(e,t)}}function re(e,t){let{statusCode:r,message:n}=Te(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Te(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Ie=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function be(e){return e.toLowerCase().includes("tray_lid")}function b(e){let t={};for(let[r,n]of Object.entries(e))if(!Ie.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let a=s.split("=")[0].trim();return!be(a)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function je(e,t){let{inputSchema:r,outputSchema:n}=Ue(t),o=e;return Pe(async s=>{let a=T(),{executionId:i,userId:c,deploymentId:f}=Ne(a,s),p=Date.now(),y=new Date().toISOString(),m=Le(s),l=Fe(s).pathname,u=z(),h=K(),E=`${m} ${l}`;q();let O={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return De(()=>I.run(O,()=>U.run(i,async()=>{let k=await Oe(s,r);if(!k.ok)return{response:k.response,errored:!1,errorMessage:null};let pe=Me(s,k.input,u,h,m,l,i,f,c);return He(o,pe,n,s,h,i,f,{method:m,path:l,rawInput:k.input})})),{executionId:i,deploymentId:f,routeOrJob:E,startedAt:y,startMs:p,userId:c,flags:O})})}async function De(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Z({...t,errored:r,errorMessage:n}),await M()}}async function Oe(e,t){try{return{ok:!0,input:await Y(e,t)}}catch(r){let n=qe(e,r);if(n)return{ok:!1,response:n};throw r}}async function He(e,t,r,n,o,s,a,i){return $.startActiveSpan("function",{root:!0,kind:Re.SERVER,attributes:{method:i.method,route:i.path,executionId:s,...a?{deploymentId:a}:{}}},async c=>{t.traceId=c.spanContext().traceId;let f=b(se(n));C(c,"input",i.rawInput),C(c,"request",{method:i.method,path:i.path,headers:f,body:i.rawInput});let p=!1,y=null,m,l;try{let u=await B.run(t,()=>e(t));if(m=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let h=r.safeParse(u);if(!h.success){let E=Object.keys(h.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:E,executionId:s}),g.outputValidationFailed(E)}l=h.data}else l=u}catch(u){p=!0,y=u instanceof Error?u.message:String(u),N("hasError"),l=Ae(u,n,o,s)}finally{We(c,n,{errored:p,errorMessage:y,handlerResult:m,response:l})}return{response:l,errored:p,errorMessage:y}})}function Ae(e,t,r,n){if(e instanceof v)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(V(e))return re(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function We(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&C(e,"output",r.handlerResult),C(e,"response",r.response);let n=I.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ne.ERROR:ne.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Ue(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ne(e,t){let r=e.mode==="lambda",n=(r?e.executionId:oe(t,"x-tray-execution-id"))??_e(),o=(r?e.userId:oe(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function qe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Me(e,t,r,n,o,s,a,i,c){return{input:t,method:o,path:s,headers:b(se(e)),http:G(),db:f=>J(f),kv:()=>Q(),files:()=>X(),log:n,config:r,status:ee(e),error:te(),state:{},request:e,executionId:a,deploymentId:i,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function $e(e){return e}import{resolve as _}from"path";import{existsSync as ae}from"fs";import{loadConfig as Ke}from"c12";import{z as d}from"zod";import{z as Ze}from"zod";var Be=["production"],S=Ze.string().refine(e=>H(e),e=>({message:`Invalid enum value. Expected ${A().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var R=d.string().uuid("projectId must be a valid UUID"),P=d.string().min(1,"workspaceId must be a non-empty string"),ze=d.object({name:d.string().min(1,"name is required"),projectId:R.optional(),workspaceId:P.optional(),env:S.default("production"),authentications:d.record(d.string()).optional().default({}),config:d.record(d.unknown()).optional().default({})}),ie=d.object({name:d.string().min(1,"name is required"),workspaceId:P.optional(),env:S,authentications:d.record(d.string()),config:d.record(d.unknown())}),Ve=d.discriminatedUnion("kind",[ie.extend({kind:d.literal("provisioned"),projectId:R}),ie.extend({kind:d.literal("unprovisioned")})]),de=["helix","tray"],ce=["ts","mts","cts","js","mjs","cjs"];function x(e){for(let t of de)for(let r of ce){let n=_(e,`${t}.config.${r}`);if(ae(n))return n}}function Ge(e){for(let t of de)if(ce.some(r=>ae(_(e,`${t}.config.${r}`))))return t;return"helix"}function L(e){return{name:Ge(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function F(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=ze.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...s}=r.data,a=o!==void 0?{workspaceId:o}:{},i=W(),c=i!==void 0?{...s,env:i}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...a}:{kind:"unprovisioned",...c,...a}}async function w(e){let t=e??process.cwd(),r;try{r=await Ke(L(t))}catch(o){throw g.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??x(t);if(!n)throw g.configLoadFailed(`helix.config.ts not found at ${_(t,"helix.config.ts")}`);return F(r.config,n)}var ue="WORKSPACE_ID_REQUIRED";function Je(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ue});return e.workspaceId}import{existsSync as Qe,watch as Xe,writeSync as Ye}from"fs";import{join as et,resolve as tt}from"path";import{watchConfig as rt}from"c12";function nt(e,t){let r=e instanceof Error?e.message:String(e);Ye(2,`[helix-watch] ${t.phase} error: ${r}
|
|
1
|
+
import{a as B,b as me}from"./chunk-L6J5L3JQ.js";import{A as Ce,B as ve,b as T,g as U,h as I,i as N,j as C,k as q,l as M,m as $,n as Z,o as ge,p as K,q as z,r as G,s as J,t as Q,x as X,y as he,z as ye}from"./chunk-3SDUCOAT.js";import{b as H,e as A,i as W,l as g,m as V}from"./chunk-H4L4UWIK.js";import{randomUUID as _e}from"crypto";import{SpanStatusCode as ne,SpanKind as Re}from"@opentelemetry/api";import{defineEventHandler as Pe,getMethod as Le,getRequestURL as Fe,getHeaders as se,getHeader as oe}from"h3";import{readBody as we,getQuery as Ee,getRouterParams as ke}from"h3";async function Y(e,t){let r=await Se(e),n=Ee(e),o=ke(e)??{},s={...n,...r,...o};return t?xe(s,t):s}async function Se(e){try{let t=await we(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function xe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var v=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function ee(e){return t=>{e.node.res.statusCode=t}}function te(){return(e,t)=>{throw new v(e,t)}}function re(e,t){let{statusCode:r,message:n}=Te(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Te(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Ie=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function be(e){return e.toLowerCase().includes("tray_lid")}function b(e){let t={};for(let[r,n]of Object.entries(e))if(!Ie.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let a=s.split("=")[0].trim();return!be(a)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function je(e,t){let{inputSchema:r,outputSchema:n}=Ue(t),o=e;return Pe(async s=>{let a=T(),{executionId:i,userId:c,deploymentId:f}=Ne(a,s),p=Date.now(),y=new Date().toISOString(),m=Le(s),l=Fe(s).pathname,u=z(),h=K(),E=`${m} ${l}`;q();let O={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return De(()=>I.run(O,()=>U.run(i,async()=>{let k=await Oe(s,r);if(!k.ok)return{response:k.response,errored:!1,errorMessage:null};let pe=Me(s,k.input,u,h,m,l,i,f,c);return He(o,pe,n,s,h,i,f,{method:m,path:l,rawInput:k.input})})),{executionId:i,deploymentId:f,routeOrJob:E,startedAt:y,startMs:p,userId:c,flags:O})})}async function De(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Z({...t,errored:r,errorMessage:n}),await M()}}async function Oe(e,t){try{return{ok:!0,input:await Y(e,t)}}catch(r){let n=qe(e,r);if(n)return{ok:!1,response:n};throw r}}async function He(e,t,r,n,o,s,a,i){return $.startActiveSpan("function",{root:!0,kind:Re.SERVER,attributes:{method:i.method,route:i.path,executionId:s,...a?{deploymentId:a}:{}}},async c=>{t.traceId=c.spanContext().traceId;let f=b(se(n));C(c,"input",i.rawInput),C(c,"request",{method:i.method,path:i.path,headers:f,body:i.rawInput});let p=!1,y=null,m,l;try{let u=await B.run(t,()=>e(t));if(m=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let h=r.safeParse(u);if(!h.success){let E=Object.keys(h.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:E,executionId:s}),g.outputValidationFailed(E)}l=h.data}else l=u}catch(u){p=!0,y=u instanceof Error?u.message:String(u),N("hasError"),l=Ae(u,n,o,s)}finally{We(c,n,{errored:p,errorMessage:y,handlerResult:m,response:l})}return{response:l,errored:p,errorMessage:y}})}function Ae(e,t,r,n){if(e instanceof v)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(V(e))return re(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function We(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&C(e,"output",r.handlerResult),C(e,"response",r.response);let n=I.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ne.ERROR:ne.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Ue(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ne(e,t){let r=e.mode==="lambda",n=(r?e.executionId:oe(t,"x-tray-execution-id"))??_e(),o=(r?e.userId:oe(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function qe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Me(e,t,r,n,o,s,a,i,c){return{input:t,method:o,path:s,headers:b(se(e)),http:G(),db:f=>J(f),kv:()=>Q(),files:()=>X(),log:n,config:r,status:ee(e),error:te(),state:{},request:e,executionId:a,deploymentId:i,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function $e(e){return e}import{resolve as _}from"path";import{existsSync as ae}from"fs";import{loadConfig as Ke}from"c12";import{z as d}from"zod";import{z as Ze}from"zod";var Be=["production"],S=Ze.string().refine(e=>H(e),e=>({message:`Invalid enum value. Expected ${A().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var R=d.string().uuid("projectId must be a valid UUID"),P=d.string().min(1,"workspaceId must be a non-empty string"),ze=d.object({name:d.string().min(1,"name is required"),projectId:R.optional(),workspaceId:P.optional(),env:S.default("production"),authentications:d.record(d.string()).optional().default({}),config:d.record(d.unknown()).optional().default({})}),ie=d.object({name:d.string().min(1,"name is required"),workspaceId:P.optional(),env:S,authentications:d.record(d.string()),config:d.record(d.unknown())}),Ve=d.discriminatedUnion("kind",[ie.extend({kind:d.literal("provisioned"),projectId:R}),ie.extend({kind:d.literal("unprovisioned")})]),de=["helix","tray"],ce=["ts","mts","cts","js","mjs","cjs"];function x(e){for(let t of de)for(let r of ce){let n=_(e,`${t}.config.${r}`);if(ae(n))return n}}function Ge(e){for(let t of de)if(ce.some(r=>ae(_(e,`${t}.config.${r}`))))return t;return"helix"}function L(e){return{name:Ge(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function F(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=ze.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...s}=r.data,a=o!==void 0?{workspaceId:o}:{},i=W(),c=i!==void 0?{...s,env:i}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...a}:{kind:"unprovisioned",...c,...a}}async function w(e){let t=e??process.cwd(),r;try{r=await Ke(L(t))}catch(o){throw g.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??x(t);if(!n)throw g.configLoadFailed(`helix.config.ts not found at ${_(t,"helix.config.ts")}`);return F(r.config,n)}var ue="WORKSPACE_ID_REQUIRED";function Je(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ue});return e.workspaceId}import{existsSync as Qe,watch as Xe,writeSync as Ye}from"fs";import{join as et,resolve as tt}from"path";import{watchConfig as rt}from"c12";function nt(e,t){let r=e instanceof Error?e.message:String(e);Ye(2,`[helix-watch] ${t.phase} error: ${r}
|
|
2
2
|
`)}function j(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ot=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,fe=new Set;function le(e){return x(e)!==void 0}async function st(e,t){if(le(e.cwd))try{return{current:await w(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:j(),initialLoadSucceeded:!1}}if(e.watch){let r=tt(e.cwd);fe.has(r)||(process.stderr.write(`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
|
|
3
3
|
`),fe.add(r))}return{current:j(),initialLoadSucceeded:!1}}var D=class{constructor(t,r,n){this.cwd=t;this.onError=r;this.emit=n}cwd;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=rt({...L(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=F(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){try{this.directoryWatcher=Xe(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();ot.test(n)&&Qe(et(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await w(this.cwd)}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function it(e){let t=e.onError??nt,r=new Set,n=await st(e,t),o=n.current;function s(i){o=i;for(let c of[...r])try{c(i)}catch(f){t(f,{phase:"reload"})}}let a=new D(e.cwd,t,s);return e.watch&&a.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!le(e.cwd)){let i=j();return s(i),i}try{let i=await w(e.cwd);return s(i),i}catch(i){return t(i,{phase:"reload"}),o}},subscribe(i){return r.add(i),()=>{r.delete(i)}},async stop(){r.clear(),await a.stop()},ready(){return a.watcherReady()}}}export{Be as ENVIRONMENT_VALUES,he as SCHEDULE_DEFINITION_KIND,ye as ScheduleConfigError,ue as WORKSPACE_ID_REQUIRED_CODE,it as createConfigService,$e as defineConfig,je as defineFunction,Ce as defineSchedule,S as environmentSchema,me as getContext,T as getSdkConfig,ve as isScheduleDefinition,w as loadConfig,Ve as loadedTrayConfigSchema,R as projectIdSchema,Je as requireWorkspaceId,x as resolveConfigFile,ge as runWithinAppSpan,P as workspaceIdSchema};
|
package/dist/internal/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as v,a as H,b as f,c as J,d as L,e as T,f as U,g as m,h,i as p,j as g,k as y,l as S,m as E,n as x,p as A,q as b,r as w,s as I,t as C,u as te,v as re,w as oe,x as D}from"../chunk-
|
|
1
|
+
import{B as v,a as H,b as f,c as J,d as L,e as T,f as U,g as m,h,i as p,j as g,k as y,l as S,m as E,n as x,p as A,q as b,r as w,s as I,t as C,u as te,v as re,w as oe,x as D}from"../chunk-3SDUCOAT.js";import{a as G,b as V,c as _,d as q,e as B,f as z,g as Q,h as W,i as X,j as Y,k as Z,m as ee}from"../chunk-H4L4UWIK.js";import{randomUUID as ne}from"crypto";import{SpanStatusCode as R,SpanKind as se}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function ie(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isRetry!="boolean"||typeof e.isManual!="boolean")throw new t("`isRetry` and `isManual` must be booleans");if(!v(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let P=F("scheduledAt",e.scheduledAt),k=F("firedAt",e.firedAt),d=f(),a=d.executionId??ne(),l=d.deploymentId??null,N=Date.now(),O=new Date().toISOString(),M=b(),j=A();y();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await h.run(i,()=>m.run(a,()=>E.startActiveSpan("schedule",{root:!0,kind:se.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let $={type:"schedule",scheduledAt:P,firedAt:k,isRetry:e.isRetry,isManual:e.isManual},K={http:w(),db:n=>I(n),kv:()=>C(),files:()=>D(),log:j,config:M,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:$};g(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isRetry:e.isRetry,isManual:e.isManual});try{await s.handler(K)}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),p("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?R.ERROR:R.OK,...u?{message:u}:{}}),o.end()}})))}finally{x({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:O,startMs:N,errored:c,errorMessage:u,userId:null,flags:i}),await S()}}function F(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{J as CONFIG_BRIDGE_CHANNEL,t as ScheduleInvocationError,te as assertValidPath,U as clearActiveConfig,re as contentFilePath,T as getActiveConfig,Y as getAdditionalEnvironmentProfiles,_ as getEnvironmentProfile,V as isKnownEnvironment,ee as isSdkError,B as listEnvironmentNames,z as listExposedEnvNames,oe as metaFilePath,Q as parseExposedEnvironment,G as registerEnvironmentProfile,q as requireEnvironmentProfile,Z as resetEnvironmentRegistryForTests,X as resolveForcedEnvironment,ie as runScheduledFunction,L as setActiveConfig,W as setForcedEnvironment,H as setSdkConfig};
|
package/package.json
CHANGED
package/dist/chunk-4ZB2OBBJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var b=new Set(["production"]),i=new Map,m={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://helix.tray.io",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};i.set(m.name,m);var v=["api","broker","ingest","weaver","app","projectHost","dashboard"],y=["auth"],h=["storePrefix","appUrl","cookieName","cookieDomain"];function w(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let r of v)if(typeof e.hosts[r]!="string"||!e.hosts[r])throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string`);for(let r of y){let n=e.hosts[r];if(n!==void 0&&(typeof n!="string"||!n))throw new Error(`EnvironmentProfile.hosts.${r} must be a non-empty string when set`)}for(let r of h)if(typeof e.login[r]!="string"||!e.login[r])throw new Error(`EnvironmentProfile.login.${r} must be a non-empty string`)}function x(e,r){return e.name===r.name&&e.exposedName===r.exposedName&&e.displayName===r.displayName&&v.every(n=>e.hosts[n]===r.hosts[n])&&y.every(n=>e.hosts[n]===r.hosts[n])&&h.every(n=>e.login[n]===r.login[n])}function j(e){w(e);let r=i.get(e.name);if(r){if(x(r,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let n of i.values())if(n.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${n.name}"`);i.set(e.name,e)}function S(e){return i.has(e)}function A(e){return i.get(e)}function _(e){let r=i.get(e);if(!r)throw new Error(`Unknown environment: ${e}`);return r}function F(){return[...i.keys()]}function T(){return[...i.values()].map(e=>e.exposedName)}function R(e){for(let r of i.values())if(r.exposedName===e)return r.name}var p=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function N(e){let r=globalThis;if(e===void 0||e.trim()===""){delete r[p];return}let n=e.trim(),o=R(n);if(o){r[p]=o;return}if(S(n)){r[p]=n;return}throw new Error(`Unknown environment: ${n}`)}function H(){return globalThis[p]}function V(){return[...i.values()].filter(e=>!b.has(e.name))}function L(){N(void 0),i.clear(),i.set(m.name,{...m,hosts:{...m.hosts},login:{...m.login}})}var f=class e extends Error{detail;constructor(r){super(P(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,o){return new e({kind:"broker_error",status:r,message:n,body:o})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,o){return new e({kind:"kv_call_failed",status:r,message:n,body:o})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,o){return new e({kind:"files_call_failed",status:r,message:n,body:o})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function O(e){return e instanceof f}function P(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}var B=new Set(["proxy-authorization","x-tray-token"]);function q(e){let r=e.toLowerCase();return B.has(r)||r.startsWith("x-tray-internal-")}function $(e){let r;return e instanceof Headers?r=Array.from(e.entries()):Array.isArray(e)?r=e:r=Object.entries(e),r.filter(([n])=>!q(n)).map(([n,o])=>({name:n,value:o}))}function I(e){return typeof e=="string"?"string":e instanceof Blob?"Blob":e instanceof FormData?"FormData":e instanceof ArrayBuffer?"ArrayBuffer":e instanceof Uint8Array?"Uint8Array":typeof ReadableStream<"u"&&e instanceof ReadableStream?"ReadableStream":null}function z(e){let r=new URL(e.url);if(r.protocol!=="https:")throw f.unsupportedScheme(r.protocol.replace(/:$/,""));let n=e.body!==void 0&&e.body!==null?I(e.body):null;if(n!==null)throw f.unsupportedBodyType(n);let o=r.host,a=r.pathname,s=[];for(let[c,d]of r.searchParams.entries())s.push({name:c,value:d});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[c,d]of e.query.entries())s.push({name:c,value:d});else for(let[c,d]of Object.entries(e.query))if(Array.isArray(d))for(let E of d)s.push({name:c,value:E});else s.push({name:c,value:d});let l=e.headers!==void 0?$(e.headers):[],u=e.body!==void 0&&e.body!==null?{host:o,method:e.method,path:a,body:e.body,headers:l,queryParams:s}:{host:o,method:e.method,path:a,headers:l,queryParams:s};return{authenticationId:e.authenticationId,httpRequest:u}}function M(e){return _(e).hosts.broker}import{z as t}from"zod";var k=t.object({name:t.string(),value:t.string()}),D=t.object({host:t.string(),method:t.string(),path:t.string().startsWith("/"),body:t.record(t.unknown()).optional(),headers:t.array(k),queryParams:t.array(k)}),J=t.object({authenticationId:t.string().uuid(),httpRequest:D}),X=t.object({httpResponse:t.object({status:t.number(),body:t.unknown().optional(),headers:t.array(k)})});function ee(e){let{status:r,body:n,headers:o}=e.httpResponse,a={};for(let{name:s,value:l}of o){let g=s.toLowerCase(),u=a[g];u===void 0?a[g]=l:Array.isArray(u)?u.push(l):a[g]=[u,l]}return{status:r,body:n,headers:a}}export{j as a,S as b,A as c,_ as d,F as e,T as f,R as g,N as h,H as i,V as j,L as k,f as l,O as m,z as n,M as o,X as p,ee as q};
|