elysia-autoload 0.0.3 → 0.1.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # elysia-autoload
2
2
 
3
- Plugin for [Elysia](https://elysiajs.com/) which autoload all routes in directory
3
+ Plugin for [Elysia](https://elysiajs.com/) which autoload all routes in directory and code-generate types for Eden
4
4
 
5
5
  ## Installation
6
6
 
@@ -55,12 +55,61 @@ Guide how `elysia-autoload` match routes
55
55
 
56
56
  ## Options
57
57
 
58
- | Key | Type | Default | Description |
59
- | -------- | -------- | --------------------------- | ------------------------------------------------------------------- |
60
- | pattern? | string | "\*\*_/\*_.{ts,js,mjs,cjs}" | [Glob patterns](<https://en.wikipedia.org/wiki/Glob_(programming)>) |
61
- | dir? | string | "./routes" | The folder where routes are located |
62
- | prefix? | string | | Prefix for routes |
63
- | schema? | Function | | Handler for providing routes guard schema |
58
+ | Key | Type | Default | Description |
59
+ | -------- | --------------------------------------- | --------------------------- | ------------------------------------------------------------------- |
60
+ | pattern? | string | "\*\*_/\*_.{ts,js,mjs,cjs}" | [Glob patterns](<https://en.wikipedia.org/wiki/Glob_(programming)>) |
61
+ | dir? | string | "./routes" | The folder where routes are located |
62
+ | prefix? | string | | Prefix for routes |
63
+ | types? | true \| [Types Options](#types-options) | | Options to configure type code-generation. |
64
+ | schema? | Function | | Handler for providing routes guard schema |
65
+
66
+ ### Types Options
67
+
68
+ | Key | Type | Default | Description |
69
+ | --------- | ------ | ------------------- | -------------------------------------------- |
70
+ | output? | string | "./routes-types.ts" | Type code-generation output |
71
+ | typeName? | string | "Routes" | Name for code-generated global type for Eden |
72
+
73
+ ### Usage of types code-generation for eden
74
+
75
+ ```ts
76
+ // app.ts
77
+ import { Elysia } from "elysia";
78
+ import { autoload } from "elysia-autoload";
79
+
80
+ const app = new Elysia()
81
+ .use(
82
+ autoload({
83
+ types: {
84
+ output: "./routes.ts",
85
+ typeName: "Routes",
86
+ }, // or pass true for use default params
87
+ }),
88
+ )
89
+ .listen(3000);
90
+
91
+ export type ElysiaApp = typeof app;
92
+ ```
93
+
94
+ ```ts
95
+ // client.ts
96
+
97
+ import { edenTreaty } from "@elysiajs/eden";
98
+
99
+ // Routes are a global type so you don't need to import it.
100
+
101
+ const app = edenTreaty<Routes>("http://localhost:3002");
102
+
103
+ const { data } = await app.test["some-path-param"].get({
104
+ $query: {
105
+ key: 2,
106
+ },
107
+ });
108
+
109
+ console.log(data);
110
+ ```
111
+
112
+ Example of app with types code-generation you can see in [example](https://github.com/kravetsone/elysia-autoload/tree/main/example)
64
113
 
65
114
  ### Usage of schema handler
66
115
 
package/dist/index.d.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  import Elysia from "elysia";
2
- export interface AutoloadOptions {
2
+ type TSchemaHandler = ({ path, url, }: {
3
+ path: string;
4
+ url: string;
5
+ }) => Parameters<InstanceType<typeof Elysia>["group"]>[1];
6
+ export interface ITypesOptions {
7
+ output?: string;
8
+ typeName?: string;
9
+ }
10
+ export interface IAutoloadOptions {
3
11
  pattern?: string;
4
12
  dir?: string;
5
13
  prefix?: string;
6
- schema?: ({ path, url, }: {
7
- path: string;
8
- url: string;
9
- }) => Parameters<InstanceType<typeof Elysia>["group"]>[1];
14
+ schema?: TSchemaHandler;
15
+ types?: ITypesOptions | true;
10
16
  }
11
- export declare function autoload({ pattern, dir, prefix, schema, }?: AutoloadOptions): Promise<Elysia<"", {
17
+ export declare function autoload({ pattern, dir, prefix, schema, types, }?: IAutoloadOptions): Promise<Elysia<"", {
12
18
  request: {};
13
19
  store: {};
14
20
  derive: {};
@@ -17,3 +23,4 @@ export declare function autoload({ pattern, dir, prefix, schema, }?: AutoloadOpt
17
23
  type: {};
18
24
  error: {};
19
25
  }, {}, {}, {}, false>>;
26
+ export * from "./types";
package/dist/index.js CHANGED
@@ -1,11 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
17
  exports.autoload = void 0;
4
18
  const elysia_1 = require("elysia");
5
19
  const node_fs_1 = require("node:fs");
6
20
  const node_path_1 = require("node:path");
7
21
  const utils_1 = require("./utils");
8
- async function autoload({ pattern, dir, prefix, schema, } = {}) {
22
+ const TYPES_OUTPUT_DEFAULT = "./routes-types.ts";
23
+ const TYPES_TYPENAME_DEFAULT = "Routes";
24
+ async function autoload({ pattern, dir, prefix, schema, types, } = {}) {
9
25
  const directoryPath = (0, utils_1.getPath)(dir || "./routes");
10
26
  if (!(0, node_fs_1.existsSync)(directoryPath))
11
27
  throw new Error(`Directory ${directoryPath} doesn't exists`);
@@ -17,13 +33,16 @@ async function autoload({ pattern, dir, prefix, schema, } = {}) {
17
33
  pattern,
18
34
  dir,
19
35
  prefix,
36
+ types,
20
37
  },
21
38
  });
22
39
  const glob = new Bun.Glob(pattern || "**/*.{ts,js,mjs,cjs}");
23
40
  const files = await Array.fromAsync(glob.scan({
24
41
  cwd: directoryPath,
25
42
  }));
43
+ const paths = [];
26
44
  for await (const path of (0, utils_1.sortByNestedParams)(files)) {
45
+ const fullPath = (0, node_path_1.join)(directoryPath, path);
27
46
  const file = await Promise.resolve(`${(0, node_path_1.join)(directoryPath, path)}`).then(s => require(s));
28
47
  if (!file.default)
29
48
  throw new Error(`${path} don't provide export default`);
@@ -34,7 +53,27 @@ async function autoload({ pattern, dir, prefix, schema, } = {}) {
34
53
  // Тип "string" не может быть назначен для типа "TSchema".ts(2345)
35
54
  // @ts-expect-error why....
36
55
  app.group((prefix ?? "") + url, groupOptions, file.default);
56
+ if (types)
57
+ paths.push(fullPath.replace(directoryPath, ""));
58
+ }
59
+ if (types) {
60
+ const imports = paths.map((x, index) => `import Route${index} from "${directoryPath + x.replace(".ts", "")}";`);
61
+ await Bun.write((0, utils_1.getPath)(types === true || !types.output
62
+ ? TYPES_OUTPUT_DEFAULT
63
+ : types.output), [
64
+ `import type { ElysiaWithBaseUrl } from "elysia-autoload";`,
65
+ imports.join("\n"),
66
+ "",
67
+ "declare global {",
68
+ ` type ${types === true || !types.typeName
69
+ ? TYPES_TYPENAME_DEFAULT
70
+ : types.typeName} = ${paths
71
+ .map((x, index) => `ElysiaWithBaseUrl<"${(0, utils_1.transformToUrl)(x) || "/"}", ReturnType<typeof Route${index}>>`)
72
+ .join("\n & ")}`,
73
+ "}",
74
+ ].join("\n"));
37
75
  }
38
76
  return app;
39
77
  }
40
78
  exports.autoload = autoload;
79
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,8 @@
1
+ import type Elysia from "elysia";
2
+ import type { RouteBase } from "elysia";
3
+ type RemoveLastChar<T extends string> = T extends `${infer V}/` ? V : T;
4
+ type RoutesWithPrefix<Routes extends RouteBase, Prefix extends string> = {
5
+ [K in keyof Routes as `${Prefix}${RemoveLastChar<K & string>}`]: Routes[K];
6
+ };
7
+ export type ElysiaWithBaseUrl<BaseUrl extends string, ElysiaType extends Elysia> = ElysiaType extends Elysia<infer BasePath, infer Decorators, infer Definitions, infer ParentSchema, infer Macro, infer Routes, infer Scoped> ? Elysia<BasePath, Decorators, Definitions, ParentSchema, Macro, RoutesWithPrefix<Routes, BaseUrl>, Scoped> : never;
8
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/utils.js CHANGED
@@ -35,7 +35,7 @@ function transformToUrl(path) {
35
35
  for (const { regex, replacement } of replacements) {
36
36
  url = url.replace(regex, replacement);
37
37
  }
38
- return "/" + url;
38
+ return url;
39
39
  }
40
40
  exports.transformToUrl = transformToUrl;
41
41
  function getParamsCount(path) {
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "elysia-autoload",
3
- "version": "0.0.3",
3
+ "version": "0.1.0",
4
4
  "author": "kravetsone",
5
- "description": "Plugin for Elysia which autoload all routes in directory",
5
+ "main": "dist/index.js",
6
+ "description": "Plugin for Elysia which autoload all routes in directory and code-generate types for Eden",
7
+ "homepage": "https://github.com/kravetsone/elysia-autoload",
6
8
  "keywords": [
7
9
  "bun",
8
10
  "elysia",
@@ -12,23 +14,25 @@
12
14
  "filerouter",
13
15
  "autoroutes"
14
16
  ],
15
- "main": "dist/index.js",
16
17
  "scripts": {
17
18
  "prepublishOnly": "tsc",
18
- "lint": "eslint \"src/**/*.{ts,tsx,js,mjs,cjs}\"",
19
- "lint:fix": "eslint \"src/**/*.{ts,tsx,js,mjs,cjs}\" --fix"
19
+ "lint": "eslint \"{src,example}/**/*.{ts,tsx,js,mjs,cjs}\"",
20
+ "lint:fix": "eslint \"{src,example}/**/*.{ts,tsx,js,mjs,cjs}\" --fix"
20
21
  },
22
+ "files": [
23
+ "dist"
24
+ ],
21
25
  "devDependencies": {
26
+ "@elysiajs/eden": "^0.8.0",
27
+ "@elysiajs/swagger": "^0.8.0",
22
28
  "bun-types": "latest",
29
+ "elysia": "^0.8.3",
23
30
  "eslint": "^8.41.0",
24
31
  "eslint-kit": "^10.0.0",
25
- "prettier": "^3.0.0"
32
+ "prettier": "^3.0.0",
33
+ "typescript": "^5.0.0"
26
34
  },
27
35
  "peerDependencies": {
28
- "typescript": "^5.0.0",
29
36
  "elysia": "^0.8.0"
30
- },
31
- "files": [
32
- "dist"
33
- ]
37
+ }
34
38
  }