@trayai/helix-sdk 0.80.0 → 0.82.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/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
- import { c as FunctionHandler, b as DefineFunctionOptions, T as TrayContext } from './types-DXkq0EN9.js';
4
- export { D as DbCallParameters, a as DbClient, F as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, S as SqlBuilder, U as UnvalidatedInput } from './types-DXkq0EN9.js';
3
+ import { d as FunctionHandler, b as DefineFunctionOptions, c as DefineScheduleConfig, e as ScheduleDefinition, T as TrayContext } from './types-BKsomkJf.js';
4
+ export { D as DbCallParameters, a as DbClient, F as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, S as ScheduleContext, f as ScheduleHandler, g as ScheduleTrigger, h as SqlBuilder, U as UnvalidatedInput } from './types-BKsomkJf.js';
5
5
  import { T as TrayConfig, L as LoadedTrayConfig, b as WatchErrorPhase } from './sdk-config-DrgARqBz.js';
6
6
  export { P as ProvisionedTrayConfig, a as SdkRuntimeConfig, U as UnprovisionedTrayConfig, W as WORKSPACE_ID_REQUIRED_CODE, c as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, d as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, e as resolveConfigFile, w as workspaceIdSchema } from './sdk-config-DrgARqBz.js';
7
7
  export { E as ENVIRONMENT_VALUES, a as Environment, e as environmentSchema } from './env-schema-CMAM3FrY.js';
@@ -10,6 +10,29 @@ import 'unstorage';
10
10
 
11
11
  declare function defineFunction<TInput extends ZodType | undefined = undefined, TOutput extends ZodType | undefined = undefined>(handler: FunctionHandler<TInput extends ZodType ? ReturnType<TInput["parse"]> : Record<string, unknown>>, schemaOrOptions?: ZodType | DefineFunctionOptions<TInput, TOutput>): h3.EventHandler<h3.EventHandlerRequest, Promise<unknown>>;
12
12
 
