milkio 0.8.2 → 1.0.0-alpha.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 (47) hide show
  1. package/action/index.ts +19 -0
  2. package/command/index.ts +53 -0
  3. package/context/index.ts +18 -0
  4. package/exception/index.ts +45 -0
  5. package/execute/execute-id-generator.ts +7 -0
  6. package/execute/index.ts +160 -0
  7. package/index.ts +11 -36
  8. package/listener/index.ts +199 -0
  9. package/logger/index.ts +67 -0
  10. package/meta/index.ts +12 -0
  11. package/middleware/index.ts +19 -0
  12. package/package.json +9 -13
  13. package/stream/index.ts +19 -0
  14. package/test/index.ts +21 -0
  15. package/types/index.ts +74 -0
  16. package/utils/create-id.ts +3 -0
  17. package/world/index.ts +65 -0
  18. package/api-test/index.ts +0 -122
  19. package/c.ts +0 -50
  20. package/defines/define-api-test.ts +0 -69
  21. package/defines/define-api.ts +0 -11
  22. package/defines/define-command-handler.ts +0 -47
  23. package/defines/define-config.ts +0 -32
  24. package/defines/define-http-handler.ts +0 -291
  25. package/defines/define-middleware.ts +0 -9
  26. package/defines/define-use.ts +0 -12
  27. package/kernel/context.ts +0 -55
  28. package/kernel/execute.ts +0 -194
  29. package/kernel/fail.ts +0 -20
  30. package/kernel/logger.ts +0 -131
  31. package/kernel/meta.ts +0 -9
  32. package/kernel/middleware.ts +0 -51
  33. package/kernel/milkio.ts +0 -87
  34. package/kernel/runtime.ts +0 -11
  35. package/kernel/validate.ts +0 -16
  36. package/scripts/gen-insignificant.ts +0 -258
  37. package/scripts/gen-significant.ts +0 -186
  38. package/types.ts +0 -101
  39. package/utils/create-ulid.ts +0 -5
  40. package/utils/env-to-boolean.ts +0 -11
  41. package/utils/env-to-number.ts +0 -5
  42. package/utils/env-to-string.ts +0 -5
  43. package/utils/exec.ts +0 -26
  44. package/utils/handle-catch-error.ts +0 -52
  45. package/utils/header-to-plain-object.ts +0 -8
  46. package/utils/remove-dir.ts +0 -22
  47. package/utils/tson.ts +0 -3
