milkio 0.0.2 → 0.0.4

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,9 +1,9 @@
1
1
  /* eslint-disable @typescript-eslint/no-unsafe-argument, no-console, @typescript-eslint/no-explicit-any */
2
2
  import { exit } from "node:process";
3
3
  import schema from "../../../generate/api-schema";
4
- import { type milkioApp } from "..";
4
+ import { type MilkioApp } from "..";
5
5
 
6
- export const defineApiTestHandler = async <Paths extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: milkioApp, paths: Paths | string | 1 | undefined) => {
6
+ export const defineApiTestHandler = async <Paths extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: MilkioApp, paths: Paths | string | 1 | undefined) => {
7
7
  console.log(`🧊 Milkio Api Testing..\n`);
8
8
 
9
9
  if (!paths) {
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable no-console */
2
- import { configFramework, loggerPushTags, loggerSubmit, useLogger, loggerSubmitAll, runtime, MiddlewareEvent } from "..";
3
- import type { ExecuteId, milkioApp, Mixin } from "..";
2
+ import { configMilkio, loggerPushTags, loggerSubmit, useLogger, loggerSubmitAll, runtime, MiddlewareEvent } from "..";
3
+ import type { ExecuteId, MilkioApp, Mixin } from "..";
4
4
  import { hanldeCatchError } from "../utils/handle-catch-error";
5
5
  import { routerHandler } from "../../../src/router";
6
6
  import schema from "../../../generate/api-schema";
@@ -20,7 +20,7 @@ export type ExecuteHttpServerOptions = {
20
20
  executeIdGenerator?: (request: Request) => string | Promise<string>;
21
21
  };
22
22
 
23
- export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOptions = {}) {
23
+ export function defineHttpHandler(app: MilkioApp, options: ExecuteHttpServerOptions = {}) {
24
24
  // If an unexpected error occurs, exit the process.
25
25
  // For modern production environments such as Serverless, Kubernetes, or Docker Compose:
26
26
  // The process will automatically restart after exiting.
@@ -33,7 +33,7 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
33
33
  exit(1);
34
34
  });
35
35
 
36
- const fetch = async (request: milkioHTTPRequest) => {
36
+ const fetch = async (request: MilkioHTTPRequest) => {
37
37
  const fullurl = new URL(request.request.url, `http://${request.request.headers.get("host") ?? "localhost"}`);
38
38
  const executeId = (options?.executeIdGenerator ? await options.executeIdGenerator(request.request) : createUlid()) as ExecuteId;
39
39
  runtime.execute.executeIds.add(executeId);
@@ -50,14 +50,14 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
50
50
  timein: new Date().getTime()
51
51
  });
52
52
 
53
- const response: milkioHTTPResponse = {
53
+ const response: MilkioHTTPResponse = {
54
54
  body: "",
55
55
  status: 200,
56
56
  headers: {
57
57
  "Content-Type": "application/json",
58
- "Access-Control-Allow-Methods": configFramework.corsAllowMethods ?? "*",
59
- "Access-Control-Allow-Headers": configFramework.corsAllowHeaders ?? "*",
60
- "Access-Control-Allow-Origin": configFramework.corsAllowOrigin ?? "*"
58
+ "Access-Control-Allow-Methods": configMilkio.corsAllowMethods ?? "*",
59
+ "Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
60
+ "Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*"
61
61
  }
62
62
  };
63
63
 
@@ -69,9 +69,9 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
69
69
 
70
70
  return new Response("", {
71
71
  headers: {
72
- "Access-Control-Allow-Methods": configFramework.corsAllowMethods ?? "*",
73
- "Access-Control-Allow-Headers": configFramework.corsAllowHeaders ?? "*",
74
- "Access-Control-Allow-Origin": configFramework.corsAllowOrigin ?? "*"
72
+ "Access-Control-Allow-Methods": configMilkio.corsAllowMethods ?? "*",
73
+ "Access-Control-Allow-Headers": configMilkio.corsAllowHeaders ?? "*",
74
+ "Access-Control-Allow-Origin": configMilkio.corsAllowOrigin ?? "*"
75
75
  }
76
76
  });
77
77
  }
@@ -80,7 +80,7 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
80
80
 
81
81
  // Compatible with API gateway's ability to differentiate versions by path
82
82
  // see: /src/config/ConfigProgram.ts in "ignorePathLevel"
83
- if (configFramework.ignorePathLevel !== 0) path = path.slice(configFramework.ignorePathLevel);
83
+ if (configMilkio.ignorePathLevel !== 0) path = path.slice(configMilkio.ignorePathLevel);
84
84
 
85
85
  let pathstr = path.join("/") as keyof (typeof schema)["apiMethodsSchema"];
86
86
 
@@ -92,7 +92,7 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
92
92
  loggerPushTags(executeId, {
93
93
  body: rawbody || "no body"
94
94
  });
95
- response.body = `{"executeId":"${executeId}","success":false,"fail":{"code":"not-found","message":${JSON.stringify(failCode["not-found"]())}}}`;
95
+ response.body = `{"executeId":"${executeId}","success":false,"fail":{"code":"NOT_FOUND","message":${JSON.stringify(failCode.NOT_FOUND())}}}`;
96
96
 
97
97
  loggerPushTags(executeId, {
98
98
  status: response.status,
@@ -188,11 +188,11 @@ export function defineHttpHandler(app: milkioApp, options: ExecuteHttpServerOpti
188
188
  return fetch;
189
189
  }
190
190
 
191
- export type milkioHTTPRequest = {
191
+ export type MilkioHTTPRequest = {
192
192
  request: Request;
193
193
  };
194
194
 
195
- export type milkioHTTPResponse = Mixin<
195
+ export type MilkioHTTPResponse = Mixin<
196
196
  ResponseInit,
197
197
  {
198
198
  //
package/kernel/config.ts CHANGED
@@ -1,13 +1,12 @@
1
1
  import { cwd, env } from "node:process";
2
2
  import { envToBoolean, envToNumber, envToString } from "..";
3
3
 
4
- export const configFramework = {
4
+ export const configMilkio = {
5
5
  cwd: cwd(),
6
6
  port: envToNumber(env.PORT, 9000),
7
7
  milkioRunMode: envToString(env.milkio_RUN_MODE, "DEFAULT"),
8
8
  milkioTest: envToString(env.milkio_TEST, ""),
9
9
  debug: envToBoolean(env.DEBUG, false),
10
- redisUrl: envToString(env.REDIS_URL, "redis://:123456@your-not-redis-url:6379"),
11
10
  ignorePathLevel: envToNumber(env.IGNORE_PATH_LEVEL, 0),
12
11
  corsAllowMethods: envToString(env.CORS_ALLOW_METHODS, "*"),
13
12
  corsAllowHeaders: envToString(env.CORS_ALLOW_HEADERS, "*"),
package/kernel/context.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { URL } from "node:url";
2
- import type { ExecuteId, Logger, milkioHTTPResponse } from "..";
2
+ import type { ExecuteId, Logger, MilkioHTTPResponse } from "..";
3
3
 
4
- export type FrameworkContext = {
4
+ export type MilkioContext = {
5
5
  path: string;
6
6
  executeId: ExecuteId;
7
7
  headers: Headers;
@@ -20,5 +20,5 @@ export type FrameworkHTTPDetail = {
20
20
  fullurl: URL;
21
21
  ip: string;
22
22
  request: Request;
23
- response: milkioHTTPResponse;
23
+ response: MilkioHTTPResponse;
24
24
  };
package/kernel/fail.ts CHANGED
@@ -4,7 +4,7 @@ export function reject<Code extends keyof typeof failCode, FailData extends (typ
4
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
5
5
  const message = failCode[code]?.(data as any) ?? "";
6
6
  const error = {
7
- name: "milkioReject",
7
+ name: "MilkioReject",
8
8
  code,
9
9
  message,
10
10
  data,
@@ -16,7 +16,7 @@ export function reject<Code extends keyof typeof failCode, FailData extends (typ
16
16
  return error;
17
17
  }
18
18
 
19
- export type milkioReject = ReturnType<typeof reject>;
19
+ export type MilkioReject = ReturnType<typeof reject>;
20
20
 
21
21
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- export type milkioFailCode = Record<string, (arg: any) => string>;
22
+ export type MilkioFailCode = Record<string, (arg: any) => string>;
@@ -2,9 +2,9 @@
2
2
 
3
3
  import type { Context } from "../../../src/context";
4
4
  import type { FrameworkHTTPDetail } from "./context";
5
- import { type milkioApp } from "milkio";
5
+ import { type MilkioApp } from "milkio";
6
6
 
7
- export type BootstrapMiddleware = (milkio: milkioApp) => Promise<void> | void;
7
+ export type BootstrapMiddleware = (milkio: MilkioApp) => Promise<void> | void;
8
8
  export type BeforeExecuteMiddleware = (context: Context) => Promise<void> | void;
9
9
  export type AfterExecuteMiddleware = (context: Context, response: { value: unknown }) => Promise<void> | void;
10
10
  export type AfterHTTPRequestMiddleware = (headers: Headers, detail: FrameworkHTTPDetail) => Promise<void> | void;
package/kernel/milkio.ts CHANGED
@@ -3,14 +3,14 @@ import { type MiddlewareOptions, _middlewares, MiddlewareEvent } from "./middlew
3
3
  import schema from "../../../generate/api-schema";
4
4
  import type { Context } from "../../../src/context";
5
5
  import { failCode } from "../../../src/fail-code";
6
- import type { FrameworkContext } from "./context";
6
+ import type { MilkioContext } from "./context";
7
7
  import { type Mixin, type ExecuteId, type Fail, type FailEnumerates, loggerPushTags, loggerSubmit, runtime, TSON, type Logger, useLogger } from "..";
8
8
  import { hanldeCatchError } from "../utils/handle-catch-error";
9
9
  import { _validate } from "./validate";
10
10
  import { cwd, exit } from "node:process";
11
11
  import { createUlid } from "../utils/create-ulid";
12
12
 
13
- export type milkioAppOptions = {
13
+ export type MilkioAppOptions = {
14
14
  /**
15
15
  * bootstraps
16
16
  * @description
@@ -39,39 +39,39 @@ export type milkioAppOptions = {
39
39
  enableMaxRunningTimeoutLimit?: number | null | undefined;
40
40
  };
41
41
 
42
- export async function createMilkioApp(milkioAppOptions: milkioAppOptions = {}) {
43
- if (milkioAppOptions?.enableMaxRequestLimit && milkioAppOptions.enableMaxRequestLimit >= 1) {
44
- runtime.maxRequest.expected = milkioAppOptions.enableMaxRequestLimit;
42
+ export async function createMilkioApp(MilkioAppOptions: MilkioAppOptions = {}) {
43
+ if (MilkioAppOptions?.enableMaxRequestLimit && MilkioAppOptions.enableMaxRequestLimit >= 1) {
44
+ runtime.maxRequest.expected = MilkioAppOptions.enableMaxRequestLimit;
45
45
  runtime.maxRequest.enable = true;
46
46
  }
47
47
 
48
- if (milkioAppOptions.enableMaxRunningTimeoutLimit && milkioAppOptions.enableMaxRunningTimeoutLimit >= 1) {
48
+ if (MilkioAppOptions.enableMaxRunningTimeoutLimit && MilkioAppOptions.enableMaxRunningTimeoutLimit >= 1) {
49
49
  setTimeout(() => {
50
- console.log('❌ milkio reached the limit of "maxRunningTimeout" in the options and automatically exited.');
50
+ console.log('❌ Milkio reached the limit of "maxRunningTimeout" in the options and automatically exited.');
51
51
  exit(0);
52
- }, milkioAppOptions.enableMaxRunningTimeoutLimit * 60 * 1000);
52
+ }, MilkioAppOptions.enableMaxRunningTimeoutLimit * 60 * 1000);
53
53
  runtime.maxRunningTimeout.enable = true;
54
54
  }
55
55
 
56
- const milkioApp = {
56
+ const MilkioApp = {
57
57
  execute: _execute,
58
58
  executeToJson: _executeToJson,
59
59
  _executeCore,
60
60
  _executeCoreToJson
61
61
  };
62
62
 
63
- if (milkioAppOptions.bootstraps) {
64
- await Promise.all(milkioAppOptions.bootstraps());
63
+ if (MilkioAppOptions.bootstraps) {
64
+ await Promise.all(MilkioAppOptions.bootstraps());
65
65
  }
66
66
 
67
- if (milkioAppOptions.middlewares) {
67
+ if (MilkioAppOptions.middlewares) {
68
68
  MiddlewareEvent.define("bootstrap", (a, b) => a.index - b.index);
69
69
  MiddlewareEvent.define("beforeExecute", (a, b) => a.index - b.index);
70
70
  MiddlewareEvent.define("afterExecute", (a, b) => b.index - a.index);
71
71
  MiddlewareEvent.define("afterHTTPRequest", (a, b) => a.index - b.index);
72
72
  MiddlewareEvent.define("beforeHTTPResponse", (a, b) => b.index - a.index);
73
73
 
74
- const middlewares = milkioAppOptions.middlewares();
74
+ const middlewares = MilkioAppOptions.middlewares();
75
75
 
76
76
  for (let index = 0; index < middlewares.length; index++) {
77
77
  const middlewareOptions = middlewares[index];
@@ -87,12 +87,12 @@ export async function createMilkioApp(milkioAppOptions: milkioAppOptions = {}) {
87
87
  }
88
88
  MiddlewareEvent._sort();
89
89
 
90
- await MiddlewareEvent.handle("bootstrap", [milkioApp]);
90
+ await MiddlewareEvent.handle("bootstrap", [MilkioApp]);
91
91
  }
92
92
 
93
93
  console.log(`🧊 Milkio is running on : ${cwd()}`);
94
94
 
95
- return milkioApp;
95
+ return MilkioApp;
96
96
  }
97
97
 
98
98
  async function _execute<Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(path: Path, params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string, headersInit: Record<string, string> | Headers = {}, options?: ExecuteOptions): Promise<ExecuteResult<Result>> {
@@ -137,7 +137,7 @@ async function _executeCore<Path extends keyof (typeof schema)["apiMethodsTypeSc
137
137
 
138
138
  if (runtime.maxRequest.enable) {
139
139
  if (runtime.maxRequest.counter >= runtime.maxRequest.expected) {
140
- console.log("❌ milkio reached the limit of 'maxRequest' in the options and automatically exited.");
140
+ console.log("❌ Milkio reached the limit of 'maxRequest' in the options and automatically exited.");
141
141
  exit(0);
142
142
  }
143
143
  runtime.maxRequest.counter++;
@@ -148,8 +148,8 @@ async function _executeCore<Path extends keyof (typeof schema)["apiMethodsTypeSc
148
148
  executeId,
149
149
  success: false,
150
150
  fail: {
151
- code: "not-found",
152
- message: failCode["not-found"](),
151
+ code: "NOT_FOUND",
152
+ message: failCode.NOT_FOUND(),
153
153
  data: undefined
154
154
  }
155
155
  } satisfies ExecuteResult<Result>;
@@ -257,7 +257,7 @@ export type ExecuteOptions = {
257
257
  * These are usually only fully implemented when called by an HTTP server
258
258
  * During testing or when calling between microservices, some or all of the values may be undefined
259
259
  */
260
- detail?: FrameworkContext["detail"];
260
+ detail?: MilkioContext["detail"];
261
261
  };
262
262
 
263
263
  export type ExecuteCoreOptions = Mixin<
@@ -5,7 +5,7 @@ export function _validate(validator: IValidation.IFailure | IValidation.ISuccess
5
5
  if (validator.success) return;
6
6
  const error = validator.errors[0];
7
7
 
8
- throw reject("general-type-safe-error", {
8
+ throw reject("TYPE_SAFE_ERROR", {
9
9
  path: error.path,
10
10
  expected: error.expected,
11
11
  value: error.value
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "milkio",
3
3
  "type": "module",
4
4
  "module": "index.ts",
5
- "version": "0.0.2",
5
+ "version": "0.0.4",
6
6
  "peerDependencies": {
7
7
  "typescript": "^5.4.2"
8
8
  },
package/types.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  import { type createMilkioApp } from ".";
4
4
  import type { failCode } from "../../src/fail-code";
5
5
 
6
- export type milkioApp = Awaited<ReturnType<typeof createMilkioApp>>;
6
+ export type MilkioApp = Awaited<ReturnType<typeof createMilkioApp>>;
7
7
 
8
8
  export type ExecuteId = string | "global";
9
9
 
@@ -19,7 +19,7 @@ export type Fail<FailCode extends keyof FailEnumerates> = {
19
19
  data: Parameters<FailEnumerates[FailCode]>[0];
20
20
  };
21
21
 
22
- export type milkioMeta = {
22
+ export type MilkioMeta = {
23
23
  //
24
24
  };
25
25
 
@@ -9,16 +9,16 @@ export function hanldeCatchError(error: any, executeId: ExecuteId): ExecuteResul
9
9
  if (error.stack) logger.error("\nError Stack: ", error.stack);
10
10
  else logger.error("\nError Stack: ", error);
11
11
 
12
- if (error.name !== "milkioReject") {
13
- // If it is not milkioReject, it is considered an internal server error that should not be exposed
14
- logger.error(`FailCode: internal-server-error`);
12
+ if (error.name !== "MilkioReject") {
13
+ // If it is not MilkioReject, it is considered an internal server error that should not be exposed
14
+ logger.error(`FailCode: INTERNAL_SERVER_ERROR`);
15
15
 
16
16
  return {
17
17
  executeId,
18
18
  success: false,
19
19
  fail: {
20
- code: "internal-server-error",
21
- message: failCode["internal-server-error"](),
20
+ code: "INTERNAL_SERVER_ERROR",
21
+ message: failCode.INTERNAL_SERVER_ERROR(),
22
22
  data: undefined
23
23
  }
24
24
  };