milkio 0.0.9 → 0.0.11

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 (45) hide show
  1. package/.co.toml +0 -0
  2. package/api-test/index.ts +64 -0
  3. package/c.ts +39 -57
  4. package/defines/define-api-test.ts +3 -3
  5. package/defines/define-api.ts +3 -3
  6. package/defines/define-http-handler.ts +60 -69
  7. package/defines/define-middleware.ts +2 -2
  8. package/defines/define-use.ts +6 -6
  9. package/index.ts +23 -22
  10. package/kernel/context.ts +1 -2
  11. package/kernel/fail.ts +6 -6
  12. package/kernel/logger.ts +38 -38
  13. package/kernel/meta.ts +5 -5
  14. package/kernel/middleware.ts +16 -16
  15. package/kernel/milkio.ts +70 -95
  16. package/kernel/runtime.ts +2 -7
  17. package/kernel/validate.ts +5 -5
  18. package/package.json +4 -1
  19. package/scripts/gen-insignificant.ts +261 -0
  20. package/scripts/gen-significant.ts +176 -0
  21. package/{scripts → scripts-del}/build-cookbook.ts +119 -119
  22. package/scripts-del/build-dto.ts +65 -0
  23. package/{scripts → scripts-del}/generate/generate-app-partial.ts +31 -31
  24. package/{scripts → scripts-del}/generate/generate-app.ts +41 -41
  25. package/scripts-del/generate/generate-database.ts +22 -0
  26. package/scripts-del/generate-partial.ts +15 -0
  27. package/scripts-del/generate.ts +23 -0
  28. package/templates/api.ts +4 -4
  29. package/types.ts +29 -19
  30. package/utils/create-template.ts +5 -5
  31. package/utils/create-ulid.ts +3 -3
  32. package/utils/env-to-boolean.ts +5 -5
  33. package/utils/env-to-number.ts +2 -2
  34. package/utils/env-to-string.ts +2 -2
  35. package/utils/exec.ts +12 -12
  36. package/utils/handle-catch-error.ts +10 -10
  37. package/utils/remove-dir.ts +11 -11
  38. package/utils/tson.ts +2 -2
  39. package/defines/define-api-test-handler.ts +0 -71
  40. package/kernel/config.ts +0 -14
  41. package/scripts/build-dto.ts +0 -65
  42. package/scripts/generate/generate-database.ts +0 -22
  43. package/scripts/generate-database.ts +0 -23
  44. package/scripts/generate-partial.ts +0 -15
  45. package/scripts/generate.ts +0 -23
@@ -1,27 +1,27 @@
1
1
  /* eslint-disable no-console */
2
2
 
3
- import ejs from "ejs";
4
- import { join } from "node:path";
5
- import { existsSync, mkdirSync } from "node:fs";
6
- import { cwd, exit } from "node:process";
7
- import { unlink, writeFile } from "node:fs/promises";
8
- import { exec as nodeExec } from "node:child_process";
9
- import { camel, hyphen } from "@poech/camel-hump-under";
10
- import { Glob } from "bun";
3
+ import ejs from "ejs"
4
+ import { join } from "node:path"
5
+ import { existsSync, mkdirSync } from "node:fs"
6
+ import { cwd, exit } from "node:process"
7
+ import { unlink, writeFile } from "node:fs/promises"
8
+ import { exec as nodeExec } from "node:child_process"
9
+ import { camel, hyphen } from "@poech/camel-hump-under"
10
+ import { Glob } from "bun"
11
11
 
12
12
  const utils = {
13
13
  camel: (str: string) => camel(str).replaceAll("-", "").replaceAll("_", ""),
14
14
  hyphen: (str: string) => hyphen(str).replaceAll("_", "")
15
- };
15
+ }
16
16
 