13
+ /**
14
+ * Discriminant for objects produced by defineSchedule. A plain string (not a
15
+ * Symbol or class) so detection survives bundling: the builder and the shim
16
+ * may evaluate a customer bundle carrying its own copy of the SDK, where
17
+ * identity-based checks (instanceof, Symbol) silently fail across copies.
18
+ */
19
+ declare const SCHEDULE_DEFINITION_KIND = "helix-schedule";
20
+ declare class ScheduleConfigError extends Error {
21
+ constructor(message: string);
22
+ }
23
+ /**
24
+ * Define a scheduled function (helix-spec 03-functions-and-routing.md
25
+ * #defineschedule). Files under `functions/_scheduled/` default-export the
26
+ * result; they are never HTTP-routable. The builder extracts `cron`,
27
+ * `timezone` and `concurrent` from the returned definition at build time and
28
+ * performs full cron validation there (including rejecting expressions that
29
+ * constrain both day-of-month and day-of-week) — validation here is the
30
+ * cheap structural subset that gives immediate feedback in dev.
31
+ */
32
+ declare function defineSchedule(config: DefineScheduleConfig): ScheduleDefinition;
33
+ /** Structural check for defineSchedule output — see SCHEDULE_DEFINITION_KIND. */
34
+ declare function isScheduleDefinition(value: unknown): value is ScheduleDefinition;
35
+
13
36
  interface RunWithinAppSpanArgs {
14
37
  executionId: string;
15
38
  deploymentId: string | null;
@@ -111,4 +134,4 @@ interface ConfigService {
111
134
  */
112
135
  declare function createConfigService(options: CreateConfigServiceOptions): Promise<ConfigService>;
113
136
 
114
- export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, FunctionHandler, LoadedTrayConfig, type RunWithinAppSpanArgs, TrayConfig, TrayContext, WatchErrorPhase, createConfigService, defineConfig, defineFunction, getContext, runWithinAppSpan };
137
+ export { type ConfigService, type CreateConfigServiceOptions, DefineFunctionOptions, DefineScheduleConfig, FunctionHandler, LoadedTrayConfig, type RunWithinAppSpanArgs, SCHEDULE_DEFINITION_KIND, ScheduleConfigError, ScheduleDefinition, TrayConfig, TrayContext, WatchErrorPhase, createConfigService, defineConfig, defineFunction, defineSchedule, getContext, isScheduleDefinition, runWithinAppSpan };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{a as wt,b as Yr}from"./chunk-L6J5L3JQ.js";import{a as k,b as D,d as y,e as O,f as T,g as pt,j as b,l as V,m as I,n as Ie,o as Ae,p as St,q as L,r as xt,s as ie,t as ae,u as ce,v as Ct}from"./chunk-W32AX5BI.js";import{a as q,b as se,c as bt,d as Et}from"./chunk-R56ARJY5.js";import{b as gt,d as F,e as yt,i as ht,l as c,m as vt}from"./chunk-7MAMPE72.js";import{randomUUID as $o}from"crypto";import{SpanStatusCode as Br,SpanKind as Ho}from"@opentelemetry/api";import{AsyncLocalStorage as qt}from"async_hooks";import{trace as dn,SpanKind as ln,SpanStatusCode as Oe}from"@opentelemetry/api";import{ExportResultCode as fn,W3CTraceContextPropagator as mn}from"@opentelemetry/core";import{NodeTracerProvider as pn,SimpleSpanProcessor as gn,BatchSpanProcessor as yn}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as Gr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Xr}from"@opentelemetry/exporter-logs-otlp-proto";function _e(e){return F(e).hosts.ingest}function Zr(){return T()??""}function Rt(){return{[k]:Zr()}}function kt(){let e=_e(b().env);return new Gr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(Rt())})}function Tt(){let e=_e(b().env);return new Xr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(Rt())})}import{logs as At,SeverityNumber as ue}from"@opentelemetry/api-logs";import{LoggerProvider as tn,BatchLogRecordProcessor as rn}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 Qr(e){return new TextEncoder().encode(e).length}var Pt="\u2026[truncated]",en=Qr(Pt),z=4096;function A(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-en);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+Pt}function h(e,t=z){return A(W(e),t)}var nn="@trayai/helix-sdk",J,It={debug:{number:ue.DEBUG,text:"DEBUG"},info:{number:ue.INFO,text:"INFO"},warn:{number:ue.WARN,text:"WARN"},error:{number:ue.ERROR,text:"ERROR"}};function on(){return y().mode==="lambda"?[new rn({exporter:Tt()})]:[]}function _t(){if(J!==void 0)return;let e=on();e.length!==0&&(J=new tn({processors:e}),At.setGlobalLoggerProvider(J))}function sn(e,t,r){let n=It[e]??It.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":h(r)}}:{}}}function Dt(e,t,r){At.getLogger(nn).emit(sn(e,t,r))}async function Ot(e=2e3){if(J===void 0)return;let t;try{await Promise.race([J.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 De(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function an(){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 R(e,t){return an()?`\x1B[${e}m${t}\x1B[0m`:t}var cn=5,un={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},Ft="32",Lt="31",de="2",jt="1";function le(e){return R(un[e]??"0",e.padEnd(cn))}function Nt(e,t){return`${le("FN")} ${R(jt,`${e} ${t}`.trim())}`}function Bt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${R(de,n)} `:""}${le(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${R(de,W(r))}`),i}function Ut(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Mt(e){return`${le("AUTH")} ${e}`}function $t(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=R(o==="error"?Lt:Ft,s);return`${le("API")} ${e} ${t} \u2192 ${i} ${R(de,`${n}ms`)}`}function Ht(e,t,r){let n=t?Lt:Ft,o=R(n,"\u25CF"),s=R(n,t?"error":"success");return`${o} ${R(jt,e)} ${s} ${R(de,`${r}ms`)}`}function j(e){try{process.stdout.write(e+`
3
- `)}catch{}}var fe=new qt,me=new qt;function x(e){let t=me.getStore();t&&(t[e]=!0)}var hn=/^[0-9a-f]{32}$/;function wn(e){let t=e.replace(/-/g,"").toLowerCase();return hn.test(t)?t:null}var vn={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},N=new Map;function Vt(e,t,r){let n=N.get(e);n?n[t]=r:N.set(e,{[t]:r})}function S(e,t,r){e.setAttribute(t,h(r))}var Y;function Kt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function bn(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Wt(e){try{process.stdout.write(W(e)+`
4
- `)}catch{}}var Fe=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=N.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;N.delete(o)}let a=fe.getStore(),u=a?wn(a):null;Wt({_otel:"span",traceId:u??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Kt(n.startTime),endTimeUnixNano:Kt(n.endTime),attributes:i,status:{code:vn[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:A(n.status.message)}:{}}})}r({code:fn.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t,r){}onEnd(t){N.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},je=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&j(`
5
- `+Nt(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=N.get(n)?.properties;j(Bt(String(r.level??"info"),String(r.message??""),o,Ut(t.startTime)));break}case"auth":j(Mt(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;j($t(String(r.method??""),String(r.host??""),n,bn(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=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 En(){let t=[De()?new je:new gn(new Fe)];return y().mode==="lambda"&&t.push(new Ne(new yn(kt()))),t.push(new Le),t}function Be(){Y===void 0&&(Y=new pn({spanProcessors:En()}),Y.register({propagator:new mn}),_t())}async function Ue(e=2e3){let t=[Ot(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.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=dn.getTracer("@trayai/helix-sdk");function Me({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(De()){j(`
7
- `+Ht(r,s,f));return}Wt({_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 Sn(e,t){let r=e.startMs??Date.now();Be();let n=!1,o=null;try{return await fe.run(e.executionId,()=>C.startActiveSpan("App",{kind:ln.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?Oe.ERROR:Oe.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:Oe.ERROR,message:o}),i}finally{s.end()}}))}finally{Me({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 Ue()}}import{defineEventHandler as Ko,getMethod as qo,getRequestURL as Vo,getHeaders as Mr,getHeader as Ur}from"h3";import{readBody as xn,getQuery as Cn,getRouterParams as Rn}from"h3";async function zt(e,t){let r=await kn(e),n=Cn(e),o=Rn(e)??{},s={...n,...r,...o};return t?Tn(s,t):s}async function kn(e){try{let t=await xn(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 Tn(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 Pn}from"@opentelemetry/api";function pe(e,t,r){let n=C.startSpan("log",{kind:Pn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Vt(n.spanContext().spanId,"properties",r),n.end(),Dt(e,t,r)}function Jt(){return{info:(e,t)=>pe("info",e,t),warn:(e,t)=>pe("warn",e,t),error:(e,t)=>pe("error",e,t),debug:(e,t)=>pe("debug",e,t)}}var G=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function Yt(e){return t=>{e.node.res.statusCode=t}}function Gt(){return(e,t)=>{throw new G(e,t)}}import _n from"ky";import{context as $e,trace as Dn,SpanKind as ye,SpanStatusCode as Qt}from"@opentelemetry/api";import In from"ky";async function Xt(e,t={}){let r=O(),n=T(),o=!!(r&&r.trim().length>0),s=!!(n&&n.trim().length>0);if(!o&&!s)throw c.missingExecutionCredentials();let{env:i}=b(),a=se(i),u=t.timeout??6e4,d={Accept:"application/json"};o&&(d[D]=r),s&&(d[k]=n);let f=y().deploymentId,l=f?{...e,deploymentId:f}:e,m=await In.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 An from"ky";async function Zt(e,t={}){let r=pt();if(!r)throw c.missingTrayToken();let{env:n}=b(),o=se(n),s=t.timeout??6e4,i=await An.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 ge(e,t={}){let r=y().mode==="lambda"?Xt:Zt,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=bt.safeParse(s);if(!i.success)throw c.brokerError(o,"broker returned malformed response",h(s));return Et(i.data)}var On=["get","post","put","patch","delete","head","options"],er="[stream body omitted]";function He(e){try{return new URL(e).hostname}catch{return e}}function Fn(e,t,r,n){let o=He(t),s="externalApi",i={kind:ye.CLIENT};return C.startActiveSpan(s,i,async a=>(a.setAttributes({method:e,host:o}),S(a,"request",{url:t,method:e,...r!==void 0?{body:r instanceof ReadableStream?er:r}:{}}),n(a)))}function Ke(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Qt.OK}:{code:Qt.ERROR,message:r}),e.end()}var Ln=16;async function jn(e,t){let r=e.clone().body;return r?tr(r,t):new Uint8Array(0)}async function tr(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>=Ln)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 rr(e,t,r){if("kyResponse"in r)try{let n=await jn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}S(e,"response",s)}catch{S(e,"response",{status:t})}else S(e,"response",r.bodyValue)}async function Nn(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 tr(o,z);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:er}}}return typeof t=="string"?{body:t}:{}}function nr(){let e=_n.create({});function t(n){return(o,s)=>{let i=$e.active(),a,u=!1,d=(l,m)=>{a&&!u&&(u=!0,Ke(a,l,m))},f=e.extend({hooks:{beforeRequest:[async(l,m)=>{let p=await Nn(l,m.body),g=p.body;if(a||(a=C.startSpan("externalApi",{kind:ye.CLIENT},i)),a.setAttributes({method:l.method.toUpperCase(),host:He(l.url)}),S(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 rr(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:ye.CLIENT},i),a.setAttributes({method:n.toUpperCase(),host:He(String(o))}),$e.with(Dn.setSpan($e.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(On.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Bn(n)}}}function Bn(e){let r=b().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 Fn(u,i,a.body,async d=>{x("hasAuth");let f=C.startSpan("auth",{kind:ye.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let l=q({authenticationId:n,method:u,url:i,body:a.body,headers:a.headers,query:a.query}),m=await ge(l,{timeout:a.timeout});return d.setAttribute("statusCode",m.status),await rr(d,m.status,{bodyValue:m.body}),Ke(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),Ke(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 zn,SpanStatusCode as ar}from"@opentelemetry/api";function X(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Un=18e4,or=Un-1e4,Mn=2e3;async function sr(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<or;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let u=Math.min(Mn,200*2**s),d=u/2+Math.random()*(u/2),f=or-(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 $n=new Set(["SELECT","WITH","SHOW"]),Hn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function Kn(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 qn(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 Vn(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 Wn(e,t){return typeof t!="number"||t<0?{}:$n.has(e)?{rowsRead:t}:Hn.has(e)?{rowsWritten:t}:{}}function ir(e){async function t(r,n,o){let s=q({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 ge(s);if(i>=400)throw qn(i,a);return Vn(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:Kn,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 sr(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=Wn(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 qe=64*1024;function Jn(e){return e.length>qe?`${e.slice(0,qe)}...[truncated]`:e}function Yn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Gn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>qe?S(e,"result",{truncated:!0,size:n.length}):S(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Xn(e,t,r){let n=X(r),o=Jn(r);return C.startActiveSpan("database",{kind:zn.CLIENT},async s=>{Yn(s,e,t,n,o);try{x("hasDb");let{result:i,metadata:a}=await e.execute(t,r),u=Gn(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:ar.OK}),u}catch(i){x("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:ar.ERROR,message:a}),i}finally{s.end()}})}function Ve(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=ir(n);function s(i,a){return o.validate(i),Xn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as ro}from"unstorage";var cr=1024,We=250*1024,Zn=new TextEncoder,Qn=/(^|\/)\.\.(\/|$)/,eo=/[?#]/,to=/[\u0000-\u001F\u007F]/;function ur(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(Qn.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(eo.test(e)||to.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=Zn.encode(e).length;if(t<1||t>cr)throw c.kvKeyInvalid(`Key must be between 1 and ${cr} UTF-8 bytes (got ${t})`)}function dr(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 Z(e){ur(e)}function he(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function lr(e){let t=he(e,"getItem"),r=he(e,"setItem"),n=he(e,"removeItem"),o=he(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return Z(i),t(i,a)},setItem(i,a,u){return Z(i),r(i,a,u)},removeItem(i,a){return Z(i),n(i,a)},hasItem(i,a){return Z(i),o(i,a)},getKeys(i,a){return i.length>0&&Z(i),s(i,a)}}}function we(e){return ro({driver:lr(e)})}import{defineDriver as no}from"unstorage";function oo(e){try{return JSON.parse(e)}catch{return e}}var so=no(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,oo(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 fr(e){return so({client:e})}import co 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 mr(e){return F(e).hosts.api}function io(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function ao(e){return e.split("/").map(encodeURIComponent).join("/")}function Q(e,t,r){return`${e}${io(t)}/${ao(r)}`}var uo=6e4,ze=v.lazy(()=>v.union([v.string(),v.number(),v.boolean(),v.null(),v.array(ze),v.record(ze)])),lo=v.object({projectId:v.string(),key:v.string(),value:ze,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 fo(){let e=O(),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[D]=e),n&&(o[k]=t),o}function mo(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 ve(e,t){throw c.kvCallFailed(e,mo(t),h(t))}async function be(e,t,r={}){try{let n=await co(t,{method:e,headers:fo(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:uo}),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 pr(e){let t=mr(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await be("get",Q(t,r,n));if(o===404)return null;(o<200||o>=300)&&ve(o,s);let i=lo.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",Q(t,r,n),{json:{value:o}});(s<200||s>=300)&&ve(s,i)},async delete(n){let{status:o,body:s}=await be("delete",Q(t,r,n));o!==204&&ve(o,s)},async has(n){let{status:o,body:s}=await be("head",Q(t,r,n));if(o===200)return!0;if(o===404)return!1;ve(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)=>{dr(r),await e.setItem(t,r,n)}}}function po(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function gr(e){let t=po(),r=e??pr(t),n=we(fr(r));return Ee(n)}import go from"unstorage/drivers/memory";var Je;function yo(){return Je||(Je=we(go())),Je}function yr(){return Ee(yo())}function ho(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function hr(){return ho()?gr():yr()}import{createHash as bo}from"crypto";import{mkdir as Eo,readFile as Sr,readdir as xr,rm as vr,unlink as So,writeFile as br}from"fs/promises";import{dirname as xo}from"path";async function wo(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>V)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${V} bytes (got more than ${V})`,V);r.push(s)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?wo(e):Buffer.from(e)}var vo={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"},wr="application/octet-stream";function Se(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return wr;let r=e.slice(t+1).toLowerCase();return vo[r]??wr}function $(){let e=y().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function M(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 Ye(e){try{let t=await Sr(ae($(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Er(e){await Eo(xo(e),{recursive:!0})}async function Co(e,t){let r=ce(e,t),n;try{n=await xr(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 Cr(e,t){let r=ce(e,t),n;try{n=await xr(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 Cr(e,i)):s.isFile()&&o.push(i)}return o}function Rr(){return{async put(e,t,r){return M(async()=>{let n=$(),o=await U(t),s=r?.contentType??Se(e),i=bo("sha1").update(o).digest("hex"),a=new Date,u=ie(n,e);await Er(u),await br(u,o);let d={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},f=ae(n,e);return await Er(f),await br(f,JSON.stringify(d)),xe(e,d)})},async get(e){return M(async()=>{let t=await Ye(e);return t?{data:await Sr(ie($(),e)),metadata:xe(e,t)}:null})},async head(e){return M(async()=>{let t=await Ye(e);return t?xe(e,t):null})},async delete(e){return M(async()=>{let t=$();await Promise.all([ie(t,e),ae(t,e)].map(async r=>{try{await So(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return M(async()=>{let t=$(),r=await Cr(t,e);return await Promise.all([vr(ce(t,e),{recursive:!0,force:!0}),vr(Ct(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return M(async()=>{let r=$(),n=t?.limit??100,s=(await Co(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let u=await Ye(a);return u?xe(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:L(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:L(t?.expiresIn)}}}}import{createHash as _o}from"crypto";function Ce(e){return F(e).hosts.api}function Ro(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ee(e,t){return`${e}${Ro(t)}`}function H(e,t,r){return`${ee(e,t)}/${encodeURIComponent(r)}`}function Re(e,t,r){return`${H(e,t,r)}/upload`}function kr(e,t,r){return`${H(e,t,r)}/download`}function Tr(e,t,r){return`${H(e,t,r)}/signed-url`}function Pr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ee(e,t)}/file?${o.toString()}`}function Ir(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ee(e,t)}?${o.toString()}`}import Xe from"ky";import{z as w}from"zod";var Ze=6e4,Ar=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()}),ko=w.object({signedURL:w.string()}),To=w.object({path:w.array(w.object({id:w.string(),name:w.string()})),elements:w.array(Ar)});function Qe(){let e=O(),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[D]=e),n&&(o[k]=t),o}function _r(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,_r(t),h(t))}function Po(e,t){return e===400&&_r(t).toLowerCase()==="resource not found"}async function Io(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 K(e,t,r={}){try{let n=await Xe(t,{method:e,headers:Qe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ze}),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 Ge(e,t){let r=Ar.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",h(t));return r.data}function Dr(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await K("post",ee(t,r),{json:n});return(o<200||o>=300)&&P(o,s),Ge(o,s)},async getByName(n,o){let{status:s,body:i}=await K("get",Pr(t,r,n,o));return s===404||Po(s,i)?null:((s<200||s>=300)&&P(s,i),Ge(s,i))},async getById(n){let{status:o,body:s}=await K("get",H(t,r,n));return o===404?null:((o<200||o>=300)&&P(o,s),Ge(o,s))},async listChildren(n,o){let{status:s,body:i}=await K("get",Ir(t,r,n,o));(s<200||s>=300)&&P(s,i);let a=To.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 Io(a),f;try{f=await Xe(Re(t,r,n),{method:"post",headers:{...Qe(),"content-type":d},body:new Uint8Array(u),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 l=await B(f);(f.status<200||f.status>=300)&&P(f.status,l)},async downloadContent(n){let o;try{o=await Xe(kr(t,r,n),{method:"get",headers:Qe(),throwHttpErrors:!1,timeout:Ze})}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 K("get",Tr(t,r,n));(o<200||o>=300)&&P(o,s);let i=ko.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 K("delete",H(t,r,n));o===204||o===404||(o<200||o>=300)&&P(o,s)}}}function et(e){return e.split("/").filter(t=>t.length>0)}function tt(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function Ao(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(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function rt(e,t){let r=et(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await Ao(e,o,s)).id;return{parentFolder:o,name:n}}async function te(e,t){let r=et(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 nt(e,t){if(t.length===0)return;let r=et(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 Do=500,Oo=8;async function Fo(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 Lo(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function jo(e){return _o("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function ke(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:jo(t)}}async function Or(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(tt(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Fr(e,t){let{elements:r}=await e.listChildren(t,Do);return(await Fo(r,Oo,async o=>{let s=o.objectType==="Folder"?await Fr(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function Lr(e){let t=Lo(),r=e??Dr(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:u,name:d}=await rt(r,s),f=await U(i),l=a?.contentType??Se(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 Or(r,u,d,l);await r.uploadContent(p.id,f,d,l);let g=await r.getById(p.id);return ke(s,g??p,l)},async get(s){let i=await te(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:ke(s,a)}},async head(s){let i=await te(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:ke(s,a)},async delete(s){let i=await te(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 nt(r,s);if(i===null)return{deleted:0};let a=await Fr(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await nt(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=>ke(s?`${s}/${l.name}`:l.name,l)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:u}=await rt(r,s),f=await r.getByName(a,u)??await Or(r,a,u,i?.contentType);return{url:Re(n,o,f.id),expiresAt:L(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await te(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:L(i?.expiresIn)}}}}function ot(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){I(n,r);let i=await U(o);return St(i.byteLength),e.put(n,i,s)},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=Ie(n);return Ae(o,r),e.deleteMany(o)},async list(n,o){let s=Ie(n??"");return Ae(s,r),e.list(s,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 No(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function jr(){if(No())return ot(Lr());let e=y().projectRoot;return ot(Rr(),{maxPathBytes:e?xt(e):void 0})}function Nr(e,t){let{statusCode:r,message:n}=Bo(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Bo(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 Uo=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Mo(e){return e.toLowerCase().includes("tray_lid")}function st(e){let t={};for(let[r,n]of Object.entries(e))if(!Uo.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!Mo(i)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Wo(e,t){let{inputSchema:r,outputSchema:n}=Zo(t),o=e;return Ko(async s=>{let i=y(),{executionId:a,userId:u,deploymentId:d}=Qo(i,s),f=Date.now(),l=new Date().toISOString(),m=qo(s),p=Vo(s).pathname,g=es(),_=Jt(),ne=`${m} ${p}`;Be();let mt={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return zo(()=>me.run(mt,()=>fe.run(a,async()=>{let oe=await Jo(s,r);if(!oe.ok)return{response:oe.response,errored:!1,errorMessage:null};let Jr=rs(s,oe.input,g,_,m,p,a,d,u);return Yo(o,Jr,n,s,_,a,d,{method:m,path:p,rawInput:oe.input})})),{executionId:a,deploymentId:d,routeOrJob:ne,startedAt:l,startMs:f,userId:u,flags:mt})})}async function zo(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Me({...t,errored:r,errorMessage:n}),await Ue()}}async function Jo(e,t){try{return{ok:!0,input:await zt(e,t)}}catch(r){let n=ts(e,r);if(n)return{ok:!1,response:n};throw r}}async function Yo(e,t,r,n,o,s,i,a){return C.startActiveSpan("function",{root:!0,kind:Ho.SERVER,attributes:{method:a.method,route:a.path,executionId:s,...i?{deploymentId:i}:{}}},async u=>{t.traceId=u.spanContext().traceId;let d=st(Mr(n));S(u,"input",a.rawInput),S(u,"request",{method:a.method,path:a.path,headers:d,body:a.rawInput});let f=!1,l=null,m,p;try{let g=await wt.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 ne=Object.keys(_.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:ne,executionId:s}),c.outputValidationFailed(ne)}p=_.data}else p=g}catch(g){f=!0,l=g instanceof Error?g.message:String(g),x("hasError"),p=Go(g,n,o,s)}finally{Xo(u,n,{errored:f,errorMessage:l,handlerResult:m,response:p})}return{response:p,errored:f,errorMessage:l}})}function Go(e,t,r,n){if(e instanceof G)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(vt(e))return Nr(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 Xo(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&S(e,"output",r.handlerResult),S(e,"response",r.response);let n=me.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?Br.ERROR:Br.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Zo(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 Qo(e,t){let r=e.mode==="lambda",n=(r?e.executionId:Ur(t,"x-tray-execution-id"))??$o(),o=(r?e.userId:Ur(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function es(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}function ts(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 rs(e,t,r,n,o,s,i,a,u){return{input:t,method:o,path:s,headers:st(Mr(e)),http:nr(),db:d=>Ve(d),kv:()=>hr(),files:()=>jr(),log:n,config:r,status:Yt(e),error:Gt(),state:{},request:e,executionId:i,deploymentId:a,userId:u,identity:u!==null?{user:{id:u}}:null,traceId:""}}function ns(e){return e}import{resolve as it}from"path";import{existsSync as Hr}from"fs";import{loadConfig as is}from"c12";import{z as E}from"zod";import{z as os}from"zod";var ss=["production"],Te=os.string().refine(e=>gt(e),e=>({message:`Invalid enum value. Expected ${yt().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var at=E.string().uuid("projectId must be a valid UUID"),ct=E.string().min(1,"workspaceId must be a non-empty string"),as=E.object({name:E.string().min(1,"name is required"),projectId:at.optional(),workspaceId:ct.optional(),env:Te.default("production"),authentications:E.record(E.string()).optional().default({}),config:E.record(E.unknown()).optional().default({})}),$r=E.object({name:E.string().min(1,"name is required"),workspaceId:ct.optional(),env:Te,authentications:E.record(E.string()),config:E.record(E.unknown())}),cs=E.discriminatedUnion("kind",[$r.extend({kind:E.literal("provisioned"),projectId:at}),$r.extend({kind:E.literal("unprovisioned")})]),Kr=["helix","tray"],qr=["ts","mts","cts","js","mjs","cjs"];function Pe(e){for(let t of Kr)for(let r of qr){let n=it(e,`${t}.config.${r}`);if(Hr(n))return n}}function us(e){for(let t of Kr)if(qr.some(r=>Hr(it(e,`${t}.config.${r}`))))return t;return"helix"}function ut(e){return{name:us(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function dt(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=as.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=ht(),u=a!==void 0?{...s,env:a}:s;return n!==void 0?{kind:"provisioned",projectId:n,...u,...i}:{kind:"unprovisioned",...u,...i}}async function re(e){let t=e??process.cwd(),r;try{r=await is(ut(t))}catch(o){throw c.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??Pe(t);if(!n)throw c.configLoadFailed(`helix.config.ts not found at ${it(t,"helix.config.ts")}`);return dt(r.config,n)}var Vr="WORKSPACE_ID_REQUIRED";function ds(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:Vr});return e.workspaceId}import{existsSync as ls,watch as fs,writeSync as ms}from"fs";import{join as ps,resolve as gs}from"path";import{watchConfig as ys}from"c12";function hs(e,t){let r=e instanceof Error?e.message:String(e);ms(2,`[helix-watch] ${t.phase} error: ${r}
8
- `)}function lt(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ws=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,Wr=new Set;function zr(e){return Pe(e)!==void 0}async function vs(e,t){if(zr(e.cwd))try{return{current:await re(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:lt(),initialLoadSucceeded:!1}}if(e.watch){let r=gs(e.cwd);Wr.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
- `),Wr.add(r))}return{current:lt(),initialLoadSucceeded:!1}}var ft=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=ys({...ut(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=dt(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=fs(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();ws.test(n)&&ls(ps(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await re(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 bs(e){let t=e.onError??hs,r=new Set,n=await vs(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 ft(e.cwd,t,s);return e.watch&&i.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!zr(e.cwd)){let a=lt();return s(a),a}try{let a=await re(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{ss as ENVIRONMENT_VALUES,Vr as WORKSPACE_ID_REQUIRED_CODE,bs as createConfigService,ns as defineConfig,Wo as defineFunction,Te as environmentSchema,Yr as getContext,y as getSdkConfig,re as loadConfig,cs as loadedTrayConfigSchema,at as projectIdSchema,ds as requireWorkspaceId,Pe as resolveConfigFile,Sn as runWithinAppSpan,ct as workspaceIdSchema};
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,4 +1,4 @@
1
- import { T as TrayContext } from '../types-DXkq0EN9.js';
1
+ import { T as TrayContext } from '../types-BKsomkJf.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
@@ -162,5 +162,62 @@ interface DefineFunctionOptions<TInput extends ZodType | undefined = undefined,
162
162
  output?: TOutput;
163
163
  }
164
164
  type FunctionHandler<T = Record<string, unknown>> = (ctx: TrayContext<T>) => Promise<unknown>;
165
+ /** `ctx.trigger` for scheduled functions (helix-spec 03 #defineschedule). */
166
+ interface ScheduleTrigger {
167
+ type: "schedule";
168
+ /** When the cron said it should fire. */
169
+ scheduledAt: Date;
170
+ /** When it actually executed (may differ due to cold start, retry, etc.). */
171
+ firedAt: Date;
172
+ /** True if this is a retry of a failed execution. */
173
+ isRetry: boolean;
174
+ /** True if triggered via `helix trigger` or the MCP tool. */
175
+ isManual: boolean;
176
+ }
177
+ /**
178
+ * Context for scheduled handlers: the full platform surface of TrayContext
179
+ * with every request-derived field (input, method, path, headers, status,
180
+ * error, request) structurally absent — scheduled runs have no request and
181
+ * no user, so those fields are omitted rather than null.
182
+ */
183
+ interface ScheduleContext {
184
+ http: HttpClient;
185
+ db(alias: string): DbClient;
186
+ kv(): KeyValueStore;
187
+ files(): FileSystemClient;
188
+ log: Logger;
189
+ config: Record<string, unknown>;
190
+ state: Record<string, unknown>;
191
+ executionId: string;
192
+ deploymentId: string | null;
193
+ traceId: string;
194
+ trigger: ScheduleTrigger;
195
+ }
196
+ type ScheduleHandler = (ctx: ScheduleContext) => Promise<void> | void;
197
+ interface DefineScheduleConfig {
198
+ /** 5-field standard cron (minute hour day-of-month month day-of-week). */
199
+ cron: string;
200
+ /** IANA timezone name. Defaults to UTC. */
201
+ timezone?: string;
202
+ handler: ScheduleHandler;
203
+ }
204
+ /**
205
+ * What defineSchedule returns and `functions/_scheduled/` files default-export.
206
+ * `kind` is the extraction/dispatch discriminant; the builder reads cron,
207
+ * timezone and concurrent from here at build time, and the Lambda shim
208
+ * resolves `handler` from here at run time.
209
+ */
210
+ interface ScheduleDefinition {
211
+ kind: "helix-schedule";
212
+ cron: string;
213
+ timezone: string;
214
+ /**
215
+ * Always true: overlap control is not customer-configurable yet, and the
216
+ * platform allows concurrent runs. Carried on the extraction/wire contract
217
+ * so enforcement can arrive without a contract change.
218
+ */
219
+ concurrent: boolean;
220
+ handler: ScheduleHandler;
221
+ }
165
222
 
166
- export type { DbCallParameters as D, FileSystemClient as F, HttpClient as H, KeyValueStore as K, Logger as L, SqlBuilder as S, TrayContext as T, UnvalidatedInput as U, DbClient as a, DefineFunctionOptions as b, FunctionHandler as c };
223
+ export type { DbCallParameters as D, FileSystemClient as F, HttpClient as H, KeyValueStore as K, Logger as L, ScheduleContext as S, TrayContext as T, UnvalidatedInput as U, DbClient as a, DefineFunctionOptions as b, DefineScheduleConfig as c, FunctionHandler as d, ScheduleDefinition as e, ScheduleHandler as f, ScheduleTrigger as g, SqlBuilder as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.80.0",
3
+ "version": "0.82.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",