@trayai/helix-sdk 0.106.0 → 0.107.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 +10 -0
- package/README.md +8 -4
- package/dist/{chunk-2XHMIUW3.js → chunk-VFVWN4RN.js} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/internal/index.js +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/{types-Dspz1laT.d.ts → types-DqH1HJU0.d.ts} +7 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,16 @@ 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.107.0
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- **`ctx.kv().setItem`'s `ttl` option is now three-state.** A positive integer number of
|
|
17
|
+
seconds still sets an expiry, but passing `ttl: null` now clears an existing expiry so the
|
|
18
|
+
key no longer expires, and omitting `ttl` leaves any current expiry unchanged (previously the
|
|
19
|
+
option only set or, in the local store, dropped an expiry). `helix dev`'s in-memory store
|
|
20
|
+
applies the same semantics. `KvSetItemOptions.ttl` widens to `number | null`.
|
|
21
|
+
|
|
12
22
|
## 0.103.0
|
|
13
23
|
|
|
14
24
|
### Added
|
package/README.md
CHANGED
|
@@ -155,12 +155,16 @@ const value = await ctx.kv().getItem('greeting');
|
|
|
155
155
|
|
|
156
156
|
// Expire a key automatically after 60 seconds.
|
|
157
157
|
await ctx.kv().setItem('session', { userId: '123' }, { ttl: 60 });
|
|
158
|
+
|
|
159
|
+
// Clear an existing expiry so the key no longer expires.
|
|
160
|
+
await ctx.kv().setItem('session', { userId: '123' }, { ttl: null });
|
|
158
161
|
```
|
|
159
162
|
|
|
160
|
-
`setItem`'s `ttl` option is a positive integer number of seconds
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
163
|
+
`setItem`'s `ttl` option is three-state: a positive integer number of seconds sets an expiry
|
|
164
|
+
after which the key is deleted, `null` clears an existing expiry, and omitting it leaves any
|
|
165
|
+
current expiry unchanged. `helix dev`'s local store enforces the same semantics — an expired
|
|
166
|
+
key is evicted lazily on its next access — but that store is in-memory only, so entries (and
|
|
167
|
+
their TTLs) don't survive a dev server restart.
|
|
164
168
|
|
|
165
169
|
### File storage — `ctx.files()`
|
|
166
170
|
|
|
@@ -4,4 +4,4 @@ import{d as _,l as c,n as tt,o as se,p as Ce,q as V,s as rt,t as nt,u as Ae,v as
|
|
|
4
4
|
`)}catch{}}var Fe=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,i=L.get(o),s={...n.attributes};if(i!==void 0){for(let[u,d]of Object.entries(i))typeof d=="string"?s[u]=D(d):typeof d=="object"&&d!==null?s[u]=g(d):s[u]=d;L.delete(o)}let a=Tt.getStore(),l=a?Vr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:vt(n.startTime),endTimeUnixNano:vt(n.endTime),attributes:s,status:{code:Jr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:D(n.status.message)}:{}}})}r({code:Br.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ne=class{onStart(t,r){}onEnd(t){L.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&N(`
|
|
5
5
|
`+ht(String(r.attributes.method??""),String(r.attributes.route??"")))}onEnd(t){let r=t.attributes;switch(t.name){case"log":{let n=t.spanContext().spanId,o=L.get(n)?.properties;N(wt(String(r.level??"info"),String(r.message??""),o,bt(t.startTime)));break}case"auth":N(St(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;N(xt(String(r.method??""),String(r.host??""),n,zr(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Be=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 qr(){let t=[Oe()?new Le:new jr(new Fe)];return w().mode==="lambda"&&t.push(new Be(new Kr(st()))),t.push(new Ne),t}function Yr(){Y===void 0&&(Y=new Ur({spanProcessors:qr()}),Y.register({propagator:new Mr}),dt())}async function Xr(e=2e3){let t=[mt(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
6
|
`)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var x=Nr.getTracer("@trayai/helix-sdk");function Gr({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:i,errored:s,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-i;if(Oe()){N(`
|
|
7
|
-
`+Et(n,s,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?D(a):null})}async function Wo(e,t){let r=e.startMs??Date.now();Yr();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>x.startActiveSpan("App",{kind:Lr.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?_e.ERROR:_e.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:_e.ERROR,message:o}),s}finally{i.end()}}))}finally{Gr({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 Xr()}}var kt=1024,C=100*1024*1024,Ct=250,Wr=3600,Qr=Wr*1e3,At=new TextEncoder,Zr=/(^|\/)\.\.(\/|$)/,en=/[?#]/;function tn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=kt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Me(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=kt){if(e.length===0)return;if(Zr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(en.test(e)||tn(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=At.encode(o).length;if(i>Ct)throw c.filesPathInvalid(`Path segment exceeds ${Ct} UTF-8 bytes (got ${i})`)}let n=At.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Dt(e){if(e>C)throw c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got ${e})`,C)}function B(e){let t=e!==void 0?e*1e3:Qr;return new Date(Date.now()+t)}import{join as G}from"path";var rn="files",nn="files-meta",on=1023,sn=1,an=5;function Ot(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,on-t-sn-an)}function me(e){return G(e,".helix",rn)}function X(e){return G(e,".helix",nn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function _t(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Ft="helix-schedule",A=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ni(e){if(typeof e!="object"||e===null)throw new A("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new A("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new A(`\`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"||!cn(r))throw new A(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new A("`concurrent` must be a boolean");if(typeof o!="function")throw new A("`handler` must be a function");return Object.freeze({kind:Ft,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function oi(e){return typeof e=="object"&&e!==null&&e.kind===Ft&&typeof e.handler=="function"}function cn(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 ln}from"@opentelemetry/api";function ye(e,t,r){let n=x.startSpan("log",{kind:ln.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),ft(e,t,r)}function li(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function fi(){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 un from"ky";import{context as Ue,trace as dn,SpanKind as Z,SpanStatusCode as Lt}from"@opentelemetry/api";async function he(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(i[P]=a),d&&(i[E]=l),r.deploymentId&&(i[tt]=r.deploymentId),o=Ce(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Ce(n,"dev")}let s;try{s=await rt({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===se?"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,g(s.body),s.code)}return s.response}async function Nt(e){nt(e.url);let t=w(),{env:r}=b(),n,o={},i={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[E]=l),t.deploymentId&&(i.deploymentId=t.deploymentId),n=Ae(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=Ae(r,"dev")}let s;try{s=await ot({signUrl:n,credentialHeaders:o,body:i,timeoutMs:e.timeout,executionId:t.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===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.result}var fn=["get","post","put","patch","delete","head","options"],Mt="[stream body omitted]";function Ut(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Mt: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 je(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n){let o=je(t),i="externalApi",s={kind:Z.CLIENT};return x.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),T(a,"request",{url:t,method:e,...r!==void 0?{body:Ut(r)}:{}}),n(a)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Lt.OK}:{code:Lt.ERROR,message:r}),e.end()}var mn=16;async function pn(e,t){let r=e.clone().body;return r?jt(r,t):new Uint8Array(0)}async function jt(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>=mn)break;continue}i=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;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 Kt(e,t,r){if("kyResponse"in r)try{let n=await pn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",Ut(r.bodyValue))}async function gn(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 jt(o,z);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Mt}}}return typeof t=="string"?{body:t}:{}}function Bi(){let e=un.create({});function t(n){return(o,i)=>{let s=Ue.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await gn(f,m.body),ie=p.body;if(a||(a=x.startSpan("externalApi",{kind:Z.CLIENT},s)),a.setAttributes({method:f.method.toUpperCase(),host:je(f.url)}),T(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,S("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Kt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(S("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(S("hasError"),u("error",f.message),f)]}});return a=x.startSpan("externalApi",{kind:Z.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:je(String(o))}),Ue.with(dn.setSpan(Ue.active(),a),()=>{let f=n==="options"?d(o,{...i,method:"OPTIONS"}):d[n](o,i);return f.catch(m=>{S("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(fn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return yn(n)}}}function yn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return Bt(u,a,l.body,async d=>{S("hasAuth");let f=x.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=V({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Kt(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw S("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function i(s,a={}){let l=a.method??"GET";return Bt(l,s,void 0,async u=>{S("hasAuth");let d=x.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Nt({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw S("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as Tn,SpanStatusCode as Jt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var hn=18e4,$t=hn-1e4,wn=2e3;async function Ht(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<$t;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(wn,200*2**i),u=l/2+Math.random()*(l/2),d=$t-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var bn=new Set(["SELECT","WITH","SHOW"]),Sn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function xn(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 En(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"?D(t):g(t);return c.dbCallFailed(i)}function vn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Rn(e,t){return typeof t!="number"||t<0?{}:bn.has(e)?{rowsRead:t}:Sn.has(e)?{rowsWritten:t}:{}}function Vt(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 he(i);if(s>=400)throw En(s,a);return vn(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:xn,async execute(r,n){let o=ee(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Ht(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Rn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var Ke=64*1024;function Pn(e){return e.length>Ke?`${e.slice(0,Ke)}...[truncated]`:e}function In(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Cn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Ke?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function An(e,t,r){let n=ee(r),o=Pn(r);return x.startActiveSpan("database",{kind:Tn.CLIENT},async i=>{In(i,e,t,n,o);try{S("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Cn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Jt.OK}),l}catch(s){S("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 kn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Vt(n);function i(s,a){return o.validate(s),An(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Nn}from"unstorage";var zt=1024,$e=250*1024,Dn=new TextEncoder,On=/(^|\/)\.\.(\/|$)/,_n=/[?#]/,Fn=/[\u0000-\u001F\u007F]/;function qt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(On.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(_n.test(e)||Fn.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=Dn.encode(e).length;if(t<1||t>zt)throw c.kvKeyInvalid(`Key must be between 1 and ${zt} UTF-8 bytes (got ${t})`)}function Yt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Xt(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>$e)throw c.kvValueTooLarge(`Value exceeds maximum size of ${$e} bytes (got ${r})`,$e)}function te(e){qt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Gt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return te(s),t(s,a)},setItem(s,a,l){return te(s),r(s,a,l)},removeItem(s,a){return te(s),n(s,a)},hasItem(s,a){return te(s),o(s,a)},getKeys(s,a){return s.length>0&&te(s),i(s,a)}}}function be(e){return Nn({driver:Gt(e)})}import{defineDriver as Ln}from"unstorage";function Bn(e){try{return JSON.parse(e)}catch{return e}}var Mn=Ln(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=Bn(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 Wt(e){return Mn({client:e})}import Kn from"ky";import{z as h}from"zod";async function M(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 _(e).hosts.api}function Un(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function jn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${Un(t)}/${jn(r)}`}var $n=6e4,He=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(He),h.record(He)])),Hn=h.object({projectId:h.string(),key:h.string(),value:He,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 Vn(){let e=I(),t=v(),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[P]=e),n&&(o[E]=t),o}function Jn(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,Jn(t),g(t))}async function xe(e,t,r={}){try{let n=await Kn(t,{method:e,headers:Vn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:$n}),o=e==="head"?void 0:await M(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 Zt(e){let t=Qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await xe("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,i);let s=Hn.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await xe("put",re(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&Se(s,a)},async delete(n){let{status:o,body:i}=await xe("delete",re(t,r,n));o!==204&&Se(o,i)},async has(n){let{status:o,body:i}=await xe("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,i)}}}function Ee(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;Xt(r),o!==void 0&&Yt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function zn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function er(e){let t=zn(),r=e??Zt(t),n=be(Wt(r));return Ee(n)}import{defineDriver as qn}from"unstorage";var Yn=qn(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 tr(){return Yn({})}var Ve;function Xn(){return Ve||(Ve=be(tr())),Ve}function rr(){return Ee(Xn())}function Gn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function $s(){return Gn()?er():rr()}import{createHash as Zn}from"crypto";import{mkdir as eo,readFile as ar,readdir as cr,rm as or,unlink as to,writeFile as ir}from"fs/promises";import{dirname as ro}from"path";async function Wn(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>C)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got more than ${C})`,C);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?Wn(e):Buffer.from(e)}var Qn={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},nr="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return nr;let r=e.slice(t+1).toLowerCase();return Qn[r]??nr}function K(){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 Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Je(e){try{let t=await ar(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function sr(e){await eo(ro(e),{recursive:!0})}async function no(e,t){let r=ge(e,t),n;try{n=await cr(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 lr(e,t){let r=ge(e,t),n;try{n=await cr(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 lr(e,s)):i.isFile()&&o.push(s)}return o}function ur(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await U(t),i=r?.contentType??ve(e),s=Zn("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await sr(l),await ir(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},d=pe(n,e);return await sr(d),await ir(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await Je(e);return t?{data:await ar(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await Je(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await to(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await lr(t,e);return await Promise.all([or(ge(t,e),{recursive:!0,force:!0}),or(_t(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,i=(await no(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Je(a);return l?Re(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:B(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}}}}import{createHash as uo}from"crypto";function Te(e){return _(e).hosts.api}function oo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${oo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Pe(e,t,r){return`${$(e,t,r)}/upload`}function dr(e,t,r){return`${$(e,t,r)}/download`}function fr(e,t,r){return`${$(e,t,r)}/signed-url`}function mr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function pr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import qe from"ky";import{z as y}from"zod";var Ye=6e4,gr=y.object({id:y.string(),workspaceId:y.string(),projectId:y.string(),parentFolder:y.string().nullable().optional(),name:y.string(),size:y.number().nullable().optional(),objectType:y.enum(["Folder","File"]),contentType:y.string().nullable().optional(),createdAt:y.string(),updatedAt:y.string()}),io=y.object({signedURL:y.string()}),so=y.object({path:y.array(y.object({id:y.string(),name:y.string()})),elements:y.array(gr)});function Xe(){let e=I(),t=v(),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[P]=e),n&&(o[E]=t),o}function yr(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 k(e,t){throw c.filesCallFailed(e,yr(t),g(t))}function ao(e,t){return e===400&&yr(t).toLowerCase()==="resource not found"}async function co(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 qe(t,{method:e,headers:Xe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ye}),o=await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function ze(e,t){let r=gr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function hr(e){let t=Te(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&k(o,i),ze(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",mr(t,r,n,o));return i===404||ao(i,s)?null:((i<200||i>=300)&&k(i,s),ze(i,s))},async getById(n){let{status:o,body:i}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&k(o,i),ze(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",pr(t,r,n,o));(i<200||i>=300)&&k(i,s);let a=so.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",g(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await co(a),d;try{d=await qe(Pe(t,r,n),{method:"post",headers:{...Xe(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Ye})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await M(d);(d.status<200||d.status>=300)&&k(d.status,f)},async downloadContent(n){let o;try{o=await qe(dr(t,r,n),{method:"get",headers:Xe(),throwHttpErrors:!1,timeout:Ye})}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 M(o);k(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",fr(t,r,n));(o<200||o>=300)&&k(o,i);let s=io.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&k(o,i)}}}function Ge(e){return e.split("/").filter(t=>t.length>0)}function We(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function lo(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(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Qe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await lo(e,o,i)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=Ge(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 Ze(e,t){if(t.length===0)return;let r=Ge(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 fo=500,mo=8;async function po(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 go(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function yo(e){return uo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Ie(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:yo(t)}}async function wr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function br(e,t){let{elements:r}=await e.listChildren(t,fo);return(await po(r,mo,async o=>{let i=o.objectType==="Folder"?await br(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function Sr(e){let t=go(),r=e??hr(t),n=Te(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Qe(r,i),d=await U(s),f=a?.contentType??ve(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 wr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Ie(i,ie??p,f)},async get(i){let s=await oe(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:Ie(i,a)}},async head(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Ie(i,a)},async delete(i){let s=await oe(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 Ze(r,i);if(s===null)return{deleted:0};let a=await br(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Ze(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(f=>f.objectType==="File").map(f=>Ie(i?`${i}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Qe(r,i),d=await r.getByName(a,l)??await wr(r,a,l,s?.contentType);return{url:Pe(n,o,d.id),expiresAt:B(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await oe(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:B(s?.expiresIn)}}}}function et(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){O(n,r);let s=await U(o);return Dt(s.byteLength),e.put(n,s,i)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Me(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let i=Me(n??"");return fe(i,r),e.list(i,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function ho(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Fa(){if(ho())return et(Sr());let e=w().projectRoot;return et(ur(),{maxPathBytes:e?Ot(e):void 0})}export{wo as a,w as b,So as c,xo as d,Eo as e,b as f,vo as g,Tt as h,$r as i,S as j,T as k,Yr as l,Xr as m,x as n,Gr as o,Wo as p,li as q,fi as r,Bi as s,kn as t,$s as u,O as v,W as w,pe as x,Fa as y,Ft as z,A,ni as B,oi as C};
|
|
7
|
+
`+Et(n,s,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:s?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:s||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:s&&a!==null?D(a):null})}async function Wo(e,t){let r=e.startMs??Date.now();Yr();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>x.startActiveSpan("App",{kind:Lr.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?_e.ERROR:_e.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:_e.ERROR,message:o}),s}finally{i.end()}}))}finally{Gr({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 Xr()}}var kt=1024,C=100*1024*1024,Ct=250,Wr=3600,Qr=Wr*1e3,At=new TextEncoder,Zr=/(^|\/)\.\.(\/|$)/,en=/[?#]/;function tn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<=31||r===127)return!0}return!1}function O(e,t=kt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Me(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=kt){if(e.length===0)return;if(Zr.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(en.test(e)||tn(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=At.encode(o).length;if(i>Ct)throw c.filesPathInvalid(`Path segment exceeds ${Ct} UTF-8 bytes (got ${i})`)}let n=At.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Dt(e){if(e>C)throw c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got ${e})`,C)}function B(e){let t=e!==void 0?e*1e3:Qr;return new Date(Date.now()+t)}import{join as G}from"path";var rn="files",nn="files-meta",on=1023,sn=1,an=5;function Ot(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,on-t-sn-an)}function me(e){return G(e,".helix",rn)}function X(e){return G(e,".helix",nn)}function W(e,t){return G(me(e),...t.split("/"))}function pe(e,t){return G(X(e),...t.split("/"))+".json"}function ge(e,t){return t.length===0?me(e):W(e,t)}function _t(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Ft="helix-schedule",A=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function ni(e){if(typeof e!="object"||e===null)throw new A("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new A("`cron` must be a non-empty string");let i=t.trim().split(/\s+/).length;if(i!==5)throw new A(`\`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"||!cn(r))throw new A(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new A("`concurrent` must be a boolean");if(typeof o!="function")throw new A("`handler` must be a function");return Object.freeze({kind:Ft,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function oi(e){return typeof e=="object"&&e!==null&&e.kind===Ft&&typeof e.handler=="function"}function cn(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 ln}from"@opentelemetry/api";function ye(e,t,r){let n=x.startSpan("log",{kind:ln.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),ft(e,t,r)}function li(){return{info:(e,t)=>ye("info",e,t),warn:(e,t)=>ye("warn",e,t),error:(e,t)=>ye("error",e,t),debug:(e,t)=>ye("debug",e,t)}}function fi(){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 un from"ky";import{context as Ue,trace as dn,SpanKind as Z,SpanStatusCode as Lt}from"@opentelemetry/api";async function he(e,t={}){let r=w(),{env:n}=b(),o,i={};if(r.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(i[P]=a),d&&(i[E]=l),r.deploymentId&&(i[tt]=r.deploymentId),o=Ce(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();i.Authorization=`Bearer ${a}`,o=Ce(n,"dev")}let s;try{s=await rt({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===se?"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,g(s.body),s.code)}return s.response}async function Nt(e){nt(e.url);let t=w(),{env:r}=b(),n,o={},i={authenticationId:e.authenticationId,url:e.url,...e.method!==void 0?{method:e.method}:{},...e.expiresIn!==void 0?{expiresIn:e.expiresIn}:{}};if(t.mode==="lambda"){let a=I(),l=v(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[E]=l),t.deploymentId&&(i.deploymentId=t.deploymentId),n=Ae(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=Ae(r,"dev")}let s;try{s=await ot({signUrl:n,credentialHeaders:o,body:i,timeoutMs:e.timeout,executionId:t.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===se?"credential broker does not support the s3 sign endpoint required by this SDK version \u2014 deploy a newer broker or pin an older SDK":s.message;throw c.brokerError(s.status,a,g(s.body),s.code)}return s.result}var fn=["get","post","put","patch","delete","head","options"],Mt="[stream body omitted]";function Ut(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?Mt: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 je(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n){let o=je(t),i="externalApi",s={kind:Z.CLIENT};return x.startActiveSpan(i,s,async a=>(a.setAttributes({method:e,host:o}),T(a,"request",{url:t,method:e,...r!==void 0?{body:Ut(r)}:{}}),n(a)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Lt.OK}:{code:Lt.ERROR,message:r}),e.end()}var mn=16;async function pn(e,t){let r=e.clone().body;return r?jt(r,t):new Uint8Array(0)}async function jt(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>=mn)break;continue}i=0;let d=t+1-o;if(u.byteLength>=d){n.push(u.slice(0,d)),o+=d;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 Kt(e,t,r){if("kyResponse"in r)try{let n=await pn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),i;try{i=JSON.parse(o)}catch{i=o}T(e,"response",i)}catch{T(e,"response",{status:t})}else T(e,"response",Ut(r.bodyValue))}async function gn(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 jt(o,z);return{body:new TextDecoder("utf-8").decode(s,{stream:!0}),request:i}}catch{return{body:Mt}}}return typeof t=="string"?{body:t}:{}}function Bi(){let e=un.create({});function t(n){return(o,i)=>{let s=Ue.active(),a,l=!1,u=(f,m)=>{a&&!l&&(l=!0,Q(a,f,m))},d=e.extend({hooks:{beforeRequest:[async(f,m)=>{let p=await gn(f,m.body),ie=p.body;if(a||(a=x.startSpan("externalApi",{kind:Z.CLIENT},s)),a.setAttributes({method:f.method.toUpperCase(),host:je(f.url)}),T(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,S("hasExternal"),p.request)return p.request}],beforeRetry:[f=>{u("error","retry"),a=void 0,l=!1}],afterResponse:[async(f,m,p)=>{a&&(a.setAttribute("statusCode",p.status),await Kt(a,p.status,{kyResponse:p}),p.ok?u("success"):i?.throwHttpErrors===!1&&(S("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(S("hasError"),u("error",f.message),f)]}});return a=x.startSpan("externalApi",{kind:Z.CLIENT},s),a.setAttributes({method:n.toUpperCase(),host:je(String(o))}),Ue.with(dn.setSpan(Ue.active(),a),()=>{let f=n==="options"?d(o,{...i,method:"OPTIONS"}):d[n](o,i);return f.catch(m=>{S("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(fn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return yn(n)}}}function yn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(s){return(a,l={})=>{let u=s.toUpperCase();return Bt(u,a,l.body,async d=>{S("hasAuth");let f=x.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=V({authenticationId:n,method:u,url:a,body:l.body,headers:l.headers,query:l.query}),p=await he(m,{timeout:l.timeout});return d.setAttribute("statusCode",p.status),await Kt(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw S("hasError"),m instanceof c&&m.detail.kind==="broker_error"&&m.detail.status>0&&d.setAttribute("statusCode",m.detail.status),Q(d,"error",m instanceof Error?m.message:String(m)),m}})}}function i(s,a={}){let l=a.method??"GET";return Bt(l,s,void 0,async u=>{S("hasAuth");let d=x.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Nt({authenticationId:n,url:s,method:l,...a.expiresIn!==void 0?{expiresIn:a.expiresIn}:{},...a.timeout!==void 0?{timeout:a.timeout}:{}});return u.setAttribute("statusCode",200),Q(u,"success"),f}catch(f){throw S("hasError"),f instanceof c&&f.detail.kind==="broker_error"&&f.detail.status>0&&u.setAttribute("statusCode",f.detail.status),Q(u,"error",f instanceof Error?f.message:String(f)),f}})}return{get:o("get"),post:o("post"),put:o("put"),patch:o("patch"),delete:o("delete"),head:o("head"),options:o("options"),s3Sign:i}}import{SpanKind as Tn,SpanStatusCode as Jt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var hn=18e4,$t=hn-1e4,wn=2e3;async function Ht(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),i=0;for(;Date.now()-o<$t;){let s=await e(t,"DescribeStatement",{Id:r}),a=s.Status;if(n.has(a))return s;let l=Math.min(wn,200*2**i),u=l/2+Math.random()*(l/2),d=$t-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),i++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var bn=new Set(["SELECT","WITH","SHOW"]),Sn=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function xn(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 En(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"?D(t):g(t);return c.dbCallFailed(i)}function vn(e){if(e==null||typeof e!="string")return e;try{return JSON.parse(e)}catch{throw c.dbCallFailed("upstream body not JSON: "+e.slice(0,200))}}function Rn(e,t){return typeof t!="number"||t<0?{}:bn.has(e)?{rowsRead:t}:Sn.has(e)?{rowsWritten:t}:{}}function Vt(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 he(i);if(s>=400)throw En(s,a);return vn(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:xn,async execute(r,n){let o=ee(n),i={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},s=await t(r.region,"ExecuteStatement",i),a=s,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(s);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Ht(t,r.region,l),d=u.Status;if(d==="FAILED"){let p=typeof u.Error=="string"?u.Error:"statement failed";throw c.dbQueryFailed(`${p} (statement: ${l})`)}if(d==="ABORTED")throw c.dbQueryFailed(`statement aborted (statement: ${l})`);let f=Rn(o,u.ResultRows);return u.HasResultSet===!1?{result:{rowsAffected:u.ResultRows??0},metadata:f}:{result:await t(r.region,"GetStatementResult",{Id:l}),metadata:f}}}}var Ke=64*1024;function Pn(e){return e.length>Ke?`${e.slice(0,Ke)}...[truncated]`:e}function In(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Cn(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>Ke?T(e,"result",{truncated:!0,size:n.length}):T(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function An(e,t,r){let n=ee(r),o=Pn(r);return x.startActiveSpan("database",{kind:Tn.CLIENT},async i=>{In(i,e,t,n,o);try{S("hasDb");let{result:s,metadata:a}=await e.execute(t,r),l=Cn(i,s,a);return i.setAttribute("status","success"),i.setStatus({code:Jt.OK}),l}catch(s){S("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 kn(e){let r=b().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=Vt(n);function i(s,a){return o.validate(s),An(o,s,a)}return{parameters(s){return{sql(a){return i(s,a)}}},sql(s){return i({},s)}}}import{createStorage as Nn}from"unstorage";var zt=1024,$e=250*1024,Dn=new TextEncoder,On=/(^|\/)\.\.(\/|$)/,_n=/[?#]/,Fn=/[\u0000-\u001F\u007F]/;function qt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(On.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(_n.test(e)||Fn.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=Dn.encode(e).length;if(t<1||t>zt)throw c.kvKeyInvalid(`Key must be between 1 and ${zt} UTF-8 bytes (got ${t})`)}function Yt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Xt(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>$e)throw c.kvValueTooLarge(`Value exceeds maximum size of ${$e} bytes (got ${r})`,$e)}function te(e){qt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Gt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),i=e.getKeys;return{...e,getItem(s,a){return te(s),t(s,a)},setItem(s,a,l){return te(s),r(s,a,l)},removeItem(s,a){return te(s),n(s,a)},hasItem(s,a){return te(s),o(s,a)},getKeys(s,a){return s.length>0&&te(s),i(s,a)}}}function be(e){return Nn({driver:Gt(e)})}import{defineDriver as Ln}from"unstorage";function Bn(e){try{return JSON.parse(e)}catch{return e}}var Mn=Ln(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=Bn(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 Wt(e){return Mn({client:e})}import Kn from"ky";import{z as h}from"zod";async function M(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 _(e).hosts.api}function Un(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function jn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${Un(t)}/${jn(r)}`}var $n=6e4,He=h.lazy(()=>h.union([h.string(),h.number(),h.boolean(),h.null(),h.array(He),h.record(He)])),Hn=h.object({projectId:h.string(),key:h.string(),value:He,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 Vn(){let e=I(),t=v(),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[P]=e),n&&(o[E]=t),o}function Jn(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}return String(e??"unknown error")}function Se(e,t){throw c.kvCallFailed(e,Jn(t),g(t))}async function xe(e,t,r={}){try{let n=await Kn(t,{method:e,headers:Vn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:$n}),o=e==="head"?void 0:await M(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 Zt(e){let t=Qt(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:i}=await xe("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,i);let s=Hn.safeParse(i);if(!s.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(i));return s.data.value},async set(n,o,i){let{status:s,body:a}=await xe("put",re(t,r,n),{json:i?.ttl!==void 0?{value:o,ttl:i.ttl}:{value:o}});(s<200||s>=300)&&Se(s,a)},async delete(n){let{status:o,body:i}=await xe("delete",re(t,r,n));o!==204&&Se(o,i)},async has(n){let{status:o,body:i}=await xe("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,i)}}}function Ee(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;Xt(r),typeof o=="number"&&Yt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function zn(){let e=b();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function er(e){let t=zn(),r=e??Zt(t),n=be(Wt(r));return Ee(n)}import{defineDriver as qn}from"unstorage";var Yn=qn(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,a=r(n),l=typeof s=="number"?Date.now()+s*1e3:s===null?void 0:a?.expiresAt;t.set(n,{value:o,expiresAt:l})},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 tr(){return Yn({})}var Ve;function Xn(){return Ve||(Ve=be(tr())),Ve}function rr(){return Ee(Xn())}function Gn(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function $s(){return Gn()?er():rr()}import{createHash as Zn}from"crypto";import{mkdir as eo,readFile as ar,readdir as cr,rm as or,unlink as to,writeFile as ir}from"fs/promises";import{dirname as ro}from"path";async function Wn(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>C)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${C} bytes (got more than ${C})`,C);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?Wn(e):Buffer.from(e)}var Qn={pdf:"application/pdf",csv:"text/csv",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",json:"application/json",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",xml:"application/xml",zip:"application/zip"},nr="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return nr;let r=e.slice(t+1).toLowerCase();return Qn[r]??nr}function K(){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 Re(e,t){return{path:e,size:t.size,contentType:t.contentType,lastModified:new Date(t.lastModified),etag:t.etag}}async function Je(e){try{let t=await ar(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function sr(e){await eo(ro(e),{recursive:!0})}async function no(e,t){let r=ge(e,t),n;try{n=await cr(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 lr(e,t){let r=ge(e,t),n;try{n=await cr(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 lr(e,s)):i.isFile()&&o.push(s)}return o}function ur(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await U(t),i=r?.contentType??ve(e),s=Zn("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await sr(l),await ir(l,o);let u={size:o.byteLength,contentType:i,lastModified:a.toISOString(),etag:s},d=pe(n,e);return await sr(d),await ir(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await Je(e);return t?{data:await ar(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await Je(e);return t?Re(e,t):null})},async delete(e){return j(async()=>{let t=K();await Promise.all([W(t,e),pe(t,e)].map(async r=>{try{await to(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await lr(t,e);return await Promise.all([or(ge(t,e),{recursive:!0,force:!0}),or(_t(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,i=(await no(r,e??"")).slice(0,n);return{files:(await Promise.all(i.map(async a=>{let l=await Je(a);return l?Re(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:B(t?.expiresIn)}},async getDownloadUrl(e,t){let r=w().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:B(t?.expiresIn)}}}}import{createHash as uo}from"crypto";function Te(e){return _(e).hosts.api}function oo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${oo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Pe(e,t,r){return`${$(e,t,r)}/upload`}function dr(e,t,r){return`${$(e,t,r)}/download`}function fr(e,t,r){return`${$(e,t,r)}/signed-url`}function mr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function pr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import qe from"ky";import{z as y}from"zod";var Ye=6e4,gr=y.object({id:y.string(),workspaceId:y.string(),projectId:y.string(),parentFolder:y.string().nullable().optional(),name:y.string(),size:y.number().nullable().optional(),objectType:y.enum(["Folder","File"]),contentType:y.string().nullable().optional(),createdAt:y.string(),updatedAt:y.string()}),io=y.object({signedURL:y.string()}),so=y.object({path:y.array(y.object({id:y.string(),name:y.string()})),elements:y.array(gr)});function Xe(){let e=I(),t=v(),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[P]=e),n&&(o[E]=t),o}function yr(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 k(e,t){throw c.filesCallFailed(e,yr(t),g(t))}function ao(e,t){return e===400&&yr(t).toLowerCase()==="resource not found"}async function co(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 qe(t,{method:e,headers:Xe(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Ye}),o=await M(n);return{status:n.status,body:o}}catch(n){if(n instanceof c)throw n;let o=n instanceof Error?n.message:String(n);throw c.filesCallFailed(0,o)}}function ze(e,t){let r=gr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function hr(e){let t=Te(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:i}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&k(o,i),ze(o,i)},async getByName(n,o){let{status:i,body:s}=await H("get",mr(t,r,n,o));return i===404||ao(i,s)?null:((i<200||i>=300)&&k(i,s),ze(i,s))},async getById(n){let{status:o,body:i}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&k(o,i),ze(o,i))},async listChildren(n,o){let{status:i,body:s}=await H("get",pr(t,r,n,o));(i<200||i>=300)&&k(i,s);let a=so.safeParse(s);if(!a.success)throw c.filesCallFailed(i,"platform returned malformed listing",g(s));return a.data},async uploadContent(n,o,i,s){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:s}),i);let{body:l,contentType:u}=await co(a),d;try{d=await qe(Pe(t,r,n),{method:"post",headers:{...Xe(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Ye})}catch(m){if(m instanceof c)throw m;let p=m instanceof Error?m.message:String(m);throw c.filesCallFailed(0,p)}let f=await M(d);(d.status<200||d.status>=300)&&k(d.status,f)},async downloadContent(n){let o;try{o=await qe(dr(t,r,n),{method:"get",headers:Xe(),throwHttpErrors:!1,timeout:Ye})}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 M(o);k(o.status,s)}let i=await o.arrayBuffer();return Buffer.from(i)},async getSignedDownloadUrl(n){let{status:o,body:i}=await H("get",fr(t,r,n));(o<200||o>=300)&&k(o,i);let s=io.safeParse(i);if(!s.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(i));return s.data.signedURL},async deleteById(n){let{status:o,body:i}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&k(o,i)}}}function Ge(e){return e.split("/").filter(t=>t.length>0)}function We(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function lo(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(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function Qe(e,t){let r=Ge(t),n=r[r.length-1],o;for(let i of r.slice(0,-1))o=(await lo(e,o,i)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=Ge(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 Ze(e,t){if(t.length===0)return;let r=Ge(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 fo=500,mo=8;async function po(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 go(){let e=b();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function yo(e){return uo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Ie(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:yo(t)}}async function wr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(We(o)){let i=await e.getByName(t,r);if(i)return i}throw o}}async function br(e,t){let{elements:r}=await e.listChildren(t,fo);return(await po(r,mo,async o=>{let i=o.objectType==="Folder"?await br(e,o.id):1;return await e.deleteById(o.id),i})).reduce((o,i)=>o+i,0)}function Sr(e){let t=go(),r=e??hr(t),n=Te(t.env),{projectId:o}=t;return{async put(i,s,a){let{parentFolder:l,name:u}=await Qe(r,i),d=await U(s),f=a?.contentType??ve(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 wr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Ie(i,ie??p,f)},async get(i){let s=await oe(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:Ie(i,a)}},async head(i){let s=await oe(r,i);if(!s)return null;let a=await r.getByName(s.parentFolder,s.name);return!a||a.objectType!=="File"?null:Ie(i,a)},async delete(i){let s=await oe(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 Ze(r,i);if(s===null)return{deleted:0};let a=await br(r,s);return i.length>0&&s!==void 0&&await r.deleteById(s),{deleted:a}},async list(i,s){let a=await Ze(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(f=>f.objectType==="File").map(f=>Ie(i?`${i}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(i,s){let{parentFolder:a,name:l}=await Qe(r,i),d=await r.getByName(a,l)??await wr(r,a,l,s?.contentType);return{url:Pe(n,o,d.id),expiresAt:B(s?.expiresIn)}},async getDownloadUrl(i,s){let a=await oe(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:B(s?.expiresIn)}}}}function et(e,t){let r=t?.maxPathBytes;return{async put(n,o,i){O(n,r);let s=await U(o);return Dt(s.byteLength),e.put(n,s,i)},async get(n){return O(n,r),e.get(n)},async head(n){return O(n,r),e.head(n)},async delete(n){return O(n,r),e.delete(n)},async deleteMany(n){let o=Me(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let i=Me(n??"");return fe(i,r),e.list(i,o)},async getUploadUrl(n,o){return O(n,r),e.getUploadUrl(n,o)},async getDownloadUrl(n,o){return O(n,r),e.getDownloadUrl(n,o)}}}function ho(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":w().mode==="lambda"}function Fa(){if(ho())return et(Sr());let e=w().projectRoot;return et(ur(),{maxPathBytes:e?Ot(e):void 0})}export{wo as a,w as b,So as c,xo as d,Eo as e,b as f,vo as g,Tt as h,$r as i,S as j,T as k,Yr as l,Xr as m,x as n,Gr as o,Wo as p,li as q,fi as r,Bi as s,kn as t,$s as u,O as v,W as w,pe as x,Fa as y,Ft as z,A,ni as B,oi as C};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as h3 from 'h3';
|
|
2
2
|
import { ZodType } from 'zod';
|
|
3
|
-
import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-
|
|
4
|
-
export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-
|
|
3
|
+
import { F as FunctionHandler, D as DefineFunctionOptions, a as DefineScheduleConfig, S as ScheduleDefinition, P as PlatformContext } from './types-DqH1HJU0.js';
|
|
4
|
+
export { B as BrokerAuthedClient, b as BrokerCallOptions, c as BrokerCallResult, d as DbCallParameters, e as DbClient, f as FileSystemClient, H as HttpClient, K as KeyValueStore, L as Logger, g as S3SignOptions, h as S3SignResult, i as ScheduleContext, j as ScheduleHandler, k as ScheduleTrigger, l as SqlBuilder, T as TrayContext, U as UnvalidatedInput } from './types-DqH1HJU0.js';
|
|
5
5
|
import { T as TrayConfig, L as LoadedTrayConfig, W as WatchErrorPhase } from './sdk-config-vY_-Reh3.js';
|
|
6
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';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as we,B as ke,C as Se,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ce,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as Ee}from"./chunk-2XHMIUW3.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-D5GPRK2D.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}`;B();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=Ke(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 K()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Be(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 Be(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 Ke(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}
|
|
1
|
+
import{A as we,B as ke,C as Se,b as R,h as M,i as F,j as Z,k as E,l as B,m as K,n as V,o as z,p as Ce,q as J,r as Q,s as Y,t as ee,u as te,y as re,z as Ee}from"./chunk-VFVWN4RN.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-D5GPRK2D.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}`;B();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=Ke(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 K()}}async function Ne(e,t){try{return{ok:!0,input:await ne(e,t)}}catch(r){let n=Be(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 Be(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 Ke(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
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
3
|
`:`warning: no helix.config.ts found at ${e.cwd}; tray running with default config \u2014 create one via \`helix init\`
|
|
4
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};
|
package/dist/internal/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as N,a as H,b as m,c as L,d as T,e as G,f as J,g as U,h,i as p,j as g,k as E,l as S,m as x,n as y,o as A,q as w,r as I,s as C,t as v,u as D,v as oe,w as ne,x as se,y as F}from"../chunk-
|
|
1
|
+
import{C as N,a as H,b as m,c as L,d as T,e as G,f as J,g as U,h,i as p,j as g,k as E,l as S,m as x,n as y,o as A,q as w,r as I,s as C,t as v,u as D,v as oe,w as ne,x as se,y as F}from"../chunk-VFVWN4RN.js";import{a as b}from"../chunk-WUCX7RZO.js";import{a as V,b as B,c as q,d as z,e as Q,f as W,g as X,h as Y,i as Z,j as ee,k as te,m as re}from"../chunk-D5GPRK2D.js";import{randomUUID as ie}from"crypto";import{SpanStatusCode as P,SpanKind as ae}from"@opentelemetry/api";var t=class extends Error{constructor(e){super(`runScheduledFunction: ${e}`),this.name="ScheduleInvocationError"}};async function le(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(!N(s))throw new t(`default export of "${r}" is not a defineSchedule definition`);let k=O("scheduledAt",e.scheduledAt),M=O("firedAt",e.firedAt),d=m(),a=d.executionId??ie(),l=d.deploymentId??null,R=Date.now(),j=new Date().toISOString(),$=I(),K=w();S();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:ae.SERVER,attributes:{method:"SCHEDULE",route:r,executionId:a,...l?{deploymentId:l}:{}}},async o=>{let _={type:"schedule",scheduledAt:k,firedAt:M,isManual:e.isManual},f={http:C(),db:n=>v(n),kv:()=>D(),files:()=>F(),log:K,config:$,state:{},executionId:a,deploymentId:l,traceId:o.spanContext().traceId,trigger:_};E(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?P.ERROR:P.OK,...u?{message:u}:{}}),o.end()}})))}finally{A({executionId:a,deploymentId:l,triggerType:"schedule",routeOrJob:r,startedAt:j,startMs:R,errored:c,errorMessage:u,userId:null,flags:i}),await x()}}function O(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 DEV_TOKEN_BRIDGE_CHANNEL,t as ScheduleInvocationError,oe as assertValidPath,U as clearActiveConfig,ne as contentFilePath,J as getActiveConfig,ee as getAdditionalEnvironmentProfiles,q as getEnvironmentProfile,B as isKnownEnvironment,re as isSdkError,Q as listEnvironmentNames,W as listExposedEnvNames,se as metaFilePath,X as parseExposedEnvironment,V as registerEnvironmentProfile,z as requireEnvironmentProfile,te as resetEnvironmentRegistryForTests,Z as resolveForcedEnvironment,le as runScheduledFunction,G as setActiveConfig,Y as setForcedEnvironment,H as setSdkConfig};
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -22,11 +22,16 @@ interface DbClient {
|
|
|
22
22
|
|
|
23
23
|
interface KvSetItemOptions {
|
|
24
24
|
/**
|
|
25
|
-
* Time-to-live
|
|
25
|
+
* Time-to-live, three-state:
|
|
26
|
+
* - a positive integer number of seconds sets a new expiry, after which the
|
|
27
|
+
* key is deleted;
|
|
28
|
+
* - `null` clears an existing expiry, so the key no longer expires;
|
|
29
|
+
* - omitting it (`undefined`) leaves any existing expiry unchanged.
|
|
30
|
+
*
|
|
26
31
|
* The dev in-memory store expires keys lazily on access (getItem/hasItem),
|
|
27
32
|
* not via a background timer.
|
|
28
33
|
*/
|
|
29
|
-
ttl?: number;
|
|
34
|
+
ttl?: number | null;
|
|
30
35
|
}
|
|
31
36
|
interface KeyValueStore {
|
|
32
37
|
getItem<T = unknown>(key: string): Promise<T | null>;
|