17
17
  export async function generateApp() {
18
18
  // Delete the files generated in the past and regenerate them
19
19
  try {
20
- await unlink(join(cwd(), "generate", "api-schema.ts"));
20
+ await unlink(join(cwd(), "generated", "api-schema.ts"))
21
21
  } catch (error) {} // Maybe the file does not exist
22
22
 
23
- if (!existsSync(join("generate", "README.md"))) {
24
- await writeFile(join("generate", "README.md"), "⚠️ All files in this directory are generated by milkio. Please do not modify the content, otherwise your modifications will be overwritten in the next generation.");
23
+ if (!existsSync(join("generated", "README.md"))) {
24
+ await writeFile(join("generated", "README.md"), "⚠️ All files in this directory are generated by milkio. Please do not modify the content, otherwise your modifications will be overwritten in the next generation.")
25
25
  }
26
26
 
27
27
  // Write a basic framework to ensure that there are no errors when reading later
@@ -31,53 +31,53 @@ export async function generateApp() {
31
31
  apiMethodsSchema: {},
32
32
  apiMethodsTypeSchema: {},
33
33
  }
34
- `;
35
- await writeFile(join(cwd(), "generate", "api-schema.ts"), ejs.render(apiSchemaSkeleton, { utils }));
34
+ `
35
+ await writeFile(join(cwd(), "generated", "api-schema.ts"), ejs.render(apiSchemaSkeleton, { utils }))
36
36
 
37
37
  // Generate api-schema.ts file through templates
38
38
  const templateVars = {
39
39
  utils,
40
40
  apiPaths: [] as Array<string>,
41
41
  apiTestPaths: [] as Array<string>
42
- };
42
+ }
43
43
 
44
- const glob = new Glob("**/*.ts");
45
- const appFiles = await Array.fromAsync(glob.scan({ cwd: join(cwd(), "src", "apps") }));
44
+ const glob = new Glob("**/*.ts")
45
+ const appFiles = await Array.fromAsync(glob.scan({ cwd: join(cwd(), "src", "apps") }))
46
46
 
47
47
  for (const path of appFiles) {
48
- if (!path.endsWith(".ts")) continue;
49
- const module = await import(/* @vite-ignore */ `../../../../src/apps/${path}`);
48
+ if (!path.endsWith(".ts")) continue
49
+ const module = await import(/* @vite-ignore */ `../../../../src/apps/${path}`)
50
50
  if (module?.api?.isApi === true) {
51
51
  // Exclude disallowed characters
52
52
  if (path.includes("_")) {
53
- console.error(`\n\nPath: ` + `"${path}"`);
54
- console.error(`Do not use "_" in the path. If you want to add a separator between words, please use "-".\n`);
55
- exit(1);
53
+ console.error(`\n\nPath: ` + `"${path}"`)
54
+ console.error(`Do not use "_" in the path. If you want to add a separator between words, please use "-".\n`)
55
+ exit(1)
56
56
  }
57
57
  if (!/^[a-z0-9/-]+$/.test(path.slice(0, -3))) {
58
- console.error(`\n\nPath: ` + `"${path}"`);
59
- console.error(`The path can only contain lowercase letters, numbers, and "-".\n`);
60
- exit(1);
58
+ console.error(`\n\nPath: ` + `"${path}"`)
59
+ console.error(`The path can only contain lowercase letters, numbers, and "-".\n`)
60
+ exit(1)
61
61
  }
62
62
 
63
- templateVars.apiPaths.push(path);
63
+ templateVars.apiPaths.push(path)
64
64
 
65
65
  if (module?.test?.isApiTest === true) {
66
- templateVars.apiTestPaths.push(path);
66
+ templateVars.apiTestPaths.push(path)
67
67
  }
68
68
 
69
69
  // typia
70
- const filePath = join(cwd(), "generate", "raw", "apps", path);
71
- const dirPath = join(cwd(), "generate", "raw", "apps", path).split("/").slice(0, -1).join("/");
70
+ const filePath = join(cwd(), "generated", "raw", "apps", path)
71
+ const dirPath = join(cwd(), "generated", "raw", "apps", path).split("/").slice(0, -1).join("/")
72
72
  if (!existsSync(dirPath)) {
73
- mkdirSync(dirPath, { recursive: true });
73
+ mkdirSync(dirPath, { recursive: true })
74
74
  }
75
- let importPath = "../../../";
75
+ let importPath = "../../../"
76
76
 
77
77
  for (let i = 0; i < path.split("/").length - 1; i++) {
78
- importPath = importPath + "../";
78
+ importPath = importPath + "../"
79
79
  }
80
- importPath = importPath + "src/apps";
80
+ importPath = importPath + "src/apps"
81
81
  const template = `
82
82
  import typia from "typia";
83
83
  import { _validate, type ExecuteResultSuccess } from "milkio";
@@ -89,15 +89,15 @@ export const params = async (params: any) => typia.misc.validatePrune<ParamsT>(p
89
89
  type ResultsT = Awaited<ReturnType<typeof <%= utils.camel(path.replaceAll('/', '$').slice(0, -${3})) %>['api']['action']>>;
90
90
  export const results = async (results: any) => { _validate(typia.validate<TSONEncode<ExecuteResultSuccess<ResultsT>>>(results)); return typia.json.stringify<TSONEncode<ExecuteResultSuccess<ResultsT>>>(results); };
91
91
 
92
- `.trim();
92
+ `.trim()
93
93
  // export const paramsSchema = typia.json.application<[{ data: ParamsT }], "swagger">();
94
94
 
95
- await writeFile(filePath, ejs.render(template, { ...templateVars, path }));
95
+ await writeFile(filePath, ejs.render(template, { ...templateVars, path }))
96
96
  }
97
97
  }
98
98
 
99
99
  await writeFile(
100
- join(cwd(), "generate", "api-schema.ts"),
100
+ join(cwd(), "generated", "api-schema.ts"),
101
101
  ejs.render(
102
102
  `
103
103
  /**
@@ -127,7 +127,7 @@ export default {
127
127
  `.trim(),
128
128
  templateVars
129
129
  )
130
- );
130
+ )
131
131
 
132
132
  // api
133
133
  const apiValidatorTemplate = `/**
@@ -141,12 +141,12 @@ export default {
141
141
  <% } %>
142
142
  },
143
143
  }
144
- `.trim();
145
- await writeFile(join(cwd(), "generate", "raw", "api-validator.ts"), ejs.render(apiValidatorTemplate, templateVars));
144
+ `.trim()
145
+ await writeFile(join(cwd(), "generated", "raw", "api-validator.ts"), ejs.render(apiValidatorTemplate, templateVars))
146
146
 
147
147
  await new Promise((resolve) =>
148
148
  nodeExec("bun run ./node_modules/typia/lib/executable/typia.js generate --input generate/raw --output generate/products --project tsconfig.json", (e) => {
149
- resolve(e);
149
+ resolve(e)
150
150
  })
151
- );
151
+ )
152
152
  }
@@ -0,0 +1,22 @@
1
+ /* eslint-disable no-console */
2
+
3
+ import ejs from "ejs"
4
+ import { join } from "node:path"
5
+ import { existsSync } from "node:fs"
6
+ import { cwd } from "node:process"
7
+ import { writeFile } from "node:fs/promises"
8
+ import { Glob } from "bun"
9
+
10
+ export async function generateDatabase() {
11
+ if (existsSync(join(cwd(), "src", "databases"))) {
12
+ if (!existsSync(join("generated", "database-schema.ts"))) {
13
+ await writeFile(join("generated", "database-schema.ts"), ``)
14
+ }
15
+ const filePath = join(cwd(), "generated", "database-schema.ts")
16
+ const glob = new Glob("**/*.ts")
17
+ const databaseFiles = await Array.fromAsync(glob.scan({ cwd: join(cwd(), "src", "databases") }))
18
+ const template = `<% for (const path of ${"databaseFiles"}) { %>export * from '${"../src/databases"}/<%= path.slice(0, -3) %>'
19
+ <% } %>`
20
+ await writeFile(filePath, ejs.render(template, { databaseFiles }))
21
+ }
22
+ }
@@ -0,0 +1,15 @@
1
+ /* eslint-disable no-console, @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument */
2
+
3
+ import { exit } from "node:process"
4
+ import { generateApp } from "./generated/generate-app"
5
+ console.log("Milkio Quick Generating..")
6
+
7
+ export async function generatePartial() {
8
+ await generateApp()
9
+ }
10
+
11
+ await generatePartial()
12
+
13
+ console.log("\n✅ Milkio Generated!")
14
+
15
+ exit(0)
@@ -0,0 +1,23 @@
1
+ /* eslint-disable no-console */
2
+
3
+ import { join } from "node:path"
4
+ import { existsSync, mkdirSync } from "node:fs"
5
+ import { exit } from "node:process"
6
+ import { generateApp } from "./generated/generate-app"
7
+
8
+ export async function generate() {
9
+ // Make sure that the existing directories are all present
10
+ existsSync(join("generated")) || mkdirSync(join("generated"))
11
+ existsSync(join("generated", "raw")) || mkdirSync(join("generated", "raw"))
12
+ existsSync(join("generated", "raw", "apps")) || mkdirSync(join("generated", "raw", "apps"))
13
+
14
+ await generateApp()
15
+ }
16
+
17
+ console.log("Milkio Generating..")
18
+
19
+ await generate()
20
+
21
+ console.log("\n✅ Milkio Generated!")
22
+
23
+ exit(0)
package/templates/api.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { createTemplate } from "../utils/create-template";
2
- import { join } from "path";
1
+ import { createTemplate } from "../utils/create-template"
2
+ import { join } from "path"
3
3
 
4
4
  await createTemplate(async (tools) => {
5
5
  return {
@@ -45,5 +45,5 @@ export const test = defineApiTest(api, [
45
45
  }
46
46
  ]);
47
47
  `.trim()
48
- };
49
- });
48
+ }
49
+ })
package/types.ts CHANGED
@@ -1,29 +1,29 @@
1
1
  /* eslint-disable @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any */
2
2
 
3
- import { type createMilkioApp } from ".";
4
- import type { failCode } from "../../src/fail-code";
3
+ import { type createMilkioApp } from "."
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
- export type ExecuteId = string | "global";
8
+ export type ExecuteId = string | "global"
9
9
 
10
- export type FailEnumerates = typeof failCode;
10
+ export type FailEnumerates = typeof failCode
11
11
 
12
- export type HTTPRequest = Request;
12
+ export type HTTPRequest = Request
13
13
 
14
- export type HTTPResponse = Override<ResponseInit & { body: string | null | undefined }, { headers: NonNullable<ResponseInit["headers"]> }>;
14
+ export type HTTPResponse = Override<ResponseInit & { body: string | null | undefined }, { headers: NonNullable<ResponseInit["headers"]> }>
15
15
 
16
16
  export type Fail<FailCode extends keyof FailEnumerates> = {
17
- code: FailCode;
18
- message: string;
19
- data: Parameters<FailEnumerates[FailCode]>[0];
20
- };
17
+ code: FailCode
18
+ message: string
19
+ data: Parameters<FailEnumerates[FailCode]>[0]
20
+ }
21
21
 
22
22
  export type MilkioMeta = {
23
23
  //
24
- };
24
+ }
25
25
 
26
- export type Cookbook = Record<string, CookbookItem>;
26
+ export type Cookbook = Record<string, CookbookItem>
27
27
 
28
28
  export type CookbookItem = {
29
29
  title?: string;
@@ -32,9 +32,19 @@ export type CookbookItem = {
32
32
  cases: Array<{
33
33
  name: string;
34
34
  handler: string;
35
- }>;
36
- };
37
-
38
- export type Override<P, S> = Omit<P, keyof S> & S;
39
-
40
- export type Mixin<T, U> = U & Omit<T, keyof U>;
35
+ }>
36
+ }
37
+
38
+ export type Override<P, S> = Omit<P, keyof S> & S
39
+
40
+ export type Mixin<T, U> = U & Omit<T, keyof U>
41
+
42
+ export type MilkioConfig = {
43
+ generate?: {
44
+ significant?: Array<string>;
45
+ insignificant?: Array<string>;
46
+ },
47
+ menubar?: {
48
+ commands?: Array<{ name?: string, script?: string, icon?: string }>;
49
+ }
50
+ };
@@ -1,5 +1,5 @@
1
- import { argv } from "bun";
2
- import { camel, hump, hyphen } from "@poech/camel-hump-under";
1
+ import { argv } from "bun"
2
+ import { camel, hump, hyphen } from "@poech/camel-hump-under"
3
3
 
4
4
  export type CreateTemplateTools = {
5
5
  name: string;
@@ -26,7 +26,7 @@ export async function createTemplate(fn: CreateTemplateFn) {
26
26
  camel: (str: string) => camel(str).replaceAll("-", "").replaceAll("_", ""),
27
27
  hump: (str: string) => hump(str).replaceAll("-", "").replaceAll("_", ""),
28
28
  hyphen: (str: string) => hyphen(str).replaceAll("_", "")
29
- };
30
- const file = await fn(tools);
31
- await Bun.write(file.path, file.content);
29
+ }
30
+ const file = await fn(tools)
31
+ await Bun.write(file.path, file.content)
32
32
  }
@@ -1,5 +1,5 @@
1
- import { monotonicFactory } from "ulidx";
1
+ import { monotonicFactory } from "ulidx"
2
2
 
3
- const ulid = monotonicFactory();
3
+ const ulid = monotonicFactory()
4
4
 
5
- export const createUlid = () => ulid();
5
+ export const createUlid = () => ulid()
@@ -1,11 +1,11 @@
1
1
  export function envToBoolean(value: string | number | undefined, defaultValue: boolean) {
2
- if (value === "true") return true;
2
+ if (value === "true") return true
3
3
 
4
- if (value === "false") return false;
4
+ if (value === "false") return false
5
5
 
6
- if (value === "") return false;
6
+ if (value === "") return false
7
7
 
8
- if (undefined === value) return defaultValue;
8
+ if (undefined === value) return defaultValue
9
9
 
10
- return Boolean(value);
10
+ return Boolean(value)
11
11
  }
@@ -1,5 +1,5 @@
1
1
  export function envToNumber(value: string | undefined, defaultValue: number) {
2
- if (value === undefined) return defaultValue;
2
+ if (value === undefined) return defaultValue
3
3
 
4
- return Number.parseInt(value, 10);
4
+ return Number.parseInt(value, 10)
5
5
  }
@@ -1,5 +1,5 @@
1
1
  export function envToString(value: string | number | undefined, defaultValue: string) {
2
- if (value === undefined) return defaultValue;
2
+ if (value === undefined) return defaultValue
3
3
 
4
- return `${value}`;
4
+ return `${value}`
5
5
  }
package/utils/exec.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { env, type SpawnOptions } from "bun";
1
+ import { env, type SpawnOptions } from "bun"
2
2
 
3
3
  /**
4
4
  * This is a legacy wrapper that was written before $ Shell was created.
@@ -7,21 +7,21 @@ import { env, type SpawnOptions } from "bun";
7
7
 
8
8
  export const exec = async (cwd: string, command: Array<string>, options: Partial<SpawnOptions.OptionsObject> = {}) => {
9
9
  return new Promise((resolve, reject) => {
10
- if (!("cwd" in options)) options.cwd = cwd;
11
- if (!("stdin" in options)) options.stdin = "inherit";
12
- if (!("stdout" in options)) options.stdout = "inherit";
13
- if (!("env" in options)) options.env = { ...env };
10
+ if (!("cwd" in options)) options.cwd = cwd
11
+ if (!("stdin" in options)) options.stdin = "inherit"
12
+ if (!("stdout" in options)) options.stdout = "inherit"
13
+ if (!("env" in options)) options.env = { ...env }
14
14
 
15
15
  options.onExit = (proc, exitCode, signalCode, error) => {
16
16
  // eslint-disable-next-line prefer-promise-reject-errors
17
- if (exitCode !== 0) reject({ proc, exitCode, signalCode, error });
18
- else resolve({ proc, exitCode, signalCode, error });
19
- };
17
+ if (exitCode !== 0) reject({ proc, exitCode, signalCode, error })
18
+ else resolve({ proc, exitCode, signalCode, error })
19
+ }
20
20
 
21
21
  try {
22
- Bun.spawn(command, options);
22
+ Bun.spawn(command, options)
23
23
  } catch (error) {
24
- reject(error);
24
+ reject(error)
25
25
  }
26
- });
27
- };
26
+ })
27
+ }
@@ -1,17 +1,17 @@
1
- import { failCode } from "../../../src/fail-code";
2
- import { useLogger, type ExecuteId, type ExecuteResult } from "..";
1
+ import { failCode } from "../../../src/fail-code"
2
+ import { useLogger, type ExecuteId, type ExecuteResult } from ".."
3
3
 
4
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
5
  export function hanldeCatchError(error: any, executeId: ExecuteId): ExecuteResult<any> {
6
- const logger = useLogger(executeId);
6
+ const logger = useLogger(executeId)
7
7
 
8
- logger.error("\nError Data: " + JSON.stringify(error));
9
- if (error.stack) logger.error("\nError Stack: ", error.stack);
10
- else logger.error("\nError Stack: ", error);
8
+ logger.error("\nError Data: " + JSON.stringify(error))
9
+ if (error.stack) logger.error("\nError Stack: ", error.stack)
10
+ else logger.error("\nError Stack: ", error)
11
11
 
12
12
  if (error.name !== "MilkioReject") {
13
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`);
14
+ logger.error(`FailCode: INTERNAL_SERVER_ERROR`)
15
15
 
16
16
  return {
17
17
  executeId,
@@ -21,9 +21,9 @@ export function hanldeCatchError(error: any, executeId: ExecuteId): ExecuteResul
21
21
  message: failCode.INTERNAL_SERVER_ERROR(),
22
22
  data: undefined
23
23
  }
24
- };
24
+ }
25
25
  } else {
26
- logger.error(`FailCode: ${error.code}`);
26
+ logger.error(`FailCode: ${error.code}`)
27
27
  return {
28
28
  executeId,
29
29
  success: false,
@@ -32,6 +32,6 @@ export function hanldeCatchError(error: any, executeId: ExecuteId): ExecuteResul
32
32
  message: error.message,
33
33
  data: error.data
34
34
  }
35
- };
35
+ }
36
36
  }
