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
package/package.json CHANGED
@@ -2,27 +2,23 @@
2
2
  "name": "milkio",
3
3
  "type": "module",
4
4
  "module": "index.ts",
5
- "version": "0.8.2",
5
+ "version": "1.0.0-alpha.0",
6
6
  "peerDependencies": {
7
7
  "typescript": "^5.4.2"
8
8
  },
9
- "bin": {
10
- "milkio": "./c.ts"
11
- },
9
+ "scripts": {},
12
10
  "dependencies": {
11
+ "@paralleldrive/cuid2": "^2.2.2",
13
12
  "@poech/camel-hump-under": "^1.1.0",
14
- "@southern-aurora/tson": "2.0.2",
13
+ "@southern-aurora/tson": "^2.0.2",
15
14
  "chalk": "^5.3.0",
16
- "ejs": "^3.1.9",
17
- "typia": "5.5.5",
18
- "ulidx": "^2.3.0"
15
+ "date-fns": "^4.1.0",
16
+ "typia": "6.9.0"
19
17
  },
20
18
  "devDependencies": {
21
19
  "@types/bun": "latest",
22
- "@types/node": "latest",
23
- "@types/ejs": "^3.1.5",
24
- "@types/js-beautify": "^1.14.3",
25
- "ts-patch": "^3.1.2",
26
- "typescript": "^5.3.3"
20
+ "@vitest/ui": "^2.0.5",
21
+ "typescript": "^5.5.0",
22
+ "vitest": "^2.0.5"
27
23
  }
28
24
  }
