@trayai/helix-sdk 0.63.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 ADDED
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@trayai/helix-sdk` are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this
6
+ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Ahead of
7
+ general availability, minor versions may include breaking changes.
8
+
9
+ The SDK and [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) are
10
+ released together and share a version — install matching versions.
11
+
12
+ ## Initial release — 2026-07-17
13
+
14
+ First **early-access** release of `@trayai/helix-sdk`. What this release provides:
15
+
16
+ - **`defineFunction`** — the core handler primitive. Merges and validates input (query,
17
+ body, and path params), validates output, maps return values to HTTP responses
18
+ (`null`/`undefined` → 204, a `Response` passes through, any other value is validated and
19
+ sent as JSON), and maps thrown errors to statuses. Accepts either a bare Zod input schema
20
+ or an `{ input, output }` options object.
21
+ - **`ctx` object** passed to every handler, plus **`getContext()`** to reach the active
22
+ context from anywhere in your code (no prop drilling).
23
+ - **Authenticated outbound HTTP** — `ctx.http.authed(alias)` for calling third-party APIs by
24
+ credential alias; the platform supplies the secret, so credentials never appear in your
25
+ code, and the same code runs locally and when deployed. Upstream non-2xx is returned as a
26
+ value rather than thrown. Plain `ctx.http` is available for unauthenticated calls.
27
+ - **Key-value store** — `ctx.kv()` (`getItem`/`setItem`/`removeItem`/`hasItem`).
28
+ - **File storage** — `ctx.files()` (`put`/`get`/`head`/`list`/`delete`/`deleteMany` plus
29
+ pre-signed `getUploadUrl`/`getDownloadUrl`).
30
+ - **Configuration** — `defineConfig` for `helix.config.ts`, `loadConfig()` returning a typed
31
+ `LoadedTrayConfig` discriminated union (provisioned/unprovisioned), `requireWorkspaceId()`
32
+ with a coded `WorkspaceIdRequiredError`, and `createConfigService()` with hot reload for
33
+ long-lived processes.
34
+ - **Structured logging** — `ctx.log.info/warn/error/debug`; `helix dev` prints human-readable
35
+ logs locally by default.
36
+ - **Minimal caller identity** — `ctx.identity` exposes the requesting user id when available.
37
+ - **Testing entry point** — `@trayai/helix-sdk/testing` exports `runWithContext` for
38
+ unit-testing handlers and shared helpers with a mock context that throws on unset fields.
39
+
40
+ ### Requirements
41
+
42
+ - Node.js ≥ 24.18.0.
43
+ - ESM only — no CommonJS build is published.
44
+
45
+ ### Known limitations
46
+
47
+ - `ctx.files().list()` returns the immediate children of a prefix.
48
+ - Authenticated HTTP bodies must be JSON objects, and outbound URLs must be `https:`.
49
+ - Early-access release — APIs may change between minor versions before general availability.
package/LICENSE.md ADDED
@@ -0,0 +1,178 @@
1
+ Copyright 2026 Tray.ai, Inc.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,230 @@
1
+ # @trayai/helix-sdk
2
+
3
+ The runtime SDK for **Helix** — a TypeScript-first platform for building integration backends. You write file-routed functions; the SDK gives every handler a batteries-included `ctx` object for authenticated HTTP, key-value and file storage, structured logging, and config.
4
+
5
+ > **Early access.** Helix is under active development. APIs are stable enough to build on but may change between minor versions ahead of general availability. Distributed as part of the Helix early-access program.
6
+
7
+ ## Contents
8
+
9
+ - [Requirements](#requirements)
10
+ - [Install](#install)
11
+ - [Quick start](#quick-start)
12
+ - [The `ctx` object](#the-ctx-object)
13
+ - [Authenticated HTTP](#authenticated-http)
14
+ - [Capability modules](#capability-modules)
15
+ - [Authentication](#authentication)
16
+ - [Configuration](#configuration)
17
+ - [Logging](#logging)
18
+ - [Testing](#testing)
19
+ - [Entry points](#entry-points)
20
+ - [Tech stack](#tech-stack)
21
+ - [License](#license)
22
+
23
+ ## Requirements
24
+
25
+ - **Node.js ≥ 24.18.0**
26
+ - ESM only (`"type": "module"`) — this package ships no CommonJS build
27
+ - A [Tray](https://tray.io) account for authenticated calls (see [Authentication](#authentication))
28
+ - The [`@trayai/helix-cli`](https://www.npmjs.com/package/@trayai/helix-cli) for scaffolding, local dev, and deploy (recommended)
29
+
30
+ The CLI and SDK are **co-versioned** — install matching versions.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install @trayai/helix-sdk
36
+ npm install -D zod
37
+ ```
38
+
39
+ Your function code imports `zod` directly (`import { z } from 'zod'`) to declare input/output
40
+ schemas, so your project must declare it as a dependency — the SDK does not re-export it, and
41
+ relying on it transitively through the SDK breaks under strict package managers like pnpm.
42
+ Listing it as a dev dependency matches what `helix init` scaffolds.
43
+
44
+ Most projects are created with `helix init`, which wires both dependencies for you.
45
+
46
+ ## Quick start
47
+
48
+ A function is a single file under `functions/`. Its filename determines the route (`functions/items.post.ts` → `POST /items`); its default export is the handler.
49
+
50
+ ```typescript
51
+ import { z } from 'zod';
52
+ import { defineFunction } from '@trayai/helix-sdk';
53
+
54
+ const input = z.object({ name: z.string().min(1) });
55
+
56
+ export default defineFunction(async (ctx) => {
57
+ ctx.log.info('creating item', { name: ctx.input.name });
58
+ ctx.status(201);
59
+ return { created: true, name: ctx.input.name };
60
+ }, {
61
+ input,
62
+ output: z.object({ created: z.boolean(), name: z.string() }),
63
+ });
64
+ ```
65
+
66
+ `defineFunction` handles input parsing and validation, output validation, and HTTP status/error mapping. Return `null`/`undefined` for a `204`, return a `Response` to pass it through untouched, or return a plain value to have it validated against your `output` schema and sent as JSON.
67
+
68
+ ## The `ctx` object
69
+
70
+ Every handler receives a `ctx` (`TrayContext`). You can also reach the current context anywhere in the async call tree — including shared helpers — with `getContext()`, so there's no need to thread `ctx` through your code.
71
+
72
+ | Property | Description |
73
+ |----------|-------------|
74
+ | `ctx.input` | Validated input — query, body, and path params merged (path wins, then body, then query) |
75
+ | `ctx.method` / `ctx.path` | Request method and path |
76
+ | `ctx.headers` | Sanitized request headers |
77
+ | `ctx.http` | HTTP client for outbound requests |
78
+ | `ctx.http.authed(alias)` | Authenticated HTTP — credentials are injected by the platform; secrets never touch your code |
79
+ | `ctx.kv()` | Key-value store |
80
+ | `ctx.files()` | File storage |
81
+ | `ctx.log.info/warn/error/debug` | Structured logging |
82
+ | `ctx.config` | The `config` block from `helix.config.ts` |
83
+ | `ctx.state` | Per-request scratch space |
84
+ | `ctx.status(code)` | Set the response status |
85
+ | `ctx.error(code, message)` | Throw an HTTP error mapped to that status |
86
+ | `ctx.executionId` / `ctx.deploymentId` / `ctx.traceId` | Invocation identifiers |
87
+ | `ctx.identity` | Minimal caller identity (`{ user: { id } }` or `null`) |
88
+ | `ctx.request` | The raw underlying request event |
89
+
90
+ ## Authenticated HTTP
91
+
92
+ `ctx.http.authed(alias)` returns a per-method client for calling third-party APIs that require credentials. You reference a credential by its `alias` (declared in `helix.config.ts`); the platform supplies the actual secret, so credentials never appear in your code. The same code runs unchanged locally and when deployed.
93
+
94
+ ```typescript
95
+ export default defineFunction(async (ctx) => {
96
+ const slack = ctx.http.authed('slack'); // alias defined in helix.config.ts
97
+ const result = await slack.post('https://slack.com/api/chat.postMessage', {
98
+ body: { channel: 'C123', text: 'hi' }, // JSON body only
99
+ });
100
+ return { ok: result.body.ok };
101
+ });
102
+ ```
103
+
104
+ Each method returns `{ status, body?, headers }`. An upstream non-2xx response is **not** thrown — you get the status as a value, matching `ctx.http`. Constraints in this release:
105
+
106
+ - Outbound URLs must be `https:` (otherwise `SdkError.unsupportedScheme`).
107
+ - Bodies are JSON objects only; strings, `Blob`, `FormData`, `ArrayBuffer`, `Uint8Array`, and streams are rejected with `SdkError.unsupportedBodyType`.
108
+ - An unknown alias throws `SdkError.unknownAlias` (the error lists the configured aliases).
109
+
110
+ ## Capability modules
111
+
112
+ ### Key-value store — `ctx.kv()`
113
+
114
+ A small, promise-based store (`getItem`, `setItem`, `removeItem`, `hasItem`).
115
+
116
+ ```typescript
117
+ await ctx.kv().setItem('greeting', { hello: 'world' });
118
+ const value = await ctx.kv().getItem('greeting');
119
+ ```
120
+
121
+ ### File storage — `ctx.files()`
122
+
123
+ Object storage with `put`, `get`, `head`, `list`, `delete`, `deleteMany`, and pre-signed `getUploadUrl` / `getDownloadUrl`.
124
+
125
+ ```typescript
126
+ await ctx.files().put('temp/a.json', JSON.stringify({ n: 1 }), {
127
+ contentType: 'application/json',
128
+ });
129
+ const file = await ctx.files().get('temp/a.json'); // { data, metadata } | null
130
+ ```
131
+
132
+ > `list` returns the immediate children of a prefix.
133
+
134
+ ## Authentication
135
+
136
+ Authenticated features (`ctx.http.authed`, `ctx.kv`, `ctx.files`) require you to be logged in during local development:
137
+
138
+ - **Local (`helix dev`):** run `helix login` once, then `helix dev`.
139
+ - **Deployed:** no token is needed — the platform handles credentials for you.
140
+
141
+ ```bash
142
+ helix login
143
+ helix dev
144
+ ```
145
+
146
+ ## Configuration
147
+
148
+ Every project has a single `helix.config.ts` at its root, authored with `defineConfig`:
149
+
150
+ ```typescript
151
+ // helix.config.ts
152
+ import { defineConfig } from '@trayai/helix-sdk';
153
+
154
+ export default defineConfig({
155
+ name: 'my-app',
156
+ projectId: '00000000-0000-4000-8000-000000000001', // optional UUID
157
+ workspaceId: '00000000-0000-4000-8000-000000000002', // optional UUID
158
+ authentications: {
159
+ notion: '<your-notion-auth-uuid>',
160
+ },
161
+ config: {
162
+ apiVersion: '2022-06-28',
163
+ },
164
+ });
165
+ ```
166
+
167
+ Read it at runtime with `loadConfig()`, which returns a `LoadedTrayConfig` — a discriminated union on `kind`:
168
+
169
+ ```typescript
170
+ import { loadConfig, requireWorkspaceId } from '@trayai/helix-sdk';
171
+
172
+ const config = await loadConfig(); // reads helix.config.ts from process.cwd()
173
+
174
+ if (config.kind === 'provisioned') {
175
+ console.log('Project:', config.projectId); // string — no optional chaining needed
176
+ }
177
+
178
+ // requireWorkspaceId returns the workspaceId or throws WorkspaceIdRequiredError
179
+ const workspaceId = requireWorkspaceId(config);
180
+ ```
181
+
182
+ For long-lived processes (a dev server, the MCP server) use `createConfigService`, which holds a stable snapshot and hot-reloads on disk edits:
183
+
184
+ ```typescript
185
+ import { createConfigService } from '@trayai/helix-sdk';
186
+
187
+ const service = await createConfigService({ cwd: process.cwd(), watch: true });
188
+ const current = service.get();
189
+ const unsubscribe = service.subscribe((next) => console.log('reloaded:', next.kind));
190
+ // ... later
191
+ await service.stop();
192
+ ```
193
+
194
+ Use the CLI (`helix project set`, `helix workspace set`, `helix auth add`) or the Helix MCP tools to write config fields — you rarely edit these by hand.
195
+
196
+ ## Logging
197
+
198
+ Use `ctx.log.info/warn/error/debug(message, properties?)` for structured logging from your handlers. `helix dev` prints human-readable logs by default.
199
+
200
+ ## Testing
201
+
202
+ Import from the `/testing` subpath to unit-test handlers and shared helpers that call `getContext()`:
203
+
204
+ ```typescript
205
+ import { runWithContext } from '@trayai/helix-sdk/testing';
206
+
207
+ const result = await runWithContext({ input: { name: 'Ada' } }, async () => {
208
+ // code under test can call getContext() here
209
+ });
210
+ ```
211
+
212
+ The mock context is a Proxy: any field your code touches that you didn't provide throws a descriptive error, so tests fail loudly instead of silently reading `undefined`.
213
+
214
+ ## Entry points
215
+
216
+ | Import | Contents |
217
+ |--------|----------|
218
+ | `@trayai/helix-sdk` | `defineFunction`, `defineConfig`, `getContext`, `loadConfig`, `requireWorkspaceId`, `createConfigService`, and the public types |
219
+ | `@trayai/helix-sdk/testing` | `runWithContext` |
220
+
221
+ Key exported types include `TrayContext`, `TrayConfig`, `LoadedTrayConfig`, `HttpClient`, `KeyValueStore`, `FileSystemClient`, `Logger`, `ConfigService`, and `WorkspaceIdRequiredError`.
222
+
223
+ ## Tech stack
224
+
225
+ - TypeScript 5.x, Node.js 24+, ESM
226
+ - [zod](https://zod.dev) — input/output schema validation
227
+
228
+ ## License
229
+
230
+ Apache-2.0 — see [LICENSE.md](./LICENSE.md).
@@ -0,0 +1,59 @@
1
+ declare const BROKER_BASE_URLS: {
2
+ readonly production: "https://api.tray.io/private/v1/code";
3
+ };
4
+ type BrokerEnvironment = keyof typeof BROKER_BASE_URLS;
5
+
6
+ interface BrokerDevCallParams {
7
+ /** Target Tray environment — selects the broker base URL. */
8
+ env: BrokerEnvironment;
9
+ /** Personal dev token (the user's local Tray login) sent as `Authorization: Bearer`. */
10
+ devToken: string;
11
+ /** Credential record UUID the broker injects auth for. */
12
+ authenticationId: string;
13
+ /** Upstream HTTP method (GET/POST/PUT/PATCH/DELETE…). */
14
+ method: string;
15
+ /** Full HTTPS URL of the upstream API. Non-https URLs are rejected by the builder. */
16
+ url: string;
17
+ /** Extra request headers forwarded to the upstream (broker injects auth headers). */
18
+ headers?: Record<string, string>;
19
+ /** JSON object body. Streams/blobs/strings are rejected by the broker contract. */
20
+ body?: unknown;
21
+ /** Extra query params appended to any already present on `url`. */
22
+ query?: Record<string, string | string[]>;
23
+ /** Per-call timeout in ms (default 60s). */
24
+ timeoutMs?: number;
25
+ }
26
+ /** The third-party API's response, as unpacked from the broker envelope. */
27
+ interface UpstreamResponse {
28
+ status: number;
29
+ headers: Record<string, string | string[]>;
30
+ body?: unknown;
31
+ }
32
+ /**
33
+ * Result of a one-shot dev broker call.
34
+ * - `upstream` — the broker accepted the call and forwarded it; carries the
35
+ * third-party API's status/headers/body.
36
+ * - `brokerError` — the broker rejected the call BEFORE reaching the upstream
37
+ * (bad/expired token, unknown authentication, malformed request).
38
+ * `brokerStatus` is the broker's own HTTP status and `body` its error payload.
39
+ */
40
+ type BrokerDevCallResult = {
41
+ kind: "upstream";
42
+ upstream: UpstreamResponse;
43
+ } | {
44
+ kind: "brokerError";
45
+ brokerStatus: number;
46
+ body: unknown;
47
+ };
48
+ /**
49
+ * Stateless, one-shot call through the credential broker's dev forward proxy.
50
+ *
51
+ * This is the path `ctx.http.authed(...)` takes inside `helix dev`, factored
52
+ * out so CLI tooling (notably the `tray_call_credential_broker` MCP tool) can
53
+ * exercise a credential and request payload without booting the dev server.
54
+ * Unlike the runtime path it reads no module-global state: the caller passes
55
+ * the env, dev token, and authentication UUID explicitly.
56
+ */
57
+ declare function callBrokerDev(params: BrokerDevCallParams): Promise<BrokerDevCallResult>;
58
+
59
+ export { type BrokerDevCallParams, type BrokerDevCallResult, type BrokerEnvironment, type UpstreamResponse, callBrokerDev };
@@ -0,0 +1 @@
1
+ import{a as n,b as s,c as i,d as a}from"../chunk-V63DM4MB.js";import"../chunk-W5TFZBQD.js";import p from"ky";var d=6e4;async function l(e){let u=n({authenticationId:e.authenticationId,method:e.method,url:e.url,body:e.body,headers:e.headers,query:e.query}),k=s(e.env),r=await p.post(`${k}/broker/http/dev`,{json:u,headers:{Authorization:`Bearer ${e.devToken}`,Accept:"application/json"},throwHttpErrors:!1,timeout:e.timeoutMs??d}),t;if((r.headers.get("content-type")??"").includes("application/json")?t=await r.json():t=await r.text(),r.status<200||r.status>=300)return{kind:"brokerError",brokerStatus:r.status,body:t};let o=i.safeParse(t);return o.success?{kind:"upstream",upstream:a(o.data)}:{kind:"brokerError",brokerStatus:r.status,body:t}}export{l as callBrokerDev};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-W5TFZBQD.js";var w="X-Helix-Project-Execution-Token",A="X-Tray-Token",E={mode:"dev",deploymentId:null},l={...E},o={};function k(t){let{internalJwt:e,helixExecutionJwt:n,devToken:r,...f}=t;"internalJwt"in t&&(o.internalJwt=e),"helixExecutionJwt"in t&&(o.helixExecutionJwt=n),"devToken"in t&&(o.devToken=r),l={...l,...f}}function y(){return l}function R(){return o.internalJwt}function D(){return o.helixExecutionJwt}function L(){return o.devToken}var F="tray-config-bridge",c=null;function N(t){c=t}function H(){if(!c)throw new Error("Active tray config not seeded. Worker boot must call setActiveConfig() before handlers run.");return c}function J(){c=null}var d=1024,g=100*1024*1024,u=250,h=3600,T=h*1e3,x=new TextEncoder,p=/(^|\/)\.\.(\/|$)/,C=/[?#]/;function S(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<=31||n===127)return!0}return!1}function M(t){if(t.length===0)throw i.filesPathInvalid("Path must be a non-empty string");v(t)}function O(t){return t.endsWith("/")?t.slice(0,-1):t}function v(t){if(t.length===0)return;if(p.test(t))throw i.filesPathInvalid("Path contains path traversal segment");if(C.test(t)||S(t))throw i.filesPathInvalid("Path contains illegal characters");let e=t.split("/");if(t.startsWith("/")||t.endsWith("/")||e.some(r=>r===""))throw i.filesPathInvalid("Path must not contain empty path segments");for(let r of e){let f=x.encode(r).length;if(f>u)throw i.filesPathInvalid(`Path segment exceeds ${u} UTF-8 bytes (got ${f})`)}let n=x.encode(t).length;if(n<1||n>d)throw i.filesPathInvalid(`Path must be between 1 and ${d} UTF-8 bytes (got ${n})`)}function X(t){if(t>g)throw i.filesValueTooLarge(`File exceeds maximum size of ${g} bytes (got ${t})`,g)}function $(t){let e=t!==void 0?t*1e3:T;return new Date(Date.now()+e)}import{join as s}from"path";var _="files",I="files-meta";function m(t){return s(t,".helix",_)}function a(t){return s(t,".helix",I)}function P(t,e){return s(m(t),...e.split("/"))}function W(t,e){return s(a(t),...e.split("/"))+".json"}function Y(t,e){return e.length===0?m(t):P(t,e)}function j(t,e){return e.length===0?a(t):s(a(t),...e.split("/"))}export{w as a,A as b,k as c,y as d,R as e,D as f,L as g,F as h,N as i,H as j,J as k,g as l,M as m,O as n,v as o,X as p,$ as q,P as r,W as s,Y as t,j as u};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as e}from"async_hooks";var o=new e;function r(){let t=o.getStore();if(!t)throw new Error("getContext() called outside of a defineFunction handler. Ensure this code runs inside a function wrapped with defineFunction().");return t}export{o as a,r as b};
@@ -0,0 +1 @@
1
+ import{a as p}from"./chunk-W5TFZBQD.js";var l=new Set(["proxy-authorization","x-tray-token"]);function m(e){let t=e.toLowerCase();return l.has(t)||t.startsWith("x-tray-internal-")}function R(e){let t;return e instanceof Headers?t=Array.from(e.entries()):Array.isArray(e)?t=e:t=Object.entries(e),t.filter(([o])=>!m(o)).map(([o,i])=>({name:o,value:i}))}function B(e){return typeof e=="string"?"string":e instanceof Blob?"Blob":e instanceof FormData?"FormData":e instanceof ArrayBuffer?"ArrayBuffer":e instanceof Uint8Array?"Uint8Array":typeof ReadableStream<"u"&&e instanceof ReadableStream?"ReadableStream":null}function S(e){let t=new URL(e.url);if(t.protocol!=="https:")throw p.unsupportedScheme(t.protocol.replace(/:$/,""));let o=e.body!==void 0&&e.body!==null?B(e.body):null;if(o!==null)throw p.unsupportedBodyType(o);let i=t.host,s=t.pathname,n=[];for(let[d,a]of t.searchParams.entries())n.push({name:d,value:a});if(e.query!==void 0)if(e.query instanceof URLSearchParams)for(let[d,a]of e.query.entries())n.push({name:d,value:a});else for(let[d,a]of Object.entries(e.query))if(Array.isArray(a))for(let h of a)n.push({name:d,value:h});else n.push({name:d,value:a});let u=e.headers!==void 0?R(e.headers):[],c=e.body!==void 0&&e.body!==null?{host:i,method:e.method,path:s,body:e.body,headers:u,queryParams:n}:{host:i,method:e.method,path:s,headers:u,queryParams:n};return{authenticationId:e.authenticationId,httpRequest:c}}var k={production:"https://api.tray.io/private/v1/code"};function q(e){return k[e]}import{z as r}from"zod";var y=r.object({name:r.string(),value:r.string()}),g=r.object({host:r.string(),method:r.string(),path:r.string().startsWith("/"),body:r.record(r.unknown()).optional(),headers:r.array(y),queryParams:r.array(y)}),v=r.object({authenticationId:r.string().uuid(),httpRequest:g}),w=r.object({httpResponse:r.object({status:r.number(),body:r.unknown().optional(),headers:r.array(y)})});function L(e){let{status:t,body:o,headers:i}=e.httpResponse,s={};for(let{name:n,value:u}of i){let f=n.toLowerCase(),c=s[f];c===void 0?s[f]=u:Array.isArray(c)?c.push(u):s[f]=[c,u]}return{status:t,body:o,headers:s}}export{S as a,q as b,w as c,L as d};
@@ -0,0 +1 @@
1
+ var a=class e extends Error{detail;constructor(r){super(s(r)),this.name="SdkError",this.detail=r}get kind(){return this.detail.kind}static unknownAlias(r,n){return new e({kind:"unknown_alias",alias:r,available:n})}static inputValidationFailed(r){return new e({kind:"input_validation_failed",fields:r})}static outputValidationFailed(r){return new e({kind:"output_validation_failed",fields:r})}static configLoadFailed(r){return new e({kind:"config_load_failed",cause:r})}static brokerError(r,n,i){return new e({kind:"broker_error",status:r,message:n,body:i})}static unsupportedBodyType(r){return new e({kind:"unsupported_body_type",actualType:r})}static unsupportedScheme(r){return new e({kind:"unsupported_scheme",scheme:r})}static missingExecutionCredentials(){return new e({kind:"missing_execution_credentials"})}static missingTrayToken(){return new e({kind:"missing_tray_token"})}static dbCallFailed(r,n){return new e({kind:"db_call_failed",message:r,cause:n})}static dbQueryFailed(r){return new e({kind:"db_query_failed",message:r})}static dbInvalidParameters(r){return new e({kind:"db_invalid_parameters",message:r})}static kvKeyInvalid(r){return new e({kind:"kv_key_invalid",message:r})}static kvValueInvalid(r){return new e({kind:"kv_value_invalid",message:r})}static kvValueTooLarge(r,n){return new e({kind:"kv_value_too_large",message:r,maxBytes:n})}static kvNotAvailable(){return new e({kind:"kv_not_available"})}static kvCallFailed(r,n,i){return new e({kind:"kv_call_failed",status:r,message:n,body:i})}static kvRequiresProvisioning(){return new e({kind:"kv_requires_provisioning"})}static filesPathInvalid(r){return new e({kind:"files_path_invalid",message:r})}static filesValueInvalid(r){return new e({kind:"files_value_invalid",message:r})}static filesValueTooLarge(r,n){return new e({kind:"files_value_too_large",message:r,maxBytes:n})}static filesNotAvailable(){return new e({kind:"files_not_available"})}static filesCallFailed(r,n,i){return new e({kind:"files_call_failed",status:r,message:n,body:i})}static filesRequiresProvisioning(){return new e({kind:"files_requires_provisioning"})}};function t(e){return e instanceof a}function s(e){switch(e.kind){case"unknown_alias":return`Unknown auth alias "${e.alias}". Available: ${e.available.join(", ")||"(none)"}`;case"input_validation_failed":return`Input validation failed for fields: ${e.fields.join(", ")}`;case"output_validation_failed":return`Output validation failed for fields: ${e.fields.join(", ")}`;case"config_load_failed":return`Config load failed: ${e.cause}`;case"broker_error":return`broker error: ${e.status} ${e.message}`;case"unsupported_body_type":return`unsupported body type: ${e.actualType}`;case"unsupported_scheme":return`unsupported scheme: ${e.scheme} (only https supported)`;case"missing_execution_credentials":return"missing execution credentials: at least one of internalJwt / helixExecutionJwt must be set before an authed broker/KV call";case"missing_tray_token":return"Not logged in. Run `helix login` to authenticate before making authed HTTP calls in dev.";case"db_call_failed":return`Database call failed: ${e.message}`;case"db_query_failed":return`Database query failed: ${e.message}`;case"db_invalid_parameters":return`Invalid database parameters: ${e.message}`;case"kv_key_invalid":return`Invalid KV key: ${e.message}`;case"kv_value_invalid":return e.message;case"kv_value_too_large":return e.message;case"kv_not_available":return"Key-value store is not available in this environment";case"kv_call_failed":return`KV platform error: ${e.status} ${e.message}`;case"kv_requires_provisioning":return"Key-value store requires a provisioned project (run helix project set)";case"files_path_invalid":return`Invalid file path: ${e.message}`;case"files_value_invalid":return e.message;case"files_value_too_large":return e.message;case"files_not_available":return"File storage is not available in this environment";case"files_call_failed":return`Files platform error: ${e.status} ${e.message}`;case"files_requires_provisioning":return"File storage requires a provisioned project (run helix project set)"}}export{a,t as b};