@genkit-ai/fetch 0.1.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/README.md +182 -0
- package/lib/index.d.mts +65 -0
- package/lib/index.d.ts +65 -0
- package/lib/index.js +353 -0
- package/lib/index.js.map +1 -0
- package/lib/index.mjs +333 -0
- package/lib/index.mjs.map +1 -0
- package/lib/utils.d.mts +25 -0
- package/lib/utils.d.ts +25 -0
- package/lib/utils.js +42 -0
- package/lib/utils.js.map +1 -0
- package/lib/utils.mjs +17 -0
- package/lib/utils.mjs.map +1 -0
- package/package.json +59 -0
- package/src/index.ts +526 -0
- package/src/utils.ts +33 -0
- package/tests/web_test.ts +802 -0
- package/typedoc.json +3 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2025 Google LLC
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
Action,
|
|
19
|
+
ActionStreamInput,
|
|
20
|
+
AsyncTaskQueue,
|
|
21
|
+
StreamNotFoundError,
|
|
22
|
+
type ActionContext,
|
|
23
|
+
type StreamManager,
|
|
24
|
+
type z,
|
|
25
|
+
} from 'genkit/beta';
|
|
26
|
+
import {
|
|
27
|
+
getCallableJSON,
|
|
28
|
+
getHttpStatus,
|
|
29
|
+
type ContextProvider,
|
|
30
|
+
type RequestData,
|
|
31
|
+
} from 'genkit/context';
|
|
32
|
+
import { logger } from 'genkit/logging';
|
|
33
|
+
import { getErrorMessage, getErrorStack } from './utils.js';
|
|
34
|
+
|
|
35
|
+
const streamDelimiter = '\n\n';
|
|
36
|
+
|
|
37
|
+
// Let the runtime provide the randomUUID function.
|
|
38
|
+
const randomUUID = () => globalThis.crypto.randomUUID();
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A wrapper object containing an action with its associated options.
|
|
42
|
+
*/
|
|
43
|
+
export type ActionWithOptions<
|
|
44
|
+
I extends z.ZodTypeAny = z.ZodTypeAny,
|
|
45
|
+
O extends z.ZodTypeAny = z.ZodTypeAny,
|
|
46
|
+
S extends z.ZodTypeAny = z.ZodTypeAny,
|
|
47
|
+
> = {
|
|
48
|
+
action: Action<I, O, S>;
|
|
49
|
+
options: {
|
|
50
|
+
contextProvider?: ContextProvider<any, I>;
|
|
51
|
+
streamManager?: StreamManager;
|
|
52
|
+
path?: string;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Options for a fetch handler (context provider, stream manager).
|
|
58
|
+
*/
|
|
59
|
+
export interface FetchHandlerOptions<
|
|
60
|
+
C extends ActionContext = ActionContext,
|
|
61
|
+
I extends z.ZodTypeAny = z.ZodTypeAny,
|
|
62
|
+
> {
|
|
63
|
+
contextProvider?: ContextProvider<C, I>;
|
|
64
|
+
streamManager?: StreamManager;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Wraps an action (flow, model, etc.) with options for use with {@link fetchHandlers}.
|
|
69
|
+
*/
|
|
70
|
+
export function withActionOptions<
|
|
71
|
+
I extends z.ZodTypeAny,
|
|
72
|
+
O extends z.ZodTypeAny,
|
|
73
|
+
S extends z.ZodTypeAny,
|
|
74
|
+
>(
|
|
75
|
+
action: Action<I, O, S>,
|
|
76
|
+
options: {
|
|
77
|
+
contextProvider?: ContextProvider<any, I>;
|
|
78
|
+
streamManager?: StreamManager;
|
|
79
|
+
path?: string;
|
|
80
|
+
}
|
|
81
|
+
): ActionWithOptions<I, O, S> {
|
|
82
|
+
return {
|
|
83
|
+
action,
|
|
84
|
+
options,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Converts Headers object to a plain object with lowercase keys.
|
|
90
|
+
*/
|
|
91
|
+
function headersToObject(headers: Headers): Record<string, string> {
|
|
92
|
+
const result: Record<string, string> = {};
|
|
93
|
+
headers.forEach((value, key) => {
|
|
94
|
+
result[key.toLowerCase()] = value;
|
|
95
|
+
});
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Gets context from the request using the context provider if available.
|
|
101
|
+
*/
|
|
102
|
+
async function getContext<C extends ActionContext, I extends z.ZodTypeAny>(
|
|
103
|
+
request: Request,
|
|
104
|
+
input: z.infer<I>,
|
|
105
|
+
provider?: ContextProvider<C, I>
|
|
106
|
+
): Promise<C> {
|
|
107
|
+
const context = {} as C;
|
|
108
|
+
if (!provider) {
|
|
109
|
+
return context;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const requestData: RequestData = {
|
|
113
|
+
method: request.method as RequestData['method'],
|
|
114
|
+
headers: headersToObject(request.headers),
|
|
115
|
+
input,
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
return await provider(requestData);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Subscribes to an existing stream using StreamManager.
|
|
123
|
+
*/
|
|
124
|
+
async function subscribeToStream(
|
|
125
|
+
streamManager: StreamManager,
|
|
126
|
+
streamId: string
|
|
127
|
+
): Promise<Response | null> {
|
|
128
|
+
try {
|
|
129
|
+
const encoder = new TextEncoder();
|
|
130
|
+
const { readable, writable } = new TransformStream();
|
|
131
|
+
const writer = writable.getWriter();
|
|
132
|
+
|
|
133
|
+
await streamManager.subscribe(streamId, {
|
|
134
|
+
onChunk: (chunk) => {
|
|
135
|
+
writer.write(
|
|
136
|
+
encoder.encode(
|
|
137
|
+
'data: ' + JSON.stringify({ message: chunk }) + streamDelimiter
|
|
138
|
+
)
|
|
139
|
+
);
|
|
140
|
+
},
|
|
141
|
+
onDone: (output) => {
|
|
142
|
+
writer.write(
|
|
143
|
+
encoder.encode(
|
|
144
|
+
'data: ' + JSON.stringify({ result: output }) + streamDelimiter
|
|
145
|
+
)
|
|
146
|
+
);
|
|
147
|
+
writer.close();
|
|
148
|
+
},
|
|
149
|
+
onError: (err) => {
|
|
150
|
+
logger.error(
|
|
151
|
+
`Streaming request failed with error: ${getErrorMessage(err)}\n${getErrorStack(err)}`
|
|
152
|
+
);
|
|
153
|
+
writer.write(
|
|
154
|
+
encoder.encode(
|
|
155
|
+
`error: ${JSON.stringify({
|
|
156
|
+
error: getCallableJSON(err),
|
|
157
|
+
})}${streamDelimiter}`
|
|
158
|
+
)
|
|
159
|
+
);
|
|
160
|
+
writer.close();
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
return new Response(readable, {
|
|
165
|
+
status: 200,
|
|
166
|
+
headers: {
|
|
167
|
+
'Content-Type': 'text/event-stream',
|
|
168
|
+
'Cache-Control': 'no-cache',
|
|
169
|
+
Connection: 'keep-alive',
|
|
170
|
+
'Transfer-Encoding': 'chunked',
|
|
171
|
+
'x-genkit-stream-id': streamId,
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
} catch (e: any) {
|
|
175
|
+
if (e instanceof StreamNotFoundError) {
|
|
176
|
+
return new Response(null, { status: 204 });
|
|
177
|
+
}
|
|
178
|
+
if (e.status === 'DEADLINE_EXCEEDED') {
|
|
179
|
+
const encoder = new TextEncoder();
|
|
180
|
+
const { readable, writable } = new TransformStream();
|
|
181
|
+
const writer = writable.getWriter();
|
|
182
|
+
writer.write(
|
|
183
|
+
encoder.encode(
|
|
184
|
+
`error: ${JSON.stringify({
|
|
185
|
+
error: getCallableJSON(e),
|
|
186
|
+
})}${streamDelimiter}`
|
|
187
|
+
)
|
|
188
|
+
);
|
|
189
|
+
writer.close();
|
|
190
|
+
return new Response(readable, {
|
|
191
|
+
status: 200,
|
|
192
|
+
headers: {
|
|
193
|
+
'Content-Type': 'text/event-stream',
|
|
194
|
+
'Cache-Control': 'no-cache',
|
|
195
|
+
Connection: 'keep-alive',
|
|
196
|
+
'Transfer-Encoding': 'chunked',
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
throw e;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Runs an action with durable streaming support.
|
|
206
|
+
*/
|
|
207
|
+
async function runActionWithDurableStreaming<
|
|
208
|
+
I extends z.ZodTypeAny,
|
|
209
|
+
O extends z.ZodTypeAny,
|
|
210
|
+
S extends z.ZodTypeAny,
|
|
211
|
+
>(
|
|
212
|
+
action: Action<I, O, S>,
|
|
213
|
+
streamManager: StreamManager | undefined,
|
|
214
|
+
streamId: string,
|
|
215
|
+
input: z.infer<I>,
|
|
216
|
+
context: ActionContext,
|
|
217
|
+
writer: WritableStreamDefaultWriter<Uint8Array>,
|
|
218
|
+
abortSignal: AbortSignal
|
|
219
|
+
): Promise<void> {
|
|
220
|
+
const encoder = new TextEncoder();
|
|
221
|
+
let taskQueue: AsyncTaskQueue | undefined;
|
|
222
|
+
let durableStream: ActionStreamInput<any, any> | undefined;
|
|
223
|
+
|
|
224
|
+
if (streamManager) {
|
|
225
|
+
taskQueue = new AsyncTaskQueue();
|
|
226
|
+
durableStream = await streamManager.open(streamId);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
let onChunk = (chunk: z.infer<S>) => {
|
|
231
|
+
writer.write(
|
|
232
|
+
encoder.encode(
|
|
233
|
+
'data: ' + JSON.stringify({ message: chunk }) + streamDelimiter
|
|
234
|
+
)
|
|
235
|
+
);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
if (streamManager && durableStream) {
|
|
239
|
+
const originalOnChunk = onChunk;
|
|
240
|
+
onChunk = (chunk: z.infer<S>) => {
|
|
241
|
+
originalOnChunk(chunk);
|
|
242
|
+
taskQueue!.enqueue(() => durableStream!.write(chunk));
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const result = await action.run(input, {
|
|
247
|
+
onChunk,
|
|
248
|
+
context,
|
|
249
|
+
abortSignal,
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
if (streamManager && durableStream) {
|
|
253
|
+
taskQueue!.enqueue(() => durableStream!.done(result.result));
|
|
254
|
+
await taskQueue!.merge();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
writer.write(
|
|
258
|
+
encoder.encode(
|
|
259
|
+
'data: ' + JSON.stringify({ result: result.result }) + streamDelimiter
|
|
260
|
+
)
|
|
261
|
+
);
|
|
262
|
+
writer.close();
|
|
263
|
+
} catch (e) {
|
|
264
|
+
if (durableStream) {
|
|
265
|
+
taskQueue!.enqueue(() => durableStream!.error(e));
|
|
266
|
+
await taskQueue!.merge();
|
|
267
|
+
}
|
|
268
|
+
logger.error(
|
|
269
|
+
`Streaming request failed with error: ${(e as Error).message}\n${
|
|
270
|
+
(e as Error).stack
|
|
271
|
+
}`
|
|
272
|
+
);
|
|
273
|
+
writer.write(
|
|
274
|
+
encoder.encode(
|
|
275
|
+
`error: ${JSON.stringify({
|
|
276
|
+
error: getCallableJSON(e),
|
|
277
|
+
})}${streamDelimiter}`
|
|
278
|
+
)
|
|
279
|
+
);
|
|
280
|
+
writer.close();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Returns a Fetch handler for a single action (flow, model, or any Genkit action).
|
|
286
|
+
* Express-like API: pass the action first, then call the returned handler with the request.
|
|
287
|
+
*
|
|
288
|
+
* @param action - The Genkit action to execute (flow, model, etc.)
|
|
289
|
+
* @param options - Optional configuration including contextProvider and streamManager
|
|
290
|
+
* @returns A handler function that takes a Request and returns a Promise<Response>
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```typescript
|
|
294
|
+
* import { fetchHandler } from '@genkit-ai/fetch';
|
|
295
|
+
*
|
|
296
|
+
* // Flow or model
|
|
297
|
+
* app.post('/myFlow', (c) => fetchHandler(myFlow)(c.req.raw));
|
|
298
|
+
* app.post('/models/gpt5', (c) => fetchHandler(gpt5)(c.req.raw));
|
|
299
|
+
*
|
|
300
|
+
* // With options
|
|
301
|
+
* app.post('/secure', (c) => fetchHandler(secureFlow, { contextProvider })(c.req.raw));
|
|
302
|
+
* ```
|
|
303
|
+
*/
|
|
304
|
+
async function handleActionRequest<
|
|
305
|
+
C extends ActionContext = ActionContext,
|
|
306
|
+
I extends z.ZodTypeAny = z.ZodTypeAny,
|
|
307
|
+
O extends z.ZodTypeAny = z.ZodTypeAny,
|
|
308
|
+
S extends z.ZodTypeAny = z.ZodTypeAny,
|
|
309
|
+
>(
|
|
310
|
+
request: Request,
|
|
311
|
+
action: Action<I, O, S>,
|
|
312
|
+
options?: FetchHandlerOptions<C, I>
|
|
313
|
+
): Promise<Response> {
|
|
314
|
+
const url = new URL(request.url);
|
|
315
|
+
const streamParam = url.searchParams.get('stream');
|
|
316
|
+
const shouldStream = streamParam === 'true';
|
|
317
|
+
|
|
318
|
+
const streamIdHeader = request.headers.get('x-genkit-stream-id');
|
|
319
|
+
const streamId = streamIdHeader || undefined;
|
|
320
|
+
|
|
321
|
+
let body: any;
|
|
322
|
+
try {
|
|
323
|
+
body = await request.json();
|
|
324
|
+
} catch (e) {
|
|
325
|
+
const errMsg =
|
|
326
|
+
`Error: Failed to parse request body as JSON. ` +
|
|
327
|
+
`Make sure the request has 'Content-Type: application/json' header.`;
|
|
328
|
+
logger.error(errMsg);
|
|
329
|
+
return new Response(
|
|
330
|
+
JSON.stringify({ message: errMsg, status: 'INVALID_ARGUMENT' }),
|
|
331
|
+
{ status: 400, headers: { 'Content-Type': 'application/json' } }
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (!body || typeof body !== 'object' || !('data' in body)) {
|
|
336
|
+
const errMsg =
|
|
337
|
+
`Error: Request body must be a JSON object with a 'data' field. ` +
|
|
338
|
+
`Expected format: {"data": ...}`;
|
|
339
|
+
logger.error(errMsg);
|
|
340
|
+
return new Response(
|
|
341
|
+
JSON.stringify({ message: errMsg, status: 'INVALID_ARGUMENT' }),
|
|
342
|
+
{ status: 400, headers: { 'Content-Type': 'application/json' } }
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const input = body.data as z.infer<I>;
|
|
347
|
+
|
|
348
|
+
let context: C;
|
|
349
|
+
try {
|
|
350
|
+
context = await getContext(request, input, options?.contextProvider);
|
|
351
|
+
} catch (e: any) {
|
|
352
|
+
logger.error(
|
|
353
|
+
`Context provider failed with error: ${(e as Error).message}\n${
|
|
354
|
+
(e as Error).stack
|
|
355
|
+
}`
|
|
356
|
+
);
|
|
357
|
+
return new Response(JSON.stringify(getCallableJSON(e)), {
|
|
358
|
+
status: getHttpStatus(e),
|
|
359
|
+
headers: { 'Content-Type': 'application/json' },
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const acceptHeader = request.headers.get('Accept') || '';
|
|
364
|
+
const isStreaming = acceptHeader === 'text/event-stream' || shouldStream;
|
|
365
|
+
|
|
366
|
+
if (isStreaming) {
|
|
367
|
+
const streamManager = options?.streamManager;
|
|
368
|
+
if (streamManager && streamId) {
|
|
369
|
+
const response = await subscribeToStream(streamManager, streamId);
|
|
370
|
+
if (response) {
|
|
371
|
+
return response;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const streamIdToUse = randomUUID();
|
|
376
|
+
const { readable, writable } = new TransformStream();
|
|
377
|
+
const writer = writable.getWriter();
|
|
378
|
+
|
|
379
|
+
runActionWithDurableStreaming(
|
|
380
|
+
action,
|
|
381
|
+
options?.streamManager,
|
|
382
|
+
streamIdToUse,
|
|
383
|
+
input,
|
|
384
|
+
context,
|
|
385
|
+
writer,
|
|
386
|
+
request.signal
|
|
387
|
+
).catch((err) => {
|
|
388
|
+
logger.error(`Error in streaming handler: ${err}`);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
const headers: Record<string, string> = {
|
|
392
|
+
'Content-Type': 'text/event-stream',
|
|
393
|
+
'Cache-Control': 'no-cache',
|
|
394
|
+
Connection: 'keep-alive',
|
|
395
|
+
'Transfer-Encoding': 'chunked',
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
if (options?.streamManager) {
|
|
399
|
+
headers['x-genkit-stream-id'] = streamIdToUse;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return new Response(readable, {
|
|
403
|
+
status: 200,
|
|
404
|
+
headers,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
try {
|
|
409
|
+
const result = await action.run(input, {
|
|
410
|
+
context,
|
|
411
|
+
abortSignal: request.signal,
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
const headers: Record<string, string> = {
|
|
415
|
+
'x-genkit-trace-id': result.telemetry.traceId,
|
|
416
|
+
'x-genkit-span-id': result.telemetry.spanId,
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
return new Response(JSON.stringify({ result: result.result }), {
|
|
420
|
+
status: 200,
|
|
421
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
422
|
+
});
|
|
423
|
+
} catch (e) {
|
|
424
|
+
logger.error(
|
|
425
|
+
`Non-streaming request failed with error: ${(e as Error).message}\n${
|
|
426
|
+
(e as Error).stack
|
|
427
|
+
}`
|
|
428
|
+
);
|
|
429
|
+
return new Response(JSON.stringify(getCallableJSON(e)), {
|
|
430
|
+
status: getHttpStatus(e),
|
|
431
|
+
headers: { 'Content-Type': 'application/json' },
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export function fetchHandler<
|
|
437
|
+
C extends ActionContext = ActionContext,
|
|
438
|
+
I extends z.ZodTypeAny = z.ZodTypeAny,
|
|
439
|
+
O extends z.ZodTypeAny = z.ZodTypeAny,
|
|
440
|
+
S extends z.ZodTypeAny = z.ZodTypeAny,
|
|
441
|
+
>(
|
|
442
|
+
action: Action<I, O, S>,
|
|
443
|
+
options?: FetchHandlerOptions<C, I>
|
|
444
|
+
): (request: Request) => Promise<Response> {
|
|
445
|
+
return (request: Request) => handleActionRequest(request, action, options);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Returns a Fetch handler for multiple actions with path-based routing.
|
|
450
|
+
* Express-like API: pass actions and optional path prefix, then call the returned handler with the request.
|
|
451
|
+
*
|
|
452
|
+
* @param actions - Array of actions (or ActionWithOptions) to expose; each is routed by path (action name or options.path)
|
|
453
|
+
* @param pathPrefix - Optional path prefix to strip from the URL (e.g., '/api')
|
|
454
|
+
* @returns A handler function that takes a Request and returns a Promise<Response>
|
|
455
|
+
*
|
|
456
|
+
* @example
|
|
457
|
+
* ```typescript
|
|
458
|
+
* import { fetchHandlers } from '@genkit-ai/fetch';
|
|
459
|
+
*
|
|
460
|
+
* // Mount all actions under /api - routes by path (e.g. POST /api/hello, POST /api/models/gpt5)
|
|
461
|
+
* app.all('/api/*', (c) => fetchHandlers(actions, '/api')(c.req.raw));
|
|
462
|
+
* ```
|
|
463
|
+
*/
|
|
464
|
+
export function fetchHandlers(
|
|
465
|
+
actions: (Action<any, any, any> | ActionWithOptions<any, any, any>)[],
|
|
466
|
+
pathPrefix?: string
|
|
467
|
+
): (request: Request) => Promise<Response> {
|
|
468
|
+
return async (request: Request): Promise<Response> => {
|
|
469
|
+
const url = new URL(request.url);
|
|
470
|
+
let pathname = url.pathname;
|
|
471
|
+
|
|
472
|
+
if (pathPrefix) {
|
|
473
|
+
const prefix = pathPrefix.endsWith('/') ? pathPrefix : pathPrefix + '/';
|
|
474
|
+
if (pathname === pathPrefix) {
|
|
475
|
+
pathname = '';
|
|
476
|
+
} else if (pathname.startsWith(prefix)) {
|
|
477
|
+
pathname = pathname.slice(prefix.length);
|
|
478
|
+
} else {
|
|
479
|
+
return new Response(
|
|
480
|
+
JSON.stringify({
|
|
481
|
+
status: 'NOT_FOUND',
|
|
482
|
+
message: 'No action matched the request path.',
|
|
483
|
+
}),
|
|
484
|
+
{ status: 404, headers: { 'Content-Type': 'application/json' } }
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
pathname = pathname.replace(/^\//, '');
|
|
490
|
+
|
|
491
|
+
let matchedAction: Action<any, any, any> | null = null;
|
|
492
|
+
let handlerOptions: FetchHandlerOptions<any, any> | undefined = undefined;
|
|
493
|
+
|
|
494
|
+
for (const item of actions) {
|
|
495
|
+
if ('action' in item) {
|
|
496
|
+
const options = item.options;
|
|
497
|
+
const actionPath = options.path ?? item.action.__action.name;
|
|
498
|
+
if (pathname === actionPath) {
|
|
499
|
+
matchedAction = item.action;
|
|
500
|
+
handlerOptions = {
|
|
501
|
+
contextProvider: options.contextProvider,
|
|
502
|
+
streamManager: options.streamManager,
|
|
503
|
+
};
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
} else {
|
|
507
|
+
if (pathname === item.__action.name) {
|
|
508
|
+
matchedAction = item;
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
if (!matchedAction) {
|
|
515
|
+
return new Response(
|
|
516
|
+
JSON.stringify({
|
|
517
|
+
status: 'NOT_FOUND',
|
|
518
|
+
message: 'No action matched the request path.',
|
|
519
|
+
}),
|
|
520
|
+
{ status: 404, headers: { 'Content-Type': 'application/json' } }
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
return handleActionRequest(request, matchedAction, handlerOptions);
|
|
525
|
+
};
|
|
526
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2025 Google LLC
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Extracts error message from the given error object, or if input is not an error then just turn the error into a string.
|
|
18
|
+
*/
|
|
19
|
+
export function getErrorMessage(e: any): string {
|
|
20
|
+
if (e instanceof Error) {
|
|
21
|
+
return e.message;
|
|
22
|
+
}
|
|
23
|
+
return `${e}`;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Extracts stack trace from the given error object, or if input is not an error then returns undefined.
|
|
27
|
+
*/
|
|
28
|
+
export function getErrorStack(e: any): string | undefined {
|
|
29
|
+
if (e instanceof Error) {
|
|
30
|
+
return e.stack;
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|