@@ -0,0 +1,19 @@
1
+ import { type $context, type $meta } from "..";
2
+
3
+ export const stream = <StreamInitT extends StreamInit>(init: StreamInitT): Stream<StreamInitT> => {
4
+ const stream = init as unknown as Stream<StreamInitT>;
5
+ stream.$milkioType = "stream";
6
+ if (stream.meta === undefined) stream.meta = {};
7
+ return stream;
8
+ };
9
+
10
+ export type StreamInit = {
11
+ meta?: $meta;
12
+ handler: (context: $context, params: any) => AsyncGenerator<unknown>;
13
+ };
14
+
15
+ export type Stream<StreamInitT extends StreamInit> = {
16
+ $milkioType: "stream";
17
+ meta: StreamInitT["meta"] extends undefined ? {} : StreamInitT["meta"];
18
+ handler: StreamInitT["handler"];
19
+ };
package/test/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { type context, type meta } from "..";
2
+
3
+ export const test = <TestInitT extends TestInit>(init: TestInitT): Test<TestInitT> => {
4
+ const test = init as unknown as Test<TestInitT>;
5
+ test.$milkioType = "test";
6
+ if (test.name === undefined) test.name = {};
7
+ return test;
8
+ };
9
+
10
+ export type TestInit = {
11
+ name: meta;
12
+ handler: (test: TestTools) => Promise<unknown>;
13
+ };
14
+
15
+ export type Test<TestInitT extends TestInit> = {
16
+ $milkioType: "test";
17
+ name: TestInitT["name"] extends undefined ? {} : TestInitT["name"];
18
+ handler: TestInitT["handler"];
19
+ };
20
+
21
+ export type TestTools = {};
package/types/index.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { type $rejectCode } from "..";
2
+
3
+ export interface $types {
4
+ [key: string]: Record<any, any>;
5
+ }
6
+
7
+ export type Override<P, S> = Omit<P, keyof S> & S;
8
+
9
+ export type Mixin<T, U> = U & Omit<T, keyof U>;
10
+
11
+ export type GeneratorGeneric<T> = T extends AsyncGenerator<infer I> ? I : never;
12
+
13
+ export type ExecuteId = string | "global";
14
+
15
+ // DON'T TRY TO WRITE A MORE DETAILED TYPE FOR THIS TYPE
16
+ // the role of this type is only to limit the foolproof operation when defineMilkio(...)
17
+ // the real generated type is defined by the framework user through declare module
18
+ export type GeneratedInit = {
19
+ routeSchema: any;
20
+ commandSchema: any;
21
+ testSchema: any;
22
+ };
23
+
24
+ export type Results<T extends unknown> = {
25
+ value: T;
26
+ };
27
+
28
+ export type ExecuteOptions = {
29
+ params?: Record<any, any>;
30
+ headers?: Record<string, string>;
31
+ };
32
+
33
+ export type Ping =
34
+ | [
35
+ {
36
+ connect: false;
37
+ delay: number;
38
+ error: any;
39
+ },
40
+ null,
41
+ ]
42
+ | [
43
+ null,
44
+ {
45
+ connect: true;
46
+ delay: number;
47
+ serverTimestamp: number;
48
+ },
49
+ ];
50
+
51
+ export type Execute = <Path extends keyof $types["generated"]["routeSchema"]["$types"]>(
52
+ path: Path,
53
+ options?: Mixin<
54
+ ExecuteOptions,
55
+ {
56
+ headers?: Record<string, string>;
57
+ params?: $types["generated"]["routeSchema"]["$types"][Path]["params"];
58
+ }
59
+ >,
60
+ ) => $types["generated"]["routeSchema"]["$types"][Path]["🐣"] extends boolean
61
+ ? // action
62
+ Promise<[Partial<$rejectCode>, null, ExecuteResultsOption] | [null, ExecuteActionResults<Path>, ExecuteResultsOption]>
63
+ : // stream
64
+ Promise<[Partial<$rejectCode>, null, ExecuteResultsOption] | [null, AsyncGenerator<[Partial<$rejectCode>, null] | [null, ExecuteStreamResults<Path>], null>, ExecuteResultsOption]>;
65
+
66
+ export type ExecuteResultsOption = { executeId: string };
67
+
68
+ export type ExecuteActionResults<Path extends keyof Generated["routeSchema"]["$types"], Generated extends $types["generated"] = $types["generated"]> = Generated["routeSchema"]["$types"][Path]["result"];
69
+
70
+ export type ExecuteStreamResults<Path extends keyof Generated["routeSchema"]["$types"], Generated extends $types["generated"] = $types["generated"]> = GeneratorGeneric<Generated["routeSchema"]["$types"][Path]["result"]>;
71
+
72
+ export type MilkioResponseReject<Code extends keyof $rejectCode = keyof $rejectCode> = { success: false; code: Code; reject: $rejectCode[Code]; executeId: string };
73
+
74
+ export type MilkioResponseSuccess<Path extends keyof Generated["routeSchema"]["$types"], Generated extends $types["generated"] = $types["generated"]> = { success: true; data: Generated["routeSchema"]["$types"][Path]["result"]; executeId: string };
@@ -0,0 +1,3 @@
1
+ import { createId as _createId } from "@paralleldrive/cuid2";
2
+
3
+ export const createId = _createId;
package/world/index.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { __initCommander, __initListener, ExecuteId, type Logger, type Mixin, type GeneratedInit, $types, Execute, Ping } from "..";
2
+ import { __initExecuter } from "../execute";
3
+ import { defineDefaultExecuteIdGenerator } from "../execute/execute-id-generator";
4
+
5
+ export type MilkioInit = {
6
+ port: {
7
+ app: number;
8
+ develop: number | "disabled";
9
+ };
10
+ getRealIp?: (request: Request) => string;
11
+ executeIdGenerator?: (request: Request) => string | Promise<string>;
12
+ corsAllowMethods?: string;
13
+ corsAllowHeaders?: string;
14
+ corsAllowOrigin?: string;
15
+ ignorePathLevel?: number;
16
+ };
17
+
18
+ export type MilkioRuntimeInit<T extends MilkioInit> = Mixin<
19
+ T,
20
+ {
21
+ executeIdGenerator: (request: Request) => string | Promise<string>;
22
+ runtime: {
23
+ request: Map<ExecuteId, { logger: Logger }>;
24
+ };
25
+ }
26
+ >;
27
+
28
+ export const createWorld = async <CookbookOptions extends MilkioInit>(generated: GeneratedInit, options: CookbookOptions): Promise<MilkioWorld<CookbookOptions>> => {
29
+ const executeIdGenerator = options.executeIdGenerator ?? defineDefaultExecuteIdGenerator();
30
+
31
+ const runtime = {
32
+ request: new Map(),
33
+ } as MilkioRuntimeInit<CookbookOptions>["runtime"];
34
+
35
+ const _: MilkioRuntimeInit<CookbookOptions> = {
36
+ ...options,
37
+ executeIdGenerator,
38
+ runtime,
39
+ };
40
+
41
+ const executer = __initExecuter(generated, _);
42
+ const commander = __initCommander(generated, _);
43
+ const listener = __initListener(generated, _, executer);
44
+
45
+ // Initialize the app
46
+ const app = {
47
+ _: _,
48
+ _executer: executer,
49
+ execute: executer.execute,
50
+ ping: executer.ping,
51
+ commander,
52
+ listener,
53
+ };
54
+
55
+ return app as MilkioWorld<CookbookOptions>;
56
+ };
57
+
58
+ export type MilkioWorld<CookbookOptions extends MilkioInit = MilkioInit> = {
59
+ _: MilkioRuntimeInit<CookbookOptions>;
60
+ _executer: Awaited<ReturnType<typeof __initExecuter<MilkioRuntimeInit<CookbookOptions>>>>;
61
+ commander: Awaited<ReturnType<typeof __initCommander<MilkioRuntimeInit<CookbookOptions>>>>;
62
+ listener: Awaited<ReturnType<typeof __initListener<MilkioRuntimeInit<CookbookOptions>>>>;
63
+ execute: Execute;
64
+ ping: (options?: { timeout?: number }) => Promise<Ping>;
65
+ };
package/api-test/index.ts DELETED
@@ -1,122 +0,0 @@
1
- import chalk from "chalk";
2
- import schema from "../../../generated/api-schema";
3
- import { ExecuteResultFail, reject, type MilkioApp } from "..";
4
- import { handleCatchError } from "../utils/handle-catch-error.ts";
5
-
6
- export const executeApiTests = async <Path extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: MilkioApp, path: Path | string | true | 1 | undefined) => {
7
- console.log(`${chalk.hex("#81C7D4")(`🧊 test running`)}`);
8
-
9
- let pathArr = [] as Array<string>;
10
- if (!path || path === "1" || path === 1 || path === true) {
11
- pathArr = Object.keys(schema.apiTestsSchema) as unknown as Path;
12
- } else if (typeof path === "string") {
13
- pathArr = [path] as Path;
14
- }
15
-
16
- const startedAt = new Date().getTime();
17
- const apiTestHooks = await import("../../../src/api-test.ts");
18
- await apiTestHooks.default.onBootstrap();
19
- const clientPackage = apiTestHooks.default?.client ? await apiTestHooks.default?.client() : undefined;
20
- const results: Array<{ path: string; case: number; fail: boolean; failMessage?: string }> = [];
21
-
22
- if (!clientPackage) {
23
- console.log(`🚨 For testing purposes, if the client package does not exist, subsequent operations might result in errors.`);
24
- console.log(`🚨 To disable this warning and ensure the test system runs correctly:`);
25
- console.log(` - Run: \`bun i packages/client && cd packages/client && bun i milkio-client\``);
26
- console.log(` - Edit: \`src/api-test.ts\``);
27
- console.log(` - Add: \`client: () => createClient({ baseUrl: "http://localhost:9000/", memoryStorage: true }),\``);
28
- console.log(` - The \`createClient\` method is imported from your client package. If you haven't changed the name in \`packages/client/package.json\`, you can use: \`import { createClient } from 'client';\`.`);
29
- } else {
30
- let done = false;
31
- for (let index = 0; index < 160; index++) {
32
- let response;
33
- try {
34
- response = await fetch(typeof clientPackage.options.baseUrl === "string" ? clientPackage.options.baseUrl : await clientPackage.options.baseUrl(), { method: "GET" });
35
- } catch (error: any) {
36
- if (error?.status && error.status < 500) {
37
- done = true;
38
- break;
39
- }
40
- }
41
- if (response?.status && response.status < 500) {
42
- console.warn(response, response.status);
43
-
44
- done = true;
45
- break;
46
- }
47
- await new Promise((resolve) => setTimeout(resolve, 100));
48
- continue;
49
- }
50
- if (!done) {
51
- console.log(`🚨 The server startup exceeded the maximum waiting time (16000ms).`);
52
- console.log(`This is likely an error encountered during the startup of the Milkio Server. Please check the 'Milkio Run & Watch' tab in your VS Code terminal panel. This is only a warning, and the tests will continue, but there is a chance they might fail due to network issues.\n`);
53
- }
54
- }
55
-
56
- const client = clientPackage
57
- ? {
58
- execute: async (options?: any) => clientPackage!.execute(path as any, options),
59
- executeOther: async (path: any, options?: any) => clientPackage!.execute(path as any, options),
60
- executeStream: async (options?: any) => clientPackage!.executeStream(path as any, options),
61
- executeStreamOther: async (path: any, options?: any) => clientPackage!.executeStream(path as any, options),
62
- }
63
- : undefined;
64
-
65
- console.log(chalk.hex("#0B346E")(`₋₋₋₋₋₋₋₋`));
66
-
67
- for (const pathRaw of pathArr) {
68
- let path = pathRaw.replaceAll("\\", "/");
69
- if (path.startsWith("/")) path = path.slice(1) as Path[number];
70
-
71
- // @ts-ignore
72
- const module = await schema.apiTestsSchema[path]().module;
73
- const cases = module.test.getCases();
74
- let i = 0;
75
- for (const cs of cases) {
76
- ++i;
77
- const csStartedAt = new Date().getTime();
78
- let fail = false;
79
- let failMessage: string | undefined = undefined;
80
- try {
81
- await cs.handler({
82
- ...((await apiTestHooks.default.onBefore()) ?? {}),
83
- log: (...args: Array<unknown>) => console.log(...args),
84
- execute: async (options?: any) => app.execute(path as any, options),
85
- executeOther: async (path: any, options?: any) => app.execute(path as any, options),
86
- executeStream: async (options?: any) => app.executeStream(path as any, options),
87
- executeStreamOther: async (path: any, options?: any) => app.executeStream(path as any, options),
88
- client,
89
- randParams: () => app.randParams(path as any),
90
- randOtherParams: (path: any) => app.randParams(path),
91
- reject: (message?: string) => {
92
- fail = true;
93
- failMessage = message;
94
- return reject("BUSINESS_FAIL", message ?? "test failed");
95
- },
96
- });
97
- } catch (e: any) {
98
- const response = handleCatchError(e, "no-execute-id") as ExecuteResultFail;
99
- fail = true;
100
- failMessage = response.fail.message;
101
- }
102
- if (fail) {
103
- console.log(`${chalk.hex("#D75455")(`\nrejected`)}${chalk.hex("#999A9E")(` · ${cs.name} | path: src/apps/${path as string}.ts | case: ${i} | time: ${new Date().getTime() - csStartedAt}ms`)}`);
104
- console.log(chalk.hex("#999A9E")(failMessage ?? "Test not satisfied"));
105
- } else {
106
- console.log(`${chalk.hex("#1B813E")(`directed`)}${chalk.hex("#999A9E")(` · ${cs.name} | path: src/apps/${path as string}.ts | case: ${i} | time: ${new Date().getTime() - csStartedAt}ms`)}`);
107
- }
108
- results.push({ path, case: i, fail, failMessage });
109
- console.log(chalk.hex("#0B346E")(`₋₋₋₋₋₋₋₋`));
110
- await new Promise((resolve) => setTimeout(resolve, 64));
111
- }
112
- }
113
-
114
- const endedAt = new Date().getTime();
115
-
116
- const failTotal = results.filter((r) => r.fail).length;
117
- const passTotal = results.length - failTotal;
118
-
119
- console.log("");
120
- if (failTotal === 0) console.log(chalk.hex("#1B813E")(`🥳 all tests ${chalk.hex("#1B813E")(`passed`)} ${chalk.hex("#999A9E")(`🌟 milkio testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s\n`)}`));
121
- else console.log(chalk.hex("#999A9E")(`🤗️️ ${failTotal} test${failTotal > 1 ? "s" : ""} ${chalk.hex("#D75455")(`failed`)}${passTotal > 0 ? `, and ${results.length - failTotal} ${chalk.hex("#1B813E")(`passed`)}` : ""} ${chalk.hex("#999A9E")(`🌟 milkio testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s`)}`));
122
- };
package/c.ts DELETED
@@ -1,50 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import { argv, exit } from "node:process";
4
- import { $, env } from "bun";
5
-
6
- const method = argv[2] as keyof typeof commands;
7
- const params = argv.slice(3) as Parameters<(typeof commands)[keyof typeof commands]>;
8
-
9
- const commands = {
10
- async gen() {
11
- console.log("🥛 Milkio Generating..\n");
12
- await (await import("./scripts/gen-significant")).default();
13
- await (await import("./scripts/gen-insignificant")).default();
14
- console.log("\n✅ Milkio Generated!");
15
- },
16
- async "gen:significant"() {
17
- console.log("🥛 Milkio Significant Generating..\n");
18
- await (await import("./scripts/gen-significant")).default();
19
- console.log("\n✅ Milkio Significant Generated!");
20
- },
21
- async "gen:insignificant"() {
22
- console.log("🥛 Milkio Insignificant Generating..\n");
23
- await (await import("./scripts/gen-insignificant")).default();
24
- console.log("\n✅ Milkio Insignificant Generated!");
25
- },
26
- async EAR(commandBase64ed: string) {
27
- try {
28
- console.clear();
29
- } catch (e) {}
30
- const command = Buffer.from(commandBase64ed, "base64").toString("utf-8");
31
- console.log("\x1B[2m%s\x1B[0m", `$ ${command}`);
32
- console.log(``);
33
- try {
34
- await $`${{ raw: command }}`.env({ ...env, FORCE_COLOR: "3" });
35
- } catch (e) {}
36
- process.on("SIGINT", () => {}); // prevent users from exiting by pressing ctrl + c
37
- while (true) await new Promise((resolve) => process.stdin.on("keypress", resolve));
38
- },
39
- };
40
-
41
- if (method === undefined || !(method in commands)) {
42
- console.log("Command does not exist, Supported commands are:");
43
- console.log(` ${Object.keys(commands).join(", ")}`);
44
- exit(1);
45
- }
46
-
47
- // @ts-ignore
48
- await commands[method](...params);
49
-
50
- exit(0);
@@ -1,69 +0,0 @@
1
- import type { Api, ExecuteResult, ExecuteOptions, GeneratorGeneric, ExecuteResultSuccess } from "..";
2
- import type schema from "../../../generated/api-schema";
3
- import type apiTestHooks from "../../../src/api-test.ts";
4
-
5
- export function defineApiTest<ApiT extends Api>(_api: ApiT, cases: Array<ApiTestCases<ApiT>>) {
6
- return {
7
- getCases: () => cases,
8
- isApiTest: true,
9
- };
10
- }
11
-
12
- export type ApiTestCases<ApiT extends Api> = {
13
- handler: (
14
- test: {
15
- log: (...params: Array<unknown>) => void;
16
- execute: (options: { params: Parameters<ApiT["action"]>[0]; headers?: Record<string, string> } & ExecuteOptions) => Promise<ExecuteResult<Awaited<ReturnType<ApiT["action"]>>>>;
17
- executeOther: <Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
18
- path: Path,
19
- options: {
20
- params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string;
21
- headers?: Record<string, string>;
22
- } & ExecuteOptions,
23
- ) => Promise<ExecuteResult<Result>>;
24
- executeStream: (options: { params: Parameters<ApiT["action"]>[0]; headers?: Record<string, string> } & ExecuteOptions) => Promise<{
25
- getResult: () => ExecuteResult<undefined>;
26
- stream: AsyncGenerator<Awaited<ReturnType<ApiT["action"]>>>;
27
- }>;
28
- executeStreamOther: <Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
29
- path: Path,
30
- options: { params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string; headers?: Record<string, string> } & ExecuteOptions,
31
- ) => Promise<{
32
- getResult: () => ExecuteResult<undefined>;
33
- stream: AsyncGenerator<Result>;
34
- }>;
35
- client: {
36
- execute: (options: { params: Parameters<ApiT["action"]>[0]; headers?: Record<string, string> } & ExecuteOptions) => Promise<ExecuteResult<Awaited<ReturnType<ApiT["action"]>>>>;
37
- executeOther: <Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
38
- path: Path,
39
- options: {
40
- params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string;
41
- headers?: Record<string, string>;
42
- } & ExecuteOptions,
43
- ) => Promise<ExecuteResult<Result>>;
44
- executeStream: (options: { params: Parameters<ApiT["action"]>[0]; headers?: Record<string, string> } & ExecuteOptions) => Promise<{
45
- getResult: () => ExecuteResult<undefined>;
46
- stream: AsyncGenerator<Awaited<ReturnType<ApiT["action"]>>>;
47
- }>;
48
- executeStreamOther: <Path extends keyof (typeof schema)["apiMethodsTypeSchema"], Result extends Awaited<ReturnType<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>>>(
49
- path: Path,
50
- options: { params: Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0] | string; headers?: Record<string, string> } & ExecuteOptions,
51
- ) => Promise<{
52
- getResult: () => ExecuteResult<undefined>;
53
- stream: AsyncGenerator<Result>;
54
- }>;
55
- };
56
- randParams: () => Promise<Parameters<ApiT["action"]>[0]>;
57
- randOtherParams: <Path extends keyof (typeof schema)["apiMethodsTypeSchema"]>(path: Path) => Promise<Parameters<(typeof schema)["apiMethodsTypeSchema"][Path]["api"]["action"]>[0]>;
58
- reject: (message?: string) => {
59
- name: string;
60
- code: "BUSINESS_FAIL";
61
- message: string;
62
- data: string;
63
- stack: string;
64
- };
65
- } & Awaited<ReturnType<(typeof apiTestHooks)["onBefore"]>>,
66
- ) => Promise<void> | void;
67
- name: string;
68
- timeout?: number;
69
- };
@@ -1,11 +0,0 @@
1
- import type { Meta } from "../../../src/meta";
2
- import type { Context } from "../../../src/context";
3
-
4
- export function defineApi<ApiT extends Api>(api: ApiT): ApiT & { isApi: true } {
5
- return { ...api, isApi: true };
6
- }
7
-
8
- export type Api = {
9
- meta: Meta;
10
- action: (params: any, context: Context) => Promise<unknown> | unknown;
11
- };
@@ -1,47 +0,0 @@
1
- import type { MilkioApp } from "..";
2
-
3
- export type CommandOptions = {
4
- notFoundHandler?: (event: { name: string; path: string; commands: Array<string>; options: Record<string, string | true> }) => void | Promise<void>;
5
- };
6
-
7
- export function defineCommandHandler(app: MilkioApp, options: CommandOptions = {}) {
8
- const call = async (argv: Array<string>) => {
9
- const params = {
10
- path: "default",
11
- commands: [] as Array<string>,
12
- options: {} as Record<string, string | true>,
13
- };
14
- for (const v of argv.slice(3)) {
15
- if (v.startsWith("--") && v.includes("=")) {
16
- const vSplited = v.split("=");
17
- params.options[vSplited[0].slice(2)] = vSplited.slice(1, vSplited.length).join("=");
18
- } else if (v.startsWith("--")) {
19
- params.options[v.slice(2)] = true;
20
- } else if (v.startsWith("-") && v.includes("=")) {
21
- const vSplited = v.split("=");
22
- params.options[vSplited[0].slice(1)] = vSplited.slice(1, vSplited.length).join("=");
23
- } else if (v.startsWith("-")) {
24
- params.options[v.slice(1)] = true;
25
- } else {
26
- params.commands.push(v);
27
- }
28
- }
29
- if (argv.length === 2) params.path = `$/default`;
30
- else params.path = `$/${argv[2] ?? "default"}`;
31
-
32
- // @ts-ignore
33
- const result = await app.execute(params.path as any, { params: params });
34
- if (!result.success) {
35
- if (result.fail.code === "NOT_FOUND") {
36
- if (options.notFoundHandler) await options.notFoundHandler({ ...params, name: argv.length === 2 ? "default" : argv[2] ?? "default" });
37
- return;
38
- }
39
- if (result.fail.code !== "INTERNAL_SERVER_ERROR") {
40
- console.log(result.fail.message);
41
- return;
42
- }
43
- }
44
- };
45
-
46
- return call;
47
- }
@@ -1,32 +0,0 @@
1
- export function defineConfig<T>(handler: (options: { config: typeof configFn }) => T): T {
2
- const result = handler({ config: configFn });
3
- if (!result) throw new Error("defineConfig must return a value, Did you forget to add a return statement?");
4
- if (typeof result !== "object" || Array.isArray(result)) throw new Error("defineConfig must return an object.");
5
- if ("environment" in result && "done" in result && typeof result["environment"] === "function" && typeof result["done"] === "function") throw new Error("Did you accidentally return the config method without adding `.done()`?");
6
- return result;
7
- }
8
-
9
- function configFn<ConfigT extends Config>(config: ConfigT): ConfigMore<ConfigT> {
10
- let skipMore = false;
11
-
12
- const configMore: ConfigMore<ConfigT> = {
13
- environment: (when, configMixin) => {
14
- if (skipMore || !when()) return configMore;
15
- skipMore = true;
16
- for (const key in configMixin) (config as any)[key] = configMixin[key];
17
- return configMore;
18
- },
19
- done: () => {
20
- return config;
21
- },
22
- } satisfies ConfigMore<ConfigT>;
23
-
24
- return configMore;
25
- }
26
-
27
- export type Config = Record<string, unknown>;
28
-
29
- export type ConfigMore<ConfigT extends Config> = {
30
- environment: (when: () => boolean, config: Partial<ConfigT>) => ConfigMore<ConfigT>;
31
- done: () => ConfigT;
32
- };