silgi 0.42.5 → 0.43.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 (266) hide show
  1. package/dist/_virtual/rolldown_runtime.mjs +11 -0
  2. package/dist/build.d.mts +3 -11
  3. package/dist/build.mjs +4 -48
  4. package/dist/cli/build/build.mjs +17 -0
  5. package/dist/cli/build/dev.d.mts +9 -0
  6. package/dist/cli/build/dev.mjs +59 -0
  7. package/dist/cli/build/prepare.d.mts +6 -0
  8. package/dist/cli/build/prepare.mjs +15 -0
  9. package/dist/cli/commands/commands.mjs +90 -0
  10. package/dist/cli/commands/env.mjs +53 -0
  11. package/dist/cli/commands/init.mjs +84 -0
  12. package/dist/cli/commands/install.mjs +52 -0
  13. package/dist/cli/commands/prepare.mjs +65 -0
  14. package/dist/cli/commands/reset.mjs +46 -0
  15. package/dist/cli/commands/run.mjs +105 -0
  16. package/dist/cli/commands/watch.mjs +48 -0
  17. package/dist/cli/config/defaults.mjs +117 -0
  18. package/dist/cli/config/index.d.mts +3 -11
  19. package/dist/cli/config/index.mjs +4 -17
  20. package/dist/cli/config/loader.d.mts +6 -0
  21. package/dist/cli/config/loader.mjs +71 -0
  22. package/dist/cli/config/resolvers/compatibility.mjs +71 -0
  23. package/dist/cli/config/resolvers/imports.mjs +35 -0
  24. package/dist/cli/config/resolvers/paths.mjs +98 -0
  25. package/dist/cli/config/resolvers/storage.mjs +23 -0
  26. package/dist/cli/config/resolvers/url.mjs +9 -0
  27. package/dist/cli/config/types.d.mts +14 -0
  28. package/dist/cli/config/types.mjs +147 -0
  29. package/dist/cli/core/apiful.mjs +36 -0
  30. package/dist/cli/core/app.mjs +105 -0
  31. package/dist/cli/core/devServer.mjs +10 -0
  32. package/dist/cli/core/env.mjs +68 -0
  33. package/dist/cli/core/installPackage.mjs +60 -0
  34. package/dist/cli/core/runtimeConfig.mjs +70 -0
  35. package/dist/cli/core/scan.mjs +35 -0
  36. package/dist/cli/core/silgi.mjs +111 -0
  37. package/dist/cli/core/templates.mjs +38 -0
  38. package/dist/cli/framework/emptyFramework.mjs +7 -0
  39. package/dist/cli/framework/h3.mjs +55 -0
  40. package/dist/cli/framework/index.mjs +15 -0
  41. package/dist/cli/framework/nitro.mjs +24 -0
  42. package/dist/cli/framework/nuxt.mjs +10 -0
  43. package/dist/cli/index.d.mts +1 -1
  44. package/dist/cli/index.mjs +24 -27
  45. package/dist/cli/module/exportScan.mjs +180 -0
  46. package/dist/cli/module/install.mjs +49 -0
  47. package/dist/cli/module/scan.mjs +195 -0
  48. package/dist/cli/scan/prepareCommands.mjs +40 -0
  49. package/dist/cli/scan/prepareConfigs.mjs +33 -0
  50. package/dist/cli/scan/prepareCoreFile.mjs +118 -0
  51. package/dist/cli/scan/prepareScanFile.mjs +59 -0
  52. package/dist/cli/scan/prepareSchema.mjs +140 -0
  53. package/dist/cli/scan/scanExportFile.mjs +312 -0
  54. package/dist/cli/scan/writeCoreFile.mjs +22 -0
  55. package/dist/cli/scan/writeTypesAndFiles.mjs +72 -0
  56. package/dist/cli/utils/cancel.mjs +14 -0
  57. package/dist/cli/utils/common.mjs +15 -0
  58. package/dist/cli/utils/compatibility.mjs +33 -0
  59. package/dist/cli/utils/debug.mjs +11 -0
  60. package/dist/cli/utils/ignore.mjs +56 -0
  61. package/dist/cli/utils/readScanFile.mjs +58 -0
  62. package/dist/cli/utils/storage.mjs +23 -0
  63. package/dist/core/context.d.mts +30 -0
  64. package/dist/core/context.mjs +32 -0
  65. package/dist/core/createSilgi.d.mts +6 -0
  66. package/dist/core/createSilgi.mjs +152 -0
  67. package/dist/core/error.d.mts +65 -0
  68. package/dist/core/error.mjs +106 -0
  69. package/dist/core/event.d.mts +26 -0
  70. package/dist/core/event.mjs +44 -0
  71. package/dist/core/index.d.mts +24 -316
  72. package/dist/core/index.mjs +27 -1345
  73. package/dist/core/orchestrate.mjs +113 -0
  74. package/dist/core/response.d.mts +20 -0
  75. package/dist/core/response.mjs +105 -0
  76. package/dist/core/silgi.d.mts +19 -0
  77. package/dist/core/silgi.mjs +141 -0
  78. package/dist/core/silgiApp.d.mts +9 -0
  79. package/dist/core/silgiApp.mjs +23 -0
  80. package/dist/core/storage.d.mts +7 -0
  81. package/dist/core/storage.mjs +15 -0
  82. package/dist/core/unctx.d.mts +21 -0
  83. package/dist/core/unctx.mjs +35 -0
  84. package/dist/core/utils/event-stream.d.mts +53 -0
  85. package/dist/core/utils/event-stream.mjs +38 -0
  86. package/dist/core/utils/event.d.mts +8 -0
  87. package/dist/core/utils/event.mjs +12 -0
  88. package/dist/core/utils/internal/event-stream.d.mts +45 -0
  89. package/dist/core/utils/internal/event-stream.mjs +137 -0
  90. package/dist/core/utils/internal/obj.mjs +9 -0
  91. package/dist/core/utils/internal/object.mjs +29 -0
  92. package/dist/core/utils/internal/query.mjs +73 -0
  93. package/dist/core/utils/internal/req.mjs +35 -0
  94. package/dist/core/utils/merge.d.mts +14 -0
  95. package/dist/core/utils/merge.mjs +27 -0
  96. package/dist/{shared/silgi.DTwQEdSr.d.mts → core/utils/middleware.d.mts} +11 -13
  97. package/dist/core/utils/middleware.mjs +12 -0
  98. package/dist/core/utils/request.mjs +35 -0
  99. package/dist/core/utils/resolver.d.mts +7 -0
  100. package/dist/core/utils/resolver.mjs +29 -0
  101. package/dist/core/utils/runtime.d.mts +7 -0
  102. package/dist/core/utils/runtime.mjs +20 -0
  103. package/dist/core/utils/sanitize.mjs +22 -0
  104. package/dist/core/utils/schema.d.mts +34 -0
  105. package/dist/core/utils/schema.mjs +33 -0
  106. package/dist/core/utils/service.d.mts +13 -0
  107. package/dist/core/utils/service.mjs +19 -0
  108. package/dist/core/utils/shared.d.mts +6 -0
  109. package/dist/core/utils/shared.mjs +7 -0
  110. package/dist/core/utils/storage.d.mts +24 -0
  111. package/dist/core/utils/storage.mjs +54 -0
  112. package/dist/index.d.mts +21 -6
  113. package/dist/index.mjs +22 -16
  114. package/dist/kit/add/add-commands.d.mts +6 -0
  115. package/dist/kit/add/add-commands.mjs +12 -0
  116. package/dist/kit/add/add-core-file.d.mts +9 -0
  117. package/dist/kit/add/add-core-file.mjs +11 -0
  118. package/dist/kit/add/add-imports.d.mts +14 -0
  119. package/dist/kit/add/add-imports.mjs +56 -0
  120. package/dist/kit/add/add-npm.d.mts +14 -0
  121. package/dist/kit/add/add-npm.mjs +23 -0
  122. package/dist/kit/define.d.mts +28 -0
  123. package/dist/kit/define.mjs +25 -0
  124. package/dist/kit/errors.d.mts +6 -0
  125. package/dist/kit/errors.mjs +11 -0
  126. package/dist/kit/esm.d.mts +11 -0
  127. package/dist/kit/esm.mjs +21 -0
  128. package/dist/kit/fs.d.mts +7 -0
  129. package/dist/kit/fs.mjs +23 -0
  130. package/dist/kit/function-utils.d.mts +27 -0
  131. package/dist/kit/function-utils.mjs +75 -0
  132. package/dist/kit/gen.d.mts +5 -0
  133. package/dist/kit/gen.mjs +26 -0
  134. package/dist/kit/hash.d.mts +4 -0
  135. package/dist/kit/hash.mjs +10 -0
  136. package/dist/kit/index.d.mts +22 -321
  137. package/dist/kit/index.mjs +23 -1039
  138. package/dist/kit/isFramework.d.mts +6 -0
  139. package/dist/kit/isFramework.mjs +21 -0
  140. package/dist/kit/logger.d.mts +6 -0
  141. package/dist/kit/logger.mjs +10 -0
  142. package/dist/kit/migration.d.mts +113 -0
  143. package/dist/kit/migration.mjs +301 -0
  144. package/dist/kit/module.d.mts +14 -0
  145. package/dist/kit/module.mjs +53 -0
  146. package/dist/kit/path.d.mts +7 -0
  147. package/dist/kit/path.mjs +26 -0
  148. package/dist/kit/preset.d.mts +8 -0
  149. package/dist/kit/preset.mjs +11 -0
  150. package/dist/kit/resolve.d.mts +37 -0
  151. package/dist/kit/resolve.mjs +82 -0
  152. package/dist/kit/template.d.mts +14 -0
  153. package/dist/kit/template.mjs +59 -0
  154. package/dist/kit/useRequest.d.mts +19 -0
  155. package/dist/kit/useRequest.mjs +63 -0
  156. package/dist/kit/utils.d.mts +34 -0
  157. package/dist/kit/utils.mjs +90 -0
  158. package/dist/package.mjs +176 -0
  159. package/dist/presets/_all.gen.d.mts +5 -2
  160. package/dist/presets/_all.gen.mjs +16 -13
  161. package/dist/presets/_resolve.d.mts +10 -6
  162. package/dist/presets/_resolve.mjs +51 -65
  163. package/dist/presets/_types.gen.d.mts +8 -5
  164. package/dist/presets/_types.gen.mjs +5 -1
  165. package/dist/presets/h3/preset.d.mts +5 -2
  166. package/dist/presets/h3/preset.mjs +33 -38
  167. package/dist/presets/hono/preset.d.mts +5 -2
  168. package/dist/presets/hono/preset.mjs +28 -35
  169. package/dist/presets/index.d.mts +3 -2
  170. package/dist/presets/index.mjs +3 -1
  171. package/dist/presets/nitro/preset.d.mts +5 -2
  172. package/dist/presets/nitro/preset.mjs +35 -42
  173. package/dist/presets/npmpackage/preset.d.mts +5 -2
  174. package/dist/presets/npmpackage/preset.mjs +27 -32
  175. package/dist/presets/nuxt/preset.d.mts +5 -2
  176. package/dist/presets/nuxt/preset.mjs +39 -44
  177. package/dist/runtime/index.d.mts +4 -3
  178. package/dist/runtime/index.mjs +5 -3
  179. package/dist/runtime/internal/config.d.mts +11 -7
  180. package/dist/runtime/internal/config.mjs +79 -90
  181. package/dist/runtime/internal/debug.d.mts +6 -3
  182. package/dist/runtime/internal/debug.mjs +9 -4
  183. package/dist/runtime/internal/defu.d.mts +4 -1
  184. package/dist/runtime/internal/defu.mjs +7 -2
  185. package/dist/runtime/internal/index.d.mts +7 -6
  186. package/dist/runtime/internal/index.mjs +8 -20
  187. package/dist/runtime/internal/nitro.d.mts +6 -3
  188. package/dist/runtime/internal/nitro.mjs +29 -37
  189. package/dist/runtime/internal/nuxt.d.mts +12 -8
  190. package/dist/runtime/internal/nuxt.mjs +12 -7
  191. package/dist/runtime/internal/ofetch.d.mts +8 -4
  192. package/dist/runtime/internal/ofetch.mjs +33 -34
  193. package/dist/runtime/internal/plugin.d.mts +7 -3
  194. package/dist/runtime/internal/plugin.mjs +7 -3
  195. package/dist/types/cliConfig.d.mts +288 -0
  196. package/dist/types/cliConfig.mjs +0 -0
  197. package/dist/types/cliHooks.d.mts +154 -0
  198. package/dist/types/cliHooks.mjs +0 -0
  199. package/dist/types/compatibility.d.mts +13 -0
  200. package/dist/types/compatibility.mjs +0 -0
  201. package/dist/types/config.d.mts +46 -0
  202. package/dist/types/config.mjs +0 -0
  203. package/dist/types/dotenv.d.mts +29 -0
  204. package/dist/types/dotenv.mjs +0 -0
  205. package/dist/types/event.d.mts +63 -0
  206. package/dist/types/event.mjs +0 -0
  207. package/dist/types/global.d.mts +24 -0
  208. package/dist/types/global.mjs +0 -0
  209. package/dist/types/helper.d.mts +25 -0
  210. package/dist/types/helper.mjs +0 -0
  211. package/dist/types/hooks.d.mts +37 -0
  212. package/dist/types/hooks.mjs +0 -0
  213. package/dist/types/index.d.mts +26 -1306
  214. package/dist/types/index.mjs +0 -1
  215. package/dist/types/kits.d.mts +32 -0
  216. package/dist/types/kits.mjs +0 -0
  217. package/dist/types/middleware.d.mts +31 -0
  218. package/dist/types/middleware.mjs +0 -0
  219. package/dist/types/module.d.mts +102 -0
  220. package/dist/types/module.mjs +0 -0
  221. package/dist/types/preset.d.mts +20 -0
  222. package/dist/types/preset.mjs +0 -0
  223. package/dist/types/route.d.mts +59 -0
  224. package/dist/types/route.mjs +0 -0
  225. package/dist/types/runtime/index.d.mts +5 -0
  226. package/dist/types/runtime/index.mjs +0 -0
  227. package/dist/types/runtime/nuxt.d.mts +13 -0
  228. package/dist/types/runtime/nuxt.mjs +0 -0
  229. package/dist/types/runtime/ofetch.d.mts +14 -0
  230. package/dist/types/runtime/ofetch.mjs +0 -0
  231. package/dist/types/runtime/plugin.d.mts +8 -0
  232. package/dist/types/runtime/plugin.mjs +0 -0
  233. package/dist/types/runtime/silgi.d.mts +11 -0
  234. package/dist/types/runtime/silgi.mjs +0 -0
  235. package/dist/types/schema.d.mts +86 -0
  236. package/dist/types/schema.mjs +0 -0
  237. package/dist/types/service.d.mts +102 -0
  238. package/dist/types/service.mjs +0 -0
  239. package/dist/types/shared.d.mts +19 -0
  240. package/dist/types/shared.mjs +0 -0
  241. package/dist/types/silgi.d.mts +71 -0
  242. package/dist/types/silgi.mjs +0 -0
  243. package/dist/types/silgiCLI.d.mts +118 -0
  244. package/dist/types/silgiCLI.mjs +0 -0
  245. package/dist/types/standard-schema.d.mts +61 -0
  246. package/dist/types/standard-schema.mjs +0 -0
  247. package/dist/types/storage.d.mts +30 -0
  248. package/dist/types/storage.mjs +0 -0
  249. package/package.json +20 -35
  250. package/dist/_chunks/silgiApp.mjs +0 -25
  251. package/dist/cli/build.mjs +0 -2190
  252. package/dist/cli/common.mjs +0 -13
  253. package/dist/cli/compatibility.mjs +0 -30
  254. package/dist/cli/dev.mjs +0 -67
  255. package/dist/cli/init.mjs +0 -112
  256. package/dist/cli/install.mjs +0 -151
  257. package/dist/cli/loader.mjs +0 -618
  258. package/dist/cli/prepare.mjs +0 -188
  259. package/dist/cli/reset.mjs +0 -55
  260. package/dist/cli/run.mjs +0 -159
  261. package/dist/cli/types.mjs +0 -232
  262. package/dist/cli/watch.mjs +0 -91
  263. package/dist/presets/next/preset.d.mts +0 -3
  264. package/dist/presets/next/preset.mjs +0 -38
  265. package/dist/runtime/internal/next.d.mts +0 -9
  266. package/dist/runtime/internal/next.mjs +0 -22
