@trayai/helix-sdk 0.82.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
@@ -1 +1 @@
1
- import{a as n,b as s,c as i,d as a}from"../chunk-R56ARJY5.js";import"../chunk-7MAMPE72.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
+ 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};
@@ -0,0 +1,7 @@
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
+ `)}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
+ `)}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
+ `)}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(`
5
+ `+mt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=L.get(n)?.properties;B(pt(String(r.level??"info"),String(r.message??""),o,gt(t.startTime)));break}case"auth":B(yt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;B(ht(String(r.method??""),String(r.host??""),n,Mr(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Fe=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Ur(){let t=[ke()?new Oe:new Fr(new Ae)];return w().mode==="lambda"&&t.push(new Fe(new _r(rt()))),t.push(new De),t}function $r(){X===void 0&&(X=new Or({spanProcessors:Ur()}),X.register({propagator:new Dr}),at())}async function Kr(e=2e3){let t=[lt(e)];X!==void 0&&t.push((async()=>{let r;try{await Promise.race([X.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
+ `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var x=kr.getTracer("@trayai/helix-sdk");function Hr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let f=new Date().toISOString(),d=Date.now()-i;if(ke()){B(`
7
+ `+wt(n,s,d));return}vt({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:f,durationMs:d,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?k(a):null})}async function zo(e,t){let r=e.startMs??Date.now();$r();let n=!1,o=null;try{return await Et.run(e.executionId,()=>x.startActiveSpan("App",{kind:Ir.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ie.ERROR:Ie.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ie.ERROR,message:o}),s}finally{i.end()}}))}finally{Hr({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await Kr()}}var Pt=1024,P=100*1024*1024,Rt=250,Vr=3600,zr=Vr*1e3,Tt=new TextEncoder,Jr=/(^|\/)\.\.(\/|$)/,qr=/[?#]/;function Yr(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function I(e,t=Pt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");le(e,t)}function _e(e){return e.endsWith("/")?e.slice(0,-1):e}function le(e,t=Pt){if(e.length===0)return;if(Jr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(qr.test(e)||Yr(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=Tt.encode(o).length;if(i>Rt)throw c.filesPathInvalid(`Path segment exceeds ${Rt} UTF-8 bytes (got ${i})`)}let n=Tt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Ct(e){if(e>P)throw c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got ${e})`,P)}function N(e){let t=e!==void 0?e*1e3:zr;return new Date(Date.now()+t)}import{join as G}from"path";var Xr="files",Wr="files-meta",Gr=1023,Qr=1,Zr=5;function kt(e){let t=Math.max(Buffer.byteLength(ue(e),"utf8"),Buffer.byteLength(W(e),"utf8"));return Math.max(0,Gr-t-Qr-Zr)}function ue(e){return G(e,".helix",Xr)}function W(e){return G(e,".helix",Wr)}function Q(e,t){return G(ue(e),...t.split("/"))}function de(e,t){return G(W(e),...t.split("/"))+".json"}function fe(e,t){return t.length===0?ue(e):Q(e,t)}function It(e,t){return t.length===0?W(e):G(W(e),...t.split("/"))}var At="helix-schedule",A=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Go(e){if(typeof e!="object"||e===null)throw new A("expected a config object");let{cron:t,timezone:r="UTC",handler:n}=e;if(typeof t!="string"||t.trim()==="")throw new A("`cron` must be a non-empty string");let o=t.trim().split(/\s+/).length;if(o!==5)throw new A(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${o} field(s) in "${t}"`);if(typeof r!="string"||!en(r))throw new A(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="function")throw new A("`handler` must be a function");return Object.freeze({kind:At,cron:t.trim(),timezone:r,concurrent:!0,handler:n})}function Qo(e){return typeof e=="object"&&e!==null&&e.kind===At&&typeof e.handler=="function"}function en(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as tn}from"@opentelemetry/api";function me(e,t,r){let n=x.startSpan("log",{kind:tn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&xt(n.spanContext().spanId,"properties",r),n.end(),ct(e,t,r)}function ni(){return{info:(e,t)=>me("info",e,t),warn:(e,t)=>me("warn",e,t),error:(e,t)=>me("error",e,t),debug:(e,t)=>me("debug",e,t)}}function si(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import on from"ky";import{context as Be,trace as sn,SpanKind as ge,SpanStatusCode as Ft}from"@opentelemetry/api";import rn from"ky";async function Dt(e,t={}){let r=_(),n=T(),o=!!(r&&r.trim().length>0),i=!!(n&&n.trim().length>0);if(!o&&!i)throw c.missingExecutionCredentials();let{env:s}=b(),a=oe(s),l=t.timeout??6e4,u={Accept:"application/json"};o&&(u[F]=r),i&&(u[R]=n);let f=w().deploymentId,d=f?{...e,deploymentId:f}:e,m=await rn.post(`${a}/broker/http`,{json:d,headers:u,throwHttpErrors:!1,timeout:l}),p;return(m.headers.get("content-type")??"").includes("application/json")?p=await m.json():p=await m.text(),{status:m.status,body:p}}import nn from"ky";async function Ot(e,t={}){let r=et();if(!r)throw c.missingTrayToken();let{env:n}=b(),o=oe(n),i=t.timeout??6e4,s=await nn.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:i}),a;return(s.headers.get("content-type")??"").includes("application/json")?a=await s.json():a=await s.text(),{status:s.status,body:a}}async function pe(e,t={}){let r=w().mode==="lambda"?Dt:Ot,n;try{n=await r(e,t)}catch(a){if(a instanceof c)throw a;let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}let{status:o,body:i}=n;if(o<200||o>=300){let a;if(i!==null&&typeof i=="object"){let l=i;typeof l.message=="string"?a=l.message:typeof l.error=="string"?a=l.error:a=String(i)}else a=String(i);throw c.brokerError(o,a,g(i))}let s=Qe.safeParse(i);if(!s.success)throw c.brokerError(o,"broker returned malformed response",g(i));return Ze(s.data)}var an=["get","post","put","patch","delete","head","options"],_t="[stream body omitted]";function Le(e){try{return new URL(e).hostname}catch{return e}}function cn(e,t,r,n){let o=Le(t),i="externalApi",s={kind:ge.CLIENT};return x.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),v(a,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?_t:r}:{}}),n(a)))}function Ne(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ft.OK}:{code:Ft.ERROR,message:r}),e.end()}var ln=16;async function un(e,t){let r=e.clone().body;return r?Bt(r,t):new Uint8Array(0)}async function Bt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=ln)break;continue}i=0;let f=t+1-o;if(u.byteLength>=f){n.push(u.slice(0,f)),o+=f;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Lt(e,t,r){if("kyResponse"in r)try{let n=await un(r.kyResponse,q),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}v(e,"response",i)}catch{v(e,"response",{status:t})}else v(e,"response",r.bodyValue)}async function dn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await Bt(o,q);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:_t}}}return typeof t=="string"?{body:t}:{}}function Ni(){let e=on.create({});function t(n){return(o,i)=>{let s=Be.active(),a,l=!1,u=(d,m)=>{a&&!l&&(l=!0,Ne(a,d,m))},f=e.extend({hooks:{beforeRequest:[async(d,m)=>{let p=await dn(d,m.body),V=p.body;if(a||(a=x.startSpan("externalApi",{kind:ge.CLIENT},s)),a.setAttributes({method:d.method.toUpperCase(),host:Le(d.url)}),v(a,"request",{url:d.url,method:d.method.toUpperCase(),...V!==void 0?{body:V}:{}}),l=!1,E("hasExternal"),p.request)return p.request}],beforeRetry:[d=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(d,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Lt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(E("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[d=>(E("hasError"),u("error",d.message),d)]}});return a=x.startSpan("externalApi",{kind:ge.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:Le(String(o))}),Be.with(sn.setSpan(Be.active(),a),()=>{let d=n==="options"?f(o,{...i,method:"OPTIONS"}):f[n](o,i);return d.catch(m=>{E("hasError"),u("error",m instanceof Error?m.message:String(m))}),d})}}let r=Object.fromEntries(an.map(n=>[n,t(n)]));return{...e,...r,authed(n){return fn(n)}}}function fn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(s,a={})=>{let l=i.toUpperCase();return cn(l,s,a.body,async u=>{E("hasAuth");let f=x.startSpan("auth",{kind:ge.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let d=z({authenticationId:n,method:l,url:s,body:a.body,headers:a.headers,query:a.query}),m=await pe(d,{timeout:a.timeout});return u.setAttribute("statusCode",m.status),await Lt(u,m.status,{bodyValue:m.body}),Ne(u,"success"),m}catch(d){throw E("hasError"),d instanceof c&&d.detail.kind==="broker_error"&&d.detail.status>0&&u.setAttribute("statusCode",d.detail.status),Ne(u,"error",d instanceof Error?d.message:String(d)),d}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as En,SpanStatusCode as Ut}from"@opentelemetry/api";function Z(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var mn=18e4,Nt=mn-1e4,pn=2e3;async function jt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Nt;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(pn,200*2**i),u=l/2+Math.random()*(l/2),f=Nt-(Date.now()-o);await new Promise(d=>setTimeout(d,Math.min(u,f))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var gn=new Set(["SELECT","WITH","SHOW"]),yn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function hn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function wn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?k(t):g(t);return c.dbCallFailed(i)}function bn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Sn(e,t){return typeof t!="number"||t<0?{}:gn.has(e)?{rowsRead:t}:yn.has(e)?{rowsWritten:t}:{}}function Mt(e){async function t(r,n,o){let i=z({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:s,body:a}=await pe(i);if(s>=400)throw wn(s,a);return bn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:hn,async execute(r,n){let o=Z(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await jt(t,r.region,l),f=u.Status;if(f==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(f==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let d=Sn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:d}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:d}}}}var je=64*1024;function xn(e){return e.length>je?`${e.slice(0,je)}...[truncated]`:e}function vn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Rn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>je?v(e,"result",{truncated:!0,size:n.length}):v(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Tn(e,t,r){let n=Z(r),o=xn(r);return x.startActiveSpan("database",{kind:En.CLIENT},async i=>{vn(i,e,t,n,o);try{E("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Rn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Ut.OK}),l}catch(s){E("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:Ut.ERROR,message:a}),s}finally{i.end()}})}function Pn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Mt(n);function i(s,a){return o.validate(s),Tn(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Dn}from"unstorage";var $t=1024,Me=250*1024,Cn=new TextEncoder,kn=/(^|\/)\.\.(\/|$)/,In=/[?#]/,An=/[\u0000-\u001F\u007F]/;function Kt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(kn.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(In.test(e)||An.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Cn.encode(e).length;if(t<1||t>$t)throw c.kvKeyInvalid(`Key must be between 1 and ${$t} UTF-8 bytes (got ${t})`)}function Ht(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>Me)throw c.kvValueTooLarge(`Value exceeds maximum size of ${Me} bytes (got ${r})`,Me)}function ee(e){Kt(e)}function ye(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Vt(e){let t=ye(e,"getItem"),r=ye(e,"setItem"),n=ye(e,"removeItem"),o=ye(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return ee(s),t(s,a)},setItem(s,a,l){return ee(s),r(s,a,l)},removeItem(s,a){return ee(s),n(s,a)},hasItem(s,a){return ee(s),o(s,a)},getKeys(s,a){return s.length>0&&ee(s),i(s,a)}}}function he(e){return Dn({driver:Vt(e)})}import{defineDriver as On}from"unstorage";function Fn(e){try{return JSON.parse(e)}catch{return e}}var _n=On(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n){await t.set(r,Fn(n))},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function zt(e){return _n({client:e})}import Nn from"ky";import{z as h}from"zod";async function j(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function Jt(e){return D(e).hosts.api}function Bn(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Ln(e){return e.split("/").map(encodeURIComponent).join("/")}function te(e,t,r){return`${e}${Bn(t)}/${Ln(r)}`}var jn=6e4,Ue=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(Ue),h.record(Ue)])),Mn=h.object({projectId:h.string(),key:h.string(),value:Ue,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function Un(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function $n(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function we(e,t){throw c.kvCallFailed(e,$n(t),g(t))}async function be(e,t,r={}){try{let n=await Nn(t,{method:e,headers:Un(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:jn}),o=e==="head"?void 0:await j(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function qt(e){let t=Jt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await be("get",te(t,r,n));if(o===404)return null;(o<200||o>=300)&&we(o,i);let s=Mn.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(i));return s.data.value},async set(n,o){let{status:i,body:s}=await be("put",te(t,r,n),{json:{value:o}});(i<200||i>=300)&&we(i,s)},async delete(n){let{status:o,body:i}=await be("delete",te(t,r,n));o!==204&&we(o,i)},async has(n){let{status:o,body:i}=await be("head",te(t,r,n));if(o===200)return!0;if(o===404)return!1;we(o,i)}}}function Se(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{Ht(r),await e.setItem(t,r,n)}}}function Kn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Yt(e){let t=Kn(),r=e??qt(t),n=he(zt(r));return Se(n)}import Hn from"unstorage/drivers/memory";var $e;function Vn(){return $e||($e=he(Hn())),$e}function Xt(){return Se(Vn())}function zn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Us(){return zn()?Yt():Xt()}import{createHash as Yn}from"crypto";import{mkdir as Xn,readFile as er,readdir as tr,rm as Gt,unlink as Wn,writeFile as Qt}from"fs/promises";import{dirname as Gn}from"path";async function Jn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>P)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got more than ${P})`,P);r.push(i)}}return Buffer.concat(r)}async function M(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?Jn(e):Buffer.from(e)}var qn={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},Wt="application/octet-stream";function Ee(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Wt;let r=e.slice(t+1).toLowerCase();return qn[r]??Wt}function $(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function U(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xe(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ke(e){try{let t=await er(de($(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Zt(e){await Xn(Gn(e),{recursive:!0})}async function Qn(e,t){let r=fe(e,t),n;try{n=await tr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function rr(e,t){let r=fe(e,t),n;try{n=await tr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await rr(e,s)):i.isFile()&&o.push(s)}return o}function nr(){return{async put(e,t,r){return U(async()=>{let n=$(),o=await M(t),i=r?.contentType??Ee(e),s=Yn("sha1").update(o).digest("hex"),a=new Date,l=Q(n,e);await Zt(l),await Qt(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},f=de(n,e);return await Zt(f),await Qt(f,JSON.stringify(u)),xe(e,u)})},async get(e){return U(async()=>{let t=await Ke(e);return t?{data:await er(Q($(),e)),metadata:xe(e,t)}:null})},async head(e){return U(async()=>{let t=await Ke(e);return t?xe(e,t):null})},async delete(e){return U(async()=>{let t=$();await Promise.all([Q(t,e),de(t,e)].map(async r=>{try{await Wn(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return U(async()=>{let t=$(),r=await rr(t,e);return await Promise.all([Gt(fe(t,e),{recursive:!0,force:!0}),Gt(It(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return U(async()=>{let r=$(),n=t?.limit??100,i=(await Qn(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Ke(a);return l?xe(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:N(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:N(t?.expiresIn)}}}}import{createHash as io}from"crypto";function ve(e){return D(e).hosts.api}function Zn(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function re(e,t){return`${e}${Zn(t)}`}function K(e,t,r){return`${re(e,t)}/${encodeURIComponent(r)}`}function Re(e,t,r){return`${K(e,t,r)}/upload`}function or(e,t,r){return`${K(e,t,r)}/download`}function ir(e,t,r){return`${K(e,t,r)}/signed-url`}function sr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${re(e,t)}/file?${o.toString()}`}function ar(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${re(e,t)}?${o.toString()}`}import Ve from"ky";import{z as y}from"zod";var ze=6e4,cr=y.object({id:y.string(),workspaceId:y.string(),projectId:y.string(),parentFolder:y.string().nullable().optional(),name:y.string(),size:y.number().nullable().optional(),objectType:y.enum(["Folder","File"]),contentType:y.string().nullable().optional(),createdAt:y.string(),updatedAt:y.string()}),eo=y.object({signedURL:y.string()}),to=y.object({path:y.array(y.object({id:y.string(),name:y.string()})),elements:y.array(cr)});function Je(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function lr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function C(e,t){throw c.filesCallFailed(e,lr(t),g(t))}function ro(e,t){return e===400&&lr(t).toLowerCase()==="resource not found"}async function no(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await Ve(t,{method:e,headers:Je(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ze}),o=await j(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function He(e,t){let r=cr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function ur(e){let t=ve(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",re(t,r),{json:n});return(o<200||o>=300)&&C(o,i),He(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",sr(t,r,n,o));return i===404||ro(i,s)?null:((i<200||i>=300)&&C(i,s),He(i,s))},async getById(n){let{status:o,body:i}=await H("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&C(o,i),He(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",ar(t,r,n,o));(i<200||i>=300)&&C(i,s);let a=to.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",g(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await no(a),f;try{f=await Ve(Re(t,r,n),{method:"post",headers:{...Je(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ze})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let d=await j(f);(f.status<200||f.status>=300)&&C(f.status,d)},async downloadContent(n){let o;try{o=await Ve(or(t,r,n),{method:"get",headers:Je(),throwHttpErrors:!1,timeout:ze})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await j(o);C(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",ir(t,r,n));(o<200||o>=300)&&C(o,i);let s=eo.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&C(o,i)}}}function qe(e){return e.split("/").filter(t=>t.length>0)}function Ye(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function oo(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Xe(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await oo(e,o,i)).id;return{parentFolder:o,name:n}}async function ne(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function We(e,t){if(t.length===0)return;let r=qe(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var so=500,ao=8;async function co(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function lo(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function uo(e){return io("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Te(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:uo(t)}}async function dr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function fr(e,t){let{elements:r}=await e.listChildren(t,so);return(await co(r,ao,async o=>{let i=o.objectType==="Folder"?await fr(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function mr(e){let t=lo(),r=e??ur(t),n=ve(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Xe(r,i),f=await M(s),d=a?.contentType??Ee(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await dr(r,l,u,d);await r.uploadContent(p.id,f,u,d);let V=await r.getById(p.id);return Te(i,V??p,d)},async get(i){let s=await ne(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Te(i,a)}},async head(i){let s=await ne(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Te(i,a)},async delete(i){let s=await ne(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await We(r,i);if(s===null)return{deleted:0};let a=await fr(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await We(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(d=>d.objectType==="File").map(d=>Te(i?`${i}/${d.name}`:d.name,d)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Xe(r,i),f=await r.getByName(a,l)??await dr(r,a,l,s?.contentType);return{url:Re(n,o,f.id),expiresAt:N(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await ne(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:N(s?.expiresIn)}}}}function Ge(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){I(n,r);let s=await M(o);return Ct(s.byteLength),e.put(n,s,i)},async get(n){return I(n,r),e.get(n)},async head(n){return I(n,r),e.head(n)},async delete(n){return I(n,r),e.delete(n)},async deleteMany(n){let o=_e(n);return le(o,r),e.deleteMany(o)},async list(n,o){let i=_e(n??"");return le(i,r),e.list(i,o)},async getUploadUrl(n,o){return I(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return I(n,r),e.getDownloadUrl(n,o)}}}function fo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Oa(){if(fo())return Ge(mr());let e=w().projectRoot;return Ge(nr(),{maxPathBytes:e?kt(e):void 0})}export{mo as a,w as b,go as c,yo as d,b as e,ho as f,Et as g,Br as h,E as i,v as j,$r as k,Kr as l,x as m,Hr as n,zo as o,ni as p,si as q,Ni as r,Pn as s,Us as t,I as u,Q as v,de as w,Oa as x,At as y,A as z,Go as A,Qo as 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,9 +1,3 @@
1
- import{a as St,b as Zr}from"./chunk-L6J5L3JQ.js";import{a as R,b as O,d as y,e as F,f as T,g as yt,j as S,l as z,m as D,n as De,o as Ae,p as Ct,q as j,r as kt,s as ae,t as ce,u as ue,v as Rt}from"./chunk-W32AX5BI.js";import{a as V,b as ie,c as Et,d as xt}from"./chunk-R56ARJY5.js";import{b as ht,d as L,e as wt,i as vt,l as c,m as bt}from"./chunk-7MAMPE72.js";import{randomUUID as Ko}from"crypto";import{SpanStatusCode as Mr,SpanKind as qo}from"@opentelemetry/api";import{AsyncLocalStorage as zt}from"async_hooks";import{trace as fn,SpanKind as mn,SpanStatusCode as Fe}from"@opentelemetry/api";import{ExportResultCode as pn,W3CTraceContextPropagator as gn}from"@opentelemetry/core";import{NodeTracerProvider as yn,SimpleSpanProcessor as hn,BatchSpanProcessor as wn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Xr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Qr}from"@opentelemetry/exporter-logs-otlp-proto";function _e(e){return L(e).hosts.ingest}function en(){return T()??""}function Tt(){return{[R]:en()}}function Pt(){let e=_e(S().env);return new Xr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Tt())})}function It(){let e=_e(S().env);return new Qr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Tt())})}import{logs as _t,SeverityNumber as de}from"@opentelemetry/api-logs";import{LoggerProvider as nn,BatchLogRecordProcessor as on}from"@opentelemetry/sdk-logs";function W(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function tn(e){return new TextEncoder().encode(e).length}var Dt="\u2026[truncated]",rn=tn(Dt),J=4096;function A(e,t=J){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-rn);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Dt}function h(e,t=J){return A(W(e),t)}var sn="@trayai/helix-sdk",Y,At={debug:{number:de.DEBUG,text:"DEBUG"},info:{number:de.INFO,text:"INFO"},warn:{number:de.WARN,text:"WARN"},error:{number:de.ERROR,text:"ERROR"}};function an(){return y().mode==="lambda"?[new on({exporter:It()})]:[]}function Ot(){if(Y!==void 0)return;let e=an();e.length!==0&&(Y=new nn({processors:e}),_t.setGlobalLoggerProvider(Y))}function cn(e,t,r){let n=At[e]??At.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":h(r)}}:{}}}function Ft(e,t,r){_t.getLogger(sn).emit(cn(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
- `)}finally{t!==void 0&&clearTimeout(t)}}function Oe(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function un(){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 k(e,t){return un()?`\x1B[${e}m${t}\x1B[0m`:t}var dn=5,ln={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},jt="32",Nt="31",le="2",Ut="1";function fe(e){return k(ln[e]??"0",e.padEnd(dn))}function Bt(e,t){return`${fe("FN")} ${k(Ut,`${e} ${t}`.trim())}`}function Mt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${k(le,n)} `:""}${fe(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${k(le,W(r))}`),i}function $t(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Ht(e){return`${fe("AUTH")} ${e}`}function Kt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=k(o==="error"?Nt:jt,s);return`${fe("API")} ${e} ${t} \u2192 ${i} ${k(le,`${n}ms`)}`}function qt(e,t,r){let n=t?Nt:jt,o=k(n,"\u25CF"),s=k(n,t?"error":"success");return`${o} ${k(Ut,e)} ${s} ${k(le,`${r}ms`)}`}function N(e){try{process.stdout.write(e+`
3
- `)}catch{}}var me=new zt,pe=new zt;function x(e){let t=pe.getStore();t&&(t[e]=!0)}var vn=/^[0-9a-f]{32}$/;function Sn(e){let t=e.replace(/-/g,"").toLowerCase();return vn.test(t)?t:null}var bn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},U=new Map;function Wt(e,t,r){let n=U.get(e);n?n[t]=r:U.set(e,{[t]:r})}function E(e,t,r){e.setAttribute(t,h(r))}var G;function Vt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function En(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Jt(e){try{process.stdout.write(W(e)+`
4
- `)}catch{}}var Le=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=U.get(o),i={...n.attributes};if(s!==void 0){for(let[d,f]of Object.entries(s))typeof f=="string"?i[d]=A(f):typeof f=="object"&&f!==null?i[d]=h(f):i[d]=f;U.delete(o)}let a=me.getStore(),u=a?Sn(a):null;Jt({_otel:"span",traceId:u??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Vt(n.startTime),endTimeUnixNano:Vt(n.endTime),attributes:i,status:{code:bn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:A(n.status.message)}:{}}})}r({code:pn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t,r){}onEnd(t){U.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
5
- `+Bt(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=U.get(n)?.properties;N(Mt(String(r.level??"info"),String(r.message??""),o,$t(t.startTime)));break}case"auth":N(Ht(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(Kt(String(r.method??""),String(r.host??""),n,En(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ue=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function xn(){let t=[Oe()?new Ne:new hn(new Le)];return y().mode==="lambda"&&t.push(new Ue(new wn(Pt()))),t.push(new je),t}function Be(){G===void 0&&(G=new yn({spanProcessors:xn()}),G.register({propagator:new gn}),Ot())}async function Me(e=2e3){let t=[Lt(e)];G!==void 0&&t.push((async()=>{let r;try{await Promise.race([G.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
- `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var C=fn.getTracer("@trayai/helix-sdk");function $e({executionId:e,deploymentId:t,routeOrJob:r,startedAt:n,startMs:o,errored:s,errorMessage:i,userId:a,flags:u}){let d=new Date().toISOString(),f=Date.now()-o;if(Oe()){N(`
7
- `+qt(r,s,f));return}Jt({_otel:"summary",executionId:e,deploymentId:t,triggerType:"http",routeOrJob:r,status:s?"error":"success",startedAt:n,finishedAt:d,durationMs:f,userId:a,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&i!==null?A(i):null})}async function Cn(e,t){let r=e.startMs??Date.now();Be();let n=!1,o=null;try{return await me.run(e.executionId,()=>C.startActiveSpan("App",{kind:mn.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return n=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",n?"error":"success"),s.setStatus({code:n?Fe.ERROR:Fe.OK}),i}catch(i){throw n=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Fe.ERROR,message:o}),i}finally{s.end()}}))}finally{$e({executionId:e.executionId,deploymentId:e.deploymentId,routeOrJob:`${e.method} ${e.route}`,startedAt:e.startedAt,startMs:r,errored:n,errorMessage:o,userId:e.userId,flags:{hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1}}),await Me()}}import{defineEventHandler as Vo,getMethod as zo,getRequestURL as Wo,getHeaders as Hr,getHeader as $r}from"h3";import{readBody as kn,getQuery as Rn,getRouterParams as Tn}from"h3";async function Yt(e,t){let r=await Pn(e),n=Rn(e),o=Tn(e)??{},s={...n,...r,...o};return t?In(s,t):s}async function Pn(e){try{let t=await kn(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 In(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}import{SpanKind as Dn}from"@opentelemetry/api";function ge(e,t,r){let n=C.startSpan("log",{kind:Dn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Wt(n.spanContext().spanId,"properties",r),n.end(),Ft(e,t,r)}function Gt(){return{info:(e,t)=>ge("info",e,t),warn:(e,t)=>ge("warn",e,t),error:(e,t)=>ge("error",e,t),debug:(e,t)=>ge("debug",e,t)}}var Z=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Zt(e){return t=>{e.node.res.statusCode=t}}function Xt(){return(e,t)=>{throw new Z(e,t)}}import On from"ky";import{context as He,trace as Fn,SpanKind as he,SpanStatusCode as tr}from"@opentelemetry/api";import An from"ky";async function Qt(e,t={}){let r=F(),n=T(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw c.missingExecutionCredentials();let{env:i}=S(),a=ie(i),u=t.timeout??6e4,d={Accept:"application/json"};o&&(d[O]=r),s&&(d[R]=n);let f=y().deploymentId,l=f?{...e,deploymentId:f}:e,m=await An.post(`${a}/broker/http`,{json:l,headers:d,throwHttpErrors:!1,timeout:u}),p;return(m.headers.get("content-type")??"").includes("application/json")?p=await m.json():p=await m.text(),{status:m.status,body:p}}import _n from"ky";async function er(e,t={}){let r=yt();if(!r)throw c.missingTrayToken();let{env:n}=S(),o=ie(n),s=t.timeout??6e4,i=await _n.post(`${o}/broker/http/dev`,{json:e,headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throwHttpErrors:!1,timeout:s}),a;return(i.headers.get("content-type")??"").includes("application/json")?a=await i.json():a=await i.text(),{status:i.status,body:a}}async function ye(e,t={}){let r=y().mode==="lambda"?Qt:er,n;try{n=await r(e,t)}catch(a){if(a instanceof c)throw a;let u=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,u)}let{status:o,body:s}=n;if(o<200||o>=300){let a;if(s!==null&&typeof s=="object"){let u=s;typeof u.message=="string"?a=u.message:typeof u.error=="string"?a=u.error:a=String(s)}else a=String(s);throw c.brokerError(o,a,h(s))}let i=Et.safeParse(s);if(!i.success)throw c.brokerError(o,"broker returned malformed response",h(s));return xt(i.data)}var Ln=["get","post","put","patch","delete","head","options"],rr="[stream body omitted]";function Ke(e){try{return new URL(e).hostname}catch{return e}}function jn(e,t,r,n){let o=Ke(t),s="externalApi",i={kind:he.CLIENT};return C.startActiveSpan(s,i,async a=>(a.setAttributes({method:e,host:o}),E(a,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?rr:r}:{}}),n(a)))}function qe(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:tr.OK}:{code:tr.ERROR,message:r}),e.end()}var Nn=16;async function Un(e,t){let r=e.clone().body;return r?nr(r,t):new Uint8Array(0)}async function nr(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:u,value:d}=await r.read();if(u)break;if(!d||d.byteLength===0){if(s+=1,s>=Nn)break;continue}s=0;let f=t+1-o;if(d.byteLength>=f){n.push(d.slice(0,f)),o+=f;break}n.push(d),o+=d.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let i=new Uint8Array(o),a=0;for(let u of n)i.set(u,a),a+=u.byteLength;return i}async function or(e,t,r){if("kyResponse"in r)try{let n=await Un(r.kyResponse,J),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}E(e,"response",s)}catch{E(e,"response",{status:t})}else E(e,"response",r.bodyValue)}async function Bn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),s=new Request(e,{body:n,duplex:"half"}),i=await nr(o,J);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:rr}}}return typeof t=="string"?{body:t}:{}}function sr(){let e=On.create({});function t(n){return(o,s)=>{let i=He.active(),a,u=!1,d=(l,m)=>{a&&!u&&(u=!0,qe(a,l,m))},f=e.extend({hooks:{beforeRequest:[async(l,m)=>{let p=await Bn(l,m.body),g=p.body;if(a||(a=C.startSpan("externalApi",{kind:he.CLIENT},i)),a.setAttributes({method:l.method.toUpperCase(),host:Ke(l.url)}),E(a,"request",{url:l.url,method:l.method.toUpperCase(),...g!==void 0?{body:g}:{}}),u=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[l=>{d("error","retry"),a=void 0,u=!1}],afterResponse:[async(l,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await or(a,p.status,{kyResponse:p}),p.ok?d("success"):s?.throwHttpErrors===!1&&(x("hasError"),d("error",`HTTP ${p.status}`)))}],beforeError:[l=>(x("hasError"),d("error",l.message),l)]}});return a=C.startSpan("externalApi",{kind:he.CLIENT},i),a.setAttributes({method:n.toUpperCase(),host:Ke(String(o))}),He.with(Fn.setSpan(He.active(),a),()=>{let l=n==="options"?f(o,{...s,method:"OPTIONS"}):f[n](o,s);return l.catch(m=>{x("hasError"),d("error",m instanceof Error?m.message:String(m))}),l})}}let r=Object.fromEntries(Ln.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Mn(n)}}}function Mn(e){let r=S().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(i,a={})=>{let u=s.toUpperCase();return jn(u,i,a.body,async d=>{x("hasAuth");let f=C.startSpan("auth",{kind:he.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let l=V({authenticationId:n,method:u,url:i,body:a.body,headers:a.headers,query:a.query}),m=await ye(l,{timeout:a.timeout});return d.setAttribute("statusCode",m.status),await or(d,m.status,{bodyValue:m.body}),qe(d,"success"),m}catch(l){throw x("hasError"),l instanceof c&&l.detail.kind==="broker_error"&&l.detail.status>0&&d.setAttribute("statusCode",l.detail.status),qe(d,"error",l instanceof Error?l.message:String(l)),l}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as Yn,SpanStatusCode as ur}from"@opentelemetry/api";function X(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var $n=18e4,ir=$n-1e4,Hn=2e3;async function ar(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<ir;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let u=Math.min(Hn,200*2**s),d=u/2+Math.random()*(u/2),f=ir-(Date.now()-o);await new Promise(l=>setTimeout(l,Math.min(d,f))),s++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Kn=new Set(["SELECT","WITH","SHOW"]),qn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Vn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function zn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?A(t):h(t);return c.dbCallFailed(s)}function Wn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Jn(e,t){return typeof t!="number"||t<0?{}:Kn.has(e)?{rowsRead:t}:qn.has(e)?{rowsWritten:t}:{}}function cr(e){async function t(r,n,o){let s=V({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:i,body:a}=await ye(s);if(i>=400)throw zn(i,a);return Wn(a)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:Vn,async execute(r,n){let o=X(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,u=typeof a?.Id=="string"?a.Id:void 0;if(!u){let p=h(i);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let d=await ar(t,r.region,u),f=d.Status;if(f==="FAILED"){let p=typeof d.Error=="string"?d.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${u})`)}if(f==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${u})`);let l=Jn(o,d.ResultRows);return d.HasResultSet===!1?{result:{rowsAffected:d.ResultRows??0},metadata:l}:{result:await t(r.region,"GetStatementResult",{Id:u}),metadata:l}}}}var Ve=64*1024;function Gn(e){return e.length>Ve?`${e.slice(0,Ve)}...[truncated]`:e}function Zn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Xn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Ve?E(e,"result",{truncated:!0,size:n.length}):E(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Qn(e,t,r){let n=X(r),o=Gn(r);return C.startActiveSpan("database",{kind:Yn.CLIENT},async s=>{Zn(s,e,t,n,o);try{x("hasDb");let{result:i,metadata:a}=await e.execute(t,r),u=Xn(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:ur.OK}),u}catch(i){x("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:ur.ERROR,message:a}),i}finally{s.end()}})}function ze(e){let r=S().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=cr(n);function s(i,a){return o.validate(i),Qn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as oo}from"unstorage";var dr=1024,We=250*1024,eo=new TextEncoder,to=/(^|\/)\.\.(\/|$)/,ro=/[?#]/,no=/[\u0000-\u001F\u007F]/;function lr(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(to.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(ro.test(e)||no.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=eo.encode(e).length;if(t<1||t>dr)throw c.kvKeyInvalid(`Key must be between 1 and ${dr} UTF-8 bytes (got ${t})`)}function fr(e){let t;try{t=JSON.stringify(e)}catch{throw c.kvValueInvalid("Value must be JSON-serializable")}if(t===void 0)throw c.kvValueInvalid("Value must be JSON-serializable");let r=Buffer.byteLength(t,"utf8");if(r>We)throw c.kvValueTooLarge(`Value exceeds maximum size of ${We} bytes (got ${r})`,We)}function Q(e){lr(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function mr(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return Q(i),t(i,a)},setItem(i,a,u){return Q(i),r(i,a,u)},removeItem(i,a){return Q(i),n(i,a)},hasItem(i,a){return Q(i),o(i,a)},getKeys(i,a){return i.length>0&&Q(i),s(i,a)}}}function ve(e){return oo({driver:mr(e)})}import{defineDriver as so}from"unstorage";function io(e){try{return JSON.parse(e)}catch{return e}}var ao=so(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n){await t.set(r,io(n))},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function pr(e){return ao({client:e})}import lo from"ky";import{z as v}from"zod";async function B(e){let t=e.headers.get("content-type")??"",r=await e.text();if(r.length!==0)return t.includes("application/json")?JSON.parse(r):r}function gr(e){return L(e).hosts.api}function co(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function uo(e){return e.split("/").map(encodeURIComponent).join("/")}function ee(e,t,r){return`${e}${co(t)}/${uo(r)}`}var fo=6e4,Je=v.lazy(()=>v.union([v.string(),v.number(),v.boolean(),v.null(),v.array(Je),v.record(Je)])),mo=v.object({projectId:v.string(),key:v.string(),value:Je,type:v.enum(["string","number","boolean","null","array","object"]),organizationId:v.string(),scope:v.string(),createdBy:v.string(),createdAt:v.number(),updatedBy:v.string(),updatedAt:v.number()});function po(){let e=F(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[O]=e),n&&(o[R]=t),o}function go(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,go(t),h(t))}async function be(e,t,r={}){try{let n=await lo(t,{method:e,headers:po(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:fo}),o=e==="head"?void 0:await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message??String(n):String(n);throw c.kvCallFailed(0,o)}}function yr(e){let t=gr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await be("get",ee(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,s);let i=mo.safeParse(s);if(!i.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",h(s));return i.data.value},async set(n,o){let{status:s,body:i}=await be("put",ee(t,r,n),{json:{value:o}});(s<200||s>=300)&&Se(s,i)},async delete(n){let{status:o,body:s}=await be("delete",ee(t,r,n));o!==204&&Se(o,s)},async has(n){let{status:o,body:s}=await be("head",ee(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,s)}}}function Ee(e){return{getItem:(t,r)=>e.getItem(t,r),removeItem:(t,r)=>e.removeItem(t,r),hasItem:(t,r)=>e.hasItem(t,r),setItem:async(t,r,n)=>{fr(r),await e.setItem(t,r,n)}}}function yo(){let e=S();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function hr(e){let t=yo(),r=e??yr(t),n=ve(pr(r));return Ee(n)}import ho from"unstorage/drivers/memory";var Ye;function wo(){return Ye||(Ye=ve(ho())),Ye}function wr(){return Ee(wo())}function vo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function vr(){return vo()?hr():wr()}import{createHash as Eo}from"crypto";import{mkdir as xo,readFile as Cr,readdir as kr,rm as br,unlink as Co,writeFile as Er}from"fs/promises";import{dirname as ko}from"path";async function So(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>z)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${z} bytes (got more than ${z})`,z);r.push(s)}}return Buffer.concat(r)}async function M(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?So(e):Buffer.from(e)}var bo={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},Sr="application/octet-stream";function xe(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Sr;let r=e.slice(t+1).toLowerCase();return bo[r]??Sr}function H(){let e=y().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function $(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function Ce(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ge(e){try{let t=await Cr(ce(H(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function xr(e){await xo(ko(e),{recursive:!0})}async function Ro(e,t){let r=ue(e,t),n;try{n=await kr(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter(o=>o.isFile()).map(o=>t.length===0?o.name:`${t}/${o.name}`)}async function Rr(e,t){let r=ue(e,t),n;try{n=await kr(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of n){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await Rr(e,i)):s.isFile()&&o.push(i)}return o}function Tr(){return{async put(e,t,r){return $(async()=>{let n=H(),o=await M(t),s=r?.contentType??xe(e),i=Eo("sha1").update(o).digest("hex"),a=new Date,u=ae(n,e);await xr(u),await Er(u,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},f=ce(n,e);return await xr(f),await Er(f,JSON.stringify(d)),Ce(e,d)})},async get(e){return $(async()=>{let t=await Ge(e);return t?{data:await Cr(ae(H(),e)),metadata:Ce(e,t)}:null})},async head(e){return $(async()=>{let t=await Ge(e);return t?Ce(e,t):null})},async delete(e){return $(async()=>{let t=H();await Promise.all([ae(t,e),ce(t,e)].map(async r=>{try{await Co(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return $(async()=>{let t=H(),r=await Rr(t,e);return await Promise.all([br(ue(t,e),{recursive:!0,force:!0}),br(Rt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return $(async()=>{let r=H(),n=t?.limit??100,s=(await Ro(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let u=await Ge(a);return u?Ce(a,u):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:j(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:j(t?.expiresIn)}}}}import{createHash as Oo}from"crypto";function ke(e){return L(e).hosts.api}function To(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function te(e,t){return`${e}${To(t)}`}function K(e,t,r){return`${te(e,t)}/${encodeURIComponent(r)}`}function Re(e,t,r){return`${K(e,t,r)}/upload`}function Pr(e,t,r){return`${K(e,t,r)}/download`}function Ir(e,t,r){return`${K(e,t,r)}/signed-url`}function Dr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${te(e,t)}/file?${o.toString()}`}function Ar(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${te(e,t)}?${o.toString()}`}import Xe from"ky";import{z as w}from"zod";var Qe=6e4,_r=w.object({id:w.string(),workspaceId:w.string(),projectId:w.string(),parentFolder:w.string().nullable().optional(),name:w.string(),size:w.number().nullable().optional(),objectType:w.enum(["Folder","File"]),contentType:w.string().nullable().optional(),createdAt:w.string(),updatedAt:w.string()}),Po=w.object({signedURL:w.string()}),Io=w.object({path:w.array(w.object({id:w.string(),name:w.string()})),elements:w.array(_r)});function et(){let e=F(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[O]=e),n&&(o[R]=t),o}function Or(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function P(e,t){throw c.filesCallFailed(e,Or(t),h(t))}function Do(e,t){return e===400&&Or(t).toLowerCase()==="resource not found"}async function Ao(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function q(e,t,r={}){try{let n=await Xe(t,{method:e,headers:et(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Qe}),o=await B(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function Ze(e,t){let r=_r.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",h(t));return r.data}function Fr(e){let t=ke(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await q("post",te(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Ze(o,s)},async getByName(n,o){let{status:s,body:i}=await q("get",Dr(t,r,n,o));return s===404||Do(s,i)?null:((s<200||s>=300)&&P(s,i),Ze(s,i))},async getById(n){let{status:o,body:s}=await q("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Ze(o,s))},async listChildren(n,o){let{status:s,body:i}=await q("get",Ar(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=Io.safeParse(i);if(!a.success)throw c.filesCallFailed(s,"platform returned malformed listing",h(i));return a.data},async uploadContent(n,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:u,contentType:d}=await Ao(a),f;try{f=await Xe(Re(t,r,n),{method:"post",headers:{...et(),"content-type":d},body:new Uint8Array(u),throwHttpErrors:!1,timeout:Qe})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let l=await B(f);(f.status<200||f.status>=300)&&P(f.status,l)},async downloadContent(n){let o;try{o=await Xe(Pr(t,r,n),{method:"get",headers:et(),throwHttpErrors:!1,timeout:Qe})}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message:String(i);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await B(o);P(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await q("get",Ir(t,r,n));(o<200||o>=300)&&P(o,s);let i=Po.safeParse(s);if(!i.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",h(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await q("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function tt(e){return e.split("/").filter(t=>t.length>0)}function rt(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function _o(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(rt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function nt(e,t){let r=tt(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await _o(e,o,s)).id;return{parentFolder:o,name:n}}async function re(e,t){let r=tt(t),n=r[r.length-1],o;for(let s of r.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:n}}async function ot(e,t){if(t.length===0)return;let r=tt(t),n;for(let o of r){let s=await e.getByName(n,o);if(!s||s.objectType!=="Folder")return null;n=s.id}return n}var Fo=500,Lo=8;async function jo(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;n[i]=await r(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}function No(){let e=S();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Uo(e){return Oo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Te(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Uo(t)}}async function Lr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(rt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function jr(e,t){let{elements:r}=await e.listChildren(t,Fo);return(await jo(r,Lo,async o=>{let s=o.objectType==="Folder"?await jr(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Nr(e){let t=No(),r=e??Fr(t),n=ke(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:u,name:d}=await nt(r,s),f=await M(i),l=a?.contentType??xe(s),m=await r.getByName(u,d);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${s}"`);let p=m??await Lr(r,u,d,l);await r.uploadContent(p.id,f,d,l);let g=await r.getById(p.id);return Te(s,g??p,l)},async get(s){let i=await re(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Te(s,a)}},async head(s){let i=await re(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Te(s,a)},async delete(s){let i=await re(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await ot(r,s);if(i===null)return{deleted:0};let a=await jr(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await ot(r,s??"");if(a===null)return{files:[],cursor:null};let u=i?.limit??100,{elements:d}=await r.listChildren(a,u);return{files:d.filter(l=>l.objectType==="File").map(l=>Te(s?`${s}/${l.name}`:l.name,l)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:u}=await nt(r,s),f=await r.getByName(a,u)??await Lr(r,a,u,i?.contentType);return{url:Re(n,o,f.id),expiresAt:j(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await re(r,s),u=a?await r.getByName(a.parentFolder,a.name):null;if(!u||u.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(u.id),expiresAt:j(i?.expiresIn)}}}}function st(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){D(n,r);let i=await M(o);return Ct(i.byteLength),e.put(n,i,s)},async get(n){return D(n,r),e.get(n)},async head(n){return D(n,r),e.head(n)},async delete(n){return D(n,r),e.delete(n)},async deleteMany(n){let o=De(n);return Ae(o,r),e.deleteMany(o)},async list(n,o){let s=De(n??"");return Ae(s,r),e.list(s,o)},async getUploadUrl(n,o){return D(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return D(n,r),e.getDownloadUrl(n,o)}}}function Bo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ur(){if(Bo())return st(Nr());let e=y().projectRoot;return st(Tr(),{maxPathBytes:e?kt(e):void 0})}function Br(e,t){let{statusCode:r,message:n}=Mo(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Mo(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 $o=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Ho(e){return e.toLowerCase().includes("tray_lid")}function it(e){let t={};for(let[r,n]of Object.entries(e))if(!$o.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let i=s.split("=")[0].trim();return!Ho(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Jo(e,t){let{inputSchema:r,outputSchema:n}=es(t),o=e;return Vo(async s=>{let i=y(),{executionId:a,userId:u,deploymentId:d}=ts(i,s),f=Date.now(),l=new Date().toISOString(),m=zo(s),p=Wo(s).pathname,g=rs(),_=Gt(),oe=`${m} ${p}`;Be();let gt={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return Yo(()=>pe.run(gt,()=>me.run(a,async()=>{let se=await Go(s,r);if(!se.ok)return{response:se.response,errored:!1,errorMessage:null};let Gr=os(s,se.input,g,_,m,p,a,d,u);return Zo(o,Gr,n,s,_,a,d,{method:m,path:p,rawInput:se.input})})),{executionId:a,deploymentId:d,routeOrJob:oe,startedAt:l,startMs:f,userId:u,flags:gt})})}async function Yo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{$e({...t,errored:r,errorMessage:n}),await Me()}}async function Go(e,t){try{return{ok:!0,input:await Yt(e,t)}}catch(r){let n=ns(e,r);if(n)return{ok:!1,response:n};throw r}}async function Zo(e,t,r,n,o,s,i,a){return C.startActiveSpan("function",{root:!0,kind:qo.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async u=>{t.traceId=u.spanContext().traceId;let d=it(Hr(n));E(u,"input",a.rawInput),E(u,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let f=!1,l=null,m,p;try{let g=await St.run(t,()=>e(t));if(m=g,g==null)n.node.res.statusCode=204,p="";else if(g instanceof Response)p=g;else if(r){let _=r.safeParse(g);if(!_.success){let oe=Object.keys(_.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:oe,executionId:s}),c.outputValidationFailed(oe)}p=_.data}else p=g}catch(g){f=!0,l=g instanceof Error?g.message:String(g),x("hasError"),p=Xo(g,n,o,s)}finally{Qo(u,n,{errored:f,errorMessage:l,handlerResult:m,response:p})}return{response:p,errored:f,errorMessage:l}})}function Xo(e,t,r,n){if(e instanceof Z)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(bt(e))return Br(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 Qo(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&E(e,"output",r.handlerResult),E(e,"response",r.response);let n=pe.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?Mr.ERROR:Mr.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function es(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 ts(e,t){let r=e.mode==="lambda",n=(r?e.executionId:$r(t,"x-tray-execution-id"))??Ko(),o=(r?e.userId:$r(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function rs(){try{return S().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function ns(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 os(e,t,r,n,o,s,i,a,u){return{input:t,method:o,path:s,headers:it(Hr(e)),http:sr(),db:d=>ze(d),kv:()=>vr(),files:()=>Ur(),log:n,config:r,status:Zt(e),error:Xt(),state:{},request:e,executionId:i,deploymentId:a,userId:u,identity:u!==null?{user:{id:u}}:null,traceId:""}}var at="helix-schedule",I=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ss(e){if(typeof e!="object"||e===null)throw new I("expected a config object");let{cron:t,timezone:r="UTC",handler:n}=e;if(typeof t!="string"||t.trim()==="")throw new I("`cron` must be a non-empty string");let o=t.trim().split(/\s+/).length;if(o!==5)throw new I(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${o} field(s) in "${t}"`);if(typeof r!="string"||!as(r))throw new I(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="function")throw new I("`handler` must be a function");return Object.freeze({kind:at,cron:t.trim(),timezone:r,concurrent:!0,handler:n})}function is(e){return typeof e=="object"&&e!==null&&e.kind===at&&typeof e.handler=="function"}function as(e){if(e.trim()==="")return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}function cs(e){return e}import{resolve as ct}from"path";import{existsSync as qr}from"fs";import{loadConfig as ls}from"c12";import{z as b}from"zod";import{z as us}from"zod";var ds=["production"],Pe=us.string().refine(e=>ht(e),e=>({message:`Invalid enum value. Expected ${wt().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var ut=b.string().uuid("projectId must be a valid UUID"),dt=b.string().min(1,"workspaceId must be a non-empty string"),fs=b.object({name:b.string().min(1,"name is required"),projectId:ut.optional(),workspaceId:dt.optional(),env:Pe.default("production"),authentications:b.record(b.string()).optional().default({}),config:b.record(b.unknown()).optional().default({})}),Kr=b.object({name:b.string().min(1,"name is required"),workspaceId:dt.optional(),env:Pe,authentications:b.record(b.string()),config:b.record(b.unknown())}),ms=b.discriminatedUnion("kind",[Kr.extend({kind:b.literal("provisioned"),projectId:ut}),Kr.extend({kind:b.literal("unprovisioned")})]),Vr=["helix","tray"],zr=["ts","mts","cts","js","mjs","cjs"];function Ie(e){for(let t of Vr)for(let r of zr){let n=ct(e,`${t}.config.${r}`);if(qr(n))return n}}function ps(e){for(let t of Vr)if(zr.some(r=>qr(ct(e,`${t}.config.${r}`))))return t;return"helix"}function lt(e){return{name:ps(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function ft(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw c.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=fs.safeParse(e);if(!r.success){let d=r.error.issues.map(f=>f.message).join("; ");throw c.configLoadFailed(`Invalid helix.config.ts at ${t}: ${d}`)}let{projectId:n,workspaceId:o,...s}=r.data,i=o!==void 0?{workspaceId:o}:{},a=vt(),u=a!==void 0?{...s,env:a}:s;return n!==void 0?{kind:"provisioned",projectId:n,...u,...i}:{kind:"unprovisioned",...u,...i}}async function ne(e){let t=e??process.cwd(),r;try{r=await ls(lt(t))}catch(o){throw c.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??Ie(t);if(!n)throw c.configLoadFailed(`helix.config.ts not found at ${ct(t,"helix.config.ts")}`);return ft(r.config,n)}var Wr="WORKSPACE_ID_REQUIRED";function gs(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:Wr});return e.workspaceId}import{existsSync as ys,watch as hs,writeSync as ws}from"fs";import{join as vs,resolve as Ss}from"path";import{watchConfig as bs}from"c12";function Es(e,t){let r=e instanceof Error?e.message:String(e);ws(2,`[helix-watch] ${t.phase} error: ${r}
8
- `)}function mt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var xs=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,Jr=new Set;function Yr(e){return Ie(e)!==void 0}async function Cs(e,t){if(Yr(e.cwd))try{return{current:await ne(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:mt(),initialLoadSucceeded:!1}}if(e.watch){let r=Ss(e.cwd);Jr.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\`
9
- `),Jr.add(r))}return{current:mt(),initialLoadSucceeded:!1}}var pt=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=bs({...lt(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=ft(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=hs(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();xs.test(n)&&ys(vs(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await ne(this.cwd)}catch(i){this.onError(i,{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 ks(e){let t=e.onError??Es,r=new Set,n=await Cs(e,t),o=n.current;function s(a){o=a;for(let u of[...r])try{u(a)}catch(d){t(d,{phase:"reload"})}}let i=new pt(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!Yr(e.cwd)){let a=mt();return s(a),a}try{let a=await ne(e.cwd);return s(a),a}catch(a){return t(a,{phase:"reload"}),o}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await i.stop()},ready(){return i.watcherReady()}}}export{ds as ENVIRONMENT_VALUES,at as SCHEDULE_DEFINITION_KIND,I as ScheduleConfigError,Wr as WORKSPACE_ID_REQUIRED_CODE,ks as createConfigService,cs as defineConfig,Jo as defineFunction,ss as defineSchedule,Pe as environmentSchema,Zr as getContext,y as getSdkConfig,is as isScheduleDefinition,ne as loadConfig,ms as loadedTrayConfigSchema,ut as projectIdSchema,gs as requireWorkspaceId,Ie as resolveConfigFile,Cn as runWithinAppSpan,dt as workspaceIdSchema};
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
+ `)}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
+ `),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};
@@ -11,6 +11,38 @@ declare function getActiveConfig(): LoadedTrayConfig;
11
11
  /** Test-only cleanup hook to drop worker-local state between cases. */
12
12
  declare function clearActiveConfig(): void;
13
13
 
14
+ declare class ScheduleInvocationError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ /**
18
+ * One schedule fire, as delivered by the platform invoke payload
19
+ * (helix-spec 03 #production-invocation). Timestamps are ISO-8601 strings on
20
+ * the wire; they surface to the handler as Dates on `ctx.trigger`.
21
+ */
22
+ interface ScheduleInvocation {
23
+ /** Handler path, e.g. `_scheduled/daily-report` — the run's identity. */
24
+ schedulePath: string;
25
+ scheduledAt: string;
26
+ firedAt: string;
27
+ isRetry: boolean;
28
+ isManual: boolean;
29
+ }
30
+ /**
31
+ * Run a `defineSchedule` handler for one schedule fire. Platform-internal —
32
+ * called by the Lambda router-shim (and, later, the dev scheduler); never by
33
+ * customer code.
34
+ *
35
+ * Mirrors defineFunction's invocation frame: OTel init + root span + paired
36
+ * summary (triggerType "schedule", no user), flags rollup, flush before the
37
+ * Lambda freezes. Identity comes from the sdk config the shim installed via
38
+ * setSdkConfig — there is no request and no user.
39
+ *
40
+ * Handler failures RETHROW after the span/summary are emitted: a schedule has
41
+ * no requester to answer, and the caller failing the invocation is what drives
42
+ * the platform's retry/DLQ semantics.
43
+ */
44
+ declare function runScheduledFunction(definition: unknown, invocation: ScheduleInvocation): Promise<void>;
45
+
14
46
  declare function assertValidPath(path: string, maxPathBytes?: number): void;
15
47
 
16
48
  type SdkErrorDetail = {
@@ -169,4 +201,4 @@ declare function getAdditionalEnvironmentProfiles(): EnvironmentProfile[];
169
201
  /** Test helper: drop non-builtin profiles and restore production. */
170
202
  declare function resetEnvironmentRegistryForTests(): void;
171
203
 
172
- export { CONFIG_BRIDGE_CHANNEL, type EnvironmentProfile, assertValidPath, clearActiveConfig, contentFilePath, getActiveConfig, getAdditionalEnvironmentProfiles, getEnvironmentProfile, isKnownEnvironment, isSdkError, listEnvironmentNames, listExposedEnvNames, metaFilePath, parseExposedEnvironment, registerEnvironmentProfile, requireEnvironmentProfile, resetEnvironmentRegistryForTests, resolveForcedEnvironment, setActiveConfig, setForcedEnvironment };
204
+ export { CONFIG_BRIDGE_CHANNEL, type EnvironmentProfile, type ScheduleInvocation, ScheduleInvocationError, assertValidPath, clearActiveConfig, contentFilePath, getActiveConfig, getAdditionalEnvironmentProfiles, getEnvironmentProfile, isKnownEnvironment, isSdkError, listEnvironmentNames, listExposedEnvNames, metaFilePath, parseExposedEnvironment, registerEnvironmentProfile, requireEnvironmentProfile, resetEnvironmentRegistryForTests, resolveForcedEnvironment, runScheduledFunction, setActiveConfig, setForcedEnvironment };
@@ -1 +1 @@
1
- import{c as e,h as n,i as o,j as r,k as t,m as x,s as P,t as C}from"../chunk-W32AX5BI.js";import{a as i,b as s,c as m,d as f,e as v,f as E,g,h as p,i as l,j as a,k as d,m as c}from"../chunk-7MAMPE72.js";export{n as CONFIG_BRIDGE_CHANNEL,x as assertValidPath,t as clearActiveConfig,P as contentFilePath,r as getActiveConfig,a as getAdditionalEnvironmentProfiles,m as getEnvironmentProfile,s as isKnownEnvironment,c as isSdkError,v as listEnvironmentNames,E as listExposedEnvNames,C as metaFilePath,g as parseExposedEnvironment,i as registerEnvironmentProfile,f as requireEnvironmentProfile,d as resetEnvironmentRegistryForTests,l as resolveForcedEnvironment,o as setActiveConfig,p as setForcedEnvironment,e as setSdkConfig};
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.82.0",
3
+ "version": "0.84.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -1 +0,0 @@
1
- var g=new Set(["production"]),i=new Map,o={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(o.name,o);var l=["api","broker","ingest","weaver","app","projectHost","dashboard"],d=["auth"],u=["storePrefix","appUrl","cookieName","cookieDomain"];function m(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 n of l)if(typeof e.hosts[n]!="string"||!e.hosts[n])throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string`);for(let n of d){let r=e.hosts[n];if(r!==void 0&&(typeof r!="string"||!r))throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string when set`)}for(let n of u)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function v(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&l.every(r=>e.hosts[r]===n.hosts[r])&&d.every(r=>e.hosts[r]===n.hosts[r])&&u.every(r=>e.login[r]===n.login[r])}function _(e){m(e);let n=i.get(e.name);if(n){if(v(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of i.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);i.set(e.name,e)}function c(e){return i.has(e)}function y(e){return i.get(e)}function E(e){let n=i.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function h(){return[...i.keys()]}function b(){return[...i.values()].map(e=>e.exposedName)}function f(e){for(let n of i.values())if(n.exposedName===e)return n.name}var s=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function p(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[s];return}let r=e.trim(),t=f(r);if(t){n[s]=t;return}if(c(r)){n[s]=r;return}throw new Error(`Unknown environment: ${r}`)}function w(){return globalThis[s]}function x(){return[...i.values()].filter(e=>!g.has(e.name))}function S(){p(void 0),i.clear(),i.set(o.name,{...o,hosts:{...o.hosts},login:{...o.login}})}var a=class e extends Error{detail;constructor(n){super(k(n)),this.name="SdkError",this.detail=n}get kind(){return this.detail.kind}static unknownAlias(n,r){return new e({kind:"unknown_alias",alias:n,available:r})}static inputValidationFailed(n){return new e({kind:"input_validation_failed",fields:n})}static outputValidationFailed(n){return new e({kind:"output_validation_failed",fields:n})}static configLoadFailed(n){return new e({kind:"config_load_failed",cause:n})}static brokerError(n,r,t){return new e({kind:"broker_error",status:n,message:r,body:t})}static unsupportedBodyType(n){return new e({kind:"unsupported_body_type",actualType:n})}static unsupportedScheme(n){return new e({kind:"unsupported_scheme",scheme:n})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(n,r){return new e({kind:"db_call_failed",message:n,cause:r})}static dbQueryFailed(n){return new e({kind:"db_query_failed",message:n})}static dbInvalidParameters(n){return new e({kind:"db_invalid_parameters",message:n})}static kvKeyInvalid(n){return new e({kind:"kv_key_invalid",message:n})}static kvValueInvalid(n){return new e({kind:"kv_value_invalid",message:n})}static kvValueTooLarge(n,r){return new e({kind:"kv_value_too_large",message:n,maxBytes:r})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(n,r,t){return new e({kind:"kv_call_failed",status:n,message:r,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(n){return new e({kind:"files_path_invalid",message:n})}static filesValueInvalid(n){return new e({kind:"files_value_invalid",message:n})}static filesValueTooLarge(n,r){return new e({kind:"files_value_too_large",message:n,maxBytes:r})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(n,r,t){return new e({kind:"files_call_failed",status:n,message:r,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function N(e){return e instanceof a}function k(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)"}}export{_ as a,c as b,y as c,E as d,h as e,b as f,f as g,p as h,w as i,x as j,S as k,a as l,N as m};
@@ -1 +0,0 @@
1
- import{d as m,l as p}from"./chunk-7MAMPE72.js";var l=new Set(["proxy-authorization","x-tray-token"]);function k(e){let t=e.toLowerCase();return l.has(t)||t.startsWith("x-tray-internal-")}function g(e){let t;return e instanceof Headers?t=Array.from(e.entries()):Array.isArray(e)?t=e:t=Object.entries(e),t.filter(([o])=>!k(o)).map(([o,i])=>({name:o,value:i}))}function B(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 q(e){let t=new URL(e.url);if(t.protocol!=="https:")throw p.unsupportedScheme(t.protocol.replace(/:$/,""));let o=e.body!==void 0&&e.body!==null?B(e.body):null;if(o!==null)throw p.unsupportedBodyType(o);let i=t.host,s=t.pathname,n=[];for(let[d,a]of t.searchParams.entries())n.push({name:d,value:a});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[d,a]of e.query.entries())n.push({name:d,value:a});else for(let[d,a]of Object.entries(e.query))if(Array.isArray(a))for(let h of a)n.push({name:d,value:h});else n.push({name:d,value:a});let u=e.headers!==void 0?g(e.headers):[],c=e.body!==void 0&&e.body!==null?{host:i,method:e.method,path:s,body:e.body,headers:u,queryParams:n}:{host:i,method:e.method,path:s,headers:u,queryParams:n};return{authenticationId:e.authenticationId,httpRequest:c}}function A(e){return m(e).hosts.broker}import{z as r}from"zod";var y=r.object({name:r.string(),value:r.string()}),R=r.object({host:r.string(),method:r.string(),path:r.string().startsWith("/"),body:r.record(r.unknown()).optional(),headers:r.array(y),queryParams:r.array(y)}),w=r.object({authenticationId:r.string().uuid(),httpRequest:R}),j=r.object({httpResponse:r.object({status:r.number(),body:r.unknown().optional(),headers:r.array(y)})});function D(e){let{status:t,body:o,headers:i}=e.httpResponse,s={};for(let{name:n,value:u}of i){let f=n.toLowerCase(),c=s[f];c===void 0?s[f]=u:Array.isArray(c)?c.push(u):s[f]=[c,u]}return{status:t,body:o,headers:s}}export{q as a,A as b,j as c,D as d};
@@ -1 +0,0 @@
1
- import{l as n}from"./chunk-7MAMPE72.js";var R="X-Helix-Project-Execution-Token",b="X-Tray-Token",h={mode:"dev",deploymentId:null},u={...h},i={};function B(t){let{internalJwt:e,helixExecutionJwt:r,devToken:o,...s}=t;"internalJwt"in t&&(i.internalJwt=e),"helixExecutionJwt"in t&&(i.helixExecutionJwt=r),"devToken"in t&&(i.devToken=o),u={...u,...s}}function D(){return u}function L(){return i.internalJwt}function F(){return i.helixExecutionJwt}function N(){return i.devToken}var J="tray-config-bridge",c=null;function M(t){c=t}function O(){if(!c)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return c}function U(){c=null}var E=1024,a=100*1024*1024,x=250,T=3600,S=T*1e3,m=new TextEncoder,_=/(^|\/)\.\.(\/|$)/,p=/[?#]/;function v(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r<=31||r===127)return!0}return!1}function $(t,e=E){if(t.length===0)throw n.filesPathInvalid("Path must be a non-empty string");A(t,e)}function G(t){return t.endsWith("/")?t.slice(0,-1):t}function A(t,e=E){if(t.length===0)return;if(_.test(t))throw n.filesPathInvalid("Path contains path traversal segment");if(p.test(t)||v(t))throw n.filesPathInvalid("Path contains illegal characters");let r=t.split("/");if(t.startsWith("/")||t.endsWith("/")||r.some(s=>s===""))throw n.filesPathInvalid("Path must not contain empty path segments");for(let s of r){let d=m.encode(s).length;if(d>x)throw n.filesPathInvalid(`Path segment exceeds ${x} UTF-8 bytes (got ${d})`)}let o=m.encode(t).length;if(o<1||o>e)throw n.filesPathInvalid(`Path must be between 1 and ${e} UTF-8 bytes (got ${o})`)}function V(t){if(t>a)throw n.filesValueTooLarge(`File exceeds maximum size of ${a} bytes (got ${t})`,a)}function W(t){let e=t!==void 0?t*1e3:S;return new Date(Date.now()+e)}import{join as f}from"path";var C="files",I="files-meta",P=1023,w=1,k=5;function K(t){let e=Math.max(Buffer.byteLength(l(t),"utf8"),Buffer.byteLength(g(t),"utf8"));return Math.max(0,P-e-w-k)}function l(t){return f(t,".helix",C)}function g(t){return f(t,".helix",I)}function y(t,e){return f(l(t),...e.split("/"))}function q(t,e){return f(g(t),...e.split("/"))+".json"}function Q(t,e){return e.length===0?l(t):y(t,e)}function Z(t,e){return e.length===0?g(t):f(g(t),...e.split("/"))}export{R as a,b,B as c,D as d,L as e,F as f,N as g,J as h,M as i,O as j,U as k,a as l,$ as m,G as n,A as o,V as p,W as q,K as r,y as s,q as t,Q as u,Z as v};