@trayai/helix-sdk 0.95.0 → 0.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,26 @@ general availability, minor versions may include breaking changes.
9
9
  The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
10
10
  released together and share a version — install matching versions.
11
11
 
12
+ ## 0.97.0
13
+
14
+ ### Added
15
+
16
+ - **Config-file override for multi-target projects.** `loadConfig`,
17
+ `createConfigService`, and `resolveConfigFile` accept an optional `{ configFile }`
18
+ naming a config file other than `helix.config.ts`, falling back to the
19
+ `HELIX_CONFIG` environment variable when the option is omitted (explicit option →
20
+ env var → default). New exports: `resolveConfigOverride`, `HELIX_CONFIG_ENV`, and
21
+ the `ConfigFileOptions` type. Pairs with the CLI's new `--config <path>` flag for
22
+ one-config-file-per-target workflows.
23
+
24
+ ## 0.96.0
25
+
26
+ ### Added
27
+
28
+ - `defineSchedule` accepts a `concurrent` option (default `false`). A scheduled run is skipped
29
+ by default when the previous run for that schedule is still in flight; set `concurrent: true`
30
+ to allow overlapping runs instead.
31
+
12
32
  ## 0.95.0
13
33
 
14
34
  ### Added
package/README.md CHANGED
@@ -154,6 +154,7 @@ import { defineSchedule } from '@trayai/helix-sdk';
154
154
  export default defineSchedule({
155
155
  cron: '0 6 * * *', // 5-field standard cron
156
156
  timezone: 'Europe/London', // IANA timezone name; defaults to UTC
157
+ concurrent: true, // allow overlapping runs instead of skipping; defaults to false
157
158
  handler: async (ctx) => {
158
159
  ctx.log.info('daily report', { firedAt: ctx.trigger.firedAt });
159
160
  },
@@ -162,6 +163,7 @@ export default defineSchedule({
162
163
 
163
164
  - **`cron`** is a 5-field standard expression (minute, hour, day-of-month, month, day-of-week). An expression that constrains both day-of-month and day-of-week is rejected at build time — leave one of them `*`.
164
165
  - **`timezone`** must be an IANA name (`"Europe/London"`); offset forms (`"+05:00"`) are rejected. Omit it for UTC.
166
+ - **`concurrent`** defaults to `false` (a fire is skipped outright when the previous run for that schedule is still in flight). Set it to `true` to allow overlapping runs instead.
165
167
  - The handler receives a `ScheduleContext`: the core `ctx` surface (`ctx.http`, `ctx.http.authed()`, `ctx.kv()`, `ctx.files()`, `ctx.log`, `ctx.config`, `ctx.state`, and the invocation identifiers) plus `ctx.trigger` (a `ScheduleTrigger`):
166
168
 
167
169
  | Property | Description |
@@ -176,7 +178,7 @@ There is no request and no user: the request-derived fields (`ctx.input`, `ctx.m
176
178
  Things to know:
177
179
 
178
180
  - Schedules fire **on the deployed platform**. The local dev server does not fire them; `helix deploy` registers the schedules present at deploy time.
179
- - Overlapping runs are possible — write handlers to tolerate running concurrently.
181
+ - A fire is skipped when the previous run for that schedule is still in flight, unless you set `concurrent: true` — write handlers to tolerate running concurrently if you opt in.
180
182
  - Files and directories starting with `_` below `_scheduled/` are treated as helpers, not schedules — the only files that belong in the directory besides schedule definitions.
181
183
  - `getContext()` works inside schedule handlers; shared code can detect a scheduled run by checking for `ctx.trigger`.
182
184
 
@@ -242,6 +244,15 @@ await service.stop();
242
244
 
243
245
  Use the CLI (`helix project set`, `helix workspace set`, `helix auth add`) or the Helix MCP tools to write config fields — you rarely edit these by hand.
244
246
 
247
+ ### Multiple config files
248
+
249
+ A config file describes exactly one target. Projects with several targets keep one config file per target (`helix.config.ts` for the one you develop against, `helix.<target>.config.ts` for the rest) and select one with the CLI's `--config` flag. `loadConfig`, `createConfigService`, and `resolveConfigFile` accept the same override as an option, and fall back to the `HELIX_CONFIG` environment variable when the option is omitted:
250
+
251
+ ```typescript
252
+ // explicit option → HELIX_CONFIG env var → ./helix.config.ts
253
+ const config = await loadConfig(process.cwd(), { configFile: 'helix.production.config.ts' });
254
+ ```
255
+
245
256
  ## Logging
246
257
 
247
258
  Use `ctx.log.info/warn/error/debug(message, properties?)` for structured logging from your handlers. `helix dev` prints human-readable logs by default.
@@ -0,0 +1,7 @@
1
+ import{d as D,l as c,n as Qe,o as Ze,p as Te,q as V,s as et}from"./chunk-Q6GJ4HQZ.js";var R="X-Helix-Project-Execution-Token",F="X-Tray-Token",yr={mode:"dev",deploymentId:null},Pe={...yr},O={};function po(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(O.internalJwt=t),"helixExecutionJwt"in e&&(O.helixExecutionJwt=r),"devToken"in e&&(O.devToken=n),Pe={...Pe,...o}}function w(){return Pe}function _(){return O.internalJwt}function T(){return O.helixExecutionJwt}function tt(){return O.devToken}var yo="tray-config-bridge",oe=null;function ho(e){oe=e}function b(){if(!oe)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return oe}function wo(){oe=null}import{AsyncLocalStorage as xt}from"async_hooks";import{trace as kr,SpanKind as Dr,SpanStatusCode as Ae}from"@opentelemetry/api";import{ExportResultCode as Or,W3CTraceContextPropagator as Fr}from"@opentelemetry/core";import{NodeTracerProvider as _r,SimpleSpanProcessor as Lr,BatchSpanProcessor as Nr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as hr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as wr}from"@opentelemetry/exporter-logs-otlp-proto";function Ce(e){return D(e).hosts.ingest}function br(){return T()??""}function rt(){return{[R]:br()}}function nt(){let e=Ce(b().env);return new hr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(rt())})}function ot(){let e=Ce(b().env);return new wr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(rt())})}import{logs as at,SeverityNumber as ie}from"@opentelemetry/api-logs";import{LoggerProvider as Er,BatchLogRecordProcessor as vr}from"@opentelemetry/sdk-logs";function z(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Sr(e){return new TextEncoder().encode(e).length}var it="\u2026[truncated]",xr=Sr(it),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-xr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+it}function y(e,t=J){return A(z(e),t)}var Rr="@trayai/helix-sdk",q,st={debug:{number:ie.DEBUG,text:"DEBUG"},info:{number:ie.INFO,text:"INFO"},warn:{number:ie.WARN,text:"WARN"},error:{number:ie.ERROR,text:"ERROR"}};function Tr(){return w().mode==="lambda"?[new vr({exporter:ot()})]:[]}function ct(){if(q!==void 0)return;let e=Tr();e.length!==0&&(q=new Er({processors:e}),at.setGlobalLoggerProvider(q))}function Pr(e,t,r){let n=st[e]??st.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":y(r)}}:{}}}function lt(e,t,r){at.getLogger(Rr).emit(Pr(e,t,r))}async function ut(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.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 Ie(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Cr(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function S(e,t){return Cr()?`\x1B[${e}m${t}\x1B[0m`:t}var Ir=5,Ar={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},dt="32",ft="31",se="2",mt="1";function ae(e){return S(Ar[e]??"0",e.padEnd(Ir))}function pt(e,t){return`${ae("FN")} ${S(mt,`${e} ${t}`.trim())}`}function gt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${S(se,n)} `:""}${ae(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${S(se,z(r))}`),s}function yt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function ht(e){return`${ae("AUTH")} ${e}`}function wt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=S(o==="error"?ft:dt,i);return`${ae("API")} ${e} ${t} \u2192 ${s} ${S(se,`${n}ms`)}`}function bt(e,t,r){let n=t?ft:dt,o=S(n,"\u25CF"),i=S(n,t?"error":"success");return`${o} ${S(mt,e)} ${i} ${S(se,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
+ `)}catch{}}var Et=new xt,Mr=new xt;function x(e){let t=Mr.getStore();t&&(t[e]=!0)}var Br=/^[0-9a-f]{32}$/;function Ur(e){let t=e.replace(/-/g,"").toLowerCase();return Br.test(t)?t:null}var jr={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 v(e,t,r){e.setAttribute(t,y(r))}var Y;function St(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function $r(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Rt(e){try{process.stdout.write(z(e)+`
4
+ `)}catch{}}var ke=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=N.get(o),s={...n.attributes};if(i!==void 0){for(let[u,f]of Object.entries(i))typeof f=="string"?s[u]=A(f):typeof f=="object"&&f!==null?s[u]=y(f):s[u]=f;N.delete(o)}let a=Et.getStore(),l=a?Ur(a):null;Rt({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:St(n.startTime),endTimeUnixNano:St(n.endTime),attributes:s,status:{code:jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:A(n.status.message)}:{}}})}r({code:Or.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},De=class{onStart(t,r){}onEnd(t){N.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Oe=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
+ `+pt(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;L(gt(String(r.level??"info"),String(r.message??""),o,yt(t.startTime)));break}case"auth":L(ht(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(wt(String(r.method??""),String(r.host??""),n,$r(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Fe=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Kr(){let t=[Ie()?new Oe:new Lr(new ke)];return w().mode==="lambda"&&t.push(new Fe(new Nr(nt()))),t.push(new De),t}function Hr(){Y===void 0&&(Y=new _r({spanProcessors:Kr()}),Y.register({propagator:new Fr}),ct())}async function Vr(e=2e3){let t=[ut(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 E=kr.getTracer("@trayai/helix-sdk");function zr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let f=new Date().toISOString(),d=Date.now()-i;if(Ie()){L(`
7
+ `+bt(n,s,d));return}Rt({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:f,durationMs:d,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?A(a):null})}async function Jo(e,t){let r=e.startMs??Date.now();Hr();let n=!1,o=null;try{return await Et.run(e.executionId,()=>E.startActiveSpan("App",{kind:Dr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ae.ERROR:Ae.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ae.ERROR,message:o}),s}finally{i.end()}}))}finally{zr({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 Vr()}}var Ct=1024,P=100*1024*1024,Tt=250,Jr=3600,qr=Jr*1e3,Pt=new TextEncoder,Yr=/(^|\/)\.\.(\/|$)/,Xr=/[?#]/;function Wr(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function k(e,t=Ct){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");ce(e,t)}function _e(e){return e.endsWith("/")?e.slice(0,-1):e}function ce(e,t=Ct){if(e.length===0)return;if(Yr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(Xr.test(e)||Wr(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=Pt.encode(o).length;if(i>Tt)throw c.filesPathInvalid(`Path segment exceeds ${Tt} UTF-8 bytes (got ${i})`)}let n=Pt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function It(e){if(e>P)throw c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got ${e})`,P)}function M(e){let t=e!==void 0?e*1e3:qr;return new Date(Date.now()+t)}import{join as W}from"path";var Gr="files",Qr="files-meta",Zr=1023,en=1,tn=5;function At(e){let t=Math.max(Buffer.byteLength(le(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,Zr-t-en-tn)}function le(e){return W(e,".helix",Gr)}function X(e){return W(e,".helix",Qr)}function G(e,t){return W(le(e),...t.split("/"))}function ue(e,t){return W(X(e),...t.split("/"))+".json"}function de(e,t){return t.length===0?le(e):G(e,t)}function kt(e,t){return t.length===0?X(e):W(X(e),...t.split("/"))}var Dt="helix-schedule",C=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Qo(e){if(typeof e!="object"||e===null)throw new C("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new C("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new C(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${i} field(s) in "${t}"`);if(typeof r!="string"||!rn(r))throw new C(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new C("`concurrent` must be a boolean");if(typeof o!="function")throw new C("`handler` must be a function");return Object.freeze({kind:Dt,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function Zo(e){return typeof e=="object"&&e!==null&&e.kind===Dt&&typeof e.handler=="function"}function rn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as nn}from"@opentelemetry/api";function fe(e,t,r){let n=E.startSpan("log",{kind:nn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&vt(n.spanContext().spanId,"properties",r),n.end(),lt(e,t,r)}function oi(){return{info:(e,t)=>fe("info",e,t),warn:(e,t)=>fe("warn",e,t),error:(e,t)=>fe("error",e,t),debug:(e,t)=>fe("debug",e,t)}}function ai(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import on from"ky";import{context as Le,trace as sn,SpanKind as pe,SpanStatusCode as Ot}from"@opentelemetry/api";async function me(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=_(),l=T(),u=!!(a&&a.trim().length>0),f=!!(l&&l.trim().length>0);if(!u&&!f)throw c.missingExecutionCredentials();u&&(i[F]=a),f&&(i[R]=l),r.deploymentId&&(i[Qe]=r.deploymentId),o=Te(n,"runtime")}else{let a=tt();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Te(n,"dev")}let s;try{s=await et({proxyUrl:o,credentialHeaders:i,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===Ze?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,y(s.body),s.code)}return s.response}var an=["get","post","put","patch","delete","head","options"],Ft="[stream body omitted]";function _t(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Ft:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Ne(e){try{return new URL(e).hostname}catch{return e}}function cn(e,t,r,n){let o=Ne(t),i="externalApi",s={kind:pe.CLIENT};return E.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),v(a,"request",{url:t,method:e,...r!==void 0?{body:_t(r)}:{}}),n(a)))}function Me(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ot.OK}:{code:Ot.ERROR,message:r}),e.end()}var ln=16;async function un(e,t){let r=e.clone().body;return r?Lt(r,t):new Uint8Array(0)}async function Lt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=ln)break;continue}i=0;let f=t+1-o;if(u.byteLength>=f){n.push(u.slice(0,f)),o+=f;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Nt(e,t,r){if("kyResponse"in r)try{let n=await un(r.kyResponse,J),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}v(e,"response",i)}catch{v(e,"response",{status:t})}else v(e,"response",_t(r.bodyValue))}async function dn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await Lt(o,J);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Ft}}}return typeof t=="string"?{body:t}:{}}function Ri(){let e=on.create({});function t(n){return(o,i)=>{let s=Le.active(),a,l=!1,u=(d,m)=>{a&&!l&&(l=!0,Me(a,d,m))},f=e.extend({hooks:{beforeRequest:[async(d,m)=>{let p=await dn(d,m.body),ne=p.body;if(a||(a=E.startSpan("externalApi",{kind:pe.CLIENT},s)),a.setAttributes({method:d.method.toUpperCase(),host:Ne(d.url)}),v(a,"request",{url:d.url,method:d.method.toUpperCase(),...ne!==void 0?{body:ne}:{}}),l=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[d=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(d,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Nt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[d=>(x("hasError"),u("error",d.message),d)]}});return a=E.startSpan("externalApi",{kind:pe.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:Ne(String(o))}),Le.with(sn.setSpan(Le.active(),a),()=>{let d=n==="options"?f(o,{...i,method:"OPTIONS"}):f[n](o,i);return d.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),d})}}let r=Object.fromEntries(an.map(n=>[n,t(n)]));return{...e,...r,authed(n){return fn(n)}}}function fn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(s,a={})=>{let l=i.toUpperCase();return cn(l,s,a.body,async u=>{x("hasAuth");let f=E.startSpan("auth",{kind:pe.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let d=V({authenticationId:n,method:l,url:s,body:a.body,headers:a.headers,query:a.query}),m=await me(d,{timeout:a.timeout});return u.setAttribute("statusCode",m.status),await Nt(u,m.status,{bodyValue:m.body}),Me(u,"success"),m}catch(d){throw x("hasError"),d instanceof c&&d.detail.kind==="broker_error"&&d.detail.status>0&&u.setAttribute("statusCode",d.detail.status),Me(u,"error",d instanceof Error?d.message:String(d)),d}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as xn,SpanStatusCode as jt}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var mn=18e4,Mt=mn-1e4,pn=2e3;async function Bt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Mt;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(pn,200*2**i),u=l/2+Math.random()*(l/2),f=Mt-(Date.now()-o);await new Promise(d=>setTimeout(d,Math.min(u,f))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var gn=new Set(["SELECT","WITH","SHOW"]),yn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function hn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function wn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?A(t):y(t);return c.dbCallFailed(i)}function bn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Sn(e,t){return typeof t!="number"||t<0?{}:gn.has(e)?{rowsRead:t}:yn.has(e)?{rowsWritten:t}:{}}function Ut(e){async function t(r,n,o){let i=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:s,body:a}=await me(i);if(s>=400)throw wn(s,a);return bn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:hn,async execute(r,n){let o=Q(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=y(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Bt(t,r.region,l),f=u.Status;if(f==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(f==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let d=Sn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:d}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:d}}}}var Be=64*1024;function En(e){return e.length>Be?`${e.slice(0,Be)}...[truncated]`:e}function vn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Rn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Be?v(e,"result",{truncated:!0,size:n.length}):v(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Tn(e,t,r){let n=Q(r),o=En(r);return E.startActiveSpan("database",{kind:xn.CLIENT},async i=>{vn(i,e,t,n,o);try{x("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Rn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:jt.OK}),l}catch(s){x("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:jt.ERROR,message:a}),s}finally{i.end()}})}function Pn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Ut(n);function i(s,a){return o.validate(s),Tn(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Dn}from"unstorage";var $t=1024,Ue=250*1024,Cn=new TextEncoder,In=/(^|\/)\.\.(\/|$)/,An=/[?#]/,kn=/[\u0000-\u001F\u007F]/;function Kt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(In.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(An.test(e)||kn.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Cn.encode(e).length;if(t<1||t>$t)throw c.kvKeyInvalid(`Key must be between 1 and ${$t} UTF-8 bytes (got ${t})`)}function Ht(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Vt(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>Ue)throw c.kvValueTooLarge(`Value exceeds maximum size of ${Ue} bytes (got ${r})`,Ue)}function Z(e){Kt(e)}function ge(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function zt(e){let t=ge(e,"getItem"),r=ge(e,"setItem"),n=ge(e,"removeItem"),o=ge(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return Z(s),t(s,a)},setItem(s,a,l){return Z(s),r(s,a,l)},removeItem(s,a){return Z(s),n(s,a)},hasItem(s,a){return Z(s),o(s,a)},getKeys(s,a){return s.length>0&&Z(s),i(s,a)}}}function ye(e){return Dn({driver:zt(e)})}import{defineDriver as On}from"unstorage";function Fn(e){try{return JSON.parse(e)}catch{return e}}var _n=On(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Fn(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},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 Jt(e){return _n({client:e})}import Mn from"ky";import{z as h}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 qt(e){return D(e).hosts.api}function Ln(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Nn(e){return e.split("/").map(encodeURIComponent).join("/")}function ee(e,t,r){return`${e}${Ln(t)}/${Nn(r)}`}var Bn=6e4,je=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(je),h.record(je)])),Un=h.object({projectId:h.string(),key:h.string(),value:je,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function jn(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function $n(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function he(e,t){throw c.kvCallFailed(e,$n(t),y(t))}async function we(e,t,r={}){try{let n=await Mn(t,{method:e,headers:jn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Bn}),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 Yt(e){let t=qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await we("get",ee(t,r,n));if(o===404)return null;(o<200||o>=300)&&he(o,i);let s=Un.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",y(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await we("put",ee(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&he(s,a)},async delete(n){let{status:o,body:i}=await we("delete",ee(t,r,n));o!==204&&he(o,i)},async has(n){let{status:o,body:i}=await we("head",ee(t,r,n));if(o===200)return!0;if(o===404)return!1;he(o,i)}}}function be(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Vt(r),o!==void 0&&Ht(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function Kn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Xt(e){let t=Kn(),r=e??Yt(t),n=ye(Jt(r));return be(n)}import{defineDriver as Hn}from"unstorage";var Vn=Hn(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl;t.set(n,{value:o,expiresAt:s!==void 0?Date.now()+s*1e3:void 0})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function Wt(){return Vn({})}var $e;function zn(){return $e||($e=ye(Wt())),$e}function Gt(){return be(zn())}function Jn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function As(){return Jn()?Xt():Gt()}import{createHash as Xn}from"crypto";import{mkdir as Wn,readFile as rr,readdir as nr,rm as Zt,unlink as Gn,writeFile as er}from"fs/promises";import{dirname as Qn}from"path";async function qn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>P)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got more than ${P})`,P);r.push(i)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?qn(e):Buffer.from(e)}var Yn={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"},Qt="application/octet-stream";function Se(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Qt;let r=e.slice(t+1).toLowerCase();return Yn[r]??Qt}function $(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xe(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ke(e){try{let t=await rr(ue($(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function tr(e){await Wn(Qn(e),{recursive:!0})}async function Zn(e,t){let r=de(e,t),n;try{n=await nr(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 or(e,t){let r=de(e,t),n;try{n=await nr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await or(e,s)):i.isFile()&&o.push(s)}return o}function ir(){return{async put(e,t,r){return j(async()=>{let n=$(),o=await U(t),i=r?.contentType??Se(e),s=Xn("sha1").update(o).digest("hex"),a=new Date,l=G(n,e);await tr(l),await er(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},f=ue(n,e);return await tr(f),await er(f,JSON.stringify(u)),xe(e,u)})},async get(e){return j(async()=>{let t=await Ke(e);return t?{data:await rr(G($(),e)),metadata:xe(e,t)}:null})},async head(e){return j(async()=>{let t=await Ke(e);return t?xe(e,t):null})},async delete(e){return j(async()=>{let t=$();await Promise.all([G(t,e),ue(t,e)].map(async r=>{try{await Gn(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=$(),r=await or(t,e);return await Promise.all([Zt(de(t,e),{recursive:!0,force:!0}),Zt(kt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=$(),n=t?.limit??100,i=(await Zn(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Ke(a);return l?xe(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}}}}import{createHash as so}from"crypto";function Ee(e){return D(e).hosts.api}function eo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function te(e,t){return`${e}${eo(t)}`}function K(e,t,r){return`${te(e,t)}/${encodeURIComponent(r)}`}function ve(e,t,r){return`${K(e,t,r)}/upload`}function sr(e,t,r){return`${K(e,t,r)}/download`}function ar(e,t,r){return`${K(e,t,r)}/signed-url`}function cr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${te(e,t)}/file?${o.toString()}`}function lr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${te(e,t)}?${o.toString()}`}import Ve from"ky";import{z as g}from"zod";var ze=6e4,ur=g.object({id:g.string(),workspaceId:g.string(),projectId:g.string(),parentFolder:g.string().nullable().optional(),name:g.string(),size:g.number().nullable().optional(),objectType:g.enum(["Folder","File"]),contentType:g.string().nullable().optional(),createdAt:g.string(),updatedAt:g.string()}),to=g.object({signedURL:g.string()}),ro=g.object({path:g.array(g.object({id:g.string(),name:g.string()})),elements:g.array(ur)});function Je(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function dr(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 I(e,t){throw c.filesCallFailed(e,dr(t),y(t))}function no(e,t){return e===400&&dr(t).toLowerCase()==="resource not found"}async function oo(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await Ve(t,{method:e,headers:Je(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ze}),o=await 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 He(e,t){let r=ur.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",y(t));return r.data}function fr(e){let t=Ee(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",te(t,r),{json:n});return(o<200||o>=300)&&I(o,i),He(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",cr(t,r,n,o));return i===404||no(i,s)?null:((i<200||i>=300)&&I(i,s),He(i,s))},async getById(n){let{status:o,body:i}=await H("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&I(o,i),He(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",lr(t,r,n,o));(i<200||i>=300)&&I(i,s);let a=ro.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",y(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await oo(a),f;try{f=await Ve(ve(t,r,n),{method:"post",headers:{...Je(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ze})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let d=await B(f);(f.status<200||f.status>=300)&&I(f.status,d)},async downloadContent(n){let o;try{o=await Ve(sr(t,r,n),{method:"get",headers:Je(),throwHttpErrors:!1,timeout:ze})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await B(o);I(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",ar(t,r,n));(o<200||o>=300)&&I(o,i);let s=to.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",y(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&I(o,i)}}}function qe(e){return e.split("/").filter(t=>t.length>0)}function Ye(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function io(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Xe(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await io(e,o,i)).id;return{parentFolder:o,name:n}}async function re(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function We(e,t){if(t.length===0)return;let r=qe(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var ao=500,co=8;async function lo(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function uo(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function fo(e){return so("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Re(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:fo(t)}}async function mr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function pr(e,t){let{elements:r}=await e.listChildren(t,ao);return(await lo(r,co,async o=>{let i=o.objectType==="Folder"?await pr(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function gr(e){let t=uo(),r=e??fr(t),n=Ee(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Xe(r,i),f=await U(s),d=a?.contentType??Se(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await mr(r,l,u,d);await r.uploadContent(p.id,f,u,d);let ne=await r.getById(p.id);return Re(i,ne??p,d)},async get(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Re(i,a)}},async head(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Re(i,a)},async delete(i){let s=await re(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await We(r,i);if(s===null)return{deleted:0};let a=await pr(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await We(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(d=>d.objectType==="File").map(d=>Re(i?`${i}/${d.name}`:d.name,d)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Xe(r,i),f=await r.getByName(a,l)??await mr(r,a,l,s?.contentType);return{url:ve(n,o,f.id),expiresAt:M(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await re(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:M(s?.expiresIn)}}}}function Ge(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){k(n,r);let s=await U(o);return It(s.byteLength),e.put(n,s,i)},async get(n){return k(n,r),e.get(n)},async head(n){return k(n,r),e.head(n)},async delete(n){return k(n,r),e.delete(n)},async deleteMany(n){let o=_e(n);return ce(o,r),e.deleteMany(o)},async list(n,o){let i=_e(n??"");return ce(i,r),e.list(i,o)},async getUploadUrl(n,o){return k(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return k(n,r),e.getDownloadUrl(n,o)}}}function mo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function xa(){if(mo())return Ge(gr());let e=w().projectRoot;return Ge(ir(),{maxPathBytes:e?At(e):void 0})}export{po as a,w as b,yo as c,ho as d,b as e,wo as f,Et as g,Mr as h,x as i,v as j,Hr as k,Vr as l,E as m,zr as n,Jo as o,oi as p,ai as q,Ri as r,Pn as s,As as t,k as u,G as v,ue as w,xa as x,Dt as y,C as z,Qo as A,Zo as B};
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import * as h3 from 'h3';
2
2
  import { ZodType } from 'zod';
3
- import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DJcXnXhR.js';
4
- export { b as DbCallParameters, c as DbClient, d as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, e as ScheduleContext, f as ScheduleHandler, g as ScheduleTrigger, h as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DJcXnXhR.js';
5
- import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-_xIe9XvP.js';
6
- export { P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, w as workspaceIdSchema } from './sdk-config-_xIe9XvP.js';
3
+ import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DCCVrmZ3.js';
4
+ export { b as DbCallParameters, c as DbClient, d as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, e as ScheduleContext, f as ScheduleHandler, g as ScheduleTrigger, h as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DCCVrmZ3.js';
5
+ import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-vY_-Reh3.js';
6
+ export { C as ConfigFileOptions, H as HELIX_CONFIG_ENV, P as ProvisionedTrayConfig, S as SdkRuntimeConfig, U as UnprovisionedTrayConfig, a as WORKSPACE_ID_REQUIRED_CODE, b as WorkspaceIdRequiredError, g as getSdkConfig, l as loadConfig, c as loadedTrayConfigSchema, p as projectIdSchema, r as requireWorkspaceId, d as resolveConfigFile, e as resolveConfigOverride, w as workspaceIdSchema } from './sdk-config-vY_-Reh3.js';
7
7
  export { a as ENVIRONMENT_VALUES, E as Environment, e as environmentSchema } from './env-schema-DkgTG5b0.js';
8
8
  import 'ky';
9
9
 
@@ -85,6 +85,13 @@ declare function defineConfig(config: TrayConfig): TrayConfig;
85
85
  interface CreateConfigServiceOptions {
86
86
  /** Directory containing `helix.config.ts`. */
87
87
  cwd: string;
88
+ /**
89
+ * Explicit config file path (the CLI's `--config` flag), overriding the
90
+ * `helix.config.ts` default. Falls back to the `HELIX_CONFIG` env var; the
91
+ * effective override is pinned once at service creation, so later env-var
92
+ * changes never re-target a live service.
93
+ */
94
+ configFile?: string;
88
95
  /** If true, attach a c12 watcher and emit subscribers on each change. */
89
96
  watch?: boolean;
90
97
  /**
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
- import{A as Ce,B as ve,b as T,g as U,h as I,i as N,j as C,k as q,l as M,m as $,n as Z,o as ge,p as K,q as z,r as G,s as J,t as Q,x as X,y as he,z as ye}from"./chunk-DO7JOK7P.js";import{a as B,b as me}from"./chunk-WUCX7RZO.js";import{b as H,e as A,i as W,l as g,m as V}from"./chunk-Q6GJ4HQZ.js";import{randomUUID as be}from"crypto";import{SpanStatusCode as ne,SpanKind as Re}from"@opentelemetry/api";import{defineEventHandler as Pe,getMethod as Le,getRequestURL as Fe,getHeaders as se,getHeader as oe}from"h3";import{readBody as we,getQuery as Ee,getRouterParams as ke}from"h3";async function Y(e,t){let r=await Se(e),n=Ee(e),o=ke(e)??{},s={...n,...r,...o};return t?xe(s,t):s}async function Se(e){try{let t=await we(e);return t&&typeof t=="object"?t:(t!=null&&t!==""&&console.warn("[helix-sdk] Request body present but not a JSON object \u2014 ignored"),{})}catch(t){if(t instanceof Error&&"statusCode"in t&&t.statusCode===400){let n=new Error("Malformed request body");throw n.statusCode=400,n.data={message:"Request body is not valid JSON"},n}let r=e.method?.toUpperCase();if(r==="GET"||r==="HEAD"||r==="DELETE")return{};throw t}}function xe(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var v=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function ee(e){return t=>{e.node.res.statusCode=t}}function te(){return(e,t)=>{throw new v(e,t)}}function re(e,t){let{statusCode:r,message:n}=Te(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Te(e){switch(e.kind){case"unknown_alias":return{statusCode:400,message:"Unknown authentication alias"};case"input_validation_failed":return{statusCode:400,message:"Input validation failed"};case"output_validation_failed":return{statusCode:500,message:"Internal server error"};case"config_load_failed":return{statusCode:500,message:"Configuration error"};case"broker_error":return{statusCode:502,message:"Broker error"};case"unsupported_body_type":return{statusCode:400,message:"Unsupported request body type"};case"unsupported_scheme":return{statusCode:400,message:"Unsupported URL scheme"};case"missing_execution_credentials":return{statusCode:401,message:"Missing execution credentials"};case"missing_tray_token":return{statusCode:500,message:"Missing Tray token"};case"db_call_failed":return{statusCode:502,message:e.message};case"db_query_failed":return{statusCode:502,message:`Database query failed: ${e.message}`};case"db_invalid_parameters":return{statusCode:400,message:e.message};case"kv_key_invalid":return{statusCode:400,message:e.message};case"kv_value_invalid":return{statusCode:400,message:e.message};case"kv_value_too_large":return{statusCode:400,message:e.message};case"kv_ttl_invalid":return{statusCode:400,message:e.message};case"kv_not_available":return{statusCode:501,message:"Key-value store is not available in this environment"};case"kv_call_failed":return{statusCode:502,message:"Key-value store request failed"};case"kv_requires_provisioning":return{statusCode:500,message:"Internal server error"};case"files_path_invalid":return{statusCode:400,message:e.message};case"files_value_invalid":return{statusCode:400,message:e.message};case"files_value_too_large":return{statusCode:400,message:e.message};case"files_not_available":return{statusCode:501,message:"File storage is not available in this environment"};case"files_call_failed":return{statusCode:502,message:"File storage request failed"};case"files_requires_provisioning":return{statusCode:500,message:"Internal server error"};default:return{statusCode:500,message:`Unhandled error kind: ${e.kind}`}}}var Ie=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function _e(e){return e.toLowerCase().includes("tray_lid")}function _(e){let t={};for(let[r,n]of Object.entries(e))if(!Ie.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(s=>s.trim()).filter(s=>{let a=s.split("=")[0].trim();return!_e(a)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function je(e,t){let{inputSchema:r,outputSchema:n}=Ue(t),o=e;return Pe(async s=>{let a=T(),{executionId:i,userId:c,deploymentId:f}=Ne(a,s),p=Date.now(),y=new Date().toISOString(),m=Le(s),l=Fe(s).pathname,u=z(),h=K(),E=`${m} ${l}`;q();let O={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return De(()=>I.run(O,()=>U.run(i,async()=>{let k=await Oe(s,r);if(!k.ok)return{response:k.response,errored:!1,errorMessage:null};let pe=Me(s,k.input,u,h,m,l,i,f,c);return He(o,pe,n,s,h,i,f,{method:m,path:l,rawInput:k.input})})),{executionId:i,deploymentId:f,routeOrJob:E,startedAt:y,startMs:p,userId:c,flags:O})})}async function De(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{Z({...t,errored:r,errorMessage:n}),await M()}}async function Oe(e,t){try{return{ok:!0,input:await Y(e,t)}}catch(r){let n=qe(e,r);if(n)return{ok:!1,response:n};throw r}}async function He(e,t,r,n,o,s,a,i){return $.startActiveSpan("function",{root:!0,kind:Re.SERVER,attributes:{method:i.method,route:i.path,executionId:s,...a?{deploymentId:a}:{}}},async c=>{t.traceId=c.spanContext().traceId;let f=_(se(n));C(c,"input",i.rawInput),C(c,"request",{method:i.method,path:i.path,headers:f,body:i.rawInput});let p=!1,y=null,m,l;try{let u=await B.run(t,()=>e(t));if(m=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let h=r.safeParse(u);if(!h.success){let E=Object.keys(h.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:E,executionId:s}),g.outputValidationFailed(E)}l=h.data}else l=u}catch(u){p=!0,y=u instanceof Error?u.message:String(u),N("hasError"),l=Ae(u,n,o,s)}finally{We(c,n,{errored:p,errorMessage:y,handlerResult:m,response:l})}return{response:l,errored:p,errorMessage:y}})}function Ae(e,t,r,n){if(e instanceof v)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(V(e))return re(t,e);r.error("Unhandled error in handler",{error:e instanceof Error?e.message:String(e),executionId:n}),t.node.res.statusCode=500;let o=process.env.NODE_ENV==="development";return{error:o&&e instanceof Error?e.message:"Internal server error",statusCode:500,...o&&e instanceof Error&&e.stack?{stack:e.stack}:{}}}function We(e,t,r){e.setAttribute("statusCode",t.node.res.statusCode),!r.errored&&r.handlerResult!==void 0&&C(e,"output",r.handlerResult),C(e,"response",r.response);let n=I.getStore();e.setAttribute("hasAuth",n?.hasAuth??!1),e.setAttribute("hasExternal",n?.hasExternal??!1),e.setAttribute("hasDb",n?.hasDb??!1),e.setAttribute("status",r.errored?"error":"success");let o=r.errored||(n?.hasError??!1);e.setStatus({code:o?ne.ERROR:ne.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Ue(e){if(!e)return{inputSchema:void 0,outputSchema:void 0};if(e instanceof Object&&"_def"in e)return{inputSchema:e,outputSchema:void 0};if(typeof e=="object"&&("input"in e||"output"in e)){let t=e;return{inputSchema:t.input,outputSchema:t.output}}return{inputSchema:e,outputSchema:void 0}}function Ne(e,t){let r=e.mode==="lambda",n=(r?e.executionId:oe(t,"x-tray-execution-id"))??be(),o=(r?e.userId:oe(t,"x-tray-user-id"))??null,s=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:s}}function qe(e,t){if(!(t instanceof Error)||!("statusCode"in t)||!("data"in t))return null;let r=t.statusCode,n=t.data;e.node.res.statusCode=r;let o=n&&typeof n=="object"&&"fieldErrors"in n?n.fieldErrors:void 0;return{error:"Input validation failed",statusCode:r,...o?{fields:Object.keys(o)}:{}}}function Me(e,t,r,n,o,s,a,i,c){return{input:t,method:o,path:s,headers:_(se(e)),http:G(),db:f=>J(f),kv:()=>Q(),files:()=>X(),log:n,config:r,status:ee(e),error:te(),state:{},request:e,executionId:a,deploymentId:i,userId:c,identity:c!==null?{user:{id:c}}:null,traceId:""}}function $e(e){return e}import{resolve as b}from"path";import{existsSync as ae}from"fs";import{loadConfig as Ke}from"c12";import{z as d}from"zod";import{z as Ze}from"zod";var Be=["production"],S=Ze.string().refine(e=>H(e),e=>({message:`Invalid enum value. Expected ${A().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var R=d.string().uuid("projectId must be a valid UUID"),P=d.string().min(1,"workspaceId must be a non-empty string"),ze=d.object({name:d.string().min(1,"name is required"),projectId:R.optional(),workspaceId:P.optional(),env:S.default("production"),authentications:d.record(d.string()).optional().default({}),config:d.record(d.unknown()).optional().default({})}),ie=d.object({name:d.string().min(1,"name is required"),workspaceId:P.optional(),env:S,authentications:d.record(d.string()),config:d.record(d.unknown())}),Ve=d.discriminatedUnion("kind",[ie.extend({kind:d.literal("provisioned"),projectId:R}),ie.extend({kind:d.literal("unprovisioned")})]),de=["helix","tray"],ce=["ts","mts","cts","js","mjs","cjs"];function x(e){for(let t of de)for(let r of ce){let n=b(e,`${t}.config.${r}`);if(ae(n))return n}}function Ge(e){for(let t of de)if(ce.some(r=>ae(b(e,`${t}.config.${r}`))))return t;return"helix"}function L(e){return{name:Ge(e),cwd:e,rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function F(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=ze.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...s}=r.data,a=o!==void 0?{workspaceId:o}:{},i=W(),c=i!==void 0?{...s,env:i}:s;return n!==void 0?{kind:"provisioned",projectId:n,...c,...a}:{kind:"unprovisioned",...c,...a}}async function w(e){let t=e??process.cwd(),r;try{r=await Ke(L(t))}catch(o){throw g.configLoadFailed(`Failed to load helix.config.ts: ${o instanceof Error?o.message:String(o)}`)}let n=r._configFile??x(t);if(!n)throw g.configLoadFailed(`helix.config.ts not found at ${b(t,"helix.config.ts")}`);return F(r.config,n)}var ue="WORKSPACE_ID_REQUIRED";function Je(e){if(e.workspaceId===void 0)throw Object.assign(new Error("No workspaceId found in helix.config.ts. Discover & choose one \u2014 self-serve fix: run `helix workspace select`; agent-driven fix: call the `tray_list_workspaces` MCP tool. Already know the id? Run `helix workspace set <id>` or call the `tray_set_workspace_id` MCP tool. deploy cannot proceed without a workspace."),{code:ue});return e.workspaceId}import{existsSync as Qe,watch as Xe,writeSync as Ye}from"fs";import{join as et,resolve as tt}from"path";import{watchConfig as rt}from"c12";function nt(e,t){let r=e instanceof Error?e.message:String(e);Ye(2,`[helix-watch] ${t.phase} error: ${r}
2
- `)}function j(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ot=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,fe=new Set;function le(e){return x(e)!==void 0}async function st(e,t){if(le(e.cwd))try{return{current:await w(e.cwd),initialLoadSucceeded:!0}}catch(r){return t(r,{phase:"reload"}),{current:j(),initialLoadSucceeded:!1}}if(e.watch){let r=tt(e.cwd);fe.has(r)||(process.stderr.write(`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
3
- `),fe.add(r))}return{current:j(),initialLoadSucceeded:!1}}var D=class{constructor(t,r,n){this.cwd=t;this.onError=r;this.emit=n}cwd;onError;emit;stopped=!1;directoryWatcher=null;c12Unwatch=null;c12AttachPromise=null;updateChain=Promise.resolve();start(t){t?this.attachC12Watcher():this.attachCreationWatcher()}watcherReady(){return this.c12AttachPromise===null?Promise.resolve():this.c12AttachPromise.catch(()=>{})}async stop(){this.stopped=!0,this.directoryWatcher&&(this.directoryWatcher.close(),this.directoryWatcher=null),this.c12AttachPromise&&await this.c12AttachPromise.catch(t=>this.onError(t,{phase:"attach"})),this.c12Unwatch&&(await this.c12Unwatch(),this.c12Unwatch=null)}attachC12Watcher(){this.c12AttachPromise===null&&(this.c12AttachPromise=rt({...L(this.cwd),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=F(t.config,this.cwd)}catch(n){this.onError(n,{phase:"validation"});return}try{this.emit(r)}catch(n){this.onError(n,{phase:"reload"})}}))}}).then(async t=>{if(this.stopped){t.unwatch();return}this.c12Unwatch=t.unwatch;let{watch:r}=await import("chokidar"),n=r(this.cwd,{persistent:!1,depth:0});try{await new Promise((o,s)=>{n.once("ready",o),n.once("error",s)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){try{this.directoryWatcher=Xe(this.cwd,{persistent:!1},(t,r)=>{if(this.stopped||!r)return;let n=r.toString();ot.test(n)&&Qe(et(this.cwd,n))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let o;try{o=await w(this.cwd)}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(o);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",t=>{this.onError(t,{phase:"attach"})})}catch(t){this.onError(t,{phase:"attach"})}}};async function it(e){let t=e.onError??nt,r=new Set,n=await st(e,t),o=n.current;function s(i){o=i;for(let c of[...r])try{c(i)}catch(f){t(f,{phase:"reload"})}}let a=new D(e.cwd,t,s);return e.watch&&a.start(n.initialLoadSucceeded),{get(){return o},async reload(){if(!le(e.cwd)){let i=j();return s(i),i}try{let i=await w(e.cwd);return s(i),i}catch(i){return t(i,{phase:"reload"}),o}},subscribe(i){return r.add(i),()=>{r.delete(i)}},async stop(){r.clear(),await a.stop()},ready(){return a.watcherReady()}}}export{Be as ENVIRONMENT_VALUES,he as SCHEDULE_DEFINITION_KIND,ye as ScheduleConfigError,ue as WORKSPACE_ID_REQUIRED_CODE,it as createConfigService,$e as defineConfig,je as defineFunction,Ce as defineSchedule,S as environmentSchema,me as getContext,T as getSdkConfig,ve as isScheduleDefinition,w as loadConfig,Ve as loadedTrayConfigSchema,R as projectIdSchema,Je as requireWorkspaceId,x as resolveConfigFile,ge as runWithinAppSpan,P as workspaceIdSchema};
1
+ import{A as ke,B as Se,b as R,g as M,h as F,i as Z,j as E,k as K,l as B,m as V,n as z,o as Ce,p as J,q as Q,r as Y,s as ee,t as te,x as re,y as Ee,z as we}from"./chunk-6OZ47QHO.js";import{a as G,b as ve}from"./chunk-WUCX7RZO.js";import{b as U,e as $,i as q,l as g,m as X}from"./chunk-Q6GJ4HQZ.js";import{randomUUID as Le}from"crypto";import{SpanStatusCode as ae,SpanKind as Oe}from"@opentelemetry/api";import{defineEventHandler as je,getMethod as De,getRequestURL as He,getHeaders as ce,getHeader as de}from"h3";import{readBody as xe,getQuery as Ie,getRouterParams as _e}from"h3";async function ne(e,t){let r=await be(e),n=Ie(e),o=_e(e)??{},i={...n,...r,...o};return t?Te(i,t):i}async function be(e){try{let t=await xe(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 Te(e,t){let r=t.safeParse(e);if(!r.success){let n=new Error("Input validation failed");throw n.statusCode=400,n.data=r.error.flatten(),n}return r.data}var w=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t,this.name="HttpError"}};function oe(e){return t=>{e.node.res.statusCode=t}}function ie(){return(e,t)=>{throw new w(e,t)}}function se(e,t){let{statusCode:r,message:n}=Re(t.detail);return e.node.res.statusCode=r,{error:n,statusCode:r}}function Re(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_ttl_invalid":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 Fe=["authorization","x-tray-token","set-cookie","x-kong-request-id","traceparent","x-real-ip","cookie"];function Pe(e){return e.toLowerCase().includes("tray_lid")}function P(e){let t={};for(let[r,n]of Object.entries(e))if(!Fe.includes(r.toLowerCase())){if(r.toLowerCase()==="cookie"&&n){let o=n.split(";").map(i=>i.trim()).filter(i=>{let d=i.split("=")[0].trim();return!Pe(d)}).join("; ");o&&(t[r]=o);continue}t[r]=n}return t}function Ae(e,t){let{inputSchema:r,outputSchema:n}=Me(t),o=e;return je(async i=>{let d=R(),{executionId:s,userId:a,deploymentId:f}=Ze(d,i),p=Date.now(),v=new Date().toISOString(),h=De(i),l=He(i).pathname,u=Q(),y=J(),S=`${h} ${l}`;K();let N={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1};return We(()=>F.run(N,()=>M.run(s,async()=>{let x=await Ne(i,r);if(!x.ok)return{response:x.response,errored:!1,errorMessage:null};let ye=Be(i,x.input,u,y,h,l,s,f,a);return Ue(o,ye,n,i,y,s,f,{method:h,path:l,rawInput:x.input})})),{executionId:s,deploymentId:f,routeOrJob:S,startedAt:v,startMs:p,userId:a,flags:N})})}async function We(e,t){let r=!1,n=null;try{let o=await e();return r=o.errored,n=o.errorMessage,o.response}finally{z({...t,errored:r,errorMessage:n}),await B()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Ke(e,r);if(n)return{ok:!1,response:n};throw r}}async function Ue(e,t,r,n,o,i,d,s){return V.startActiveSpan("function",{root:!0,kind:Oe.SERVER,attributes:{method:s.method,route:s.path,executionId:i,...d?{deploymentId:d}:{}}},async a=>{t.traceId=a.spanContext().traceId;let f=P(ce(n));E(a,"input",s.rawInput),E(a,"request",{method:s.method,path:s.path,headers:f,body:s.rawInput});let p=!1,v=null,h,l;try{let u=await G.run(t,()=>e(t));if(h=u,u==null)n.node.res.statusCode=204,l="";else if(u instanceof Response)l=u;else if(r){let y=r.safeParse(u);if(!y.success){let S=Object.keys(y.error.flatten().fieldErrors);throw o.error("Output validation failed",{fields:S,executionId:i}),g.outputValidationFailed(S)}l=y.data}else l=u}catch(u){p=!0,v=u instanceof Error?u.message:String(u),Z("hasError"),l=$e(u,n,o,i)}finally{qe(a,n,{errored:p,errorMessage:v,handlerResult:h,response:l})}return{response:l,errored:p,errorMessage:v}})}function $e(e,t,r,n){if(e instanceof w)return t.node.res.statusCode=e.statusCode,{error:e.message,statusCode:e.statusCode};if(X(e))return se(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 qe(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=F.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?ae.ERROR:ae.OK,...r.errorMessage?{message:r.errorMessage}:{}}),e.end()}function Me(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 Ze(e,t){let r=e.mode==="lambda",n=(r?e.executionId:de(t,"x-tray-execution-id"))??Le(),o=(r?e.userId:de(t,"x-tray-user-id"))??null,i=r?e.deploymentId??null:null;return{executionId:n,userId:o,deploymentId:i}}function Ke(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 Be(e,t,r,n,o,i,d,s,a){return{input:t,method:o,path:i,headers:P(ce(e)),http:Y(),db:f=>ee(f),kv:()=>te(),files:()=>re(),log:n,config:r,status:oe(e),error:ie(),state:{},request:e,executionId:d,deploymentId:s,userId:a,identity:a!==null?{user:{id:a}}:null,traceId:""}}function Ve(e){return e}import{resolve as m}from"path";import{existsSync as _,realpathSync as ue}from"fs";import{loadConfig as Je}from"c12";import{z as c}from"zod";import{z as ze}from"zod";var Ge=["production"],I=ze.string().refine(e=>U(e),e=>({message:`Invalid enum value. Expected ${$().map(t=>`'${t}'`).join(" | ")}, received '${e}'`}));var L=c.string().uuid("projectId must be a valid UUID"),O=c.string().min(1,"workspaceId must be a non-empty string"),Qe=c.object({name:c.string().min(1,"name is required"),projectId:L.optional(),workspaceId:O.optional(),env:I.default("production"),authentications:c.record(c.string()).optional().default({}),config:c.record(c.unknown()).optional().default({})}),fe=c.object({name:c.string().min(1,"name is required"),workspaceId:O.optional(),env:I,authentications:c.record(c.string()),config:c.record(c.unknown())}),Xe=c.discriminatedUnion("kind",[fe.extend({kind:c.literal("provisioned"),projectId:L}),fe.extend({kind:c.literal("unprovisioned")})]),le=["helix","tray"],pe=["ts","mts","cts","js","mjs","cjs"],j="HELIX_CONFIG";function C(e){let t=e?.trim();return t||process.env[j]?.trim()||void 0}function b(e,t){let r=C(t?.configFile);if(r!==void 0){let n=m(e,r);return _(n)?n:void 0}for(let n of le)for(let o of pe){let i=m(e,`${n}.config.${o}`);if(_(i))return i}}function Ye(e){for(let t of le)if(pe.some(r=>_(m(e,`${t}.config.${r}`))))return t;return"helix"}function et(e,t){return m(e,t).replace(/\.(?:m|c)?[jt]s$/,"")}function D(e,t){let r=C(t?.configFile);return{name:Ye(e),cwd:e,...r!==void 0?{configFile:et(e,r)}:{},rcFile:!1,globalRc:!1,packageJson:!1,dotenv:!1,extend:!1}}function H(e,t){if(e!==null&&typeof e=="object"&&"extends"in e)throw g.configLoadFailed(`helix.config.ts at ${t}: 'extends' is not supported \u2014 remove the field`);let r=Qe.safeParse(e);if(!r.success){let f=r.error.issues.map(p=>p.message).join("; ");throw g.configLoadFailed(`Invalid helix.config.ts at ${t}: ${f}`)}let{projectId:n,workspaceId:o,...i}=r.data,d=o!==void 0?{workspaceId:o}:{},s=q(),a=s!==void 0?{...i,env:s}:i;return n!==void 0?{kind:"provisioned",projectId:n,...a,...d}:{kind:"unprovisioned",...a,...d}}async function k(e,t){let r=e??process.cwd(),n=C(t?.configFile),o=n!==void 0?m(r,n):void 0;if(o!==void 0&&!_(o)){let s=t?.configFile?.trim()?"":` (from ${j})`;throw g.configLoadFailed(`Config file not found: ${o}${s}`)}let i;try{i=await Je(D(r,t))}catch(s){throw g.configLoadFailed(`Failed to load helix.config.ts: ${s instanceof Error?s.message:String(s)}`)}let d=i._configFile??b(r,t);if(!d)throw g.configLoadFailed(`helix.config.ts not found at ${m(r,"helix.config.ts")}`);if(o!==void 0&&i._configFile!==void 0){let s=ue(o);if(ue(m(i._configFile))!==s)throw g.configLoadFailed(`Config file conflict: requested ${o} but ${m(i._configFile)} takes extension-resolution precedence \u2014 remove or rename the sibling file`)}return H(i.config,d)}var ge="WORKSPACE_ID_REQUIRED";function tt(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:ge});return e.workspaceId}import{existsSync as rt,watch as nt,writeSync as ot}from"fs";import{basename as it,dirname as st,join as at,resolve as T}from"path";import{watchConfig as dt}from"c12";function ct(e,t){let r=e instanceof Error?e.message:String(e);ot(2,`[helix-watch] ${t.phase} error: ${r}
2
+ `)}function A(){return{kind:"unprovisioned",name:"",authentications:{},config:{},env:"production"}}var ut=/^(?:helix|tray)\.config\.(?:m|c)?[jt]s$/,me=new Set;function he(e,t){return b(e,{configFile:t})!==void 0}async function ft(e,t,r){if(he(e.cwd,t))try{return{current:await k(e.cwd,{configFile:t}),initialLoadSucceeded:!0}}catch(n){return r(n,{phase:"reload"}),{current:A(),initialLoadSucceeded:!1}}if(e.watch){let n=t!==void 0?T(e.cwd,t):T(e.cwd);me.has(n)||(process.stderr.write(t!==void 0?`warning: config file ${T(e.cwd,t)} not found; tray running with default config
3
+ `:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
4
+ `),me.add(n))}return{current:A(),initialLoadSucceeded:!1}}var W=class{constructor(t,r,n,o){this.cwd=t;this.configFile=r;this.onError=n;this.emit=o}cwd;configFile;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=dt({...D(this.cwd,{configFile:this.configFile}),onUpdate:({newConfig:t})=>{this.stopped||(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let r;try{r=H(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,i)=>{n.once("ready",o),n.once("error",i)})}finally{await n.close()}}).catch(t=>{this.onError(t,{phase:"attach"})}))}attachCreationWatcher(){let t=this.configFile!==void 0?T(this.cwd,this.configFile):void 0,r=t!==void 0?st(t):this.cwd;try{this.directoryWatcher=nt(r,{persistent:!1},(n,o)=>{if(this.stopped||!o)return;let i=o.toString();if(t!==void 0){if(i!==it(t))return}else if(!ut.test(i))return;rt(at(r,i))&&(this.updateChain=this.updateChain.then(async()=>{if(this.stopped)return;let d;try{d=await k(this.cwd,{configFile:this.configFile})}catch(a){this.onError(a,{phase:"reload"});return}if(this.stopped)return;this.emit(d);let s=this.directoryWatcher;s&&(this.directoryWatcher=null,s.close()),this.attachC12Watcher()}))}),this.directoryWatcher.on("error",n=>{this.onError(n,{phase:"attach"})})}catch(n){this.onError(n,{phase:"attach"})}}};async function lt(e){let t=e.onError??ct,r=new Set,n=C(e.configFile),o=await ft(e,n,t),i=o.current;function d(a){i=a;for(let f of[...r])try{f(a)}catch(p){t(p,{phase:"reload"})}}let s=new W(e.cwd,n,t,d);return e.watch&&s.start(o.initialLoadSucceeded),{get(){return i},async reload(){if(!he(e.cwd,n)){let a=A();return d(a),a}try{let a=await k(e.cwd,{configFile:n});return d(a),a}catch(a){return t(a,{phase:"reload"}),i}},subscribe(a){return r.add(a),()=>{r.delete(a)}},async stop(){r.clear(),await s.stop()},ready(){return s.watcherReady()}}}export{Ge as ENVIRONMENT_VALUES,j as HELIX_CONFIG_ENV,Ee as SCHEDULE_DEFINITION_KIND,we as ScheduleConfigError,ge as WORKSPACE_ID_REQUIRED_CODE,lt as createConfigService,Ve as defineConfig,Ae as defineFunction,ke as defineSchedule,I as environmentSchema,ve as getContext,R as getSdkConfig,Se as isScheduleDefinition,k as loadConfig,Xe as loadedTrayConfigSchema,L as projectIdSchema,tt as requireWorkspaceId,b as resolveConfigFile,C as resolveConfigOverride,Ce as runWithinAppSpan,O as workspaceIdSchema};
@@ -1,5 +1,5 @@
1
- import { L as LoadedTrayConfig } from '../sdk-config-_xIe9XvP.js';
2
- export { e as SdkConfigInput, s as setSdkConfig } from '../sdk-config-_xIe9XvP.js';
1
+ import { L as LoadedTrayConfig } from '../sdk-config-vY_-Reh3.js';
2
+ export { f as SdkConfigInput, s as setSdkConfig } from '../sdk-config-vY_-Reh3.js';
3
3
  import 'zod';
4
4
 
5
5
  /** BroadcastChannel name for parent→worker config updates. */
@@ -1 +1 @@
1
- import{B as P,a as J,b as m,c as L,d as T,e as U,f as G,g as h,h as p,i as g,j as S,k as E,l as x,m as y,n as A,p as w,q as I,r as v,s as C,t as D,u as re,v as oe,w as ne,x as F}from"../chunk-DO7JOK7P.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as _,c as q,d as B,e as z,f as Q,g as W,h as X,i as Y,j as Z,k as ee,m as te}from"../chunk-Q6GJ4HQZ.js";import{randomUUID as se}from"crypto";import{SpanStatusCode as k,SpanKind as ie}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function ae(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new t("`isManual` must be a boolean");if(!P(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let O=N("scheduledAt",e.scheduledAt),M=N("firedAt",e.firedAt),d=m(),a=d.executionId??se(),l=d.deploymentId??null,j=Date.now(),R=new Date().toISOString(),$=I(),K=w();E();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ie.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let H={type:"schedule",scheduledAt:O,firedAt:M,isManual:e.isManual},f={http:v(),db:n=>C(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:H};S(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?k.ERROR:k.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:R,startMs:j,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function N(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{L as CONFIG_BRIDGE_CHANNEL,t as ScheduleInvocationError,re as assertValidPath,G as clearActiveConfig,oe as contentFilePath,U as getActiveConfig,Z as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,_ as isKnownEnvironment,te as isSdkError,z as listEnvironmentNames,Q as listExposedEnvNames,ne as metaFilePath,W as parseExposedEnvironment,V as registerEnvironmentProfile,B as requireEnvironmentProfile,ee as resetEnvironmentRegistryForTests,Y as resolveForcedEnvironment,ae as runScheduledFunction,T as setActiveConfig,X as setForcedEnvironment,J as setSdkConfig};
1
+ import{B as P,a as J,b as m,c as L,d as T,e as U,f as G,g as h,h as p,i as g,j as S,k as E,l as x,m as y,n as A,p as w,q as I,r as v,s as C,t as D,u as re,v as oe,w as ne,x as F}from"../chunk-6OZ47QHO.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as _,c as q,d as B,e as z,f as Q,g as W,h as X,i as Y,j as Z,k as ee,m as te}from"../chunk-Q6GJ4HQZ.js";import{randomUUID as se}from"crypto";import{SpanStatusCode as k,SpanKind as ie}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function ae(s,e){if(typeof e!="object"||e===null)throw new t("`invocation` must be an object");let{schedulePath:r}=e;if(typeof r!="string"||r.length===0)throw new t("`schedulePath` must be a non-empty string");if(typeof e.isManual!="boolean")throw new t("`isManual` must be a boolean");if(!P(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let O=N("scheduledAt",e.scheduledAt),M=N("firedAt",e.firedAt),d=m(),a=d.executionId??se(),l=d.deploymentId??null,j=Date.now(),R=new Date().toISOString(),$=I(),K=w();E();let i={hasDb:!1,hasExternal:!1,hasAuth:!1,hasError:!1},c=!1,u=null;try{await p.run(i,()=>h.run(a,()=>y.startActiveSpan("schedule",{root:!0,kind:ie.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let H={type:"schedule",scheduledAt:O,firedAt:M,isManual:e.isManual},f={http:v(),db:n=>C(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:H};S(o,"input",{scheduledAt:e.scheduledAt,firedAt:e.firedAt,isManual:e.isManual});try{await b.run(f,()=>s.handler(f))}catch(n){throw c=!0,u=n instanceof Error?n.message:String(n),g("hasError"),n}finally{o.setAttribute("hasAuth",i.hasAuth),o.setAttribute("hasExternal",i.hasExternal),o.setAttribute("hasDb",i.hasDb),o.setAttribute("status",c?"error":"success");let n=c||i.hasError;o.setStatus({code:n?k.ERROR:k.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:R,startMs:j,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function N(s,e){if(typeof e!="string"||e.length===0)throw new t(`\`${s}\` must be a timestamp string; got ${JSON.stringify(e)}`);let r=new Date(e);if(Number.isNaN(r.getTime()))throw new t(`\`${s}\` must be a Date-parseable timestamp; got ${JSON.stringify(e)}`);return r}export{L as CONFIG_BRIDGE_CHANNEL,t as ScheduleInvocationError,re as assertValidPath,G as clearActiveConfig,oe as contentFilePath,U as getActiveConfig,Z as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,_ as isKnownEnvironment,te as isSdkError,z as listEnvironmentNames,Q as listExposedEnvNames,ne as metaFilePath,W as parseExposedEnvironment,V as registerEnvironmentProfile,B as requireEnvironmentProfile,ee as resetEnvironmentRegistryForTests,Y as resolveForcedEnvironment,ae as runScheduledFunction,T as setActiveConfig,X as setForcedEnvironment,J as setSdkConfig};
@@ -101,16 +101,42 @@ type ProvisionedTrayConfig = Extract<LoadedTrayConfig, {
101
101
  type UnprovisionedTrayConfig = Extract<LoadedTrayConfig, {
102
102
  kind: "unprovisioned";
103
103
  }>;
104
+ /**
105
+ * Env var naming an alternate config file (relative paths resolve against cwd).
106
+ * Sits between the explicit `configFile` option (the CLI's `--config` flag) and
107
+ * the `helix.config.ts` default in resolution precedence.
108
+ */
109
+ declare const HELIX_CONFIG_ENV = "HELIX_CONFIG";
110
+ /** Options accepted by every config entry point that resolves the config file. */
111
+ interface ConfigFileOptions {
112
+ /**
113
+ * Explicit config file path (the CLI's `--config` flag). Resolution
114
+ * precedence: this option → `HELIX_CONFIG` env var → `helix.config.ts`
115
+ * (then legacy `tray.config.*`) in cwd.
116
+ */
117
+ configFile?: string;
118
+ }
119
+ /**
120
+ * The effective config-file override, if any: the explicit `configFile` option
121
+ * (CLI `--config` flag) wins over the `HELIX_CONFIG` env var. Returns the raw
122
+ * (possibly relative) path — callers resolve it against their cwd.
123
+ */
124
+ declare function resolveConfigOverride(configFile?: string): string | undefined;
104
125
  /**
105
126
  * Absolute path of the project config file in `cwd`, preferring `helix.config.*`
106
127
  * and falling back to a legacy `tray.config.*`. Returns undefined when neither exists.
128
+ * A config-file override (option or HELIX_CONFIG) replaces the default search
129
+ * entirely: only the named file is considered.
107
130
  */
108
- declare function resolveConfigFile(cwd: string): string | undefined;
131
+ declare function resolveConfigFile(cwd: string, options?: ConfigFileOptions): string | undefined;
109
132
  /**
110
- * One-shot stateless read of `helix.config.ts`. NO caching — every call hits disk.
111
- * For hot-reload or stable snapshot, use {@link createConfigService} instead.
133
+ * One-shot stateless read of the project config. NO caching — every call hits disk.
134
+ * Reads `helix.config.ts` (legacy `tray.config.*` fallback) unless an override
135
+ * names another file — `options.configFile` (CLI `--config` flag) first, then
136
+ * the `HELIX_CONFIG` env var. For hot-reload or stable snapshot, use
137
+ * {@link createConfigService} instead.
112
138
  */
113
- declare function loadConfig(cwd?: string): Promise<LoadedTrayConfig>;
139
+ declare function loadConfig(cwd?: string, options?: ConfigFileOptions): Promise<LoadedTrayConfig>;
114
140
  /** Phase that surfaced an error inside ConfigService watcher. */
115
141
  type WatchErrorPhase = "attach" | "reload" | "validation";
116
142
  /** Stable code on errors thrown by {@link requireWorkspaceId}. Narrow by this, not instanceof. */
@@ -181,4 +207,4 @@ interface SdkConfigInput extends Partial<SdkRuntimeConfig>, BrokerSecrets {
181
207
  declare function setSdkConfig(options: SdkConfigInput): void;
182
208
  declare function getSdkConfig(): Readonly<SdkRuntimeConfig>;
183
209
 
184
- export { type LoadedTrayConfig as L, type ProvisionedTrayConfig as P, type SdkRuntimeConfig as S, type TrayConfig as T, type UnprovisionedTrayConfig as U, type WatchErrorPhase as W, WORKSPACE_ID_REQUIRED_CODE as a, type WorkspaceIdRequiredError as b, loadedTrayConfigSchema as c, resolveConfigFile as d, type SdkConfigInput as e, getSdkConfig as g, loadConfig as l, projectIdSchema as p, requireWorkspaceId as r, setSdkConfig as s, workspaceIdSchema as w };
210
+ export { type ConfigFileOptions as C, HELIX_CONFIG_ENV as H, type LoadedTrayConfig as L, type ProvisionedTrayConfig as P, type SdkRuntimeConfig as S, type TrayConfig as T, type UnprovisionedTrayConfig as U, type WatchErrorPhase as W, WORKSPACE_ID_REQUIRED_CODE as a, type WorkspaceIdRequiredError as b, loadedTrayConfigSchema as c, resolveConfigFile as d, resolveConfigOverride as e, type SdkConfigInput as f, getSdkConfig as g, loadConfig as l, projectIdSchema as p, requireWorkspaceId as r, setSdkConfig as s, workspaceIdSchema as w };
@@ -1,4 +1,4 @@
1
- import { P as PlatformContext } from '../types-DJcXnXhR.js';
1
+ import { P as PlatformContext } from '../types-DCCVrmZ3.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
@@ -243,6 +243,12 @@ interface DefineScheduleConfig {
243
243
  cron: string;
244
244
  /** IANA timezone name. Defaults to UTC. */
245
245
  timezone?: string;
246
+ /**
247
+ * Whether overlapping runs are allowed. Defaults to `false` — a fire that
248
+ * lands while the previous run is still in flight is skipped instead of
249
+ * overlapping it. Set `true` to invoke it anyway.
250
+ */
251
+ concurrent?: boolean;
246
252
  handler: ScheduleHandler;
247
253
  }
248
254
  /**
@@ -256,9 +262,9 @@ interface ScheduleDefinition {
256
262
  cron: string;
257
263
  timezone: string;
258
264
  /**
259
- * Always true: overlap control is not customer-configurable yet, and the
260
- * platform allows concurrent runs. Carried on the extraction/wire contract
261
- * so enforcement can arrive without a contract change.
265
+ * `false` (the default) skips a fire when the previous run is still in
266
+ * flight; `true` allows overlapping runs. Enforced upstream of the handler
267
+ * — a skipped fire never invokes the Lambda at all.
262
268
  */
263
269
  concurrent: boolean;
264
270
  handler: ScheduleHandler;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.95.0",
3
+ "version": "0.97.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -1,7 +0,0 @@
1
- import{d as D,l as c,n as Qe,o as Ze,p as Te,q as V,s as et}from"./chunk-Q6GJ4HQZ.js";var R="X-Helix-Project-Execution-Token",F="X-Tray-Token",yr={mode:"dev",deploymentId:null},Pe={...yr},O={};function po(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(O.internalJwt=t),"helixExecutionJwt"in e&&(O.helixExecutionJwt=r),"devToken"in e&&(O.devToken=n),Pe={...Pe,...o}}function w(){return Pe}function _(){return O.internalJwt}function T(){return O.helixExecutionJwt}function tt(){return O.devToken}var yo="tray-config-bridge",oe=null;function ho(e){oe=e}function b(){if(!oe)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return oe}function wo(){oe=null}import{AsyncLocalStorage as xt}from"async_hooks";import{trace as kr,SpanKind as Dr,SpanStatusCode as Ae}from"@opentelemetry/api";import{ExportResultCode as Or,W3CTraceContextPropagator as Fr}from"@opentelemetry/core";import{NodeTracerProvider as _r,SimpleSpanProcessor as Lr,BatchSpanProcessor as Nr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as hr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as wr}from"@opentelemetry/exporter-logs-otlp-proto";function Ce(e){return D(e).hosts.ingest}function br(){return T()??""}function rt(){return{[R]:br()}}function nt(){let e=Ce(b().env);return new hr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(rt())})}function ot(){let e=Ce(b().env);return new wr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(rt())})}import{logs as at,SeverityNumber as ie}from"@opentelemetry/api-logs";import{LoggerProvider as Er,BatchLogRecordProcessor as vr}from"@opentelemetry/sdk-logs";function z(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function Sr(e){return new TextEncoder().encode(e).length}var it="\u2026[truncated]",xr=Sr(it),J=4096;function I(e,t=J){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-xr);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+it}function y(e,t=J){return I(z(e),t)}var Rr="@trayai/helix-sdk",q,st={debug:{number:ie.DEBUG,text:"DEBUG"},info:{number:ie.INFO,text:"INFO"},warn:{number:ie.WARN,text:"WARN"},error:{number:ie.ERROR,text:"ERROR"}};function Tr(){return w().mode==="lambda"?[new vr({exporter:ot()})]:[]}function ct(){if(q!==void 0)return;let e=Tr();e.length!==0&&(q=new Er({processors:e}),at.setGlobalLoggerProvider(q))}function Pr(e,t,r){let n=st[e]??st.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":y(r)}}:{}}}function lt(e,t,r){at.getLogger(Rr).emit(Pr(e,t,r))}async function ut(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.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 Ie(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function Cr(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function S(e,t){return Cr()?`\x1B[${e}m${t}\x1B[0m`:t}var Ir=5,Ar={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},dt="32",ft="31",se="2",mt="1";function ae(e){return S(Ar[e]??"0",e.padEnd(Ir))}function pt(e,t){return`${ae("FN")} ${S(mt,`${e} ${t}`.trim())}`}function gt(e,t,r,n){let o=e.toUpperCase(),s=`${n?`${S(se,n)} `:""}${ae(o)} ${t}`;return r&&Object.keys(r).length>0&&(s+=` ${S(se,z(r))}`),s}function yt(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function ht(e){return`${ae("AUTH")} ${e}`}function wt(e,t,r,n,o){let i=r===void 0?"ERR":String(r),s=S(o==="error"?ft:dt,i);return`${ae("API")} ${e} ${t} \u2192 ${s} ${S(se,`${n}ms`)}`}function bt(e,t,r){let n=t?ft:dt,o=S(n,"\u25CF"),i=S(n,t?"error":"success");return`${o} ${S(mt,e)} ${i} ${S(se,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Et=new xt,Mr=new xt;function x(e){let t=Mr.getStore();t&&(t[e]=!0)}var Br=/^[0-9a-f]{32}$/;function Ur(e){let t=e.replace(/-/g,"").toLowerCase();return Br.test(t)?t:null}var jr={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 v(e,t,r){e.setAttribute(t,y(r))}var Y;function St(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function $r(e){return Math.round(e[0]*1e3+e[1]/1e6)}function Rt(e){try{process.stdout.write(z(e)+`
4
- `)}catch{}}var ke=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=N.get(o),s={...n.attributes};if(i!==void 0){for(let[u,f]of Object.entries(i))typeof f=="string"?s[u]=I(f):typeof f=="object"&&f!==null?s[u]=y(f):s[u]=f;N.delete(o)}let a=Et.getStore(),l=a?Ur(a):null;Rt({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:St(n.startTime),endTimeUnixNano:St(n.endTime),attributes:s,status:{code:jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:I(n.status.message)}:{}}})}r({code:Or.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},De=class{onStart(t,r){}onEnd(t){N.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Oe=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
- `+pt(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;L(gt(String(r.level??"info"),String(r.message??""),o,yt(t.startTime)));break}case"auth":L(ht(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(wt(String(r.method??""),String(r.host??""),n,$r(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Fe=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function Kr(){let t=[Ie()?new Oe:new Lr(new ke)];return w().mode==="lambda"&&t.push(new Fe(new Nr(nt()))),t.push(new De),t}function Hr(){Y===void 0&&(Y=new _r({spanProcessors:Kr()}),Y.register({propagator:new Fr}),ct())}async function Vr(e=2e3){let t=[ut(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 E=kr.getTracer("@trayai/helix-sdk");function zr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let f=new Date().toISOString(),d=Date.now()-i;if(Ie()){L(`
7
- `+bt(n,s,d));return}Rt({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:f,durationMs:d,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?I(a):null})}async function Jo(e,t){let r=e.startMs??Date.now();Hr();let n=!1,o=null;try{return await Et.run(e.executionId,()=>E.startActiveSpan("App",{kind:Dr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async i=>{try{let s=await t(),a=s?.httpResponse?.status??404;return n=a>=400,i.setAttribute("http.response.status_code",a),i.setAttribute("helix.status",n?"error":"success"),i.setStatus({code:n?Ae.ERROR:Ae.OK}),s}catch(s){throw n=!0,o=s instanceof Error?s.message:String(s),i.setAttribute("http.response.status_code",500),i.setAttribute("helix.status","error"),i.setStatus({code:Ae.ERROR,message:o}),s}finally{i.end()}}))}finally{zr({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 Vr()}}var Ct=1024,P=100*1024*1024,Tt=250,Jr=3600,qr=Jr*1e3,Pt=new TextEncoder,Yr=/(^|\/)\.\.(\/|$)/,Xr=/[?#]/;function Wr(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function A(e,t=Ct){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");ce(e,t)}function _e(e){return e.endsWith("/")?e.slice(0,-1):e}function ce(e,t=Ct){if(e.length===0)return;if(Yr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(Xr.test(e)||Wr(e))throw c.filesPathInvalid("Path contains illegal characters");let r=e.split("/");if(e.startsWith("/")||e.endsWith("/")||r.some(o=>o===""))throw c.filesPathInvalid("Path must not contain empty path segments");for(let o of r){let i=Pt.encode(o).length;if(i>Tt)throw c.filesPathInvalid(`Path segment exceeds ${Tt} UTF-8 bytes (got ${i})`)}let n=Pt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function It(e){if(e>P)throw c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got ${e})`,P)}function M(e){let t=e!==void 0?e*1e3:qr;return new Date(Date.now()+t)}import{join as W}from"path";var Gr="files",Qr="files-meta",Zr=1023,en=1,tn=5;function At(e){let t=Math.max(Buffer.byteLength(le(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,Zr-t-en-tn)}function le(e){return W(e,".helix",Gr)}function X(e){return W(e,".helix",Qr)}function G(e,t){return W(le(e),...t.split("/"))}function ue(e,t){return W(X(e),...t.split("/"))+".json"}function de(e,t){return t.length===0?le(e):G(e,t)}function kt(e,t){return t.length===0?X(e):W(X(e),...t.split("/"))}var Dt="helix-schedule",k=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function Qo(e){if(typeof e!="object"||e===null)throw new k("expected a config object");let{cron:t,timezone:r="UTC",handler:n}=e;if(typeof t!="string"||t.trim()==="")throw new k("`cron` must be a non-empty string");let o=t.trim().split(/\s+/).length;if(o!==5)throw new k(`\`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"||!rn(r))throw new k(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="function")throw new k("`handler` must be a function");return Object.freeze({kind:Dt,cron:t.trim(),timezone:r,concurrent:!0,handler:n})}function Zo(e){return typeof e=="object"&&e!==null&&e.kind===Dt&&typeof e.handler=="function"}function rn(e){if(!/^[A-Za-z]/.test(e))return!1;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}import{SpanKind as nn}from"@opentelemetry/api";function fe(e,t,r){let n=E.startSpan("log",{kind:nn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&vt(n.spanContext().spanId,"properties",r),n.end(),lt(e,t,r)}function oi(){return{info:(e,t)=>fe("info",e,t),warn:(e,t)=>fe("warn",e,t),error:(e,t)=>fe("error",e,t),debug:(e,t)=>fe("debug",e,t)}}function ai(){try{return b().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import on from"ky";import{context as Le,trace as sn,SpanKind as pe,SpanStatusCode as Ot}from"@opentelemetry/api";async function me(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=_(),l=T(),u=!!(a&&a.trim().length>0),f=!!(l&&l.trim().length>0);if(!u&&!f)throw c.missingExecutionCredentials();u&&(i[F]=a),f&&(i[R]=l),r.deploymentId&&(i[Qe]=r.deploymentId),o=Te(n,"runtime")}else{let a=tt();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Te(n,"dev")}let s;try{s=await et({proxyUrl:o,credentialHeaders:i,request:e,timeoutMs:t.timeout,executionId:r.executionId})}catch(a){let l=a instanceof Error?a.message??String(a):String(a);throw c.brokerError(0,l)}if(s.kind==="brokerError"){let a=s.code===Ze?"credential broker does not support the raw proxy endpoints required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,y(s.body),s.code)}return s.response}var an=["get","post","put","patch","delete","head","options"],Ft="[stream body omitted]";function _t(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Ft:e instanceof ArrayBuffer?`[binary body: ${e.byteLength} bytes]`:ArrayBuffer.isView(e)?`[binary body: ${e.byteLength} bytes]`:typeof Blob<"u"&&e instanceof Blob?`[binary body: ${e.size} bytes]`:e}function Ne(e){try{return new URL(e).hostname}catch{return e}}function cn(e,t,r,n){let o=Ne(t),i="externalApi",s={kind:pe.CLIENT};return E.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),v(a,"request",{url:t,method:e,...r!==void 0?{body:_t(r)}:{}}),n(a)))}function Me(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ot.OK}:{code:Ot.ERROR,message:r}),e.end()}var ln=16;async function un(e,t){let r=e.clone().body;return r?Lt(r,t):new Uint8Array(0)}async function Lt(e,t){let r=e.getReader(),n=[],o=0,i=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(i+=1,i>=ln)break;continue}i=0;let f=t+1-o;if(u.byteLength>=f){n.push(u.slice(0,f)),o+=f;break}n.push(u),o+=u.byteLength}}finally{r.cancel().catch(()=>{}),r.releaseLock()}let s=new Uint8Array(o),a=0;for(let l of n)s.set(l,a),a+=l.byteLength;return s}async function Nt(e,t,r){if("kyResponse"in r)try{let n=await un(r.kyResponse,J),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}v(e,"response",i)}catch{v(e,"response",{status:t})}else v(e,"response",_t(r.bodyValue))}async function dn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),i=new Request(e,{body:n,duplex:"half"}),s=await Lt(o,J);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Ft}}}return typeof t=="string"?{body:t}:{}}function Ri(){let e=on.create({});function t(n){return(o,i)=>{let s=Le.active(),a,l=!1,u=(d,m)=>{a&&!l&&(l=!0,Me(a,d,m))},f=e.extend({hooks:{beforeRequest:[async(d,m)=>{let p=await dn(d,m.body),ne=p.body;if(a||(a=E.startSpan("externalApi",{kind:pe.CLIENT},s)),a.setAttributes({method:d.method.toUpperCase(),host:Ne(d.url)}),v(a,"request",{url:d.url,method:d.method.toUpperCase(),...ne!==void 0?{body:ne}:{}}),l=!1,x("hasExternal"),p.request)return p.request}],beforeRetry:[d=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(d,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Nt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[d=>(x("hasError"),u("error",d.message),d)]}});return a=E.startSpan("externalApi",{kind:pe.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:Ne(String(o))}),Le.with(sn.setSpan(Le.active(),a),()=>{let d=n==="options"?f(o,{...i,method:"OPTIONS"}):f[n](o,i);return d.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),d})}}let r=Object.fromEntries(an.map(n=>[n,t(n)]));return{...e,...r,authed(n){return fn(n)}}}function fn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(s,a={})=>{let l=i.toUpperCase();return cn(l,s,a.body,async u=>{x("hasAuth");let f=E.startSpan("auth",{kind:pe.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let d=V({authenticationId:n,method:l,url:s,body:a.body,headers:a.headers,query:a.query}),m=await me(d,{timeout:a.timeout});return u.setAttribute("statusCode",m.status),await Nt(u,m.status,{bodyValue:m.body}),Me(u,"success"),m}catch(d){throw x("hasError"),d instanceof c&&d.detail.kind==="broker_error"&&d.detail.status>0&&u.setAttribute("statusCode",d.detail.status),Me(u,"error",d instanceof Error?d.message:String(d)),d}})}}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options")}}import{SpanKind as xn,SpanStatusCode as jt}from"@opentelemetry/api";function Q(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var mn=18e4,Mt=mn-1e4,pn=2e3;async function Bt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<Mt;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(pn,200*2**i),u=l/2+Math.random()*(l/2),f=Mt-(Date.now()-o);await new Promise(d=>setTimeout(d,Math.min(u,f))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var gn=new Set(["SELECT","WITH","SHOW"]),yn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function hn(e){if(!e.clusterIdentifier&&!e.workgroupName)throw c.dbInvalidParameters("either clusterIdentifier or workgroupName is required");if(e.clusterIdentifier&&e.workgroupName)throw c.dbInvalidParameters("clusterIdentifier and workgroupName are mutually exclusive (Provisioned vs Serverless)");if(!e.database)throw c.dbInvalidParameters("database is required");if(e.clusterIdentifier&&!e.dbUser)throw c.dbInvalidParameters("dbUser is required when using clusterIdentifier (Provisioned)");if(!e.region)throw c.dbInvalidParameters("region is required")}function wn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let i=typeof t=="string"?I(t):y(t);return c.dbCallFailed(i)}function bn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Sn(e,t){return typeof t!="number"||t<0?{}:gn.has(e)?{rowsRead:t}:yn.has(e)?{rowsWritten:t}:{}}function Ut(e){async function t(r,n,o){let i=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:s,body:a}=await me(i);if(s>=400)throw wn(s,a);return bn(a)}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message??String(s):String(s);throw c.dbCallFailed(a,s instanceof Error?s:void 0)}}return{system:"redshift",validate:hn,async execute(r,n){let o=Q(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=y(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Bt(t,r.region,l),f=u.Status;if(f==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(f==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let d=Sn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:d}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:d}}}}var Be=64*1024;function En(e){return e.length>Be?`${e.slice(0,Be)}...[truncated]`:e}function vn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Rn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Be?v(e,"result",{truncated:!0,size:n.length}):v(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Tn(e,t,r){let n=Q(r),o=En(r);return E.startActiveSpan("database",{kind:xn.CLIENT},async i=>{vn(i,e,t,n,o);try{x("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Rn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:jt.OK}),l}catch(s){x("hasError");let a=s instanceof Error?s.message:String(s);throw i.setAttribute("status","error"),i.setStatus({code:jt.ERROR,message:a}),s}finally{i.end()}})}function Pn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Ut(n);function i(s,a){return o.validate(s),Tn(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Dn}from"unstorage";var $t=1024,Ue=250*1024,Cn=new TextEncoder,In=/(^|\/)\.\.(\/|$)/,An=/[?#]/,kn=/[\u0000-\u001F\u007F]/;function Kt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(In.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(An.test(e)||kn.test(e))throw c.kvKeyInvalid("Key contains illegal characters");if(e.startsWith("/")||e.endsWith("/")||e.split("/").some(r=>r===""))throw c.kvKeyInvalid("Key must not contain empty path segments");let t=Cn.encode(e).length;if(t<1||t>$t)throw c.kvKeyInvalid(`Key must be between 1 and ${$t} UTF-8 bytes (got ${t})`)}function Ht(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Vt(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>Ue)throw c.kvValueTooLarge(`Value exceeds maximum size of ${Ue} bytes (got ${r})`,Ue)}function Z(e){Kt(e)}function ge(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function zt(e){let t=ge(e,"getItem"),r=ge(e,"setItem"),n=ge(e,"removeItem"),o=ge(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return Z(s),t(s,a)},setItem(s,a,l){return Z(s),r(s,a,l)},removeItem(s,a){return Z(s),n(s,a)},hasItem(s,a){return Z(s),o(s,a)},getKeys(s,a){return s.length>0&&Z(s),i(s,a)}}}function ye(e){return Dn({driver:zt(e)})}import{defineDriver as On}from"unstorage";function Fn(e){try{return JSON.parse(e)}catch{return e}}var _n=On(e=>{let{client:t}=e;return{name:"helix-kv",async getItem(r){let n=await t.get(r);return n===null?null:JSON.stringify(n)},async setItem(r,n,o){let i=o?.ttl,s=Fn(n);i!==void 0?await t.set(r,s,{ttl:i}):await t.set(r,s)},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 Jt(e){return _n({client:e})}import Mn from"ky";import{z as h}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 qt(e){return D(e).hosts.api}function Ln(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Nn(e){return e.split("/").map(encodeURIComponent).join("/")}function ee(e,t,r){return`${e}${Ln(t)}/${Nn(r)}`}var Bn=6e4,je=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(je),h.record(je)])),Un=h.object({projectId:h.string(),key:h.string(),value:je,type:h.enum(["string","number","boolean","null","array","object"]),organizationId:h.string(),scope:h.string(),createdBy:h.string(),createdAt:h.number(),updatedBy:h.string(),updatedAt:h.number()});function jn(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function $n(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function he(e,t){throw c.kvCallFailed(e,$n(t),y(t))}async function we(e,t,r={}){try{let n=await Mn(t,{method:e,headers:jn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Bn}),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 Yt(e){let t=qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await we("get",ee(t,r,n));if(o===404)return null;(o<200||o>=300)&&he(o,i);let s=Un.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",y(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await we("put",ee(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&he(s,a)},async delete(n){let{status:o,body:i}=await we("delete",ee(t,r,n));o!==204&&he(o,i)},async has(n){let{status:o,body:i}=await we("head",ee(t,r,n));if(o===200)return!0;if(o===404)return!1;he(o,i)}}}function be(e){return{getItem:t=>e.getItem(t),removeItem:t=>e.removeItem(t),hasItem:t=>e.hasItem(t),setItem:async(t,r,n)=>{let o=n?.ttl;Vt(r),o!==void 0&&Ht(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function Kn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Xt(e){let t=Kn(),r=e??Yt(t),n=ye(Jt(r));return be(n)}import{defineDriver as Hn}from"unstorage";var Vn=Hn(e=>{let t=new Map;function r(n){let o=t.get(n);if(o&&o.expiresAt!==void 0&&o.expiresAt<=Date.now()){t.delete(n);return}return o}return{name:"memory-ttl",getItem(n){return r(n)?.value??null},setItem(n,o,i){let s=i?.ttl;t.set(n,{value:o,expiresAt:s!==void 0?Date.now()+s*1e3:void 0})},removeItem(n){t.delete(n)},hasItem(n){return r(n)!==void 0},getKeys(){return[...t.keys()].filter(n=>r(n)!==void 0)},clear(){t.clear()}}});function Wt(){return Vn({})}var $e;function zn(){return $e||($e=ye(Wt())),$e}function Gt(){return be(zn())}function Jn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function As(){return Jn()?Xt():Gt()}import{createHash as Xn}from"crypto";import{mkdir as Wn,readFile as rr,readdir as nr,rm as Zt,unlink as Gn,writeFile as er}from"fs/promises";import{dirname as Qn}from"path";async function qn(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:i}=await t.read();if(o)break;if(i){if(n+=i.byteLength,n>P)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${P} bytes (got more than ${P})`,P);r.push(i)}}return Buffer.concat(r)}async function U(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?qn(e):Buffer.from(e)}var Yn={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"},Qt="application/octet-stream";function Se(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return Qt;let r=e.slice(t+1).toLowerCase();return Yn[r]??Qt}function $(){let e=w().projectRoot;if(!e)throw c.filesNotAvailable();return e}async function j(e){try{return await e()}catch(t){if(t instanceof c)throw t;let r=t?.code;throw r?c.filesCallFailed(0,`Local file storage operation failed: ${r}`):c.filesCallFailed(0,"Local file storage operation failed: unknown error")}}function xe(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Ke(e){try{let t=await rr(ue($(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function tr(e){await Wn(Qn(e),{recursive:!0})}async function Zn(e,t){let r=de(e,t),n;try{n=await nr(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 or(e,t){let r=de(e,t),n;try{n=await nr(r,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let o=[];for(let i of n){let s=t.length===0?i.name:`${t}/${i.name}`;i.isDirectory()?o.push(...await or(e,s)):i.isFile()&&o.push(s)}return o}function ir(){return{async put(e,t,r){return j(async()=>{let n=$(),o=await U(t),i=r?.contentType??Se(e),s=Xn("sha1").update(o).digest("hex"),a=new Date,l=G(n,e);await tr(l),await er(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},f=ue(n,e);return await tr(f),await er(f,JSON.stringify(u)),xe(e,u)})},async get(e){return j(async()=>{let t=await Ke(e);return t?{data:await rr(G($(),e)),metadata:xe(e,t)}:null})},async head(e){return j(async()=>{let t=await Ke(e);return t?xe(e,t):null})},async delete(e){return j(async()=>{let t=$();await Promise.all([G(t,e),ue(t,e)].map(async r=>{try{await Gn(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=$(),r=await or(t,e);return await Promise.all([Zt(de(t,e),{recursive:!0,force:!0}),Zt(kt(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=$(),n=t?.limit??100,i=(await Zn(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Ke(a);return l?xe(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:M(t?.expiresIn)}}}}import{createHash as so}from"crypto";function Ee(e){return D(e).hosts.api}function eo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function te(e,t){return`${e}${eo(t)}`}function K(e,t,r){return`${te(e,t)}/${encodeURIComponent(r)}`}function ve(e,t,r){return`${K(e,t,r)}/upload`}function sr(e,t,r){return`${K(e,t,r)}/download`}function ar(e,t,r){return`${K(e,t,r)}/signed-url`}function cr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${te(e,t)}/file?${o.toString()}`}function lr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${te(e,t)}?${o.toString()}`}import Ve from"ky";import{z as g}from"zod";var ze=6e4,ur=g.object({id:g.string(),workspaceId:g.string(),projectId:g.string(),parentFolder:g.string().nullable().optional(),name:g.string(),size:g.number().nullable().optional(),objectType:g.enum(["Folder","File"]),contentType:g.string().nullable().optional(),createdAt:g.string(),updatedAt:g.string()}),to=g.object({signedURL:g.string()}),ro=g.object({path:g.array(g.object({id:g.string(),name:g.string()})),elements:g.array(ur)});function Je(){let e=_(),t=T(),r=!!(e&&e.trim().length>0),n=!!(t&&t.trim().length>0);if(!r&&!n)throw c.missingExecutionCredentials();let o={Accept:"application/json"};return r&&(o[F]=e),n&&(o[R]=t),o}function dr(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function C(e,t){throw c.filesCallFailed(e,dr(t),y(t))}function no(e,t){return e===400&&dr(t).toLowerCase()==="resource not found"}async function oo(e){let t=new Response(e),r=t.headers.get("content-type")??"multipart/form-data",n=await t.arrayBuffer();return{body:Buffer.from(n),contentType:r}}async function H(e,t,r={}){try{let n=await Ve(t,{method:e,headers:Je(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:ze}),o=await 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 He(e,t){let r=ur.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",y(t));return r.data}function fr(e){let t=Ee(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",te(t,r),{json:n});return(o<200||o>=300)&&C(o,i),He(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",cr(t,r,n,o));return i===404||no(i,s)?null:((i<200||i>=300)&&C(i,s),He(i,s))},async getById(n){let{status:o,body:i}=await H("get",K(t,r,n));return o===404?null:((o<200||o>=300)&&C(o,i),He(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",lr(t,r,n,o));(i<200||i>=300)&&C(i,s);let a=ro.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",y(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await oo(a),f;try{f=await Ve(ve(t,r,n),{method:"post",headers:{...Je(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:ze})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let d=await B(f);(f.status<200||f.status>=300)&&C(f.status,d)},async downloadContent(n){let o;try{o=await Ve(sr(t,r,n),{method:"get",headers:Je(),throwHttpErrors:!1,timeout:ze})}catch(s){if(s instanceof c)throw s;let a=s instanceof Error?s.message:String(s);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let s=await B(o);C(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",ar(t,r,n));(o<200||o>=300)&&C(o,i);let s=to.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",y(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",K(t,r,n));o===204||o===404||(o<200||o>=300)&&C(o,i)}}}function qe(e){return e.split("/").filter(t=>t.length>0)}function Ye(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function io(e,t,r){let n=await e.getByName(t,r);if(n)return n;try{return await e.createMetadata({parentFolder:t,objectType:"Folder",name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Xe(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await io(e,o,i)).id;return{parentFolder:o,name:n}}async function re(e,t){let r=qe(t),n=r[r.length-1],o;for(let i of r.slice(0,-1)){let s=await e.getByName(o,i);if(!s||s.objectType!=="Folder")return null;o=s.id}return{parentFolder:o,name:n}}async function We(e,t){if(t.length===0)return;let r=qe(t),n;for(let o of r){let i=await e.getByName(n,o);if(!i||i.objectType!=="Folder")return null;n=i.id}return n}var ao=500,co=8;async function lo(e,t,r){let n=new Array(e.length),o=0;async function i(){for(;o<e.length;){let s=o++;n[s]=await r(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}function uo(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function fo(e){return so("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Re(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:fo(t)}}async function mr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Ye(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function pr(e,t){let{elements:r}=await e.listChildren(t,ao);return(await lo(r,co,async o=>{let i=o.objectType==="Folder"?await pr(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function gr(e){let t=uo(),r=e??fr(t),n=Ee(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Xe(r,i),f=await U(s),d=a?.contentType??Se(i),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${i}"`);let p=m??await mr(r,l,u,d);await r.uploadContent(p.id,f,u,d);let ne=await r.getById(p.id);return Re(i,ne??p,d)},async get(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Re(i,a)}},async head(i){let s=await re(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Re(i,a)},async delete(i){let s=await re(r,i);if(!s)return;let a=await r.getByName(s.parentFolder,s.name);a&&await r.deleteById(a.id)},async deleteMany(i){let s=await We(r,i);if(s===null)return{deleted:0};let a=await pr(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await We(r,i??"");if(a===null)return{files:[],cursor:null};let l=s?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(d=>d.objectType==="File").map(d=>Re(i?`${i}/${d.name}`:d.name,d)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Xe(r,i),f=await r.getByName(a,l)??await mr(r,a,l,s?.contentType);return{url:ve(n,o,f.id),expiresAt:M(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await re(r,i),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${i}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:M(s?.expiresIn)}}}}function Ge(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){A(n,r);let s=await U(o);return It(s.byteLength),e.put(n,s,i)},async get(n){return A(n,r),e.get(n)},async head(n){return A(n,r),e.head(n)},async delete(n){return A(n,r),e.delete(n)},async deleteMany(n){let o=_e(n);return ce(o,r),e.deleteMany(o)},async list(n,o){let i=_e(n??"");return ce(i,r),e.list(i,o)},async getUploadUrl(n,o){return A(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return A(n,r),e.getDownloadUrl(n,o)}}}function mo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function xa(){if(mo())return Ge(gr());let e=w().projectRoot;return Ge(ir(),{maxPathBytes:e?At(e):void 0})}export{po as a,w as b,yo as c,ho as d,b as e,wo as f,Et as g,Mr as h,x as i,v as j,Hr as k,Vr as l,E as m,zr as n,Jo as o,oi as p,ai as q,Ri as r,Pn as s,As as t,A as u,G as v,ue as w,xa as x,Dt as y,k as z,Qo as A,Zo as B};