stitchkit 0.67.0 → 0.68.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.
Files changed (83) hide show
  1. package/dist/agent-runtime.js +5 -6
  2. package/dist/application/admission.d.ts +131 -0
  3. package/dist/application/admission.d.ts.map +1 -0
  4. package/dist/application/channel.d.ts +106 -0
  5. package/dist/application/channel.d.ts.map +1 -0
  6. package/dist/application/latest-sink.d.ts.map +1 -1
  7. package/dist/application-grammy.js +1 -1
  8. package/dist/application-opentelemetry.js +1 -1
  9. package/dist/application.d.ts +2 -0
  10. package/dist/application.d.ts.map +1 -1
  11. package/dist/application.js +386 -17
  12. package/dist/browser/client.d.ts +2 -3
  13. package/dist/browser/client.d.ts.map +1 -1
  14. package/dist/browser/contract-stream.d.ts +5 -0
  15. package/dist/browser/contract-stream.d.ts.map +1 -0
  16. package/dist/browser/http.d.ts +3 -0
  17. package/dist/browser/http.d.ts.map +1 -1
  18. package/dist/browser/stream.d.ts +4 -1
  19. package/dist/browser/stream.d.ts.map +1 -1
  20. package/dist/browser/transport.d.ts +3 -0
  21. package/dist/browser/transport.d.ts.map +1 -0
  22. package/dist/cli.js +6 -7
  23. package/dist/contract/define.d.ts +34 -2
  24. package/dist/contract/define.d.ts.map +1 -1
  25. package/dist/contract/errors.d.ts +4 -0
  26. package/dist/contract/errors.d.ts.map +1 -1
  27. package/dist/contract/index.d.ts +2 -1
  28. package/dist/contract/index.d.ts.map +1 -1
  29. package/dist/contract/index.js +5 -1
  30. package/dist/contract/stream.d.ts +19 -0
  31. package/dist/contract/stream.d.ts.map +1 -0
  32. package/dist/{index-xxye8j3k.js → index-0w9abg87.js} +4 -0
  33. package/dist/index-69m2278y.js +115 -0
  34. package/dist/{index-physbf4z.js → index-6wzr93cg.js} +1 -1
  35. package/dist/{index-1pgeyyee.js → index-7pn02bgv.js} +4 -6
  36. package/dist/index-9ky9hhg3.js +484 -0
  37. package/dist/{index-wrhf06ak.js → index-avjd67h6.js} +8 -8
  38. package/dist/{index-413xk7ga.js → index-cq9q73nf.js} +50 -1
  39. package/dist/{index-6taryy00.js → index-dafax5md.js} +1 -1
  40. package/dist/{index-8mxadm34.js → index-nymn7wbg.js} +1092 -19
  41. package/dist/{index-y91zd0ch.js → index-pr0qsmjy.js} +3 -2
  42. package/dist/index-v5bayx1z.js +138 -0
  43. package/dist/{index-mfw1pec7.js → index-wqyrvhzz.js} +3 -3
  44. package/dist/{index-svqhcrrj.js → index-zd4v31v2.js} +156 -10
  45. package/dist/{index-x8v8b7rc.js → index-zpyj7hsv.js} +330 -58
  46. package/dist/index.js +270 -105
  47. package/dist/internal/bounded-lines.d.ts +4 -0
  48. package/dist/internal/bounded-lines.d.ts.map +1 -0
  49. package/dist/node.d.ts +1 -0
  50. package/dist/node.d.ts.map +1 -1
  51. package/dist/node.js +11 -8
  52. package/dist/observability/index.js +6 -7
  53. package/dist/remote.js +5 -6
  54. package/dist/server/contract-stream.d.ts +5 -0
  55. package/dist/server/contract-stream.d.ts.map +1 -0
  56. package/dist/server/create.d.ts.map +1 -1
  57. package/dist/server/implement.d.ts.map +1 -1
  58. package/dist/server/index.d.ts +1 -0
  59. package/dist/server/index.d.ts.map +1 -1
  60. package/dist/server/index.js +41 -283
  61. package/dist/server/openapi.d.ts.map +1 -1
  62. package/dist/server/stream.d.ts +3 -1
  63. package/dist/server/stream.d.ts.map +1 -1
  64. package/dist/server/streaming-route.d.ts +2 -0
  65. package/dist/server/streaming-route.d.ts.map +1 -1
  66. package/dist/server/types.d.ts +13 -3
  67. package/dist/server/types.d.ts.map +1 -1
  68. package/dist/server/unix-client-body.d.ts +4 -0
  69. package/dist/server/unix-client-body.d.ts.map +1 -0
  70. package/dist/server/unix-client-bun.d.ts +13 -0
  71. package/dist/server/unix-client-bun.d.ts.map +1 -0
  72. package/dist/server/unix-client-error.d.ts +9 -0
  73. package/dist/server/unix-client-error.d.ts.map +1 -0
  74. package/dist/server/unix-client.d.ts +25 -0
  75. package/dist/server/unix-client.d.ts.map +1 -0
  76. package/dist/testing.js +6 -5
  77. package/dist/tools.js +14 -16
  78. package/llms-full.txt +337 -17
  79. package/package.json +1 -1
  80. package/dist/index-48ffdxgk.js +0 -6
  81. package/dist/index-pzyt11ch.js +0 -127
  82. package/dist/index-tvwcrx2d.js +0 -224
  83. package/dist/index-wd8g8z6e.js +0 -206