@@ -0,0 +1,118 @@
1
+ import { addImports, baseHeaderBannerComment, hash, toArray } from "silgi/kit";
2
+ import { genImport, genObjectFromRawEntries, genTypeImport } from "knitwork";
3
+
4
+ //#region src/cli/scan/prepareCoreFile.ts
5
+ async function prepareCoreFile(silgi) {
6
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
7
+ imports: [
8
+ {
9
+ specifier: "silgi/runtime",
10
+ imports: [{ name: "mergeDeep" }]
11
+ },
12
+ {
13
+ specifier: "silgi",
14
+ imports: [{ name: "createSilgi" }]
15
+ },
16
+ {
17
+ specifier: "./scan",
18
+ imports: [
19
+ { name: "services" },
20
+ { name: "shareds" },
21
+ { name: "schemas" },
22
+ { name: "middlewares" },
23
+ { name: "resolvers" }
24
+ ]
25
+ },
26
+ {
27
+ specifier: "./configs",
28
+ imports: [{ name: "cliConfigs" }]
29
+ },
30
+ {
31
+ specifier: "./meta",
32
+ imports: [{ name: "meta" }]
33
+ }
34
+ ],
35
+ typeImports: [{
36
+ specifier: "silgi/types",
37
+ imports: [{ name: "SilgiRuntimeOptions" }, { name: "BuildSilgi" }]
38
+ }]
39
+ });
40
+ const before = [];
41
+ const after = [];
42
+ const _data = {
43
+ silgiConfigs: [],
44
+ addImportItem,
45
+ addImportItemType,
46
+ addBuildFunction: (data) => {
47
+ for (const item of toArray(data)) {
48
+ if (item.where === "after") if (item.custom) after.push(item.custom);
49
+ else after.push(item.params?.length ? ` await ${item.name}(option, ${item.params.join(",")})` : ` await ${item.name}(option)`);
50
+ if (item.where === "before") if (item.custom) before.push(item.custom);
51
+ else before.push(item.params?.length ? ` await ${item.name}(option, ${item.params.join(",")})` : ` await ${item.name}(option)`);
52
+ }
53
+ }
54
+ };
55
+ await silgi.callHook("before:core.ts", _data);
56
+ const plugins = [];
57
+ for (const plugin of silgi.options.plugins) {
58
+ const pluginImportName = hash(plugin.packageImport);
59
+ addImportItem({
60
+ specifier: plugin.packageImport,
61
+ imports: pluginImportName
62
+ });
63
+ plugins.push(pluginImportName);
64
+ }
65
+ const importsContent = [
66
+ ...genImports.map(({ specifier, imports, options }) => {
67
+ return genImport(specifier, imports, options);
68
+ }),
69
+ ...genTypeImports.map(({ specifier, imports }) => {
70
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
71
+ }),
72
+ ""
73
+ ];
74
+ const importData = [
75
+ "",
76
+ "export async function buildSilgi(option?: BuildSilgi) {",
77
+ "",
78
+ "// buildSilgiBefore",
79
+ ...before,
80
+ "",
81
+ "const silgi = await createSilgi({",
82
+ " framework: option?.framework,",
83
+ " shared: shareds,",
84
+ " services: services,",
85
+ " middlewares: middlewares,",
86
+ " schemas: schemas,",
87
+ " resolvers: resolvers,",
88
+ ` plugins: [${plugins.join(", ")}],`,
89
+ "",
90
+ _data.silgiConfigs.length > 0 ? _data.silgiConfigs.map((item) => {
91
+ const code = genObjectFromRawEntries(Object.entries(item));
92
+ return ` ${code.slice(1, -1).trim()},`;
93
+ }).filter(Boolean).join("\n") : "",
94
+ "",
95
+ " options: mergeDeep(cliConfigs, {",
96
+ " runtimeConfig: {} as SilgiRuntimeOptions,",
97
+ " meta: meta,",
98
+ ` present: '${silgi.options.preset}',`,
99
+ " ...option?.modules,",
100
+ " ...option?.options,",
101
+ " }) as any,",
102
+ " })",
103
+ "",
104
+ "// buildSilgiAfter",
105
+ ...after,
106
+ "",
107
+ " return silgi",
108
+ "}",
109
+ ""
110
+ ];
111
+ await silgi.callHook("after:core.ts", importData);
112
+ importData.unshift(...importsContent);
113
+ importData.unshift(...baseHeaderBannerComment);
114
+ return importData;
115
+ }
116
+
117
+ //#endregion
118
+ export { prepareCoreFile };
@@ -0,0 +1,59 @@
1
+ import { resolve } from "pathe";
2
+ import { addImports, baseHeaderBannerComment, writeFile } from "silgi/kit";
3
+ import { genImport, genTypeImport } from "knitwork";
4
+
5
+ //#region src/cli/scan/prepareScanFile.ts
6
+ async function prepareScanFile(silgi) {
7
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({});
8
+ const scanned = {
9
+ services: [],
10
+ shareds: [],
11
+ resolvers: [],
12
+ schemas: [],
13
+ middlewares: [],
14
+ addImportItem,
15
+ addImportItemType
16
+ };
17
+ await silgi.callHook("before:scan.ts", scanned);
18
+ const importsContent = [
19
+ ...genImports.map(({ specifier, imports, options }) => {
20
+ return genImport(specifier, imports, options);
21
+ }),
22
+ ...genTypeImports.map(({ specifier, imports }) => {
23
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
24
+ }),
25
+ ""
26
+ ];
27
+ const generateExport = (name, items, defaultEmpty = "{}", asArray = false) => {
28
+ const hasItems = items.length > 0;
29
+ if (asArray) return [
30
+ `export const ${name} = [`,
31
+ ...items.map((item) => ` ${item},`),
32
+ "]",
33
+ ""
34
+ ];
35
+ if (hasItems) return [
36
+ `export const ${name} = {`,
37
+ ...items.map((item) => ` ...${item},`),
38
+ "}",
39
+ ""
40
+ ];
41
+ else return [`export const ${name} = ${defaultEmpty}`, ""];
42
+ };
43
+ const importData = [
44
+ "",
45
+ ...generateExport("schemas", scanned.schemas),
46
+ ...generateExport("services", scanned.services),
47
+ ...generateExport("shareds", scanned.shareds, "undefined"),
48
+ ...generateExport("resolvers", scanned.resolvers, "[]", true),
49
+ ...generateExport("middlewares", scanned.middlewares)
50
+ ];
51
+ await silgi.callHook("after:scan.ts", importData);
52
+ importData.unshift(...importsContent);
53
+ importData.unshift(...baseHeaderBannerComment);
54
+ await writeFile(resolve(silgi.options.silgi.serverDir, "scan.ts"), importData.join("\n"));
55
+ return importData;
56
+ }
57
+
58
+ //#endregion
59
+ export { prepareScanFile };
@@ -0,0 +1,140 @@
1
+ import { addImports, getServicePath, relativeWithDot } from "silgi/kit";
2
+ import { genAugmentation, genImport, genTypeImport } from "knitwork";
3
+ import { generateTypes, resolveSchema } from "untyped";
4
+
5
+ //#region src/cli/scan/prepareSchema.ts
6
+ async function prepareSchema(silgi) {
7
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
8
+ imports: [],
9
+ typeImports: [{
10
+ specifier: "silgi/types",
11
+ imports: [{ name: "URIsTypes" }, { name: "SilgiRuntimeContext" }]
12
+ }]
13
+ });
14
+ const data = {
15
+ addImportItem,
16
+ addImportItemType,
17
+ options: [],
18
+ contexts: [],
19
+ setupModuleOption: [],
20
+ shareds: [],
21
+ resolvers: [],
22
+ events: [],
23
+ hooks: [],
24
+ runtimeHooks: [],
25
+ runtimeOptions: [],
26
+ methods: [],
27
+ routeRules: [],
28
+ metaDatas: []
29
+ };
30
+ await silgi.callHook("before:schema.ts", data);
31
+ const silgiScanTS = relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/scan`);
32
+ let addSilgiContext = false;
33
+ const importsContent = [
34
+ ...genImports.map(({ specifier, imports, options }) => {
35
+ return genImport(specifier, imports, options);
36
+ }),
37
+ ...genTypeImports.map(({ specifier, imports }) => {
38
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
39
+ }),
40
+ ""
41
+ ];
42
+ const importData = [
43
+ "",
44
+ `type SchemaExtends = typeof import('${silgiScanTS}')['schemas']`,
45
+ `type BaseServices = typeof import('${silgiScanTS}')['services']`,
46
+ `type ResolversExtend = ${data.resolvers?.length ? data.resolvers.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
47
+ "",
48
+ "",
49
+ `type SilgiModuleContextExtends = ${data.contexts.length ? data.contexts.map(({ value }) => value).join(" & ") : "{}"}`,
50
+ "",
51
+ data.events.length ? `interface SilgiModuleEventsExtends extends ${data.events.map((item) => item.extends ? item.value : "").join(", ")} {
52
+ ${data.events.map((item) => {
53
+ if (item.isSilgiContext) addSilgiContext = true;
54
+ return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: SilgiRuntimeContext" : "";
55
+ }).join(",\n")}
56
+ }` : "interface SilgiModuleEventsExtends {}",
57
+ "",
58
+ `type SetupModuleOptionExtend = ${data.setupModuleOption?.length ? data.setupModuleOption.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
59
+ "",
60
+ `type RuntimeMethodExtends = ${data.methods?.length ? data.methods.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
61
+ "",
62
+ `type SilgiModuleSharedExtends = ${data.shareds.length ? data.shareds.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
63
+ "",
64
+ `type SilgiModuleOptionExtend = ${data.options?.length ? data.options.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
65
+ "",
66
+ `type SilgiRuntimeOptionExtends = ${data.runtimeOptions?.length ? data.runtimeOptions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
67
+ "",
68
+ `type RouteRulesExtend = ${data.routeRules?.length ? data.routeRules.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
69
+ "",
70
+ `type MetaDataExtend = ${data.metaDatas?.length ? data.metaDatas.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
71
+ "",
72
+ silgi.options.typescript.generateRuntimeConfigTypes ? generateTypes(await resolveSchema({ ...Object.fromEntries(Object.entries(silgi.options.runtimeConfig).filter(([key]) => ![
73
+ "app",
74
+ "nitro",
75
+ "nuxt"
76
+ ].includes(key))) }), {
77
+ interfaceName: "SilgiRuntimeConfigExtends",
78
+ addExport: false,
79
+ addDefaults: false,
80
+ allowExtraKeys: false,
81
+ indentation: 0
82
+ }) : "",
83
+ "",
84
+ generateTypes(await resolveSchema({ ...Object.fromEntries(Object.entries(silgi.options.runtimeConfig).filter(([key]) => ![
85
+ "app",
86
+ "nitro",
87
+ "nuxt"
88
+ ].includes(key))) }), {
89
+ interfaceName: "SilgiRuntimeConfigExtends",
90
+ addExport: false,
91
+ addDefaults: false,
92
+ allowExtraKeys: false,
93
+ indentation: 0
94
+ }),
95
+ "",
96
+ generateTypes(await resolveSchema({ ...silgi.services ? Object.values(silgi.services).reduce((acc, service) => {
97
+ const { route } = getServicePath(service.path);
98
+ if (route) acc[route] = "";
99
+ return acc;
100
+ }, {}) : {} }), {
101
+ interfaceName: "RoutersExtend",
102
+ addExport: false,
103
+ addDefaults: false,
104
+ allowExtraKeys: false,
105
+ indentation: 0
106
+ }),
107
+ "",
108
+ `type ModuleHooksExtend = ${data.hooks?.length ? data.hooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
109
+ "",
110
+ `type SilgiRuntimeHooksExtends = ${data.runtimeHooks?.length ? data.runtimeHooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
111
+ "",
112
+ genAugmentation("silgi/types", {
113
+ SilgiSchema: [{}, { extends: ["SchemaExtends"] }],
114
+ ServicesObject: [{}, { extends: ["BaseServices"] }],
115
+ SilgiStorageBase: [{}, { extends: ["SilgiStorageBaseExtends"] }],
116
+ SilgiRuntimeContext: [{}, { extends: ["SilgiModuleContextExtends"] }],
117
+ SilgiEvent: [{}, { extends: ["SilgiModuleEventsExtends"] }],
118
+ SilgiRuntimeSharedsExtend: [{}, { extends: ["SilgiModuleSharedExtends"] }],
119
+ SetupModuleOption: [{}, { extends: ["SetupModuleOptionExtend"] }],
120
+ SilgiRuntimeOptions: [{}, { extends: ["SilgiRuntimeOptionExtends"] }],
121
+ SilgiRuntimeHooks: [{}, { extends: ["SilgiRuntimeHooksExtends"] }],
122
+ SilgiRuntimeConfig: [{}, { extends: ["SilgiRuntimeConfigExtends"] }],
123
+ SilgiHooks: [{}, { extends: ["ModuleHooksExtend"] }],
124
+ SilgiRuntimeMethods: [{}, { extends: ["RuntimeMethodExtends"] }],
125
+ Resolvers: [{}, { extends: ["ResolversExtend"] }],
126
+ SilgiModuleOptions: [{}, { extends: ["SilgiModuleOptionExtend"] }],
127
+ RouteRules: [{}, { extends: ["RouteRulesExtend"] }],
128
+ MetaData: [{}, { extends: ["MetaDataExtend"] }],
129
+ Routers: [{}, { extends: ["RoutersExtend"] }]
130
+ }).replace(/,\s*/g, "\n"),
131
+ "",
132
+ "export {}"
133
+ ];
134
+ await silgi.callHook("after:schema.ts", importData);
135
+ importData.unshift(...importsContent);
136
+ return importData;
137
+ }
138
+
139
+ //#endregion
140
+ export { prepareSchema };
@@ -0,0 +1,312 @@
1
+ import { isIgnored } from "../utils/ignore.mjs";
2
+ import { consola as consola$1 } from "consola";
3
+ import { basename, dirname, extname, join, relative, resolve } from "pathe";
4
+ import { useSilgiCLI } from "silgi";
5
+ import { hash, relativeWithDot, removeExtension } from "silgi/kit";
6
+ import { withTrailingSlash } from "ufo";
7
+ import { readFile, readdir } from "node:fs/promises";
8
+ import micromatch from "micromatch";
9
+ import { parseAsync } from "oxc-parser";
10
+ import { glob } from "tinyglobby";
11
+
12
+ //#region src/cli/scan/scanExportFile.ts
13
+ const DEFAULT_FUNCTION_EXPORT_NAMES = [
14
+ "createSchema",
15
+ "createService",
16
+ "createWebSocket",
17
+ "createResolver",
18
+ "createShared",
19
+ "createMiddleware"
20
+ ];
21
+ const DEFAULT_INTERFACE_EXTENDS_NAMES = ["ExtendShared", "ExtendContext"];
22
+ /**
23
+ * Generate a unique identifier for an export based on its file path and name
24
+ * Used to prevent naming collisions when registering exports
25
+ *
26
+ * @param filePath - Path to the file containing the export
27
+ * @param exportName - Name of the exported entity
28
+ * @returns A unique string identifier
29
+ */
30
+ function generateUniqueIdentifier(filePath, exportName) {
31
+ const fileBaseName = basename(filePath);
32
+ const uniqueString = `${fileBaseName}${exportName}`;
33
+ return hash(uniqueString);
34
+ }
35
+ /**
36
+ * Process extracted exports and categorize them for use in Silgi
37
+ * Separates exports into runtime (scannable) and type-only (schema) groups
38
+ *
39
+ * @param exportedEntities - List of entities exported from a file
40
+ * @param filePath - Path to the source file
41
+ * @param functionExportCategories - Map of function names to categories
42
+ * @param interfaceExportCategories - Map of interface extends names to categories
43
+ * @returns Object containing runtime exports and type-only exports
44
+ */
45
+ function categorizeExports(exportedEntities, filePath, functionExportCategories = {
46
+ createService: "service",
47
+ createWebSocket: "websocket",
48
+ createSchema: "schema",
49
+ createShared: "shared",
50
+ createResolver: "resolver",
51
+ createMiddleware: "middleware"
52
+ }, interfaceExportCategories = {
53
+ ExtendShared: "shared",
54
+ ExtendContext: "context"
55
+ }) {
56
+ const runtimeExports = [];
57
+ const typeExports = [];
58
+ for (const [functionName, category] of Object.entries(functionExportCategories)) {
59
+ const matchingExports = exportedEntities.filter((entity) => entity.funcName === functionName);
60
+ for (const exportEntity of matchingExports) {
61
+ if (!exportEntity.name) continue;
62
+ runtimeExports.push({
63
+ exportName: exportEntity.name,
64
+ path: filePath,
65
+ uniqueId: generateUniqueIdentifier(filePath, exportEntity.name),
66
+ category
67
+ });
68
+ }
69
+ }
70
+ for (const [extensionName, category] of Object.entries(interfaceExportCategories)) {
71
+ const matchingExports = exportedEntities.filter((entity) => entity.declaration === "interface" && entity.extends?.includes(extensionName));
72
+ for (const exportEntity of matchingExports) {
73
+ if (!exportEntity.name) continue;
74
+ typeExports.push({
75
+ exportName: exportEntity.name,
76
+ path: filePath,
77
+ uniqueId: generateUniqueIdentifier(filePath, exportEntity.name),
78
+ category
79
+ });
80
+ }
81
+ }
82
+ return {
83
+ runtimeExports,
84
+ typeExports
85
+ };
86
+ }
87
+ /**
88
+ * Transform an import path based on package information
89
+ * If a package name is provided, replace dist and preceding directories with the package name
90
+ *
91
+ * @param path - Original file path
92
+ * @param packageName - Optional package name to use in import path
93
+ * @param relativeTo - Directory to make the path relative to if no package name
94
+ * @returns Transformed import path
95
+ */
96
+ function transformImportPath(path, packageName, relativeTo) {
97
+ let importPath = path;
98
+ if (packageName) {
99
+ const distMatch = importPath.match(/.*?(\/dist\/.*)/);
100
+ if (distMatch && distMatch[1]) {
101
+ importPath = packageName + distMatch[1].substring(5);
102
+ importPath = removeExtension(importPath, true);
103
+ }
104
+ } else if (relativeTo) importPath = removeExtension(relativeWithDot(relativeTo, path));
105
+ return importPath;
106
+ }
107
+ /**
108
+ * Register discovered exports with the Silgi CLI via hooks
109
+ * This enables Silgi to use these exports in code generation
110
+ *
111
+ * @param silgiInstance - The Silgi CLI instance
112
+ * @param runtimeExports - Runtime exports to register
113
+ * @param typeExports - Type-only exports to register
114
+ * @param packageName - Optional package name for imports
115
+ */
116
+ function registerExportsWithHooks(silgiInstance, runtimeExports, typeExports, packageName) {
117
+ silgiInstance.hook("before:scan.ts", (options) => {
118
+ const ignored = Array.isArray(silgiInstance.options.watchOptions?.ignored) ? silgiInstance.options.watchOptions.ignored : [];
119
+ for (const { exportName, path, uniqueId, category } of runtimeExports) {
120
+ if (!isWatchedPath(path, ignored)) silgiInstance.options.devServer.watch.push(path);
121
+ switch (category) {
122
+ case "service":
123
+ options.services.push(uniqueId);
124
+ break;
125
+ case "websocket":
126
+ options.services?.push?.(uniqueId);
127
+ break;
128
+ case "shared":
129
+ options.shareds.push(uniqueId);
130
+ break;
131
+ case "schema":
132
+ options.schemas.push(uniqueId);
133
+ break;
134
+ case "resolver":
135
+ options.resolvers.push(uniqueId);
136
+ break;
137
+ case "middleware":
138
+ options.middlewares?.push?.(uniqueId);
139
+ break;
140
+ }
141
+ options.addImportItem({
142
+ specifier: transformImportPath(path, packageName, silgiInstance.options.silgi.serverDir),
143
+ imports: [{
144
+ name: exportName,
145
+ as: uniqueId
146
+ }]
147
+ });
148
+ }
149
+ });
150
+ silgiInstance.hook("before:schema.ts", (options) => {
151
+ const ignored = Array.isArray(silgiInstance.options.watchOptions?.ignored) ? silgiInstance.options.watchOptions.ignored : [];
152
+ for (const { exportName, path, uniqueId, category } of typeExports) {
153
+ if (!isWatchedPath(path, ignored)) silgiInstance.options.devServer.watch.push(path);
154
+ if (category === "shared" || category === "context") {
155
+ const targetCollection = category === "shared" ? options.shareds : options.contexts;
156
+ targetCollection.push({
157
+ key: uniqueId,
158
+ value: uniqueId
159
+ });
160
+ }
161
+ options.addImportItem({
162
+ imports: [{
163
+ name: exportName,
164
+ as: uniqueId
165
+ }],
166
+ specifier: transformImportPath(path, packageName, silgiInstance.options.build.typesDir)
167
+ });
168
+ }
169
+ });
170
+ }
171
+ /**
172
+ * Check for case sensitivity issues in directory paths
173
+ * This helps users identify path issues on case-insensitive file systems
174
+ *
175
+ * @param directoryPath - The directory path to verify
176
+ * @param rootDirectory - The root directory for relative path calculation
177
+ */
178
+ async function verifyDirectoryCaseSensitivity(directoryPath, rootDirectory) {
179
+ const directoryName = basename(directoryPath);
180
+ const parentDirectory = dirname(directoryPath);
181
+ try {
182
+ const siblingEntries = await readdir(parentDirectory);
183
+ if (!siblingEntries.includes(directoryName)) {
184
+ const directoryNameLowerCase = directoryName.toLowerCase();
185
+ const caseInsensitiveMatch = siblingEntries.find((sibling) => sibling.toLowerCase() === directoryNameLowerCase);
186
+ if (caseInsensitiveMatch) {
187
+ const originalRelative = relative(rootDirectory, directoryPath);
188
+ const correctedRelative = relative(rootDirectory, join(parentDirectory, caseInsensitiveMatch));
189
+ consola$1.warn(`Components not scanned from \`~/${correctedRelative}\`. Did you mean to name the directory \`~/${originalRelative}\` instead?`);
190
+ }
191
+ }
192
+ } catch {}
193
+ }
194
+ /**
195
+ * Parse a file and extract exported entities (interfaces and function exports)
196
+ * @param absoluteFilePath - Absolute path to the file
197
+ * @param functionExportNames - Function export names to look for
198
+ * @param interfaceExtendsNames - Interface extends names to look for
199
+ * @returns Array of ExportedEntity
200
+ */
201
+ async function extractExportEntitiesFromFile(absoluteFilePath, functionExportNames = DEFAULT_FUNCTION_EXPORT_NAMES, interfaceExtendsNames = DEFAULT_INTERFACE_EXTENDS_NAMES) {
202
+ const exportEntities = [];
203
+ const fileContent = await readFile(absoluteFilePath, "utf-8");
204
+ const parsed = await parseAsync(absoluteFilePath, fileContent);
205
+ for (const node of parsed.program.body) if (node.type === "ExportNamedDeclaration" && node.declaration && node.declaration.type === "TSInterfaceDeclaration") {
206
+ const decl = node.declaration;
207
+ if (Array.isArray(decl.extends) && decl.extends.some((dec) => dec.type === "TSInterfaceHeritage" && dec.expression.type === "Identifier" && interfaceExtendsNames.includes(dec.expression.name))) exportEntities.push({
208
+ name: decl.id?.name,
209
+ type: "interface",
210
+ declaration: "interface",
211
+ extends: decl.extends.filter((e) => e.type === "TSInterfaceHeritage" && e.expression.type === "Identifier").map((e) => e.expression.type === "Identifier" ? e.expression.name : false).filter((name) => Boolean(name))
212
+ });
213
+ }
214
+ for (const node of parsed.program.body) if (node.type === "ExportNamedDeclaration" && node.declaration && node.declaration.type === "VariableDeclaration") {
215
+ const decls = node.declaration.declarations;
216
+ if (Array.isArray(decls)) {
217
+ for (const decl of decls) if (decl.type === "VariableDeclarator" && decl.id.type === "Identifier" && decl.init && decl.init.type === "CallExpression" && decl.init.callee.type === "Identifier" && functionExportNames.includes(decl.init.callee.name)) {
218
+ let servicePath;
219
+ let serviceMethod;
220
+ if (decl.init.callee.name === "createService" || decl.init.callee.name === "createWebSocket") {
221
+ const firstArg = decl.init.arguments?.[0];
222
+ if (firstArg && firstArg.type === "ObjectExpression" && Array.isArray(firstArg.properties)) {
223
+ for (const prop of firstArg.properties) if (prop.type === "Property" && prop.key.type === "Identifier") {
224
+ if (prop.key.name === "path" && prop.value.type === "Literal" && typeof prop.value.value === "string") servicePath = prop.value.value;
225
+ if (prop.key.name === "method" && prop.value.type === "Literal" && typeof prop.value.value === "string") serviceMethod = prop.value.value;
226
+ }
227
+ }
228
+ }
229
+ exportEntities.push({
230
+ name: decl.id.name,
231
+ type: "function",
232
+ funcName: decl.init.callee.name,
233
+ servicePath,
234
+ serviceMethod
235
+ });
236
+ }
237
+ }
238
+ }
239
+ return exportEntities;
240
+ }
241
+ /**
242
+ * Main function to scan files for exports and register them with the Silgi CLI
243
+ * This enables automatic discovery and registration of services, schemas, etc.
244
+ *
245
+ * @param path - The path to scan for exports
246
+ * @param packageName - Optional package name for import path transformation
247
+ * @param silgiInstance - The Silgi CLI instance
248
+ * @param scanOptions - Options for scanning
249
+ */
250
+ async function scanSilgiExports(path, packageName, silgiInstance = useSilgiCLI(), scanOptions = {}) {
251
+ const processedFilePaths = new Set();
252
+ const alreadyScannedPaths = [];
253
+ const serverDirectory = path || silgiInstance.options.serverDir;
254
+ const functionExportNames = scanOptions.functionExportNames ?? DEFAULT_FUNCTION_EXPORT_NAMES;
255
+ const interfaceExtendsNames = scanOptions.interfaceExtendsNames ?? DEFAULT_INTERFACE_EXTENDS_NAMES;
256
+ const functionExportCategories = {};
257
+ functionExportNames.forEach((name) => {
258
+ if (name === "createService") functionExportCategories[name] = "service";
259
+ else if (name === "createWebSocket") functionExportCategories[name] = "websocket";
260
+ else if (name === "createSchema") functionExportCategories[name] = "schema";
261
+ else if (name === "createShared") functionExportCategories[name] = "shared";
262
+ else if (name === "createResolver") functionExportCategories[name] = "resolver";
263
+ else if (name === "createMiddleware") functionExportCategories[name] = "middleware";
264
+ else functionExportCategories[name] = name;
265
+ });
266
+ const interfaceExportCategories = {};
267
+ interfaceExtendsNames.forEach((name) => {
268
+ if (name === "ExtendShared") interfaceExportCategories[name] = "shared";
269
+ else if (name === "ExtendContext") interfaceExportCategories[name] = "context";
270
+ else interfaceExportCategories[name] = name;
271
+ });
272
+ if (!serverDirectory) {
273
+ consola$1.warn("No server directory specified for scanning");
274
+ return;
275
+ }
276
+ try {
277
+ const matchedFiles = await glob(serverDirectory, {
278
+ cwd: silgiInstance.options.rootDir,
279
+ ignore: silgiInstance.options.ignore
280
+ });
281
+ if (matchedFiles.length) await verifyDirectoryCaseSensitivity(serverDirectory, silgiInstance.options.rootDir);
282
+ for (const relativeFilePath of matchedFiles.sort()) {
283
+ const absoluteFilePath = resolve(silgiInstance.options.rootDir, relativeFilePath);
284
+ if (alreadyScannedPaths.find((path$1) => absoluteFilePath.startsWith(withTrailingSlash(path$1))) || isIgnored(absoluteFilePath, silgiInstance) || processedFilePaths.has(absoluteFilePath)) continue;
285
+ processedFilePaths.add(absoluteFilePath);
286
+ const fileExtension = extname(absoluteFilePath);
287
+ if (!silgiInstance.options.extensions?.includes(fileExtension)) continue;
288
+ try {
289
+ const exportEntities = await extractExportEntitiesFromFile(absoluteFilePath, functionExportNames, interfaceExtendsNames);
290
+ const seenServiceSignatures = new Map();
291
+ for (const entity of exportEntities) if ((entity.funcName === "createService" || entity.funcName === "createWebSocket") && entity.servicePath && entity.serviceMethod) {
292
+ const key = `${entity.serviceMethod}:${entity.servicePath}`;
293
+ if (seenServiceSignatures.has(key)) throw new Error(`Duplicate ${entity.funcName} detected for path "${entity.servicePath}" and method "${entity.serviceMethod}".\nFirst found in: ${seenServiceSignatures.get(key)}\nDuplicate in: ${absoluteFilePath}\nPlease ensure each service path/method combination is unique.`);
294
+ seenServiceSignatures.set(key, absoluteFilePath);
295
+ }
296
+ const allExportedEntities = exportEntities;
297
+ const { runtimeExports, typeExports } = categorizeExports(allExportedEntities, absoluteFilePath, functionExportCategories, interfaceExportCategories);
298
+ registerExportsWithHooks(silgiInstance, runtimeExports, typeExports, packageName);
299
+ } catch (error) {
300
+ consola$1.error(`Error processing file ${absoluteFilePath}:`, error);
301
+ }
302
+ }
303
+ } catch (error) {
304
+ consola$1.error("Error scanning export files:", error);
305
+ }
306
+ }
307
+ function isWatchedPath(path, ignoredPatterns) {
308
+ return micromatch.isMatch(path, ignoredPatterns);
309
+ }
310
+
311
+ //#endregion
312
+ export { scanSilgiExports };
@@ -0,0 +1,22 @@
1
+ import { prepareCoreFile } from "./prepareCoreFile.mjs";
2
+ import { join, resolve } from "pathe";
3
+ import { writeFile } from "silgi/kit";
4
+
5
+ //#region src/cli/scan/writeCoreFile.ts
6
+ async function writeCoreFile(silgi) {
7
+ const coreContent = await prepareCoreFile(silgi);
8
+ const silgiDir = resolve(silgi.options.silgi.serverDir);
9
+ const buildFiles = [];
10
+ buildFiles.push({
11
+ path: join(silgiDir, "core.ts"),
12
+ contents: coreContent.join("\n")
13
+ });
14
+ buildFiles.push({
15
+ path: join(silgiDir, "meta.ts"),
16
+ contents: `export const meta = ${JSON.stringify(silgi.meta, null, 2)}`
17
+ });
18
+ for await (const file of buildFiles) if (!silgi.errors.length) await writeFile(resolve(silgi.options.build.dir, file.path), file.contents);
19
+ }
20
+
21
+ //#endregion
22
+ export { writeCoreFile };