37
37
  }
@@ -1,22 +1,22 @@
1
- import { existsSync, lstatSync, readdirSync, rmdirSync, unlinkSync } from "node:fs";
2
- import path from "node:path";
1
+ import { existsSync, lstatSync, readdirSync, rmdirSync, unlinkSync } from "node:fs"
2
+ import path from "node:path"
3
3
 
4
4
  export function removeDir(pathstr: string, skips: Array<string> = []) {
5
- if (!existsSync(pathstr)) return;
6
- const files = readdirSync(pathstr);
5
+ if (!existsSync(pathstr)) return
6
+ const files = readdirSync(pathstr)
7
7
  files.forEach((file) => {
8
- const dirname = path.resolve(pathstr, file);
9
- const stats = lstatSync(dirname);
8
+ const dirname = path.resolve(pathstr, file)
9
+ const stats = lstatSync(dirname)
10
10
  for (const skip of skips) {
11
- if (dirname.startsWith(skip)) return;
11
+ if (dirname.startsWith(skip)) return
12
12
  }
13
13
  if (stats.isDirectory()) {
14
- removeDir(dirname);
14
+ removeDir(dirname)
15
15
  } else {
16
- unlinkSync(dirname);
16
+ unlinkSync(dirname)
17
17
  }
18
- });
18
+ })
19
19
  try {
20
- rmdirSync(pathstr);
20
+ rmdirSync(pathstr)
21
21
  } catch (error) {}
