@kaito-http/core 3.0.1 → 3.0.2

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,156 +0,0 @@
1
- export class KaitoSSEResponse<_T> extends Response {
2
- constructor(body: ReadableStream<string>, init?: ResponseInit) {
3
- const headers = new Headers(init?.headers);
4
-
5
- headers.set('Content-Type', 'text/event-stream');
6
- headers.set('Cache-Control', 'no-cache');
7
- headers.set('Connection', 'keep-alive');
8
-
9
- super(body, {
10
- ...init,
11
- headers,
12
- });
13
- }
14
-
15
- async *[Symbol.asyncIterator]() {
16
- for await (const chunk of this.body!) {
17
- yield chunk;
18
- }
19
- }
20
- }
21
-
22
- export type SSEEvent<T, E extends string> = (
23
- | {
24
- data: T;
25
- event?: E | undefined;
26
- }
27
- | {
28
- data?: T | undefined;
29
- event: E;
30
- }
31
- ) & {
32
- retry?: number;
33
- id?: string;
34
- };
35
-
36
- /**
37
- * Converts an SSE Event into a string, ready for sending to the client
38
- * @param event The SSE Event
39
- * @returns A stringified version
40
- */
41
- export function sseEventToString(event: SSEEvent<unknown, string>): string {
42
- let result = '';
43
-
44
- if (event.event) {
45
- result += `event:${event.event}\n`;
46
- }
47
-
48
- if (event.id) {
49
- result += `id:${event.id}\n`;
50
- }
51
-
52
- if (event.retry) {
53
- result += `retry:${event.retry}\n`;
54
- }
55
-
56
- if (event.data !== undefined) {
57
- result += `data:${JSON.stringify(event.data)}`;
58
- }
59
-
60
- return result;
61
- }
62
-
63
- export class SSEController<U, E extends string> implements Disposable {
64
- private readonly controller: ReadableStreamDefaultController<string>;
65
-
66
- public constructor(controller: ReadableStreamDefaultController<string>) {
67
- this.controller = controller;
68
- }
69
-
70
- public enqueue(event: SSEEvent<U, E>): void {
71
- this.controller.enqueue(sseEventToString(event) + '\n\n');
72
- }
73
-
74
- public close(): void {
75
- this.controller.close();
76
- }
77
-
78
- [Symbol.dispose](): void {
79
- this.close();
80
- }
81
- }
82
-
83
- export interface SSESource<U, E extends string> {
84
- cancel?: UnderlyingSourceCancelCallback;
85
- start?(controller: SSEController<U, E>): Promise<void>;
86
- pull?(controller: SSEController<U, E>): Promise<void>;
87
- }
88
-
89
- function sseFromSource<U, E extends string>(source: SSESource<U, E>) {
90
- const start = source.start;
91
- const pull = source.pull;
92
- const cancel = source.cancel;
93
-
94
- const readable = new ReadableStream<string>({
95
- ...(cancel ? {cancel} : {}),
96
-
97
- ...(start
98
- ? {
99
- start: async controller => {
100
- await start(new SSEController<U, E>(controller));
101
- },
102
- }
103
- : {}),
104
-
105
- ...(pull
106
- ? {
107
- pull: async controller => {
108
- await pull(new SSEController<U, E>(controller));
109
- },
110
- }
111
- : {}),
112
- });
113
-
114
- return new KaitoSSEResponse<SSEEvent<U, E>>(readable);
115
- }
116
-
117
- export function sse<U, E extends string, T extends SSEEvent<U, E>>(
118
- source: SSESource<U, E> | AsyncGenerator<T, unknown, unknown> | (() => AsyncGenerator<T, unknown, unknown>),
119
- ): KaitoSSEResponse<T> {
120
- const evaluated = typeof source === 'function' ? source() : source;
121
-
122
- if ('next' in evaluated) {
123
- const generator = evaluated;
124
- return sseFromSource<U, E>({
125
- async start(controller) {
126
- // TODO: use `using` once Node.js supports it
127
- // // ensures close is called on controller when we're done
128
- // using c = controller;
129
- try {
130
- for await (const event of generator) {
131
- controller.enqueue(event);
132
- }
133
- } finally {
134
- controller.close();
135
- }
136
- },
137
- });
138
- } else {
139
- // if the SSESource interface is used only strings are permitted.
140
- // serialization / deserialization for objects is left to the user
141
- return sseFromSource<U, E>(evaluated);
142
- }
143
- }
144
-
145
- export function sseFromAnyReadable<R, U, E extends string>(
146
- stream: ReadableStream<R>,
147
- transform: (chunk: R) => SSEEvent<U, E>,
148
- ): KaitoSSEResponse<SSEEvent<U, E>> {
149
- const transformer = new TransformStream({
150
- transform: (chunk, controller) => {
151
- controller.enqueue(transform(chunk));
152
- },
153
- });
154
-
155
- return sse(stream.pipeThrough(transformer));
156
- }
package/src/util.ts DELETED
@@ -1,83 +0,0 @@
1
- import type {KaitoHead} from './head.ts';
2
- import type {KaitoRequest} from './request.ts';
3
- import {Router} from './router/router.ts';
4
-
5
- /**
6
- * A helper to check if the environment is Node.js-like and the NODE_ENV is development
7
- */
8
- export const isNodeLikeDev =
9
- typeof process !== 'undefined' && typeof process.env !== 'undefined' && process.env.NODE_ENV === 'development';
10
-
11
- export type ErroredAPIResponse = {success: false; data: null; message: string};
12
- export type SuccessfulAPIResponse<T> = {success: true; data: T; message: 'OK'};
13
- export type APIResponse<T> = ErroredAPIResponse | SuccessfulAPIResponse<T>;
14
- export type AnyResponse = APIResponse<unknown>;
15
- export type MakeOptional<T, K extends keyof T> = T extends T ? Omit<T, K> & Partial<Pick<T, K>> : never;
16
-
17
- export type ExtractRouteParams<T extends string> = string extends T
18
- ? Record<string, string>
19
- : T extends `${string}:${infer Param}/${infer Rest}`
20
- ? {[k in Param | keyof ExtractRouteParams<Rest>]: string}
21
- : T extends `${string}:${infer Param}`
22
- ? {[k in Param]: string}
23
- : {};
24
-
25
- /**
26
- * A function that is called to get the context for a request.
27
- *
28
- * This is useful for things like authentication, to pass in a database connection, etc.
29
- *
30
- * It's fine for this function to throw; if it does, the error is passed to the `onError` function.
31
- *
32
- * @param req - The kaito request object, which contains the request method, url, headers, etc
33
- * @param head - The kaito head object, which contains getters and setters for headers and status
34
- * @returns The context for your routes
35
- */
36
- export type GetContext<Result> = (req: KaitoRequest, head: KaitoHead) => Promise<Result>;
37
-
38
- /**
39
- * A helper function to create typed necessary functions
40
- *
41
- * @example
42
- * ```ts
43
- * const {router, getContext} = createUtilities(async (req, res) => {
44
- * // Return context here
45
- * })
46
- *
47
- * const app = router().get('/', async () => "hello");
48
- *
49
- * const server = createKaitoHandler({
50
- * router: app,
51
- * getContext,
52
- * // ...
53
- * });
54
- * ```
55
- */
56
- export function createUtilities<Context>(getContext: GetContext<Context>): {
57
- getContext: GetContext<Context>;
58
- router: () => Router<Context, Context, never>;
59
- } {
60
- return {
61
- getContext,
62
- router: () => Router.create<Context>(),
63
- };
64
- }
65
-
66
- export interface Parsable<Output = any, Input = Output> {
67
- _input: Input;
68
- parse: (value: unknown) => Output;
69
- }
70
-
71
- export type InferParsable<T> =
72
- T extends Parsable<infer Output, infer Input>
73
- ? {
74
- input: Input;
75
- output: Output;
76
- }
77
- : never;
78
-
79
- export function parsable<T>(parse: (value: unknown) => T): Parsable<T, T> {
80
- return {
81
- parse,
82
- } as Parsable<T, T>;
83
- }