@@ -0,0 +1,484 @@
1
+ import {
2
+ isRecord
3
+ } from "./index-smpbdg6k.js";
4
+ import {
5
+ AppError
6
+ } from "./index-0w9abg87.js";
7
+
8
+ // src/contract/define.ts
9
+ import { z } from "zod";
10
+
11
+ // src/internal/route-pattern.ts
12
+ var PARAM_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
13
+ function joinRoutePath(...parts) {
14
+ const joined = parts.filter((part) => Boolean(part)).map((part) => part.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
15
+ return `/${joined}`;
16
+ }
17
+ function parseTrailingWildcard(path) {
18
+ const segments = path.split("/").filter(Boolean);
19
+ const paramNames = new Set;
20
+ let wildcard = null;
21
+ for (const [segmentIndex, segment] of segments.entries()) {
22
+ if (segment.startsWith(":")) {
23
+ const name2 = segment.slice(1);
24
+ if (!PARAM_IDENTIFIER.test(name2)) {
25
+ throw new Error(`Invalid route parameter name "${name2}" in path "${path}"`);
26
+ }
27
+ if (paramNames.has(name2)) {
28
+ throw new Error(`Duplicate route parameter name "${name2}" in path "${path}"`);
29
+ }
30
+ paramNames.add(name2);
31
+ continue;
32
+ }
33
+ if (!segment.startsWith("*")) {
34
+ if (segment.includes("*")) {
35
+ throw new Error(`Wildcard must occupy its own segment in path "${path}"`);
36
+ }
37
+ continue;
38
+ }
39
+ const name = segment.slice(1);
40
+ if (!PARAM_IDENTIFIER.test(name)) {
41
+ throw new Error(`Trailing wildcard in path "${path}" must be named, for example "/*filePath"`);
42
+ }
43
+ if (segmentIndex !== segments.length - 1) {
44
+ throw new Error(`Wildcard "*${name}" must be the final segment in path "${path}"`);
45
+ }
46
+ if (wildcard) {
47
+ throw new Error(`Path "${path}" contains more than one wildcard`);
48
+ }
49
+ if (paramNames.has(name)) {
50
+ throw new Error(`Duplicate route parameter name "${name}" in path "${path}"`);
51
+ }
52
+ wildcard = { name, segmentIndex };
53
+ }
54
+ return wildcard;
55
+ }
56
+
57
+ // src/internal/safe-json.ts
58
+ function isUnsafeKey(key) {
59
+ return key === "__proto__";
60
+ }
61
+ function safeJsonParse(text) {
62
+ return JSON.parse(text, (key, value) => isUnsafeKey(key) ? undefined : value);
63
+ }
64
+
65
+ // src/contract/define.ts
66
+ function defineContract(meta, endpoints) {
67
+ const toolTransports = new Map;
68
+ for (const [key, ep] of Object.entries(endpoints)) {
69
+ const wildcard = parseTrailingWildcard(ep.path);
70
+ if (wildcard) {
71
+ if (!ep.params) {
72
+ throw new Error(`Contract "${meta.prefix}": endpoint "${key}" wildcard "${wildcard.name}" requires a params schema field`);
73
+ }
74
+ const paramsJson = z.toJSONSchema(ep.params, { io: "input" });
75
+ if (!paramsJson.properties || !(wildcard.name in paramsJson.properties)) {
76
+ throw new Error(`Contract "${meta.prefix}": endpoint "${key}" params schema is missing wildcard field "${wildcard.name}"`);
77
+ }
78
+ }
79
+ if (ep.desc.trim() === "") {
80
+ throw new Error(`Contract "${meta.prefix}": endpoint "${key}" has an empty desc`);
81
+ }
82
+ if (ep.maxJsonBodyBytes !== undefined && (!Number.isSafeInteger(ep.maxJsonBodyBytes) || ep.maxJsonBodyBytes <= 0)) {
83
+ throw new Error(`Contract "${meta.prefix}": endpoint "${key}" maxJsonBodyBytes must be a positive safe integer, received ${ep.maxJsonBodyBytes}`);
84
+ }
85
+ if (ep.multipart)
86
+ assertMultipartEndpoint(meta.prefix, key, ep);
87
+ if (ep.rawResponse)
88
+ assertRawEndpoint(meta.prefix, key, ep);
89
+ if ("stream" in ep)
90
+ assertStreamingResponseEndpoint(meta.prefix, key, ep);
91
+ if (ep.method === "HEAD")
92
+ assertHeadEndpoint(meta.prefix, key, ep);
93
+ if (ep.rawBody)
94
+ assertRawBodyEndpoint(meta.prefix, key, ep);
95
+ if ("responseMeta" in ep)
96
+ assertResponseMetaEndpoint(meta.prefix, key, ep);
97
+ if (!("toolName" in ep) || !ep.toolName)
98
+ continue;
99
+ const transports = new Set(ep.expose ? ep.expose.filter((t) => t !== "HTTP") : ["MCP", "AGENT"]);
100
+ if (transports.size === 0) {
101
+ throw new Error(`Contract "${meta.prefix}": endpoint "${key}" sets toolName "${ep.toolName}" but is not exposed on any tool transport (MCP / AGENT)`);
102
+ }
103
+ const existing = toolTransports.get(ep.toolName);
104
+ if (existing) {
105
+ for (const t of transports) {
106
+ if (existing.transports.has(t)) {
107
+ throw new Error(`Contract "${meta.prefix}": duplicate toolName "${ep.toolName}" on transport "${t}" (endpoints: "${existing.key}" and "${key}")`);
108
+ }
109
+ existing.transports.add(t);
110
+ }
111
+ } else {
112
+ toolTransports.set(ep.toolName, { key, transports });
113
+ }
114
+ }
115
+ return { meta, endpoints };
116
+ }
117
+ function assertPositiveLimit(where, name, value) {
118
+ if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
119
+ throw new Error(`${where} ${name} must be a positive safe integer, received ${value}`);
120
+ }
121
+ }
122
+ function assertMultipartEndpoint(prefix, key, ep) {
123
+ const where = `Contract "${prefix}": multipart endpoint "${key}"`;
124
+ if (ep.method !== "POST" && ep.method !== "PUT" && ep.method !== "PATCH") {
125
+ throw new Error(`${where} must use POST, PUT or PATCH`);
126
+ }
127
+ const multipart = ep.multipart;
128
+ if (!multipart || typeof multipart !== "object") {
129
+ throw new Error(`${where} must declare a multipart descriptor`);
130
+ }
131
+ assertPositiveLimit(where, "maxRequestBytes", multipart.maxRequestBytes);
132
+ assertPositiveLimit(where, "maxFieldBytes", multipart.maxFieldBytes);
133
+ const entries = Object.entries(multipart.files);
134
+ if (entries.length === 0)
135
+ throw new Error(`${where} must declare at least one file field`);
136
+ for (const [field, policy] of entries) {
137
+ if (!field || isUnsafeKey(field))
138
+ throw new Error(`${where} has an invalid file field name`);
139
+ assertPositiveLimit(`${where} field "${field}"`, "maxBytes", policy.maxBytes);
140
+ assertPositiveLimit(`${where} field "${field}"`, "maxFiles", policy.maxFiles);
141
+ if (policy.multiple !== true && policy.maxFiles !== undefined) {
142
+ throw new Error(`${where} field "${field}" may set maxFiles only with multiple: true`);
143
+ }
144
+ if (policy.contentTypes) {
145
+ if (policy.contentTypes.length === 0) {
146
+ throw new Error(`${where} field "${field}" contentTypes cannot be empty`);
147
+ }
148
+ for (const contentType of policy.contentTypes) {
149
+ if (!/^[a-z0-9!#$&^_.+-]+\/(?:[a-z0-9!#$&^_.+-]+|\*)$/i.test(contentType)) {
150
+ throw new Error(`${where} field "${field}" has invalid content type policy "${contentType}"`);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ }
156
+ function assertRawEndpoint(prefix, key, ep) {
157
+ const where = `Contract "${prefix}": raw endpoint "${key}"`;
158
+ if (ep.output)
159
+ throw new Error(`${where} cannot declare an output schema`);
160
+ if ("toolName" in ep && ep.toolName)
161
+ throw new Error(`${where} cannot set a toolName`);
162
+ if ("ui" in ep && ep.ui)
163
+ throw new Error(`${where} cannot set MCP ui metadata`);
164
+ if ("annotations" in ep && ep.annotations) {
165
+ throw new Error(`${where} cannot set MCP annotations`);
166
+ }
167
+ const nonHttp = (ep.expose ?? []).filter((t) => t !== "HTTP");
168
+ if (nonHttp.length > 0) {
169
+ throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
170
+ }
171
+ }
172
+ function assertStreamingResponseEndpoint(prefix, key, ep) {
173
+ const where = `Contract "${prefix}": streaming endpoint "${key}"`;
174
+ if (!("stream" in ep) || !ep.stream || typeof ep.stream !== "object") {
175
+ throw new Error(`${where} must declare a stream descriptor`);
176
+ }
177
+ if (!ep.stream.item || typeof ep.stream.item.parse !== "function") {
178
+ throw new Error(`${where} must declare an item schema`);
179
+ }
180
+ assertPositiveLimit(where, "maxFrameBytes", ep.stream.maxFrameBytes);
181
+ assertPositiveLimit(where, "lifetimeMs", ep.stream.lifetimeMs);
182
+ assertPositiveLimit(where, "heartbeatMs", ep.stream.heartbeatMs);
183
+ if (ep.stream.idleTimeoutSeconds !== undefined && (!Number.isSafeInteger(ep.stream.idleTimeoutSeconds) || ep.stream.idleTimeoutSeconds < 0)) {
184
+ throw new Error(`${where} idleTimeoutSeconds must be a non-negative safe integer`);
185
+ }
186
+ if (ep.output)
187
+ throw new Error(`${where} cannot declare an output schema`);
188
+ if (ep.rawResponse)
189
+ throw new Error(`${where} cannot also be rawResponse`);
190
+ if (ep.multipart)
191
+ throw new Error(`${where} cannot be multipart`);
192
+ if ("toolName" in ep && ep.toolName)
193
+ throw new Error(`${where} cannot set a toolName`);
194
+ const nonHttp = (ep.expose ?? []).filter((transport) => transport !== "HTTP");
195
+ if (nonHttp.length > 0) {
196
+ throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
197
+ }
198
+ }
199
+ function assertHeadEndpoint(prefix, key, ep) {
200
+ const where = `Contract "${prefix}": HEAD endpoint "${key}"`;
201
+ if (!ep.rawResponse)
202
+ throw new Error(`${where} must declare rawResponse: true`);
203
+ if (ep.input)
204
+ throw new Error(`${where} cannot declare an input schema`);
205
+ if (ep.multipart)
206
+ throw new Error(`${where} cannot be multipart`);
207
+ if (ep.rawBody)
208
+ throw new Error(`${where} cannot retain a raw body`);
209
+ }
210
+ function assertRawBodyEndpoint(prefix, key, ep) {
211
+ const where = `Contract "${prefix}": rawBody endpoint "${key}"`;
212
+ if (!ep.input)
213
+ throw new Error(`${where} must declare an input schema`);
214
+ if (ep.multipart)
215
+ throw new Error(`${where} cannot be multipart`);
216
+ if (ep.method !== "POST" && ep.method !== "PUT" && ep.method !== "PATCH") {
217
+ throw new Error(`${where} must use POST, PUT or PATCH`);
218
+ }
219
+ if ("toolName" in ep && ep.toolName)
220
+ throw new Error(`${where} cannot set a toolName`);
221
+ if ("ui" in ep && ep.ui)
222
+ throw new Error(`${where} cannot set MCP ui metadata`);
223
+ if ("annotations" in ep && ep.annotations) {
224
+ throw new Error(`${where} cannot set MCP annotations`);
225
+ }
226
+ const nonHttp = (ep.expose ?? []).filter((transport) => transport !== "HTTP");
227
+ if (nonHttp.length > 0) {
228
+ throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
229
+ }
230
+ }
231
+ function assertResponseMetaEndpoint(prefix, key, ep) {
232
+ const where = `Contract "${prefix}": responseMeta endpoint "${key}"`;
233
+ if (!ep.responseMeta || typeof ep.responseMeta !== "object") {
234
+ throw new Error(`${where} must declare responseMeta as an object`);
235
+ }
236
+ const status = ep.responseMeta.status;
237
+ if (status !== undefined && (!Number.isSafeInteger(status) || status < 200 || status > 299)) {
238
+ throw new Error(`${where} status must be a successful 2xx integer, received ${status}`);
239
+ }
240
+ if (ep.output && (status === 204 || status === 205)) {
241
+ throw new Error(`${where} cannot combine output with bodyless status ${status}`);
242
+ }
243
+ if (ep.rawResponse)
244
+ throw new Error(`${where} cannot also be a rawResponse endpoint`);
245
+ if ("toolName" in ep && ep.toolName)
246
+ throw new Error(`${where} cannot set a toolName`);
247
+ if ("ui" in ep && ep.ui)
248
+ throw new Error(`${where} cannot set MCP ui metadata`);
249
+ if ("annotations" in ep && ep.annotations) {
250
+ throw new Error(`${where} cannot set MCP annotations`);
251
+ }
252
+ const nonHttp = (ep.expose ?? []).filter((transport) => transport !== "HTTP");
253
+ if (nonHttp.length > 0) {
254
+ throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
255
+ }
256
+ }
257
+ function mergeMeta(contractMeta, endpointMeta) {
258
+ if (!contractMeta)
259
+ return endpointMeta;
260
+ if (!endpointMeta)
261
+ return { ...contractMeta };
262
+ return { ...contractMeta, ...endpointMeta };
263
+ }
264
+ // src/contract/errors-factory.ts
265
+ import { z as z2 } from "zod";
266
+ // src/contract/pagination.ts
267
+ import { z as z3 } from "zod";
268
+
269
+ // src/internal/base64url.ts
270
+ function bytesToBase64Url(bytes) {
271
+ let binary = "";
272
+ for (const byte of bytes)
273
+ binary += String.fromCharCode(byte);
274
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
275
+ }
276
+ function base64UrlToBytes(segment) {
277
+ if (!/^[A-Za-z0-9_-]*$/.test(segment) || segment.length % 4 === 1) {
278
+ throw new Error("invalid base64url segment");
279
+ }
280
+ const b64 = segment.replace(/-/g, "+").replace(/_/g, "/");
281
+ const padded = b64.padEnd(Math.ceil(b64.length / 4) * 4, "=");
282
+ return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
283
+ }
284
+ // src/contract/stream.ts
285
+ import { z as z4 } from "zod";
286
+ var DEFAULT_CONTRACT_STREAM_FRAME_BYTES = 256 * 1024;
287
+ var ContractStreamFrameSchema = z4.discriminatedUnion("type", [
288
+ z4.object({ type: z4.literal("data"), data: z4.unknown() }).strict(),
289
+ z4.object({
290
+ type: z4.literal("error"),
291
+ error: z4.object({
292
+ code: z4.string(),
293
+ message: z4.string().optional(),
294
+ details: z4.unknown().optional(),
295
+ hint: z4.string().optional()
296
+ }).strict()
297
+ }).strict(),
298
+ z4.object({ type: z4.literal("end") }).strict()
299
+ ]);
300
+ // src/internal/errors.ts
301
+ import { z as z5 } from "zod";
302
+ function issuePath(path) {
303
+ return path.length > 0 ? path.map(String).join(".") : "(root)";
304
+ }
305
+ function formatZodError(error) {
306
+ const issues = error.issues.slice(0, 5);
307
+ const lines = issues.map((issue) => `${issuePath(issue.path)}: ${issue.message}`);
308
+ const suffix = error.issues.length > 5 ? `
309
+ ...and ${error.issues.length - 5} more issues` : "";
310
+ return lines.join(`
311
+ `) + suffix;
312
+ }
313
+ function zodIssues(error) {
314
+ return error.issues.map((issue) => ({
315
+ path: issuePath(issue.path),
316
+ code: issue.code,
317
+ message: issue.message
318
+ }));
319
+ }
320
+ var MAX_DETAIL_ISSUES = 20;
321
+ function errorCode(err) {
322
+ if (AppError.is(err))
323
+ return err.code;
324
+ if (err instanceof z5.ZodError)
325
+ return "VALIDATION_ERROR";
326
+ return;
327
+ }
328
+ function recordedErrorMessage(code, envelopeMessage, thrown) {
329
+ if ((code === "INTERNAL_SERVER_ERROR" || code === "REALTIME_CONTRACT_VIOLATION") && thrown !== undefined) {
330
+ if (thrown instanceof Error)
331
+ return thrown.message;
332
+ if (typeof thrown === "string")
333
+ return thrown;
334
+ }
335
+ return envelopeMessage;
336
+ }
337
+ function normalizeError(err) {
338
+ if (AppError.is(err)) {
339
+ if (err.code === "REALTIME_CONTRACT_VIOLATION") {
340
+ return new AppError("REALTIME_CONTRACT_VIOLATION", "Realtime contract violation", 500);
341
+ }
342
+ return err;
343
+ }
344
+ if (err instanceof z5.ZodError) {
345
+ return new AppError("VALIDATION_ERROR", formatZodError(err), 400, {
346
+ issues: zodIssues(err).slice(0, MAX_DETAIL_ISSUES)
347
+ });
348
+ }
349
+ console.error("[stitchkit] unhandled error:", err);
350
+ return new AppError("INTERNAL_SERVER_ERROR", "Internal server error", 500);
351
+ }
352
+ function strippedPaths(before, after, prefix) {
353
+ if (Array.isArray(before)) {
354
+ if (!Array.isArray(after))
355
+ return [];
356
+ return before.flatMap((item, i) => strippedPaths(item, after[i], `${prefix}[${i}]`));
357
+ }
358
+ if (!isRecord(before) || !isRecord(after))
359
+ return [];
360
+ const paths = [];
361
+ for (const [key, value] of Object.entries(before)) {
362
+ const path = prefix ? `${prefix}.${key}` : key;
363
+ if (!(key in after)) {
364
+ paths.push(path);
365
+ continue;
366
+ }
367
+ paths.push(...strippedPaths(value, after[key], path));
368
+ }
369
+ return paths;
370
+ }
371
+ function validateHandlerOutput(schema, data, onStripped) {
372
+ const parsed = schema.safeParse(data);
373
+ if (parsed.success) {
374
+ if (onStripped) {
375
+ const paths = strippedPaths(data, parsed.data, "");
376
+ if (paths.length > 0)
377
+ onStripped(paths);
378
+ }
379
+ return { ok: true, data: parsed.data };
380
+ }
381
+ return {
382
+ ok: false,
383
+ message: `Handler output does not match the contract: ${formatZodError(parsed.error)}`
384
+ };
385
+ }
386
+ function validateDeclaredOutput(schema, data, onStripped) {
387
+ if (!schema) {
388
+ if (data === undefined || data === null)
389
+ return { ok: true, data };
390
+ return {
391
+ ok: false,
392
+ message: "Handler returned data but the contract declares no output"
393
+ };
394
+ }
395
+ if (data === undefined) {
396
+ return {
397
+ ok: false,
398
+ message: "Handler returned undefined but the contract declares an output"
399
+ };
400
+ }
401
+ return validateHandlerOutput(schema, data, onStripped);
402
+ }
403
+
404
+ // src/observability/trace.ts
405
+ var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(.*)$/i;
406
+ function randomHex(bytes) {
407
+ const arr = new Uint8Array(bytes);
408
+ crypto.getRandomValues(arr);
409
+ let hex = "";
410
+ for (const byte of arr)
411
+ hex += byte.toString(16).padStart(2, "0");
412
+ return hex;
413
+ }
414
+ function createTraceContext() {
415
+ return { traceId: randomHex(16), spanId: randomHex(8) };
416
+ }
417
+ function parseTraceparent(header) {
418
+ if (!header)
419
+ return null;
420
+ const match = TRACEPARENT_RE.exec(header.trim());
421
+ if (!match?.[1] || !match[2] || !match[3] || !match[4] || match[5] === undefined)
422
+ return null;
423
+ const version = match[1].toLowerCase();
424
+ if (version === "ff")
425
+ return null;
426
+ const suffix = match[5];
427
+ if (version === "00" ? suffix !== "" : suffix !== "" && !/^(?:-[0-9a-f]{2,})+$/i.test(suffix)) {
428
+ return null;
429
+ }
430
+ const traceId = match[2].toLowerCase();
431
+ const parentSpanId = match[3].toLowerCase();
432
+ const traceFlags = match[4].toLowerCase();
433
+ if (/^0+$/.test(traceId) || /^0+$/.test(parentSpanId))
434
+ return null;
435
+ return { traceId, spanId: randomHex(8), parentSpanId, traceFlags };
436
+ }
437
+ function formatTraceparent(ctx) {
438
+ return `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags ?? "01"}`;
439
+ }
440
+ function resolveTraceContext(req) {
441
+ return parseTraceparent(req.headers.get("traceparent")) ?? createTraceContext();
442
+ }
443
+ function childSpan(parent) {
444
+ return {
445
+ traceId: parent.traceId,
446
+ spanId: randomHex(8),
447
+ parentSpanId: parent.spanId,
448
+ ...parent.tracestate !== undefined && { tracestate: parent.tracestate },
449
+ ...parent.baggage !== undefined && { baggage: parent.baggage },
450
+ ...parent.traceFlags !== undefined && { traceFlags: parent.traceFlags }
451
+ };
452
+ }
453
+ var encoder = new TextEncoder;
454
+ function boundedPropagationValue(value, maxBytes, maxMembers) {
455
+ if (typeof value !== "string")
456
+ return;
457
+ const trimmed = value.trim();
458
+ if (!trimmed || encoder.encode(trimmed).byteLength > maxBytes)
459
+ return;
460
+ for (const character of trimmed) {
461
+ const code = character.charCodeAt(0);
462
+ if (code <= 31 || code === 127)
463
+ return;
464
+ }
465
+ const members = trimmed.split(",");
466
+ if (members.length > maxMembers || members.some((member) => !member.trim())) {
467
+ return;
468
+ }
469
+ return trimmed;
470
+ }
471
+ function resolvePropagationContext(metadata, fallback) {
472
+ const traceparent = metadata?.traceparent;
473
+ const parsed = typeof traceparent === "string" ? parseTraceparent(traceparent) : null;
474
+ const trace = traceparent === undefined ? fallback ?? createTraceContext() : parsed ?? createTraceContext();
475
+ const tracestate = parsed ? boundedPropagationValue(metadata?.tracestate, 512, 32) : undefined;
476
+ const baggage = boundedPropagationValue(metadata?.baggage, 8192, 180);
477
+ return {
478
+ ...trace,
479
+ ...tracestate !== undefined && { tracestate },
480
+ ...baggage !== undefined && { baggage }
481
+ };
482
+ }
483
+
484
+ export { joinRoutePath, parseTrailingWildcard, isUnsafeKey, safeJsonParse, defineContract, mergeMeta, bytesToBase64Url, base64UrlToBytes, DEFAULT_CONTRACT_STREAM_FRAME_BYTES, ContractStreamFrameSchema, formatZodError, zodIssues, errorCode, recordedErrorMessage, normalizeError, validateDeclaredOutput, createTraceContext, parseTraceparent, formatTraceparent, resolveTraceContext, childSpan, resolvePropagationContext };
@@ -2,16 +2,16 @@ import {
2
2
  objectShapeKeys
3
3
  } from "./index-6djpbnda.js";
4
4
  import {
5
- formatZodError,
6
5
  getRequestContext,
7
- normalizeError,
8
- runWithRequestContext,
9
- validateDeclaredOutput
10
- } from "./index-tvwcrx2d.js";
6
+ runWithRequestContext
7
+ } from "./index-69m2278y.js";
11
8
  import {
9
+ formatZodError,
12
10
  isUnsafeKey,
13
- safeJsonParse
14
- } from "./index-wd8g8z6e.js";
11
+ normalizeError,
12
+ safeJsonParse,
13
+ validateDeclaredOutput
14
+ } from "./index-9ky9hhg3.js";
15
15
  import {
16
16
  isRecord
17
17
  } from "./index-smpbdg6k.js";
@@ -19,7 +19,7 @@ import {
19
19
  AppError,
20
20
  STITCH_ERROR_STATUS,
21
21
  isStitchErrorCode
22
- } from "./index-xxye8j3k.js";
22
+ } from "./index-0w9abg87.js";
23
23
 
24
24
  // src/tools/coerce.ts
25
25
  import { z } from "zod";
@@ -77,6 +77,8 @@ function defineContract(meta, endpoints) {
77
77
  assertMultipartEndpoint(meta.prefix, key, ep);
78
78
  if (ep.rawResponse)
79
79
  assertRawEndpoint(meta.prefix, key, ep);
80
+ if ("stream" in ep)
81
+ assertStreamingResponseEndpoint(meta.prefix, key, ep);
80
82
  if (ep.method === "HEAD")
81
83
  assertHeadEndpoint(meta.prefix, key, ep);
82
84
  if (ep.rawBody)
@@ -158,6 +160,33 @@ function assertRawEndpoint(prefix, key, ep) {
158
160
  throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
159
161
  }
160
162
  }
163
+ function assertStreamingResponseEndpoint(prefix, key, ep) {
164
+ const where = `Contract "${prefix}": streaming endpoint "${key}"`;
165
+ if (!("stream" in ep) || !ep.stream || typeof ep.stream !== "object") {
166
+ throw new Error(`${where} must declare a stream descriptor`);
167
+ }
168
+ if (!ep.stream.item || typeof ep.stream.item.parse !== "function") {
169
+ throw new Error(`${where} must declare an item schema`);
170
+ }
171
+ assertPositiveLimit(where, "maxFrameBytes", ep.stream.maxFrameBytes);
172
+ assertPositiveLimit(where, "lifetimeMs", ep.stream.lifetimeMs);
173
+ assertPositiveLimit(where, "heartbeatMs", ep.stream.heartbeatMs);
174
+ if (ep.stream.idleTimeoutSeconds !== undefined && (!Number.isSafeInteger(ep.stream.idleTimeoutSeconds) || ep.stream.idleTimeoutSeconds < 0)) {
175
+ throw new Error(`${where} idleTimeoutSeconds must be a non-negative safe integer`);
176
+ }
177
+ if (ep.output)
178
+ throw new Error(`${where} cannot declare an output schema`);
179
+ if (ep.rawResponse)
180
+ throw new Error(`${where} cannot also be rawResponse`);
181
+ if (ep.multipart)
182
+ throw new Error(`${where} cannot be multipart`);
183
+ if ("toolName" in ep && ep.toolName)
184
+ throw new Error(`${where} cannot set a toolName`);
185
+ const nonHttp = (ep.expose ?? []).filter((transport) => transport !== "HTTP");
186
+ if (nonHttp.length > 0) {
187
+ throw new Error(`${where} is HTTP-only — remove ${nonHttp.join(", ")} from expose`);
188
+ }
189
+ }
161
190
  function assertHeadEndpoint(prefix, key, ep) {
162
191
  const where = `Contract "${prefix}": HEAD endpoint "${key}"`;
163
192
  if (!ep.rawResponse)
@@ -291,6 +320,10 @@ var STITCH_ERROR_STATUS = {
291
320
  DOWNLOAD_NOT_FOUND: 404,
292
321
  VIEW_HTTP_ERROR: 502,
293
322
  OPERATION_NOT_SUCCEEDED: 409,
323
+ STREAM_ITEM_INVALID: 500,
324
+ STREAM_FRAME_TOO_LARGE: 500,
325
+ STREAM_TERMINAL_MISSING: 500,
326
+ STREAM_LIFETIME_EXCEEDED: 408,
294
327
  INTERNAL_SERVER_ERROR: 500
295
328
  };
296
329
  function isStitchErrorCode(code) {
@@ -427,4 +460,20 @@ function decodeCursor(cursor, schema) {
427
460
  return null;
428
461
  }
429
462
  }
430
- export { parseTrailingWildcard, ALL_TRANSPORTS, defineContract, AppError, notFound, badRequest, unauthorized, forbidden, conflict, rateLimited, STITCH_ERROR_STATUS, isStitchErrorCode, appError, defineErrors, createContractFactory, ManagedFilePathSchema, ManagedFileRefSchema, paginatedSchema, encodeCursor, decodeCursor };
463
+ // src/contract/stream.ts
464
+ import { z as z5 } from "zod";
465
+ var DEFAULT_CONTRACT_STREAM_FRAME_BYTES = 256 * 1024;
466
+ var ContractStreamFrameSchema = z5.discriminatedUnion("type", [
467
+ z5.object({ type: z5.literal("data"), data: z5.unknown() }).strict(),
468
+ z5.object({
469
+ type: z5.literal("error"),
470
+ error: z5.object({
471
+ code: z5.string(),
472
+ message: z5.string().optional(),
473
+ details: z5.unknown().optional(),
474
+ hint: z5.string().optional()
475
+ }).strict()
476
+ }).strict(),
477
+ z5.object({ type: z5.literal("end") }).strict()
478
+ ]);
479
+ export { parseTrailingWildcard, ALL_TRANSPORTS, defineContract, AppError, notFound, badRequest, unauthorized, forbidden, conflict, rateLimited, STITCH_ERROR_STATUS, isStitchErrorCode, appError, defineErrors, createContractFactory, ManagedFilePathSchema, ManagedFileRefSchema, paginatedSchema, encodeCursor, decodeCursor, DEFAULT_CONTRACT_STREAM_FRAME_BYTES, ContractStreamFrameSchema };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isUnsafeKey
3
- } from "./index-wd8g8z6e.js";
3
+ } from "./index-9ky9hhg3.js";
4
4
  import {
5
5
  isRecord
6
6
  } from "./index-smpbdg6k.js";