@trayai/helix-sdk 0.113.0 → 0.115.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.
@@ -1,7 +1,9 @@
1
- import { P as PlatformContext } from '../types-DoNQWbb9.js';
1
+ import { P as PlatformContext } from '../types-B9ZTUx-H.js';
2
2
  import 'h3';
3
3
  import 'ky';
4
4
  import 'zod';
5
+ import 'ai';
6
+ import '@ai-sdk/provider';
5
7
 
6
8
  /**
7
9
  * Run code within a mock PlatformContext — for unit testing shared code that
@@ -1 +1 @@
1
- import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,callFunctionAsync:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0,parentExecutionId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,u){let i=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(i,u)}export{l as runWithContext};
1
+ import{a as n}from"../chunk-WUCX7RZO.js";var f={http:!0,db:!0,kv:!0,files:!0,callFunctionAsync:!0,ai:!0,log:!0,config:!0,state:!0,executionId:!0,deploymentId:!0,traceId:!0,parentExecutionId:!0},d={input:!0,method:!0,path:!0,headers:!0,status:!0,error:!0,request:!0,userId:!0,identity:!0,trigger:!0};async function l(o,u){let i=new Proxy(o,{get(e,t,r){if(typeof t=="symbol"||t==="then"||t==="toJSON"||t in e)return Reflect.get(e,t,r);if(!(t in d))throw t in f?new Error(`Accessed unset context field "${String(t)}" in test. Provide it via runWithContext({ ${String(t)}: ... }, fn).`):new Error(`Accessed unknown context field "${String(t)}" in test \u2014 not a PlatformContext member.`)}});return n.run(i,u)}export{l as runWithContext};
@@ -1,6 +1,8 @@
1
1
  import { H3Event } from 'h3';
2
2
  import { KyInstance } from 'ky';
3
3
  import { ZodType } from 'zod';
4
+ import { EmbeddingModel, ImageModel, LanguageModel, SpeechModel, TranscriptionModel, generateText, streamText, generateObject, streamObject, embed, embedMany, generateImage, transcribe, generateSpeech } from 'ai';
5
+ import { LanguageModelV4, EmbeddingModelV4, ImageModelV4, TranscriptionModelV4, SpeechModelV4 } from '@ai-sdk/provider';
4
6
 
5
7
  /** Connection + call params supplied by the caller at `.parameters()` time. */