22
22
  }
package/utils/tson.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { TSON as _TSON } from "@southern-aurora/tson";
1
+ import { TSON as _TSON } from "@southern-aurora/tson"
2
2
 
3
- export const TSON = _TSON;
3
+ export const TSON = _TSON
@@ -1,71 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unsafe-argument, no-console, @typescript-eslint/no-explicit-any */
2
- import { exit } from "node:process";
3
- import schema from "../../../generate/api-schema";
4
- import { type MilkioApp } from "..";
5
-
6
- export const defineApiTestHandler = async <Paths extends Array<keyof (typeof schema)["apiTestsSchema"]>>(app: MilkioApp, paths: Paths | string | 1 | undefined) => {
7
- console.log(`🧊 Milkio Api Testing..\n`);
8
-
9
- if (!paths) {
10
- console.log("🧊 No paths specified.");
11
- exit(1);
12
- }
13
-
14
- if (paths === "1" || paths === 1) {
15
- paths = Object.keys(schema.apiTestsSchema) as unknown as Paths;
16
- } else if (typeof paths === "string") {
17
- if (!paths.startsWith("[")) {
18
- paths = [paths] as Paths;
19
- } else {
20
- paths = JSON.parse(paths) as Paths;
21
- }
22
- }
23
-
24
- const tests = [];
25
- const startedAt = new Date().getTime();
26
-
27
- for (let path of paths) {
28
- if (path.startsWith("/")) path = path.slice(1) as Paths[number];
29
- tests.push(
30
- // @ts-ignore
31
- (async () => {
32
- // @ts-ignore
33
- const module = await schema.apiTestsSchema[path]().module;
34
- const cases = module.test.getCases();
35
- let i = 0;
36
- for (const cs of cases) {
37
- ++i;
38
- const csStartedAt = new Date().getTime();
39
- const clear = setTimeout(() => {
40
- console.error(`------`);
41
- console.error(`❌ TIMEOUT -- More than ${cs.timeout ?? 8192}ms`);
42
- console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i}`);
43
- console.error(`------`);
44
- exit(1);
45
- }, cs.timeout ?? 8192);
46
- await cs.handler({
47
- execute: async (params: any, headers?: any, options?: any) => app.execute(path, params, headers ?? {}, options),
48
- executeOther: async (path: any, params: any, headers?: any, options?: any) => app.execute(path, params, headers ?? {}, options),
49
- reject: (message?: string) => {
50
- console.error(`------`);
51
- console.error(`❌ REJECT -- ${message ?? "Test not satisfied"}`);
52
- console.error(` ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`);
53
- console.error(`------`);
54
- exit(1);
55
- }
56
- } as any);
57
- clearTimeout(clear);
58
- console.log(`✅ DIRECT -- ${cs.name} | Path: src/apps/${path as string}.ts | Case: ${i} | Time: ${new Date().getTime() - csStartedAt}ms`);
59
- }
60
- })()
61
- );
62
- }
63
-
64
- await Promise.all(tests);
65
-
66
- const endedAt = new Date().getTime();
67
-
68
- console.log(`\n✅ All tests passed.`);
69
- console.log(`🧊 Milkio Api Testing took ${((endedAt - startedAt) / 1000).toFixed(2)}s\n`);
70
- exit(0);
71
- };
package/kernel/config.ts DELETED
@@ -1,14 +0,0 @@
1
- import { cwd, env } from "node:process";
2
- import { envToBoolean, envToNumber, envToString } from "..";
3
-
4
- export const configMilkio = {
5
- cwd: cwd(),
6
- port: envToNumber(env.PORT, 9000),
7
- milkioRunMode: envToString(env.MILKIO_RUN_MODE, "DEFAULT"),
8
- milkioTest: envToString(env.MILKIO_TEST, ""),
9
- debug: envToBoolean(env.DEBUG, false),
10
- ignorePathLevel: envToNumber(env.IGNORE_PATH_LEVEL, 0),
11
- corsAllowMethods: envToString(env.CORS_ALLOW_METHODS, "*"),
12
- corsAllowHeaders: envToString(env.CORS_ALLOW_HEADERS, "*"),
13
- corsAllowOrigin: envToString(env.CORS_ALLOW_ORIGIN, "*")
14
- };
@@ -1,65 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { cwd, platform } from "node:process";
3
- import { exec as nodeExec } from "node:child_process";
4
- import { removeDir } from "../utils/remove-dir";
5
- import { join } from "node:path";
6
- import { copyFile, mkdir } from "node:fs/promises";
7
-
8
- export async function buildDTO() {
9
- console.log("🧊 Milkio DTO Building..");
10
-
11
- removeDir(join(cwd(), "packages", "dto", "dist"));
12
- removeDir(join(cwd(), "packages", "dto", "generate"));
13
- await mkdir(join(cwd(), "packages", "dto", "dist"));
14
- await mkdir(join(cwd(), "packages", "dto", "generate"));
15
-
16
- // Generate the corresponding types for the files in the project and output them to the /packages/dto/generate directory.
17
- await new Promise((resolve) =>
18
- nodeExec("bun ./node_modules/typescript/bin/tsc --project tsconfig.build-dto.json", (e, stdout) => {
19
- resolve(e);
20
- })
21
- );
22
- await copyFile(join(cwd(), "src", "fail-code.ts"), join(cwd(), "packages", "dto", "generate", "src", "fail-code.ts"));
23
-
24
- // Packaging type for the dto
25
- await new Promise((resolve) =>
26
- nodeExec("cd ./packages/dto && bunx tsc", (e) => {
27
- resolve(e);
28
- })
29
- );
30
-
31
- // build /src/dto/index.ts to js
32
- await Bun.build({
33
- entrypoints: ["./packages/dto/index.ts"],
34
- outdir: "./packages/dto"
35
- });
36
-
37
- const root = join(cwd(), "packages", "dto");
38
-
39
- console.log("🧊 Milkio DTO Build Finished");
40
- console.log("\x1B[2m");
41
- console.log("Now, your latest code (including changes to your interface) is built to the latest version and waiting for your release!");
42
- console.log("");
43
- console.log("If you want to publish it to NPM, you can use a command similar to the following.");
44
- console.log(`(But before that, you may need to modify the package name (${join(cwd(), "packages", "dto", "package.json")}) and login to your NPM account or private NPM repository)`);
45
-
46
- if (platform !== "win32") {
47
- console.log("You can publish it to npm by running this commands:\n");
48
- console.log("\u001B[0m---");
49
- console.log(`cd ${join(root)} \\`);
50
- console.log(" && npm version major \\");
51
- console.log(" && npm publish --access public \\");
52
- console.log(` && cd ${join(cwd())}`);
53
- } else {
54
- console.log("You can publish it to npm by running this commands (use \x1B[42mPowerShell\x1B[0m):");
55
- console.log("\u001B[0m---");
56
- console.log('$ErrorActionPreference = "Stop";');
57
- console.log(`Set-Location ${join(root)};`);
58
- console.log("npm version major;");
59
- console.log("npm publish --access public;");
60
- console.log(`Set-Location ${join(cwd())};`);
61
- }
62
- console.log("---");
63
- }
64
-
65
- await buildDTO();