@@ -1,291 +0,0 @@
1
- import { loggerPushTags, loggerSubmit, useLogger, runtime, MiddlewareEvent, reject } from "..";
2
- import type { ExecuteId, MilkioApp, Mixin } from "..";
3
- import { handleCatchError } from "../utils/handle-catch-error";
4
- import { routerHandler } from "../../../src/router";
5
- import schema from "../../../generated/api-schema";
6
- import { failCode } from "../../../src/fail-code";
7
- import { TSON } from "@southern-aurora/tson";
8
- import { createUlid } from "../utils/create-ulid";
9
- import { configMilkio } from "../../../src/config/milkio";
10
- import { headerToPlainObject } from "../utils/header-to-plain-object";
11
-
12
- export type ExecuteHttpServerOptions = {
13
- /**
14
- * The execution ID generator
15
- * If you have enabled this option, the executeId will be generated each time by calling this method. Otherwise, it will be generated using the built-in method.
16
- *
17
- * @param request
18
- * @returns
19
- */
20
- executeIdGenerator?: (request: Request) => string | Promise<string>;
21
- getRealIp?: (request: Request) => string;
22
- mixin?: Record<string, unknown>;
23
- };
24
-
25
- export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOptions = {}) {
26
- const fetch = async (request: MilkioHttpRequest) => {
27
- const fullurl = new URL(request.request.url, `http://${request.request.headers.get("host") ?? "localhost"}`);
28
- const executeId = (options?.executeIdGenerator ? await options.executeIdGenerator(request.request) : createUlid()) as ExecuteId;
29
- runtime.execute.executeIds.add(executeId);
30
- const logger = useLogger(executeId);
31
- const ip = options.getRealIp ? options.getRealIp(request.request) : (request.request.headers.get("X-Forwarded-For") as string | undefined)?.split(",")[0] ?? "0.0.0.0";
32
- const headers = request.request.headers as Headers;
33
-
34
- loggerPushTags(executeId, {
35
- from: "http-server",
36
- url: fullurl.pathname,
37
- ip,
38
- method: request.request.method,
39
- // @ts-ignore
40
- requestHeaders: headerToPlainObject(request.request.headers),
41
- timein: new Date().getTime(),
42
- });
43
-
44
- const response: MilkioHttpResponse = {
45
- body: "",
46
- status: 200,
47
- headers: {
48
- "Content-Type": "application/json",
49
- "Access-Control-Allow-Methods": configMilkio.corsAllowMethods ?? "*",
50
- "Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
51
- "Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*",
52
- },
53
- };
54
-
55
- try {
56
- // Process OPTIONS pre inspection requests
57
- if (request.request.method === "OPTIONS") {
58
- await loggerSubmit(executeId);
59
- runtime.execute.executeIds.delete(executeId);
60
-
61
- return new Response("", {
62
- headers: {
63
- "Access-Control-Allow-Methods": configMilkio.corsAllowMethods ?? "*",
64
- "Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
65
- "Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*",
66
- },
67
- });
68
- }
69
-
70
- let path = fullurl.pathname.substring(1).split("/");
71
-
72
- // Compatible with API gateway's ability to differentiate versions by path
73
- // see: /src/config/ConfigProgram.ts in "ignorePathLevel"
74
- if (configMilkio.ignorePathLevel !== 0) path = path.slice(configMilkio.ignorePathLevel);
75
-
76
- let pathstr = path.join("/") as keyof (typeof schema)["apiMethodsSchema"];
77
-
78
- const detail = {
79
- ...(options.mixin ?? {}),
80
- path: pathstr,
81
- ip,
82
- executeId,
83
- fullurl: fullurl as URL,
84
- request: request.request,
85
- response,
86
- };
87
-
88
- // Special processing: do not run middleware when encountering 404 and return quickly
89
- if (!(pathstr in schema.apiMethodsSchema) || pathstr.startsWith("$/")) {
90
- // @ts-ignore
91
- const redirectPath = await routerHandler(pathstr, fullurl);
92
- if (!redirectPath) {
93
- const rawbody = await request.request.text();
94
- loggerPushTags(executeId, {
95
- body: rawbody || "no body",
96
- });
97
-
98
- if (!detail.response.body) {
99
- if (!detail.response.headers["Content-Type"]) detail.response.headers["Content-Type"] = "application/json";
100
- if (!detail.response.headers["Cache-Control"]) detail.response.headers["Cache-Control"] = "no-cache";
101
- detail.response.body = `{"executeId":"${executeId}","success":false,"fail":{"code":"NOT_FOUND","message":"${failCode.NOT_FOUND(undefined)}"}}`;
102
- }
103
- await MiddlewareEvent.handle("httpNotFound", [detail]);
104
-
105
- loggerPushTags(executeId, {
106
- status: detail.response.status,
107
- responseHeaders: detail.response.headers,
108
- timeout: new Date().getTime(),
109
- });
110
-
111
- await loggerSubmit(executeId);
112
- runtime.execute.executeIds.delete(executeId);
113
-
114
- return new Response(detail.response.body, detail.response);
115
- }
116
-
117
- pathstr = redirectPath as typeof pathstr;
118
- }
119
-
120
- loggerPushTags(executeId, {
121
- path: pathstr,
122
- });
123
-
124
- // execute api
125
- // after request middleware
126
- await MiddlewareEvent.handle("afterHttpRequest", [headers, detail]);
127
- const mode = headers.get("Accept") === "text/event-stream" ? "stream" : "execute";
128
-
129
- const rawbody = await request.request.text();
130
- loggerPushTags(executeId, {
131
- body: rawbody || "no body",
132
- });
133
-
134
- let params: any;
135
- try {
136
- if (rawbody) params = JSON.parse(rawbody);
137
- else params = undefined;
138
- // Doing so may pose security risks, as attackers may trigger your requests through link redirection without being protected by browser CORS.
139
- // Therefore, this feature was commented out after v0.3.0.
140
- // else if (request.request.method === 'GET' && fullurl.searchParams.get('params')) { params = JSON.parse(decodeURIComponent(fullurl.searchParams.get('params')!)); }
141
- } catch (error) {
142
- const logger = useLogger(executeId);
143
- logger.log("TIP: body is not json, the content is not empty, but the content is not in a valid JSON format. The original content value can be retrieved via request.request.text()");
144
- params = undefined;
145
- }
146
-
147
- loggerPushTags(executeId, {
148
- params,
149
- });
150
-
151
- const resultsRaw = await app._call(mode, pathstr, params, headers, { executeId, logger, detail });
152
-
153
- let fn: any;
154
- try {
155
- fn = await schema.apiValidator.validate[pathstr]();
156
- } catch (error) {
157
- throw reject("BUSINESS_FAIL", "This is the new API, which takes effect after restarting the server or saving any changes. It will be fixed in the future.");
158
- }
159
-
160
- if (mode === "execute") {
161
- const result: string = JSON.stringify(TSON.encode(resultsRaw.$result));
162
- if (!detail.response.body) detail.response.body = result;
163
-
164
- // before response middleware
165
- const middlewareResponse = {
166
- value: detail.response.body,
167
- };
168
- await MiddlewareEvent.handle("beforeHttpResponse", [middlewareResponse, detail]);
169
-
170
- if (!detail.response.headers["Content-Type"]) detail.response.headers["Content-Type"] = "application/json";
171
- if (!detail.response.headers["Cache-Control"]) detail.response.headers["Cache-Control"] = "no-cache";
172
- if (!detail.response.body) detail.response.body = middlewareResponse.value;
173
- }
174
-
175
- if (mode === "stream") {
176
- let stream: ReadableStream;
177
- let control: ReadableStreamDirectController | ReadableStreamDefaultController;
178
-
179
- // Handshake failure (usually due to incorrect parameters)
180
- if (resultsRaw.$type === "result" && resultsRaw.$result.success === false) {
181
- stream = new ReadableStream({
182
- async pull(controller) {
183
- control = controller;
184
- controller.enqueue(`data:@${JSON.stringify(TSON.encode(resultsRaw.$result))}\n\n`);
185
- controller.close();
186
- },
187
- cancel() {
188
- control.close();
189
- },
190
- });
191
- } else {
192
- // Handshake successful
193
- const generator = (resultsRaw as any).$generator as AsyncGenerator;
194
- // SSE has a default timeout, which helps prevent memory leaks, especially when you are writing code with a while (true) loop
195
-
196
- if (global?.Bun) {
197
- // bun
198
- stream = new ReadableStream({
199
- type: "direct",
200
- async pull(controller: ReadableStreamDirectController) {
201
- control = controller;
202
- try {
203
- controller.write(`data:@${JSON.stringify(TSON.encode(resultsRaw.$result))}\n\n`);
204
- for await (const value of generator) {
205
- if (!request.request.signal.aborted) {
206
- const result: string = JSON.stringify(TSON.encode(value));
207
- controller.write(`data:${result}\n\n`);
208
- } else {
209
- generator.return(undefined);
210
- controller.close();
211
- }
212
- }
213
- } catch (error) {
214
- const result = handleCatchError(error, executeId);
215
- controller.write(`data:@${JSON.stringify(TSON.encode(result))}\n\n`);
216
- }
217
- await new Promise((resolve) => setTimeout(resolve, 0));
218
- controller.close();
219
- },
220
- cancel() {
221
- control.close();
222
- },
223
- });
224
- } else {
225
- // node.js or others
226
- stream = new ReadableStream({
227
- async pull(controller) {
228
- control = controller;
229
- try {
230
- controller.enqueue(`data:@${JSON.stringify(TSON.encode(resultsRaw.$result))}\n\n`);
231
- for await (const value of generator) {
232
- if (!request.request.signal.aborted) {
233
- const result: string = JSON.stringify(TSON.encode(value));
234
- controller.enqueue(`data:${result}\n\n`);
235
- } else {
236
- generator.return(undefined);
237
- controller.close();
238
- }
239
- }
240
- } catch (error) {
241
- const result = handleCatchError(error, executeId);
242
- controller.enqueue(`data:@${JSON.stringify(TSON.encode(result))}\n\n`);
243
- }
244
- await new Promise((resolve) => setTimeout(resolve, 0));
245
- controller.close();
246
- },
247
- cancel() {
248
- control.close();
249
- },
250
- });
251
- }
252
- }
253
- detail.response.headers["Content-Type"] = "text/event-stream";
254
- detail.response.headers["Cache-Control"] = "no-cache";
255
- detail.response.body = stream;
256
- }
257
- } catch (error) {
258
- const result = handleCatchError(error, executeId);
259
- if (!response.headers["Content-Type"]) response.headers["Content-Type"] = "application/json";
260
- if (!response.headers["Cache-Control"]) response.headers["Cache-Control"] = "no-cache";
261
- if (!response.body) response.body = TSON.stringify(result);
262
- }
263
-
264
- loggerPushTags(executeId, {
265
- status: response.status,
266
- responseHeaders: response.headers,
267
- body: response.body?.toString() ?? "",
268
- timeout: new Date().getTime(),
269
- });
270
-
271
- await loggerSubmit(executeId);
272
- runtime.execute.executeIds.delete(executeId);
273
-
274
- return new Response(response.body, response);
275
- };
276
-
277
- return fetch;
278
- }
279
-
280
- export type MilkioHttpRequest = {
281
- request: Request;
282
- };
283
-
284
- export type MilkioHttpResponse = Mixin<
285
- ResponseInit,
286
- {
287
- body: string | Blob | FormData | URLSearchParams | ReadableStream<Uint8Array>;
288
- status: number;
289
- headers: Record<string, string>;
290
- }
291
- >;
@@ -1,9 +0,0 @@
1
- import type { MiddlewareOptions } from "..";
2
-
3
- export function defineMiddleware(options: MiddlewareOptions): () => MiddlewareOptions {
4
- return () => ({
5
- ...options,
6
- // @ts-ignore
7
- isMiddleware: true,
8
- });
9
- }
@@ -1,12 +0,0 @@
1
- export const defineUse = <CreatorFn extends () => Promise<unknown> | unknown>(creatorFn: CreatorFn): (() => Promise<Awaited<ReturnType<CreatorFn>>>) => {
2
- let use: any | undefined;
3
-
4
- const getUse = async () => {
5
- if (use === undefined) {
6
- use = await creatorFn();
7
- }
8
- return use;
9
- };
10
-
11
- return getUse;
12
- };
package/kernel/context.ts DELETED
@@ -1,55 +0,0 @@
1
- import type { ExecuteId, Logger, MilkioHttpResponse, Mixin, ToEmptyObject, Remove$ } from "..";
2
-
3
- export type MilkioContext = {
4
- path: string;
5
- executeId: ExecuteId;
6
- headers: Headers;
7
- logger: Logger;
8
- /**
9
- * Additional information about the request
10
- * These are usually only fully implemented when called by an Http server
11
- * During testing or when calling between microservices, some or all of the values may be undefined
12
- */
13
- detail: FrameworkHttpDetail;
14
- step: Steps<{}>["step"];
15
- };
16
-
17
- export type FrameworkHttpDetail = {
18
- path: string;
19
- executeId: ExecuteId;
20
- fullurl: URL;
21
- ip: string;
22
- request: Request;
23
- response: MilkioHttpResponse;
24
- };
25
-
26
- export type Steps<StageT extends Record<any, any>> = {
27
- step: StepFunction<StageT>;
28
- // run: <HandlerT extends (stage: StageT) => Record<any, any> | Promise<Record<any, any>>>(handler: HandlerT) => Promise<Awaited<ReturnType<HandlerT>>>,
29
- run: () => Promise<Remove$<StageT>>;
30
- };
31
-
32
- type StepFunction<StageT extends Record<any, any>> = <HandlerT extends (stage: Readonly<StageT>) => Record<any, any> | Promise<Record<any, any>>>(handler: HandlerT) => Steps<Awaited<StageT> & ToEmptyObject<Awaited<ReturnType<HandlerT>>>>;
33
-
34
- export const createStep = () => {
35
- const stepController = {
36
- _steps: [] as Array<(stage: any) => Promise<any>>,
37
- step(handler: (stage: any) => Promise<any>) {
38
- stepController._steps.push(handler);
39
- return stepController;
40
- },
41
- async run() {
42
- let stage = {};
43
- for (const step of stepController._steps) {
44
- stage = { ...stage, ...(await step(stage)) };
45
- }
46
- let result: Record<any, any> = {};
47
- for (const key in stage) {
48
- const value = (stage as any)[key];
49
- if (!key.startsWith("$")) result[key] = value;
50
- }
51
- return result;
52
- },
53
- };
54
- return stepController.step as any as Steps<{}>["step"];
55
- };
package/kernel/execute.ts DELETED
@@ -1,194 +0,0 @@
1
- import type { Context } from "../../../src/context";
2
- import { failCode } from "../../../src/fail-code";
3
- import schema from "../../../generated/api-schema";
4
- import { type ExecuteId, type ExecuteOptions, type ExecuteResult, createUlid, useLogger, runtime, loggerPushTags, headerToPlainObject, loggerSubmit, type ExecuteCoreOptions, TSON, MiddlewareEvent, reject, _validate, ExecuteStreamResult, createStep, Steps } from "..";
5
- import { handleCatchError } from "../utils/handle-catch-error";
6
-
7
- const apis = new Map<string, any>();
8
-
9
- /**
10
- * call is a low-level API that is useful only when you want to execute the Milkio Api without using execute or httpServer.
11
- * It only does the most basic thing internally, which is calling the API. The external handling of functions such as making executeId, logging, middleware, etc., are all handled externally.
12
- * Both execute and httpServer essentially call call.
13
- */
14
- export async function _call(
15
- mode: "execute" | "stream",
16
- path: string,
17
- params: unknown | string,
18
- headersInit: Record<string, string> | Headers = {},
19
- options: ExecuteCoreOptions,
20
- ): Promise<{ $type: "result"; $result: ExecuteResult<unknown> } | { $type: "stream"; $result: ExecuteResult<unknown>; $generator: AsyncGenerator }> {
21
- const executeId = options.executeId as ExecuteId;
22
-
23
- params = TSON.decode(params);
24
-
25
- if (!(path in schema.apiMethodsSchema)) {
26
- const result = {
27
- executeId,
28
- success: false,
29
- fail: {
30
- code: "NOT_FOUND",
31
- message: failCode.NOT_FOUND(undefined),
32
- data: undefined,
33
- },
34
- } as ExecuteResult<unknown>;
35
-
36
- return { $type: "result", $result: result };
37
- }
38
-
39
- let headers: Headers;
40
- if (!(headersInit instanceof Headers)) {
41
- // @ts-ignore
42
- headers = new Headers({
43
- ...headersInit,
44
- });
45
- } else {
46
- headers = headersInit;
47
- }
48
-
49
- if (options?.onAfterHeaders) {
50
- await options.onAfterHeaders(headers);
51
- }
52
-
53
- const context: Context = {
54
- executeId,
55
- path: path as string,
56
- headers,
57
- logger: options.logger,
58
- detail: options?.detail ?? ({} as any),
59
- step: createStep() as any,
60
- };
61
-
62
- let result: { value: unknown };
63
- try {
64
- // before execute middleware
65
- await MiddlewareEvent.handle("beforeExecute", [context]);
66
-
67
- let fn: any;
68
- // check type
69
- try {
70
- // @ts-ignore
71
- fn = await schema.apiValidator.validate[path]();
72
- } catch (error) {
73
- throw reject("BUSINESS_FAIL", "This is the new API, which takes effect after restarting the server or saving any changes. It will be fixed in the future.");
74
- }
75
- params = _validate(await fn.validateParams(params));
76
-
77
- // execute api
78
- let api: any;
79
- if (apis.has(path as string)) api = apis.get(path as string);
80
- else {
81
- // @ts-ignore
82
- api = schema.apiMethodsSchema[path as string]();
83
- apis.set(path as string, api);
84
- }
85
- const apiModuleAwaited = await api.module;
86
- const apiMethod = apiModuleAwaited.api.action;
87
- // @ts-ignore
88
- result = { value: await apiMethod(params, context) };
89
- // after execute middleware
90
- await MiddlewareEvent.handle("afterExecute", [context, result]);
91
-
92
- if (mode === "execute" && !(result.value as AsyncGenerator)?.[Symbol.asyncIterator]) return { $type: "result", $result: { executeId, success: true, data: result.value } };
93
- if (mode === "stream" && (result.value as AsyncGenerator)?.[Symbol.asyncIterator]) return { $type: "stream", $result: { executeId, success: true, data: "$" }, $generator: result.value as AsyncGenerator };
94
- console.log(mode);
95
-
96
- throw reject("BUSINESS_FAIL", `It looks like you used the wrong syntax, for this API you should use "client.${mode}(...)"`);
97
- } catch (error: any) {
98
- const errorResult = handleCatchError(error, executeId);
99
-
100
- return { $type: "result", $result: errorResult };
101
- }
102
- }
103
-
104
- export async function _execute<Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
105
- path: Path,
106
- options: {
107
- params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string;
108
- headers?: Record<string, string> | Headers;
109
- } & ExecuteOptions,
110
- ): Promise<ExecuteResult<Result>> {
111
- if (!options.headers) options.headers = {};
112
- const executeId = (options?.executeId ?? createUlid()) as ExecuteId;
113
- const logger = useLogger(executeId);
114
- runtime.execute.executeIds.add(executeId);
115
-
116
- loggerPushTags(executeId, {
117
- from: "execute",
118
- executeId,
119
- params: options.params,
120
- path,
121
- });
122
-
123
- const result = await _call("execute", path, options.params, options.headers, {
124
- ...options,
125
- executeId,
126
- logger,
127
- onAfterHeaders: (headers) => {
128
- loggerPushTags(executeId, {
129
- requestHeaders: headerToPlainObject(headers),
130
- });
131
- },
132
- });
133
-
134
- loggerPushTags(executeId, { result: result.$result });
135
- await loggerSubmit(executeId);
136
- runtime.execute.executeIds.delete(executeId);
137
-
138
- return result.$result as ExecuteResult<Result>;
139
- }
140
-
141
- export async function _executeToJson<Path extends keyof (typeof schema)["apiMethodsTypeSchema"]>(
142
- path: Path,
143
- options: {
144
- params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string;
145
- headers?: Record<string, string> | Headers;
146
- } & ExecuteOptions,
147
- ): Promise<string> {
148
- const resultsRaw = await _execute(path, options);
149
- let fn: any;
150
- try {
151
- fn = await schema.apiValidator.validate[path]();
152
- } catch (error) {
153
- throw reject("BUSINESS_FAIL", "This is the new API, which takes effect after restarting the server or saving any changes. It will be fixed in the future.");
154
- }
155
- const results = JSON.stringify(TSON.encode(resultsRaw));
156
- return results;
157
- }
158
-
159
- export async function _executeStream<Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
160
- path: Path,
161
- options: {
162
- params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string;
163
- headers?: Record<string, string> | Headers;
164
- } & ExecuteOptions,
165
- ): Promise<ExecuteStreamResult<Path, Result>> {
166
- if (!options.headers) options.headers = {};
167
- const executeId = (options?.executeId ?? createUlid()) as ExecuteId;
168
- const logger = useLogger(executeId);
169
- runtime.execute.executeIds.add(executeId);
170
-
171
- loggerPushTags(executeId, {
172
- from: "execute",
173
- executeId,
174
- params: options.params,
175
- path,
176
- });
177
-
178
- const result = await _call("stream", path, options.params, options.headers, {
179
- ...options,
180
- executeId,
181
- logger,
182
- onAfterHeaders: (headers) => {
183
- loggerPushTags(executeId, {
184
- requestHeaders: headerToPlainObject(headers),
185
- });
186
- },
187
- });
188
-
189
- loggerPushTags(executeId, { result: result.$result });
190
- await loggerSubmit(executeId);
191
- runtime.execute.executeIds.delete(executeId);
192
-
193
- return { getResult: () => result.$result, stream: (result as any).$generator } as ExecuteStreamResult<Path, Result>;
194
- }
package/kernel/fail.ts DELETED
@@ -1,20 +0,0 @@
1
- import { failCode } from "../../../src/fail-code";
2
-
3
- export function reject<Code extends keyof typeof failCode, FailData extends (typeof failCode)[Code]>(code: Code, data: Parameters<FailData>[0]) {
4
- const message = failCode[code]?.(data as any) ?? "";
5
- const error = {
6
- name: "MilkioReject",
7
- code,
8
- message,
9
- data,
10
- stack: "",
11
- };
12
- Error.captureStackTrace(error);
13
- error.stack = error.stack.replace(/\n.*\n/, "\n");
14
-
15
- return error;
16
- }
17
-
18
- export type MilkioReject = ReturnType<typeof reject>;
19
-
20
- export type MilkioFailCode = Record<string, (arg: any) => string>;