6
8
  interface DbCallParameters {
@@ -118,6 +120,113 @@ interface FileSystemClient {
118
120
  */
119
121
  type CallFunctionAsync = (functionPath: string, input?: unknown) => Promise<void>;
120
122
 
123
+ /**
124
+ * Interim client-side cost estimation.
125
+ *
126
+ * The AI-gateway spec (helix-spec 11) makes the credentials broker the
127
+ * authority on cost: it sees model + token usage on every forwarded request
128
+ * and meters centrally (surfaced via `helix ai usage`). Until broker-side
129
+ * metering returns per-request cost to the SDK, `result.helix.cost` is
130
+ * estimated here from the provider's reported usage and public list prices.
131
+ * Unknown models estimate to 0 — the platform-side record remains authoritative.
132
+ *
133
+ * Prices are USD per 1M tokens, matched by longest model-id prefix so dated
134
+ * snapshot ids (e.g. `gpt-4o-2024-11-20`) resolve to their family.
135
+ */
136
+ interface HelixCost {
137
+ amount: number;
138
+ currency: "USD";
139
+ }
140
+
141
+ /**
142
+ * Public `ctx.ai` types (helix-spec 11).
143
+ *
144
+ * Options and results are the AI SDK's own — derived from the `ai` package's
145
+ * call functions so they track the pinned major exactly. The alias-scoped
146
+ * methods take `model` as a string id resolved against the provider; the
147
+ * top-level `ctx.ai.*` functions take a model *instance* (the `& object`
148
+ * intersection strips the AI SDK's string arm — bare ids would route via the
149
+ * implicit global provider, which Helix disables).
150
+ */
151
+ interface HelixResultMeta {
152
+ helix: {
153
+ /** Estimated from provider-reported usage (broker-side metering is the
154
+ authoritative record — see `helix ai usage`). */
155
+ cost: HelixCost;
156
+ requestId: string;
157
+ };
158
+ }
159
+ type AiLanguageModelInstance = LanguageModel & object;
160
+ type AiEmbeddingModelInstance = EmbeddingModel & object;
161
+ type AiImageModelInstance = ImageModel & object;
162
+ type AiTranscriptionModelInstance = TranscriptionModel & object;
163
+ type AiSpeechModelInstance = SpeechModel & object;
164
+ type WithStringModel<O> = Omit<O, "model"> & {
165
+ model: string;
166
+ };
167
+ type WithModelInstance<O, M> = Omit<O, "model"> & {
168
+ model: M;
169
+ };
170
+ type GenerateTextOptions = Parameters<typeof generateText>[0];
171
+ type StreamTextOptions = Parameters<typeof streamText>[0];
172
+ type GenerateObjectOptions = Parameters<typeof generateObject>[0];
173
+ type StreamObjectOptions = Parameters<typeof streamObject>[0];
174
+ type EmbedOptions = Parameters<typeof embed>[0];
175
+ type EmbedManyOptions = Parameters<typeof embedMany>[0];
176
+ type GenerateImageOptions = Parameters<typeof generateImage>[0];
177
+ type TranscribeOptions = Parameters<typeof transcribe>[0];
178
+ type GenerateSpeechOptions = Parameters<typeof generateSpeech>[0];
179
+ type GenerateTextReturn = Awaited<ReturnType<typeof generateText>>;
180
+ type StreamTextReturn = ReturnType<typeof streamText>;
181
+ type GenerateObjectReturn = Awaited<ReturnType<typeof generateObject>>;
182
+ type StreamObjectReturn = ReturnType<typeof streamObject>;
183
+ type EmbedReturn = Awaited<ReturnType<typeof embed>>;
184
+ type EmbedManyReturn = Awaited<ReturnType<typeof embedMany>>;
185
+ type GenerateImageReturn = Awaited<ReturnType<typeof generateImage>>;
186
+ type TranscribeReturn = Awaited<ReturnType<typeof transcribe>>;
187
+ type GenerateSpeechReturn = Awaited<ReturnType<typeof generateSpeech>>;
188
+ /**
189
+ * `ctx.ai(alias)` — a real AI SDK provider bound to the credentials broker,
190
+ * plus mirrored call functions taking string model ids.
191
+ */
192
+ interface HelixAIProvider {
193
+ /** Callable shorthand for languageModel(). */
194
+ (modelId: string): LanguageModelV4;
195
+ languageModel(modelId: string): LanguageModelV4;
196
+ embeddingModel(modelId: string): EmbeddingModelV4;
197
+ /** Spec-11 name for embeddingModel — same models. */
198
+ textEmbeddingModel(modelId: string): EmbeddingModelV4;
199
+ imageModel(modelId: string): ImageModelV4;
200
+ transcriptionModel(modelId: string): TranscriptionModelV4;
201
+ speechModel(modelId: string): SpeechModelV4;
202
+ generateText(options: WithStringModel<GenerateTextOptions>): Promise<GenerateTextReturn & HelixResultMeta>;
203
+ streamText(options: WithStringModel<StreamTextOptions>): StreamTextReturn;
204
+ generateObject(options: WithStringModel<GenerateObjectOptions>): Promise<GenerateObjectReturn & HelixResultMeta>;
205
+ streamObject(options: WithStringModel<StreamObjectOptions>): StreamObjectReturn;
206
+ embed(options: WithStringModel<EmbedOptions>): Promise<EmbedReturn>;
207
+ embedMany(options: WithStringModel<EmbedManyOptions>): Promise<EmbedManyReturn>;
208
+ generateImage(options: WithStringModel<GenerateImageOptions>): Promise<GenerateImageReturn & HelixResultMeta>;
209
+ transcribe(options: WithStringModel<TranscribeOptions>): Promise<TranscribeReturn>;
210
+ generateSpeech(options: WithStringModel<GenerateSpeechOptions>): Promise<GenerateSpeechReturn>;
211
+ }
212
+ /**
213
+ * `ctx.ai` — callable (alias → provider) and carrying the top-level call
214
+ * functions that take a model instance (from any `ctx.ai(alias)` provider).
215
+ * This is the governed request entry point for custom agent loops.
216
+ */
217
+ interface HelixAI {
218
+ (alias: string): HelixAIProvider;
219
+ generateText(options: WithModelInstance<GenerateTextOptions, AiLanguageModelInstance>): Promise<GenerateTextReturn & HelixResultMeta>;
220
+ streamText(options: WithModelInstance<StreamTextOptions, AiLanguageModelInstance>): StreamTextReturn;
221
+ generateObject(options: WithModelInstance<GenerateObjectOptions, AiLanguageModelInstance>): Promise<GenerateObjectReturn & HelixResultMeta>;
222
+ streamObject(options: WithModelInstance<StreamObjectOptions, AiLanguageModelInstance>): StreamObjectReturn;
223
+ embed(options: WithModelInstance<EmbedOptions, AiEmbeddingModelInstance>): Promise<EmbedReturn>;
224
+ embedMany(options: WithModelInstance<EmbedManyOptions, AiEmbeddingModelInstance>): Promise<EmbedManyReturn>;
225
+ generateImage(options: WithModelInstance<GenerateImageOptions, AiImageModelInstance>): Promise<GenerateImageReturn & HelixResultMeta>;
226
+ transcribe(options: WithModelInstance<TranscribeOptions, AiTranscriptionModelInstance>): Promise<TranscribeReturn>;
227
+ generateSpeech(options: WithModelInstance<GenerateSpeechOptions, AiSpeechModelInstance>): Promise<GenerateSpeechReturn>;
228
+ }
229
+
121
230
  interface Logger {
122
231
  info(message: string, data?: Record<string, unknown>): void;
123
232
  warn(message: string, data?: Record<string, unknown>): void;
@@ -203,6 +312,9 @@ interface ContextCore {
203
312
  * reports) that execution's outcome.
204
313
  */
205
314
  callFunctionAsync: CallFunctionAsync;
315
+ /** AI client (helix-spec 11): `ctx.ai(alias)` for broker-routed providers,
316
+ `ctx.ai.generateText({ model })` etc. for model-instance calls. */
317
+ ai: HelixAI;
206
318
  log: Logger;
207
319
  config: Record<string, unknown>;
208
320
  state: Record<string, unknown>;
@@ -321,4 +433,4 @@ interface ScheduleDefinition {
321
433
  handler: ScheduleHandler;
322
434
  }
323
435
 
324
- export type { BrokerAuthedClient as B, CallFunctionAsync as C, DefineFunctionOptions as D, FunctionHandler as F, HttpClient as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, BrokerCallOptions as b, BrokerCallResult as c, DbCallParameters as d, DbClient as e, FileSystemClient as f, S3SignOptions as g, S3SignResult as h, ScheduleContext as i, ScheduleHandler as j, ScheduleTrigger as k, SqlBuilder as l };
436
+ export type { AiEmbeddingModelInstance as A, BrokerAuthedClient as B, CallFunctionAsync as C, DefineFunctionOptions as D, FunctionHandler as F, HelixAI as H, KeyValueStore as K, Logger as L, PlatformContext as P, ScheduleDefinition as S, TrayContext as T, UnvalidatedInput as U, DefineScheduleConfig as a, AiImageModelInstance as b, AiLanguageModelInstance as c, AiSpeechModelInstance as d, AiTranscriptionModelInstance as e, BrokerCallOptions as f, BrokerCallResult as g, DbCallParameters as h, DbClient as i, FileSystemClient as j, HelixAIProvider as k, HelixCost as l, HelixResultMeta as m, HttpClient as n, S3SignOptions as o, S3SignResult as p, ScheduleContext as q, ScheduleHandler as r, ScheduleTrigger as s, SqlBuilder as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trayai/helix-sdk",
3
- "version": "0.113.0",
3
+ "version": "0.115.0",
4
4
  "description": "Helix SDK runtime — defineFunction, ctx, defineConfig, authed HTTP",
5
5
  "license": "Apache-2.0",
6
6
  "author": "trayio",
@@ -41,6 +41,13 @@
41
41
  "node": ">=24.19.0"
42
42
  },
43
43
  "dependencies": {
44
+ "@ai-sdk/anthropic": "^4.0.49",
45
+ "@ai-sdk/cohere": "^4.0.37",
46
+ "@ai-sdk/google": "^4.0.63",
47
+ "@ai-sdk/mistral": "^4.0.39",
48
+ "@ai-sdk/openai": "^4.0.58",
49
+ "@ai-sdk/openai-compatible": "^3.0.43",
50
+ "@ai-sdk/provider": "^4.0.10",
44
51
  "@opentelemetry/api": "^1.9.1",
45
52
  "@opentelemetry/api-logs": "0.220.0",
46
53
  "@opentelemetry/core": ">=2.8.0 <3",
@@ -50,6 +57,7 @@
50
57
  "@opentelemetry/sdk-logs": "0.220.0",
51
58
  "@opentelemetry/sdk-trace-base": "^2.11.0",
52
59
  "@opentelemetry/sdk-trace-node": "^2.11.0",
60
+ "ai": "^7.0.92",
53
61
  "c12": "^3.3.4",
54
62
  "chokidar": "^5.0.0",
55
63
  "h3": "^1.15.11",
@@ -1 +0,0 @@
1
- var P=new Set(["production"]),a=new Map,g={name:"production",exposedName:"us1",displayName:"production",hosts:{api:"https://api.tray.io",broker:"https://api.tray.io/private/v1/code",ingest:"https://api.tray.io/private/v1/helix/otlp",weaver:"https://weaver.tray.io",app:"https://app.tray.io",projectHost:"helix-app.ai",dashboard:"https://app.helix.tray.ai",auth:"https://auth.tray.io"},login:{storePrefix:"PROD",appUrl:"https://app.tray.io",cookieName:"prod_tray_lid",cookieDomain:"tray.io"}};a.set(g.name,g);var E=["api","broker","ingest","weaver","app","projectHost","dashboard"],x=["auth"],b=["storePrefix","appUrl","cookieName","cookieDomain"];function R(e){if(!e.name||typeof e.name!="string")throw new Error("EnvironmentProfile.name must be a non-empty string");if(!e.exposedName||typeof e.exposedName!="string")throw new Error("EnvironmentProfile.exposedName must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("EnvironmentProfile.displayName must be a non-empty string");if(!e.hosts||typeof e.hosts!="object")throw new Error("EnvironmentProfile.hosts must be an object");if(!e.login||typeof e.login!="object")throw new Error("EnvironmentProfile.login must be an object");for(let n of E)if(typeof e.hosts[n]!="string"||!e.hosts[n])throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string`);for(let n of x){let r=e.hosts[n];if(r!==void 0&&(typeof r!="string"||!r))throw new Error(`EnvironmentProfile.hosts.${n} must be a non-empty string when set`)}for(let n of b)if(typeof e.login[n]!="string"||!e.login[n])throw new Error(`EnvironmentProfile.login.${n} must be a non-empty string`)}function I(e,n){return e.name===n.name&&e.exposedName===n.exposedName&&e.displayName===n.displayName&&E.every(r=>e.hosts[r]===n.hosts[r])&&x.every(r=>e.hosts[r]===n.hosts[r])&&b.every(r=>e.login[r]===n.login[r])}function V(e){R(e);let n=a.get(e.name);if(n){if(I(n,e))return;throw new Error(`EnvironmentProfile.name "${e.name}" is already registered with different values`)}for(let r of a.values())if(r.exposedName===e.exposedName)throw new Error(`EnvironmentProfile.exposedName "${e.exposedName}" is already used by "${r.name}"`);a.set(e.name,e)}function N(e){return a.has(e)}function J(e){return a.get(e)}function y(e){let n=a.get(e);if(!n)throw new Error(`Unknown environment: ${e}`);return n}function G(){return[...a.keys()]}function Y(){return[...a.values()].map(e=>e.exposedName)}function T(e){for(let n of a.values())if(n.exposedName===e)return n.name}var m=Symbol.for("@trayai/helix-sdk.forcedEnvironment");function D(e){let n=globalThis;if(e===void 0||e.trim()===""){delete n[m];return}let r=e.trim(),t=T(r);if(t){n[m]=t;return}if(N(r)){n[m]=r;return}throw new Error(`Unknown environment: ${r}`)}function z(){return globalThis[m]}function W(){return[...a.values()].filter(e=>!P.has(e.name))}function X(){D(void 0),a.clear(),a.set(g.name,{...g,hosts:{...g.hosts},login:{...g.login}})}var u=class e extends Error{detail;constructor(n){super(U(n)),this.name="SdkError",this.detail=n}get kind(){return this.detail.kind}static unknownAlias(n,r){return new e({kind:"unknown_alias",alias:n,available:r})}static inputValidationFailed(n){return new e({kind:"input_validation_failed",fields:n})}static outputValidationFailed(n){return new e({kind:"output_validation_failed",fields:n})}static configLoadFailed(n){return new e({kind:"config_load_failed",cause:n})}static brokerError(n,r,t,i){return new e({kind:"broker_error",status:n,message:r,body:t,code:i})}static unsupportedBodyType(n){return new e({kind:"unsupported_body_type",actualType:n})}static unsupportedScheme(n){return new e({kind:"unsupported_scheme",scheme:n})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(n,r){return new e({kind:"db_call_failed",message:n,cause:r})}static dbQueryFailed(n){return new e({kind:"db_query_failed",message:n})}static dbInvalidParameters(n){return new e({kind:"db_invalid_parameters",message:n})}static kvKeyInvalid(n){return new e({kind:"kv_key_invalid",message:n})}static kvValueInvalid(n){return new e({kind:"kv_value_invalid",message:n})}static kvValueTooLarge(n,r){return new e({kind:"kv_value_too_large",message:n,maxBytes:r})}static kvTtlInvalid(n){return new e({kind:"kv_ttl_invalid",message:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(n,r,t){return new e({kind:"kv_call_failed",status:n,message:r,body:t})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(n){return new e({kind:"files_path_invalid",message:n})}static filesValueInvalid(n){return new e({kind:"files_value_invalid",message:n})}static filesValueTooLarge(n,r){return new e({kind:"files_value_too_large",message:n,maxBytes:r})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(n,r,t){return new e({kind:"files_call_failed",status:n,message:r,body:t})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}static callFunctionPathInvalid(n){return new e({kind:"call_function_path_invalid",message:n})}static callFunctionCallFailed(n,r,t){return new e({kind:"call_function_call_failed",status:n,message:r,body:t})}static callFunctionRequiresProvisioning(){return new e({kind:"call_function_requires_provisioning"})}static callFunctionNotAvailable(){return new e({kind:"call_function_not_available"})}static callFunctionMissingExecutionJwt(){return new e({kind:"call_function_missing_execution_jwt"})}};function Z(e){return e instanceof u}function U(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return e.code?`broker error: ${e.status} ${e.code}: ${e.message}`:`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_ttl_invalid":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)";case"call_function_path_invalid":return`Invalid function path: ${e.message}`;case"call_function_call_failed":return`Async function call failed: ${e.status} ${e.message}`;case"call_function_requires_provisioning":return"callFunctionAsync requires a provisioned project (run helix project set)";case"call_function_not_available":return"callFunctionAsync is not available: no running dev server was found";case"call_function_missing_execution_jwt":return"ctx.callFunctionAsync requires a helix project-execution JWT \u2014 a legacy internalJwt-only execution cannot call it"}}import{z as f}from"zod";var w="x-helix-destination-url",S="x-helix-authentication-id",A="x-helix-deployment-id",v="x-execution-id",q="x-helix-broker-error",ie="route_not_found",O=new Set([w,S,A,"authorization","x-tray-token","x-helix-project-execution-token","host","content-length","connection","transfer-encoding","te","upgrade","keep-alive","expect","proxy-authorization","proxy-connection","accept-encoding","x-request-id",v]);function $(e){let n=e.toLowerCase();return O.has(n)||n.startsWith("x-tray-internal-")}var k=f.object({error:f.object({code:f.string(),message:f.string(),issues:f.array(f.unknown()).optional()})});function oe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/http/raw`;return n==="dev"?`${r}/dev`:r}function F(e){return typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream}function se(e){let n=new URL(e.url);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""));if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[s,o]of e.query.entries())n.searchParams.append(s,o);else for(let[s,o]of Object.entries(e.query))for(let p of Array.isArray(o)?o:[o])n.searchParams.append(s,p);let r;e.headers===void 0?r=[]:e.headers instanceof Headers?r=Array.from(e.headers.entries()):Array.isArray(e.headers)?r=e.headers:r=Object.entries(e.headers);let t=r.filter(([s])=>!$(s)),i=e.body!==void 0&&e.body!==null,d,l,c=!1;return i&&(F(e.body)?(d=e.body,c=typeof ReadableStream<"u"&&e.body instanceof ReadableStream):(d=JSON.stringify(e.body),t.some(([o])=>o.toLowerCase()==="content-type")||(l="application/json"))),{authenticationId:e.authenticationId,method:e.method.toUpperCase(),destinationUrl:n.toString(),headers:t,body:d,isStreamBody:c,defaultContentType:l}}var j=6e4;function H(e){return e.includes("json")}function C(e){return e.startsWith("text/")||e.includes("xml")||e.includes("urlencoded")||e.includes("javascript")||e.includes("ecmascript")}function B(e,n){if(e.byteLength===0)return;let r=n.toLowerCase();if(H(r)){let t=new TextDecoder("utf-8").decode(e);try{return JSON.parse(t)}catch{return t}}return C(r)?new TextDecoder("utf-8").decode(e):e}function L(e){let n={};for(let[r,t]of e.entries())n[r.toLowerCase()]=t;return n}async function ae(e){let{request:n}=e,r=new Headers;for(let[s,o]of n.headers)r.append(s,o);n.defaultContentType&&!r.has("content-type")&&r.set("content-type",n.defaultContentType),r.set(w,n.destinationUrl),r.set(S,n.authenticationId);for(let[s,o]of Object.entries(e.credentialHeaders))r.set(s,o);e.executionId&&r.set(v,e.executionId);let t={method:n.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??j)};n.body!==void 0&&(t.body=n.body,n.isStreamBody&&(t.duplex="half"));let i=await fetch(e.proxyUrl,t),d=i.headers.get(q);if(d!==null){let s=await i.text(),o=s,p=s||d;try{o=JSON.parse(s);let h=k.safeParse(o);h.success&&(p=h.data.error.message)}catch{}return{kind:"brokerError",status:i.status,code:d,message:p,body:o}}let l=new Uint8Array(await i.arrayBuffer()),c=i.headers.get("content-type")??"";return{kind:"upstream",response:{status:i.status,headers:L(i.headers),body:B(l,c)}}}import{z as _}from"zod";var M=3e4;function fe(e){let n=new URL(e);if(n.protocol!=="https:")throw u.unsupportedScheme(n.protocol.replace(/:$/,""))}function pe(e,n){let r=`${y(e).hosts.api}/private/v1/helix/broker/s3/sign`;return n==="dev"?`${r}/dev`:r}var K=_.object({url:_.string(),method:_.string(),expiresAt:_.string()});async function me(e){let n=new Headers({"content-type":"application/json"});for(let[l,c]of Object.entries(e.credentialHeaders))n.set(l,c);e.executionId&&n.set(v,e.executionId);let r=await fetch(e.signUrl,{method:"POST",headers:n,body:JSON.stringify(e.body),redirect:"manual",signal:AbortSignal.timeout(e.timeoutMs??M)}),t=await r.text(),i=t;try{i=JSON.parse(t)}catch{}if(r.ok){let l=K.safeParse(i);return l.success?{kind:"signed",result:l.data}:{kind:"brokerError",status:r.status,message:"malformed s3-sign response from credential broker",body:i}}let d=k.safeParse(i);return d.success?{kind:"brokerError",status:r.status,code:d.data.error.code,message:d.data.error.message,body:i}:{kind:"brokerError",status:r.status,message:t||`s3-sign request failed with status ${r.status}`,body:i}}export{V as a,N as b,J as c,y as d,G as e,Y as f,T as g,D as h,z as i,W as j,X as k,u as l,Z as m,A as n,ie as o,oe as p,se as q,j as r,ae as s,fe as t,pe as u,me as v};
@@ -1,7 +0,0 @@
1
- import{d as T,l as c,n as rt,o as se,p as Ae,q as J,s as nt,t as ot,u as ke,v as it}from"./chunk-KUXDW5ED.js";var S="X-Helix-Project-Execution-Token",P="X-Tray-Token",Ar={mode:"dev",deploymentId:null},De={...Ar},N={};function Oo(e){let{internalJwt:t,helixExecutionJwt:r,devToken:n,...o}=e;"internalJwt"in e&&(N.internalJwt=t),"helixExecutionJwt"in e&&(N.helixExecutionJwt=r),"devToken"in e&&(N.devToken=n),De={...De,...o}}function y(){return De}function I(){return N.internalJwt}function E(){return N.helixExecutionJwt}function ae(){return N.devToken}var Lo="tray-config-bridge",Mo="tray-dev-token-bridge",ce=null;function Uo(e){ce=e}function h(){if(!ce)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return ce}function Bo(){ce=null}import{AsyncLocalStorage as Ct}from"async_hooks";import{trace as Hr,SpanKind as Jr,SpanStatusCode as Oe}from"@opentelemetry/api";import{ExportResultCode as Vr,W3CTraceContextPropagator as zr}from"@opentelemetry/core";import{NodeTracerProvider as qr,SimpleSpanProcessor as Yr,BatchSpanProcessor as Xr}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter as kr}from"@opentelemetry/exporter-trace-otlp-proto";import{OTLPLogExporter as Dr}from"@opentelemetry/exporter-logs-otlp-proto";function Fe(e){return T(e).hosts.ingest}function Fr(){return E()??""}function st(){return{[S]:Fr()}}function at(){let e=Fe(h().env);return new kr({url:`${e}/v1/traces`,headers:()=>Promise.resolve(st())})}function ct(){let e=Fe(h().env);return new Dr({url:`${e}/v1/logs`,headers:()=>Promise.resolve(st())})}import{logs as dt,SeverityNumber as le}from"@opentelemetry/api-logs";import{LoggerProvider as Nr,BatchLogRecordProcessor as Lr}from"@opentelemetry/sdk-logs";function V(e){try{return JSON.stringify(e)}catch(t){return JSON.stringify({_serialization_error:t instanceof Error?t.message:String(t)})}}function _r(e){return new TextEncoder().encode(e).length}var lt="\u2026[truncated]",Or=_r(lt),z=4096;function _(e,t=z){let r=new TextEncoder().encode(e);if(r.length<=t)return e;let n=r.subarray(0,t-Or);return new TextDecoder("utf-8").decode(n).replace(/�$/,"")+lt}function g(e,t=z){return _(V(e),t)}var Mr="@trayai/helix-sdk",q,ut={debug:{number:le.DEBUG,text:"DEBUG"},info:{number:le.INFO,text:"INFO"},warn:{number:le.WARN,text:"WARN"},error:{number:le.ERROR,text:"ERROR"}};function Ur(){return y().mode==="lambda"?[new Lr({exporter:ct()})]:[]}function ft(){if(q!==void 0)return;let e=Ur();e.length!==0&&(q=new Nr({processors:e}),dt.setGlobalLoggerProvider(q))}function Br(e,t,r){let n=ut[e]??ut.info;return{severityNumber:n.number,severityText:n.text,body:t,...r?{attributes:{"tray.log.meta":g(r)}}:{}}}function mt(e,t,r){dt.getLogger(Mr).emit(Br(e,t,r))}async function pt(e=2e3){if(q===void 0)return;let t;try{await Promise.race([q.forceFlush(),new Promise(r=>{t=setTimeout(r,e)})])}catch(r){process.stderr.write(`[helix-sdk] otel log flush failed: ${r instanceof Error?r.message:String(r)}
2
- `)}finally{t!==void 0&&clearTimeout(t)}}function _e(){let e=process.env.TRAY_PRETTY_LOGS;return e==="1"||e==="true"}function jr(){if(process.env.NO_COLOR!==void 0)return!1;let e=process.env.FORCE_COLOR;return e!==void 0&&e!=="0"&&e!=="false"?!0:!!process.stdout.isTTY&&process.env.TERM!=="dumb"}function R(e,t){return jr()?`\x1B[${e}m${t}\x1B[0m`:t}var Kr=5,$r={FN:"1;35",INFO:"34",AUTH:"35",API:"36",WARN:"33",ERROR:"31",DEBUG:"90"},gt="32",yt="31",ue="2",ht="1";function de(e){return R($r[e]??"0",e.padEnd(Kr))}function wt(e,t){return`${de("FN")} ${R(ht,`${e} ${t}`.trim())}`}function bt(e,t,r,n){let o=e.toUpperCase(),i=`${n?`${R(ue,n)} `:""}${de(o)} ${t}`;return r&&Object.keys(r).length>0&&(i+=` ${R(ue,V(r))}`),i}function St(e){return new Date(e[0]*1e3).toTimeString().slice(0,8)}function Et(e){return`${de("AUTH")} ${e}`}function xt(e,t,r,n,o){let s=r===void 0?"ERR":String(r),i=R(o==="error"?yt:gt,s);return`${de("API")} ${e} ${t} \u2192 ${i} ${R(ue,`${n}ms`)}`}function vt(e,t,r){let n=t?yt:gt,o=R(n,"\u25CF"),s=R(n,t?"error":"success");return`${o} ${R(ht,e)} ${s} ${R(ue,`${r}ms`)}`}function L(e){try{process.stdout.write(e+`
3
- `)}catch{}}var Tt=new Ct,Gr=new Ct;function x(e){let t=Gr.getStore();t&&(t[e]=!0)}var Wr=/^[0-9a-f]{32}$/;function Qr(e){let t=e.replace(/-/g,"").toLowerCase();return Wr.test(t)?t:null}var Zr={0:"STATUS_CODE_UNSET",1:"STATUS_CODE_OK",2:"STATUS_CODE_ERROR"},M=new Map;function Pt(e,t,r){let n=M.get(e);n?n[t]=r:M.set(e,{[t]:r})}function C(e,t,r){e.setAttribute(t,g(r))}var Y;function Rt(e){return`${e[0]}${String(e[1]).padStart(9,"0")}`}function en(e){return Math.round(e[0]*1e3+e[1]/1e6)}function It(e){try{process.stdout.write(V(e)+`
4
- `)}catch{}}var Ne=class{export(t,r){for(let n of t){let o=n.spanContext().spanId,s=M.get(o),i={...n.attributes};if(s!==void 0){for(let[u,d]of Object.entries(s))typeof d=="string"?i[u]=_(d):typeof d=="object"&&d!==null?i[u]=g(d):i[u]=d;M.delete(o)}let a=Tt.getStore(),l=a?Qr(a):null;It({_otel:"span",traceId:l??n.spanContext().traceId,spanId:o,parentSpanId:n.parentSpanContext?.spanId??"",name:n.name,kind:n.kind,startTimeUnixNano:Rt(n.startTime),endTimeUnixNano:Rt(n.endTime),attributes:i,status:{code:Zr[n.status.code]??"STATUS_CODE_UNSET",...n.status.message?{message:_(n.status.message)}:{}}})}r({code:Vr.SUCCESS})}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Le=class{onStart(t,r){}onEnd(t){M.delete(t.spanContext().spanId)}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Me=class{onStart(t){let r=t;(r.name==="function"||r.name==="App")&&L(`
5
- `+wt(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=M.get(n)?.properties;L(bt(String(r.level??"info"),String(r.message??""),o,St(t.startTime)));break}case"auth":L(Et(String(r.alias??"")));break;case"externalApi":{let n=typeof r.statusCode=="number"?r.statusCode:void 0;L(xt(String(r.method??""),String(r.host??""),n,en(t.duration),r.status==="error"?"error":"success"));break}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Ue=class{constructor(t){this.inner=t}inner;onStart(t,r){this.inner.onStart(t,r)}onEnd(t){t.name!=="log"&&this.inner.onEnd(t)}forceFlush(){return this.inner.forceFlush()}shutdown(){return this.inner.shutdown()}};function tn(){let t=[_e()?new Me:new Yr(new Ne)];return y().mode==="lambda"&&t.push(new Ue(new Xr(at()))),t.push(new Le),t}function rn(){Y===void 0&&(Y=new qr({spanProcessors:tn()}),Y.register({propagator:new zr}),ft())}async function nn(e=2e3){let t=[pt(e)];Y!==void 0&&t.push((async()=>{let r;try{await Promise.race([Y.forceFlush(),new Promise(n=>{r=setTimeout(n,e)})])}catch(n){process.stderr.write(`[helix-sdk] otel flush failed: ${n instanceof Error?n.message:String(n)}
6
- `)}finally{r!==void 0&&clearTimeout(r)}})()),await Promise.all(t)}var v=Hr.getTracer("@trayai/helix-sdk");function on({executionId:e,deploymentId:t,triggerType:r="http",routeOrJob:n,startedAt:o,startMs:s,errored:i,errorMessage:a,userId:l,flags:u}){let d=new Date().toISOString(),f=Date.now()-s;if(_e()){L(`
7
- `+vt(n,i,f));return}It({_otel:"summary",executionId:e,deploymentId:t,triggerType:r,routeOrJob:n,status:i?"error":"success",startedAt:o,finishedAt:d,durationMs:f,userId:l,hasError:i||u.hasError,hasAuth:u.hasAuth,hasExternal:u.hasExternal,hasDb:u.hasDb,errorSummary:i&&a!==null?_(a):null})}async function mi(e,t){let r=e.startMs??Date.now();rn();let n=!1,o=null;try{return await Tt.run(e.executionId,()=>v.startActiveSpan("App",{kind:Jr.SERVER,attributes:{method:e.method,route:e.route,...e.deploymentId?{deploymentId:e.deploymentId}:{}}},async s=>{try{let i=await t(),a=i?.httpResponse?.status??404;return n=a>=400,s.setAttribute("http.response.status_code",a),s.setAttribute("helix.status",n?"error":"success"),s.setStatus({code:n?Oe.ERROR:Oe.OK}),i}catch(i){throw n=!0,o=i instanceof Error?i.message:String(i),s.setAttribute("http.response.status_code",500),s.setAttribute("helix.status","error"),s.setStatus({code:Oe.ERROR,message:o}),i}finally{s.end()}}))}finally{on({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 nn()}}var Dt=1024,A=100*1024*1024,At=250,sn=3600,an=sn*1e3,kt=new TextEncoder,cn=/(^|\/)\.\.(\/|$)/,ln=/[?#]/;function un(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=Dt){if(e.length===0)throw c.filesPathInvalid("Path must be a non-empty string");fe(e,t)}function Be(e){return e.endsWith("/")?e.slice(0,-1):e}function fe(e,t=Dt){if(e.length===0)return;if(cn.test(e))throw c.filesPathInvalid("Path contains path traversal segment");if(ln.test(e)||un(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 s=kt.encode(o).length;if(s>At)throw c.filesPathInvalid(`Path segment exceeds ${At} UTF-8 bytes (got ${s})`)}let n=kt.encode(e).length;if(n<1||n>t)throw c.filesPathInvalid(`Path must be between 1 and ${t} UTF-8 bytes (got ${n})`)}function Ft(e){if(e>A)throw c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got ${e})`,A)}function U(e){let t=e!==void 0?e*1e3:an;return new Date(Date.now()+t)}import{join as G}from"path";var dn="files",fn="files-meta",mn=1023,pn=1,gn=5;function _t(e){let t=Math.max(Buffer.byteLength(me(e),"utf8"),Buffer.byteLength(X(e),"utf8"));return Math.max(0,mn-t-pn-gn)}function me(e){return G(e,".helix",dn)}function X(e){return G(e,".helix",fn)}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 Ot(e,t){return t.length===0?X(e):G(X(e),...t.split("/"))}var Nt="helix-schedule",k=class extends Error{constructor(t){super(`defineSchedule: ${t}`),this.name="ScheduleConfigError"}};function bi(e){if(typeof e!="object"||e===null)throw new k("expected a config object");let{cron:t,timezone:r="UTC",concurrent:n=!1,handler:o}=e;if(typeof t!="string"||t.trim()==="")throw new k("`cron` must be a non-empty string");let s=t.trim().split(/\s+/).length;if(s!==5)throw new k(`\`cron\` must be a 5-field standard expression (minute hour day-of-month month day-of-week); got ${s} field(s) in "${t}"`);if(typeof r!="string"||!yn(r))throw new k(`\`timezone\` must be a valid IANA timezone name (e.g. "Europe/London"); got "${String(r)}"`);if(typeof n!="boolean")throw new k("`concurrent` must be a boolean");if(typeof o!="function")throw new k("`handler` must be a function");return Object.freeze({kind:Nt,cron:t.trim(),timezone:r,concurrent:n,handler:o})}function Si(e){return typeof e=="object"&&e!==null&&e.kind===Nt&&typeof e.handler=="function"}function yn(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 hn}from"@opentelemetry/api";function ye(e,t,r){let n=v.startSpan("log",{kind:hn.INTERNAL});n.setAttribute("message",t),n.setAttribute("level",e),r&&Pt(n.spanContext().spanId,"properties",r),n.end(),mt(e,t,r)}function Lt(){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 Pi(){try{return h().config??{}}catch(e){return console.warn(`[helix-sdk] Config not loaded: ${e instanceof Error?e.message:String(e)}. Using empty config.`),{}}}import wn from"ky";import{context as je,trace as bn,SpanKind as Z,SpanStatusCode as Ut}from"@opentelemetry/api";async function he(e,t={}){let r=y(),{env:n}=h(),o,s={};if(r.mode==="lambda"){let a=I(),l=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(s[P]=a),d&&(s[S]=l),r.deploymentId&&(s[rt]=r.deploymentId),o=Ae(n,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();s.Authorization=`Bearer ${a}`,o=Ae(n,"dev")}let i;try{i=await nt({proxyUrl:o,credentialHeaders:s,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(i.kind==="brokerError"){let a=i.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":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.response}async function Mt(e){ot(e.url);let t=y(),{env:r}=h(),n,o={},s={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=E(),u=!!(a&&a.trim().length>0),d=!!(l&&l.trim().length>0);if(!u&&!d)throw c.missingExecutionCredentials();u&&(o[P]=a),d&&(o[S]=l),t.deploymentId&&(s.deploymentId=t.deploymentId),n=ke(r,"runtime")}else{let a=ae();if(!a)throw c.missingTrayToken();o.Authorization=`Bearer ${a}`,n=ke(r,"dev")}let i;try{i=await it({signUrl:n,credentialHeaders:o,body:s,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(i.kind==="brokerError"){let a=i.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":i.message;throw c.brokerError(i.status,a,g(i.body),i.code)}return i.result}var Sn=["get","post","put","patch","delete","head","options"],jt="[stream body omitted]";function Kt(e){return typeof ReadableStream<"u"&&e instanceof ReadableStream?jt: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 Ke(e){try{return new URL(e).hostname}catch{return e}}function Bt(e,t,r,n,o){let s=Ke(t),i="externalApi",a={kind:Z.CLIENT};return v.startActiveSpan(i,a,async l=>(l.setAttributes({method:e,host:s,"peer.service":n}),C(l,"request",{url:t,method:e,...r!==void 0?{body:Kt(r)}:{}}),o(l)))}function Q(e,t,r){e.setAttribute("status",t),e.setStatus(t==="success"?{code:Ut.OK}:{code:Ut.ERROR,message:r}),e.end()}var En=16;async function xn(e,t){let r=e.clone().body;return r?$t(r,t):new Uint8Array(0)}async function $t(e,t){let r=e.getReader(),n=[],o=0,s=0;try{for(;;){let{done:l,value:u}=await r.read();if(l)break;if(!u||u.byteLength===0){if(s+=1,s>=En)break;continue}s=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 i=new Uint8Array(o),a=0;for(let l of n)i.set(l,a),a+=l.byteLength;return i}async function Ht(e,t,r){if("kyResponse"in r)try{let n=await xn(r.kyResponse,z),o=new TextDecoder("utf-8").decode(n,{stream:!0}),s;try{s=JSON.parse(o)}catch{s=o}C(e,"response",s)}catch{C(e,"response",{status:t})}else C(e,"response",Kt(r.bodyValue))}async function vn(e,t){if(t instanceof ReadableStream){let r=e.body??t;try{let[n,o]=r.tee(),s=new Request(e,{body:n,duplex:"half"}),i=await $t(o,z);return{body:new TextDecoder("utf-8").decode(i,{stream:!0}),request:s}}catch{return{body:jt}}}return typeof t=="string"?{body:t}:{}}function Qi(){let e=wn.create({});function t(n){return(o,s)=>{let i=je.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 vn(f,m.body),ie=p.body;if(a||(a=v.startSpan("externalApi",{kind:Z.CLIENT},i)),a.setAttributes({method:f.method.toUpperCase(),host:Ke(f.url)}),C(a,"request",{url:f.url,method:f.method.toUpperCase(),...ie!==void 0?{body:ie}:{}}),l=!1,x("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 Ht(a,p.status,{kyResponse:p}),p.ok?u("success"):s?.throwHttpErrors===!1&&(x("hasError"),u("error",`HTTP ${p.status}`)))}],beforeError:[f=>(x("hasError"),u("error",f.message),f)]}});return a=v.startSpan("externalApi",{kind:Z.CLIENT},i),a.setAttributes({method:n.toUpperCase(),host:Ke(String(o))}),je.with(bn.setSpan(je.active(),a),()=>{let f=n==="options"?d(o,{...s,method:"OPTIONS"}):d[n](o,s);return f.catch(m=>{x("hasError"),u("error",m instanceof Error?m.message:String(m))}),f})}}let r=Object.fromEntries(Sn.map(n=>[n,t(n)]));return{...e,...r,authed(n){return Rn(n)}}}function Rn(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e];function o(i){return(a,l={})=>{let u=i.toUpperCase();return Bt(u,a,l.body,e,async d=>{x("hasAuth");let f=v.startSpan("auth",{kind:Z.INTERNAL});f.setAttribute("alias",e),f.setAttribute("id",n),f.end();try{let m=J({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 Ht(d,p.status,{bodyValue:p.body}),Q(d,"success"),p}catch(m){throw x("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 s(i,a={}){let l=a.method??"GET";return Bt(l,i,void 0,e,async u=>{x("hasAuth");let d=v.startSpan("auth",{kind:Z.INTERNAL});d.setAttribute("alias",e),d.setAttribute("id",n),d.end();try{let f=await Mt({authenticationId:n,url:i,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 x("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:s}}import{SpanKind as _n,SpanStatusCode as qt}from"@opentelemetry/api";function ee(e){let t=e.trimStart().match(/^([A-Za-z]+)/);return t?t[1].toUpperCase():"QUERY"}var Cn=18e4,Jt=Cn-1e4,Tn=2e3;async function Vt(e,t,r){let n=new Set(["FINISHED","FAILED","ABORTED"]),o=Date.now(),s=0;for(;Date.now()-o<Jt;){let i=await e(t,"DescribeStatement",{Id:r}),a=i.Status;if(n.has(a))return i;let l=Math.min(Tn,200*2**s),u=l/2+Math.random()*(l/2),d=Jt-(Date.now()-o);await new Promise(f=>setTimeout(f,Math.min(u,d))),s++}throw c.dbCallFailed(`statement polling exceeded budget after ${Date.now()-o}ms`)}var Pn=new Set(["SELECT","WITH","SHOW"]),In=new Set(["INSERT","UPDATE","DELETE","MERGE"]);function An(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 kn(e,t){let r=null;if(typeof t=="string")try{r=JSON.parse(t)}catch{}else t!==null&&typeof t=="object"&&(r=t);let n=typeof r?.__type=="string"?r.__type:void 0,o=typeof r?.message=="string"?r.message:void 0;if(n&&o)return c.dbQueryFailed(`${n}: ${o}`);let s=typeof t=="string"?_(t):g(t);return c.dbCallFailed(s)}function Dn(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 Fn(e,t){return typeof t!="number"||t<0?{}:Pn.has(e)?{rowsRead:t}:In.has(e)?{rowsWritten:t}:{}}function zt(e){async function t(r,n,o){let s=J({authenticationId:e,method:"POST",url:`https://redshift-data.${r}.amazonaws.com/`,body:o,headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`RedshiftData.${n}`}});try{let{status:i,body:a}=await he(s);if(i>=400)throw kn(i,a);return Dn(a)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.dbCallFailed(a,i instanceof Error?i:void 0)}}return{system:"redshift",validate:An,async execute(r,n){let o=ee(n),s={Sql:n,Database:r.database,...r.clusterIdentifier&&{ClusterIdentifier:r.clusterIdentifier,DbUser:r.dbUser},...r.workgroupName&&{WorkgroupName:r.workgroupName},...r.statementName&&{StatementName:r.statementName}},i=await t(r.region,"ExecuteStatement",s),a=i,l=typeof a?.Id=="string"?a.Id:void 0;if(!l){let p=g(i);throw c.dbCallFailed(`ExecuteStatement response missing Id; got: ${p}`)}let u=await Vt(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=Fn(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 $e=64*1024;function On(e){return e.length>$e?`${e.slice(0,$e)}...[truncated]`:e}function Nn(e,t,r,n,o){e.setAttributes({system:t.system,statement:o,namespace:r.database,operation:n})}function Ln(e,t,r){let n=typeof t=="string"?t:JSON.stringify(t);return n.length>$e?C(e,"result",{truncated:!0,size:n.length}):C(e,"result",t),r.rowsRead!==void 0&&e.setAttribute("rowsRead",r.rowsRead),r.rowsWritten!==void 0&&e.setAttribute("rowsWritten",r.rowsWritten),n}async function Mn(e,t,r){let n=ee(r),o=On(r);return v.startActiveSpan("database",{kind:_n.CLIENT},async s=>{Nn(s,e,t,n,o);try{x("hasDb");let{result:i,metadata:a}=await e.execute(t,r),l=Ln(s,i,a);return s.setAttribute("status","success"),s.setStatus({code:qt.OK}),l}catch(i){x("hasError");let a=i instanceof Error?i.message:String(i);throw s.setAttribute("status","error"),s.setStatus({code:qt.ERROR,message:a}),i}finally{s.end()}})}function Un(e){let r=h().authentications??{};if(!r[e])throw c.unknownAlias(e,Object.keys(r));let n=r[e],o=zt(n);function s(i,a){return o.validate(i),Mn(o,i,a)}return{parameters(i){return{sql(a){return s(i,a)}}},sql(i){return s({},i)}}}import{createStorage as Hn}from"unstorage";var Yt=1024,He=250*1024,Bn=new TextEncoder,jn=/(^|\/)\.\.(\/|$)/,Kn=/[?#]/,$n=/[\u0000-\u001F\u007F]/;function Xt(e){if(e.length===0)throw c.kvKeyInvalid("Key must be a non-empty string");if(jn.test(e))throw c.kvKeyInvalid("Key contains path traversal segment");if(Kn.test(e)||$n.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=Bn.encode(e).length;if(t<1||t>Yt)throw c.kvKeyInvalid(`Key must be between 1 and ${Yt} UTF-8 bytes (got ${t})`)}function Gt(e){if(!Number.isInteger(e)||e<=0)throw c.kvTtlInvalid(`ttl must be a positive integer number of seconds (got ${e})`)}function Wt(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>He)throw c.kvValueTooLarge(`Value exceeds maximum size of ${He} bytes (got ${r})`,He)}function te(e){Xt(e)}function we(e,t){let r=e[t];if(typeof r!="function")throw new Error(`KV driver is missing ${t}`);return r}function Qt(e){let t=we(e,"getItem"),r=we(e,"setItem"),n=we(e,"removeItem"),o=we(e,"hasItem"),s=e.getKeys;return{...e,getItem(i,a){return te(i),t(i,a)},setItem(i,a,l){return te(i),r(i,a,l)},removeItem(i,a){return te(i),n(i,a)},hasItem(i,a){return te(i),o(i,a)},getKeys(i,a){return i.length>0&&te(i),s(i,a)}}}function be(e){return Hn({driver:Qt(e)})}import{defineDriver as Jn}from"unstorage";function Vn(e){try{return JSON.parse(e)}catch{return e}}var zn=Jn(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 s=o?.ttl,i=Vn(n);s!==void 0?await t.set(r,i,{ttl:s}):await t.set(r,i)},async removeItem(r){await t.delete(r)},async hasItem(r){return await t.has(r)},async getKeys(){throw new Error("KV key listing is not supported")}}});function Zt(e){return zn({client:e})}import Xn from"ky";import{z as b}from"zod";async function D(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 er(e){return T(e).hosts.api}function qn(e){return`/private/v1/helix/projects/${encodeURIComponent(e)}/storage/kv`}function Yn(e){return e.split("/").map(encodeURIComponent).join("/")}function re(e,t,r){return`${e}${qn(t)}/${Yn(r)}`}var Gn=6e4,Je=b.lazy(()=>b.union([b.string(),b.number(),b.boolean(),b.null(),b.array(Je),b.record(Je)])),Wn=b.object({projectId:b.string(),key:b.string(),value:Je,type:b.enum(["string","number","boolean","null","array","object"]),organizationId:b.string(),scope:b.string(),createdBy:b.string(),createdAt:b.number(),updatedBy:b.string(),updatedAt:b.number()});function Qn(){let e=I(),t=E(),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[S]=t),o}function Zn(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,Zn(t),g(t))}async function Ee(e,t,r={}){try{let n=await Xn(t,{method:e,headers:Qn(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Gn}),o=e==="head"?void 0:await D(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 tr(e){let t=er(e.env),{projectId:r}=e;return{async get(n){let{status:o,body:s}=await Ee("get",re(t,r,n));if(o===404)return null;(o<200||o>=300)&&Se(o,s);let i=Wn.safeParse(s);if(!i.success)throw c.kvCallFailed(o,"platform returned malformed KeyValueEntry",g(s));return i.data.value},async set(n,o,s){let{status:i,body:a}=await Ee("put",re(t,r,n),{json:s?.ttl!==void 0?{value:o,ttl:s.ttl}:{value:o}});(i<200||i>=300)&&Se(i,a)},async delete(n){let{status:o,body:s}=await Ee("delete",re(t,r,n));o!==204&&Se(o,s)},async has(n){let{status:o,body:s}=await Ee("head",re(t,r,n));if(o===200)return!0;if(o===404)return!1;Se(o,s)}}}function xe(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;Wt(r),typeof o=="number"&&Gt(o),await e.setItem(t,r,o!==void 0?{ttl:o}:void 0)}}}function eo(){let e=h();if(e.kind!=="provisioned")throw c.kvRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function rr(e){let t=eo(),r=e??tr(t),n=be(Zt(r));return xe(n)}import{defineDriver as to}from"unstorage";var ro=to(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,s){let i=s?.ttl,a=r(n),l=typeof i=="number"?Date.now()+i*1e3:i===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 nr(){return ro({})}var Ve;function no(){return Ve||(Ve=be(nr())),Ve}function or(){return xe(no())}function oo(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function na(){return oo()?rr():or()}import{createHash as ao}from"crypto";import{mkdir as co,readFile as lr,readdir as ur,rm as sr,unlink as lo,writeFile as ar}from"fs/promises";import{dirname as uo}from"path";async function io(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:s}=await t.read();if(o)break;if(s){if(n+=s.byteLength,n>A)throw await t.cancel(),c.filesValueTooLarge(`File exceeds maximum size of ${A} bytes (got more than ${A})`,A);r.push(s)}}return Buffer.concat(r)}async function B(e){return Buffer.isBuffer(e)?e:typeof e=="string"?Buffer.from(e,"utf-8"):e instanceof ReadableStream?io(e):Buffer.from(e)}var so={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"},ir="application/octet-stream";function ve(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return ir;let r=e.slice(t+1).toLowerCase();return so[r]??ir}function K(){let e=y().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 ze(e){try{let t=await lr(pe(K(),e),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function cr(e){await co(uo(e),{recursive:!0})}async function fo(e,t){let r=ge(e,t),n;try{n=await ur(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 dr(e,t){let r=ge(e,t),n;try{n=await ur(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return[];throw s}let o=[];for(let s of n){let i=t.length===0?s.name:`${t}/${s.name}`;s.isDirectory()?o.push(...await dr(e,i)):s.isFile()&&o.push(i)}return o}function fr(){return{async put(e,t,r){return j(async()=>{let n=K(),o=await B(t),s=r?.contentType??ve(e),i=ao("sha1").update(o).digest("hex"),a=new Date,l=W(n,e);await cr(l),await ar(l,o);let u={size:o.byteLength,contentType:s,lastModified:a.toISOString(),etag:i},d=pe(n,e);return await cr(d),await ar(d,JSON.stringify(u)),Re(e,u)})},async get(e){return j(async()=>{let t=await ze(e);return t?{data:await lr(W(K(),e)),metadata:Re(e,t)}:null})},async head(e){return j(async()=>{let t=await ze(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 lo(r)}catch(n){if(n.code!=="ENOENT")throw n}}))})},async deleteMany(e){return j(async()=>{let t=K(),r=await dr(t,e);return await Promise.all([sr(ge(t,e),{recursive:!0,force:!0}),sr(Ot(t,e),{recursive:!0,force:!0})]),{deleted:r.length}})},async list(e,t){return j(async()=>{let r=K(),n=t?.limit??100,s=(await fo(r,e??"")).slice(0,n);return{files:(await Promise.all(s.map(async a=>{let l=await ze(a);return l?Re(a,l):null}))).filter(a=>a!==null),cursor:null}})},async getUploadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}},async getDownloadUrl(e,t){let r=y().devServerUrl;if(!r)throw c.filesNotAvailable();return{url:`${r}/_helix/files/${e}`,expiresAt:U(t?.expiresIn)}}}}import{createHash as bo}from"crypto";function Ce(e){return T(e).hosts.api}function mo(e){return`/private/v1/helix/files/projects/${encodeURIComponent(e)}`}function ne(e,t){return`${e}${mo(t)}`}function $(e,t,r){return`${ne(e,t)}/${encodeURIComponent(r)}`}function Te(e,t,r){return`${$(e,t,r)}/upload`}function mr(e,t,r){return`${$(e,t,r)}/download`}function pr(e,t,r){return`${$(e,t,r)}/signed-url`}function gr(e,t,r,n){let o=new URLSearchParams({name:n});return r&&o.set("parentFolder",r),`${ne(e,t)}/file?${o.toString()}`}function yr(e,t,r,n){let o=new URLSearchParams({limit:String(n)});return r&&o.set("id",r),`${ne(e,t)}?${o.toString()}`}import Ye from"ky";import{z as w}from"zod";var Xe=6e4,hr=w.object({id:w.string(),workspaceId:w.string(),projectId:w.string(),parentFolder:w.string().nullable().optional(),name:w.string(),size:w.number().nullable().optional(),objectType:w.enum(["Folder","File"]),contentType:w.string().nullable().optional(),createdAt:w.string(),updatedAt:w.string()}),po=w.object({signedURL:w.string()}),go=w.object({path:w.array(w.object({id:w.string(),name:w.string()})),elements:w.array(hr)});function Ge(){let e=I(),t=E(),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[S]=t),o}function wr(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 F(e,t){throw c.filesCallFailed(e,wr(t),g(t))}function yo(e,t){return e===400&&wr(t).toLowerCase()==="resource not found"}async function ho(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 Ye(t,{method:e,headers:Ge(),...r.json!==void 0?{json:r.json}:{},throwHttpErrors:!1,timeout:Xe}),o=await D(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 qe(e,t){let r=hr.safeParse(t);if(!r.success)throw c.filesCallFailed(e,"platform returned malformed ObjectMetadata",g(t));return r.data}function br(e){let t=Ce(e.env),{projectId:r}=e;return{async createMetadata(n){let{status:o,body:s}=await H("post",ne(t,r),{json:n});return(o<200||o>=300)&&F(o,s),qe(o,s)},async getByName(n,o){let{status:s,body:i}=await H("get",gr(t,r,n,o));return s===404||yo(s,i)?null:((s<200||s>=300)&&F(s,i),qe(s,i))},async getById(n){let{status:o,body:s}=await H("get",$(t,r,n));return o===404?null:((o<200||o>=300)&&F(o,s),qe(o,s))},async listChildren(n,o){let{status:s,body:i}=await H("get",yr(t,r,n,o));(s<200||s>=300)&&F(s,i);let a=go.safeParse(i);if(!a.success)throw c.filesCallFailed(s,"platform returned malformed listing",g(i));return a.data},async uploadContent(n,o,s,i){let a=new FormData;a.append("fileUploadContentInput",new Blob([new Uint8Array(o)],{type:i}),s);let{body:l,contentType:u}=await ho(a),d;try{d=await Ye(Te(t,r,n),{method:"post",headers:{...Ge(),"content-type":u},body:new Uint8Array(l),throwHttpErrors:!1,timeout:Xe})}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 D(d);(d.status<200||d.status>=300)&&F(d.status,f)},async downloadContent(n){let o;try{o=await Ye(mr(t,r,n),{method:"get",headers:Ge(),throwHttpErrors:!1,timeout:Xe})}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message:String(i);throw c.filesCallFailed(0,a)}if(o.status<200||o.status>=300){let i=await D(o);F(o.status,i)}let s=await o.arrayBuffer();return Buffer.from(s)},async getSignedDownloadUrl(n){let{status:o,body:s}=await H("get",pr(t,r,n));(o<200||o>=300)&&F(o,s);let i=po.safeParse(s);if(!i.success)throw c.filesCallFailed(o,"platform returned malformed signed URL response",g(s));return i.data.signedURL},async deleteById(n){let{status:o,body:s}=await H("delete",$(t,r,n));o===204||o===404||(o<200||o>=300)&&F(o,s)}}}function We(e){return e.split("/").filter(t=>t.length>0)}function Qe(e){return e instanceof c&&e.detail.kind==="files_call_failed"&&e.detail.status===409}async function wo(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(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Ze(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1))o=(await wo(e,o,s)).id;return{parentFolder:o,name:n}}async function oe(e,t){let r=We(t),n=r[r.length-1],o;for(let s of r.slice(0,-1)){let i=await e.getByName(o,s);if(!i||i.objectType!=="Folder")return null;o=i.id}return{parentFolder:o,name:n}}async function et(e,t){if(t.length===0)return;let r=We(t),n;for(let o of r){let s=await e.getByName(n,o);if(!s||s.objectType!=="Folder")return null;n=s.id}return n}var So=500,Eo=8;async function xo(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;o<e.length;){let i=o++;n[i]=await r(e[i])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}function vo(){let e=h();if(e.kind!=="provisioned")throw c.filesRequiresProvisioning();return{projectId:e.projectId,env:e.env}}function Ro(e){return bo("sha1").update(`${e.id}:${e.updatedAt}:${e.size??0}`).digest("hex")}function Pe(e,t,r){return{path:e,size:t.size??0,contentType:t.contentType??r??"application/octet-stream",lastModified:new Date(t.updatedAt),etag:Ro(t)}}async function Sr(e,t,r,n){try{return await e.createMetadata({parentFolder:t,objectType:"File",contentType:n,name:r})}catch(o){if(Qe(o)){let s=await e.getByName(t,r);if(s)return s}throw o}}async function Er(e,t){let{elements:r}=await e.listChildren(t,So);return(await xo(r,Eo,async o=>{let s=o.objectType==="Folder"?await Er(e,o.id):1;return await e.deleteById(o.id),s})).reduce((o,s)=>o+s,0)}function xr(e){let t=vo(),r=e??br(t),n=Ce(t.env),{projectId:o}=t;return{async put(s,i,a){let{parentFolder:l,name:u}=await Ze(r,s),d=await B(i),f=a?.contentType??ve(s),m=await r.getByName(l,u);if(m&&m.objectType!=="File")throw c.filesCallFailed(409,`A folder already exists at "${s}"`);let p=m??await Sr(r,l,u,f);await r.uploadContent(p.id,d,u,f);let ie=await r.getById(p.id);return Pe(s,ie??p,f)},async get(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:{data:await r.downloadContent(a.id),metadata:Pe(s,a)}},async head(s){let i=await oe(r,s);if(!i)return null;let a=await r.getByName(i.parentFolder,i.name);return!a||a.objectType!=="File"?null:Pe(s,a)},async delete(s){let i=await oe(r,s);if(!i)return;let a=await r.getByName(i.parentFolder,i.name);a&&await r.deleteById(a.id)},async deleteMany(s){let i=await et(r,s);if(i===null)return{deleted:0};let a=await Er(r,i);return s.length>0&&i!==void 0&&await r.deleteById(i),{deleted:a}},async list(s,i){let a=await et(r,s??"");if(a===null)return{files:[],cursor:null};let l=i?.limit??100,{elements:u}=await r.listChildren(a,l);return{files:u.filter(f=>f.objectType==="File").map(f=>Pe(s?`${s}/${f.name}`:f.name,f)),cursor:null}},async getUploadUrl(s,i){let{parentFolder:a,name:l}=await Ze(r,s),d=await r.getByName(a,l)??await Sr(r,a,l,i?.contentType);return{url:Te(n,o,d.id),expiresAt:U(i?.expiresIn)}},async getDownloadUrl(s,i){let a=await oe(r,s),l=a?await r.getByName(a.parentFolder,a.name):null;if(!l||l.objectType!=="File")throw c.filesCallFailed(404,`File not found: ${s}`);return{url:await r.getSignedDownloadUrl(l.id),expiresAt:U(i?.expiresIn)}}}}function tt(e,t){let r=t?.maxPathBytes;return{async put(n,o,s){O(n,r);let i=await B(o);return Ft(i.byteLength),e.put(n,i,s)},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=Be(n);return fe(o,r),e.deleteMany(o)},async list(n,o){let s=Be(n??"");return fe(s,r),e.list(s,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 Co(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Xa(){if(Co())return tt(xr());let e=y().projectRoot;return tt(fr(),{maxPathBytes:e?_t(e):void 0})}import Po from"ky";function vr(e){return T(e).hosts.api}function To(){return"/private/v1/helix/function-calls"}function Rr(e){return`${e}${To()}`}var Io=5e3;function Ao(){let e=E();if(!!!(e&&e.trim().length>0))throw c.callFunctionMissingExecutionJwt();return{Accept:"application/json",[S]:e}}function ko(e,t){throw c.callFunctionCallFailed(e,Do(t),g(t))}function Do(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 Cr(e){let t=vr(e.env);return{async callAsync(r,n){let o,s;try{let i=await Po(Rr(t),{method:"post",headers:Ao(),json:{functionPath:r,input:n},throwHttpErrors:!1,timeout:Io});o=i.status,s=await D(i)}catch(i){if(i instanceof c)throw i;let a=i instanceof Error?i.message??String(i):String(i);throw c.callFunctionCallFailed(0,a)}(o<200||o>=300)&&ko(o,s)}}}var Tr=1024;function Ie(e){if(typeof e!="string"||e.trim().length===0)throw c.callFunctionPathInvalid("functionPath must be a non-empty string");if(e.length>Tr)throw c.callFunctionPathInvalid(`functionPath must be at most ${Tr} characters`)}function Fo(){let e=h();if(e.kind!=="provisioned")throw c.callFunctionRequiresProvisioning();return{env:e.env}}function Pr(e){return async function(r,n){Ie(r),await(e??Cr(Fo())).callAsync(r,n)}}function Ir(){return async function(t,r){Ie(t);let n=y().devServerUrl;if(!n)throw c.callFunctionNotAvailable();let o=t.startsWith("/")?t:`/${t}`,s=Lt();fetch(`${n}${o}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r??{})}).then(i=>{i.ok||s.warn("ctx.callFunctionAsync: dev-mode dispatch returned a non-2xx response",{functionPath:t,status:i.status})}).catch(i=>{s.warn("ctx.callFunctionAsync: dev-mode dispatch failed",{functionPath:t,error:i instanceof Error?i.message:String(i)})})}}function _o(){return typeof __TRAY_SDK_MODE__<"u"?__TRAY_SDK_MODE__==="lambda":y().mode==="lambda"}function Ec(){return _o()?Pr():Ir()}export{Oo as a,y as b,Lo as c,Mo as d,Uo as e,h as f,Bo as g,Tt as h,Gr as i,x as j,C as k,rn as l,nn as m,v as n,on as o,mi as p,Lt as q,Pi as r,Qi as s,Un as t,na as u,O as v,W as w,pe as x,Xa as y,Ec as z,Nt as A,k as B,bi as C,Si as D};
@@ -1,9 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- /** Built-in environments shipped in the published SDK. */
4
- declare const ENVIRONMENT_VALUES: readonly ["production"];
5
- /** Runtime environment name (built-ins plus any registered profiles). */
6
- type Environment = string;
7
- declare const environmentSchema: z.ZodEffects<z.ZodString, string, string>;
8
-
9
- export { type Environment as E, ENVIRONMENT_VALUES as a, environmentSchema as e };
@@ -1,217 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- declare const projectIdSchema: z.ZodString;
4
- declare const workspaceIdSchema: z.ZodString;
5
- declare const trayConfigSchema: z.ZodObject<{
6
- name: z.ZodString;
7
- projectId: z.ZodOptional<z.ZodString>;
8
- workspaceId: z.ZodOptional<z.ZodString>;
9
- env: z.ZodDefault<z.ZodEffects<z.ZodString, string, string>>;
10
- authentications: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
11
- config: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
12
- }, "strip", z.ZodTypeAny, {
13
- name: string;
14
- env: string;
15
- authentications: Record<string, string>;
16
- config: Record<string, unknown>;
17
- projectId?: string | undefined;
18
- workspaceId?: string | undefined;
19
- }, {
20
- name: string;
21
- projectId?: string | undefined;
22
- workspaceId?: string | undefined;
23
- env?: string | undefined;
24
- authentications?: Record<string, string> | undefined;
25
- config?: Record<string, unknown> | undefined;
26
- }>;
27
- /** User-facing config type — auth/config optional; Zod defaults fill at load time. */
28
- type TrayConfig = z.input<typeof trayConfigSchema>;
29
- /**
30
- * Runtime validator for the LoadedTrayConfig discriminated union.
31
- * Used to validate BroadcastChannel payloads before calling setActiveConfig —
32
- * prevents malformed cross-channel data from corrupting the worker-local
33
- * config slot.
34
- */
35
- declare const loadedTrayConfigSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
36
- name: z.ZodString;
37
- workspaceId: z.ZodOptional<z.ZodString>;
38
- env: z.ZodEffects<z.ZodString, string, string>;
39
- authentications: z.ZodRecord<z.ZodString, z.ZodString>;
40
- config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
41
- } & {
42
- kind: z.ZodLiteral<"provisioned">;
43
- projectId: z.ZodString;
44
- }, "strip", z.ZodTypeAny, {
45
- kind: "provisioned";
46
- name: string;
47
- projectId: string;
48
- env: string;
49
- authentications: Record<string, string>;
50
- config: Record<string, unknown>;
51
- workspaceId?: string | undefined;
52
- }, {
53
- kind: "provisioned";
54
- name: string;
55
- projectId: string;
56
- env: string;
57
- authentications: Record<string, string>;
58
- config: Record<string, unknown>;
59
- workspaceId?: string | undefined;
60
- }>, z.ZodObject<{
61
- name: z.ZodString;
62
- workspaceId: z.ZodOptional<z.ZodString>;
63
- env: z.ZodEffects<z.ZodString, string, string>;
64
- authentications: z.ZodRecord<z.ZodString, z.ZodString>;
65
- config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
66
- } & {
67
- kind: z.ZodLiteral<"unprovisioned">;
68
- }, "strip", z.ZodTypeAny, {
69
- kind: "unprovisioned";
70
- name: string;
71
- env: string;
72
- authentications: Record<string, string>;
73
- config: Record<string, unknown>;
74
- workspaceId?: string | undefined;
75
- }, {
76
- kind: "unprovisioned";
77
- name: string;
78
- env: string;
79
- authentications: Record<string, string>;
80
- config: Record<string, unknown>;
81
- workspaceId?: string | undefined;
82
- }>]>;
83
- /** Base fields on all config variants — schema output minus projectId. */
84
- type LoadedTrayConfigBase = Omit<z.output<typeof trayConfigSchema>, "projectId">;
85
- /**
86
- * Discriminated union returned by loadConfig / ConfigService#get.
87
- * - "provisioned" — projectId present, no optional-chaining needed.
88
- * - "unprovisioned" — `projectId?: never` structurally excludes it.
89
- * workspaceId is optional on both variants — independent of provisioning.
90
- */
91
- type LoadedTrayConfig = ({
92
- kind: "provisioned";
93
- projectId: string;
94
- } & LoadedTrayConfigBase) | ({
95
- kind: "unprovisioned";
96
- projectId?: never;
97
- } & LoadedTrayConfigBase);
98
- type ProvisionedTrayConfig = Extract<LoadedTrayConfig, {
99
- kind: "provisioned";
100
- }>;
101
- type UnprovisionedTrayConfig = Extract<LoadedTrayConfig, {
102
- kind: "unprovisioned";
103
- }>;
104
- /**
105
- * Env var naming an alternate config file (relative paths resolve against cwd).
106
- * Sits between the explicit `configFile` option (the CLI's `--config` flag) and
107
- * the `helix.config.ts` default in resolution precedence.
108
- */
109
- declare const HELIX_CONFIG_ENV = "HELIX_CONFIG";
110
- /** Options accepted by every config entry point that resolves the config file. */
111
- interface ConfigFileOptions {
112
- /**
113
- * Explicit config file path (the CLI's `--config` flag). Resolution
114
- * precedence: this option → `HELIX_CONFIG` env var → `helix.config.ts`
115
- * (then legacy `tray.config.*`) in cwd.
116
- */
117
- configFile?: string;
118
- }
119
- /**
120
- * The effective config-file override, if any: the explicit `configFile` option
121
- * (CLI `--config` flag) wins over the `HELIX_CONFIG` env var. Returns the raw
122
- * (possibly relative) path — callers resolve it against their cwd.
123
- */
124
- declare function resolveConfigOverride(configFile?: string): string | undefined;
125
- /**
126
- * Absolute path of the project config file in `cwd`, preferring `helix.config.*`
127
- * and falling back to a legacy `tray.config.*`. Returns undefined when neither exists.
128
- * A config-file override (option or HELIX_CONFIG) replaces the default search
129
- * entirely: only the named file is considered.
130
- */
131
- declare function resolveConfigFile(cwd: string, options?: ConfigFileOptions): string | undefined;
132
- /**
133
- * One-shot stateless read of the project config. NO caching — every call hits disk.
134
- * Reads `helix.config.ts` (legacy `tray.config.*` fallback) unless an override
135
- * names another file — `options.configFile` (CLI `--config` flag) first, then
136
- * the `HELIX_CONFIG` env var. For hot-reload or stable snapshot, use
137
- * {@link createConfigService} instead.
138
- */
139
- declare function loadConfig(cwd?: string, options?: ConfigFileOptions): Promise<LoadedTrayConfig>;
140
- /** Phase that surfaced an error inside ConfigService watcher. */
141
- type WatchErrorPhase = "attach" | "reload" | "validation";
142
- /** Stable code on errors thrown by {@link requireWorkspaceId}. Narrow by this, not instanceof. */
143
- declare const WORKSPACE_ID_REQUIRED_CODE: "WORKSPACE_ID_REQUIRED";
144
- /**
145
- * Shape of errors thrown by {@link requireWorkspaceId}.
146
- * Type alias — no class hierarchy; callers narrow via `error.code === WORKSPACE_ID_REQUIRED_CODE`.
147
- *
148
- * The thrown message references CLI (`helix workspace select` / `helix workspace set`)
149
- * and MCP (`tray_list_workspaces` / `tray_set_workspace_id`) commands — keep those
150
- * names in sync with the message literal in requireWorkspaceId.
151
- */
152
- type WorkspaceIdRequiredError = Error & {
153
- readonly code: typeof WORKSPACE_ID_REQUIRED_CODE;
154
- };
155
- /**
156
- * Returns workspaceId from config, or throws a plain Error with code WORKSPACE_ID_REQUIRED.
157
- * Pure, no I/O. workspaceId is independent of provisioning state.
158
- */
159
- declare function requireWorkspaceId(config: LoadedTrayConfig): string;
160
-
161
- interface SdkRuntimeConfig {
162
- /**
163
- * Execution mode. `"lambda"` is set via `setSdkConfig({ mode: "lambda", ... })`
164
- * before the first handler invocation. `"dev"` is the default for `helix dev`
165
- * and local invocations.
166
- */
167
- mode: "lambda" | "dev";
168
- /**
169
- * Execution ID for the current invocation. Set via `setSdkConfig(...)` at
170
- * handler entry in lambda mode. In `dev` mode, define-function falls back to
171
- * the `x-tray-execution-id` header (or a random UUID).
172
- */
173
- executionId?: string;
174
- /**
175
- * User ID for the current invocation. Set via `setSdkConfig(...)` at handler
176
- * entry in lambda mode. In `dev` mode, define-function reads from the
177
- * `x-tray-user-id` header.
178
- */
179
- userId?: string;
180
- /**
181
- * Deployment ID for the current invocation. Set via `setSdkConfig(...)` at
182
- * handler entry. Only meaningful in `lambda` mode; `dev` mode has no
183
- * deployment concept yet.
184
- */
185
- deploymentId?: string | null;
186
- /**
187
- * Running dev server's own base URL (e.g. `http://localhost:3000`). Set by
188
- * the CLI's `sdk-context` Nitro plugin in `dev` mode so `ctx.files()` can
189
- * build local signed URLs pointing at `/_helix/files/**`. Absent in `lambda`
190
- * mode — production signed URLs point at the platform API host instead.
191
- */
192
- devServerUrl?: string;
193
- /**
194
- * Absolute path to the project root in `dev` mode, set by the CLI's
195
- * `sdk-context` Nitro plugin. Used by `ctx.files()`'s local dev store to
196
- * resolve `.helix/files/` on disk. Absent in `lambda` mode.
197
- */
198
- projectRoot?: string;
199
- /**
200
- * The calling execution's id, set via `setSdkConfig(...)` only for a
201
- * function-call-triggered invocation (`ctx.callFunctionAsync`, SUR-929).
202
- * The shim explicitly clears this (passes `undefined`) on every other
203
- * invocation kind so a warm container never leaks a prior call's parentage.
204
- */
205
- parentExecutionId?: string | null;
206
- }
207
- interface BrokerSecrets {
208
- internalJwt?: string;
209
- helixExecutionJwt?: string;
210
- devToken?: string;
211
- }
212
- interface SdkConfigInput extends Partial<SdkRuntimeConfig>, BrokerSecrets {
213
- }
214
- declare function setSdkConfig(options: SdkConfigInput): void;
215
- declare function getSdkConfig(): Readonly<SdkRuntimeConfig>;
216
-
217
- export { type ConfigFileOptions as C, HELIX_CONFIG_ENV as H, type LoadedTrayConfig as L, type ProvisionedTrayConfig as P, type SdkRuntimeConfig as S, type TrayConfig as T, type UnprovisionedTrayConfig as U, type WatchErrorPhase as W, WORKSPACE_ID_REQUIRED_CODE as a, type WorkspaceIdRequiredError as b, loadedTrayConfigSchema as c, resolveConfigFile as d, resolveConfigOverride as e, type SdkConfigInput as f, getSdkConfig as g, loadConfig as l, projectIdSchema as p, requireWorkspaceId as r, setSdkConfig as s, workspaceIdSchema as w };