silgi 0.42.4 → 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 -233
  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,72 @@
1
+ import { silgiGenerateType } from "../config/types.mjs";
2
+ import { prepareSchema } from "./prepareSchema.mjs";
3
+ import { isAbsolute, join, relative, resolve } from "pathe";
4
+ import { isDirectory, writeFile } from "silgi/kit";
5
+ import { runtimeDir } from "silgi/runtime/meta";
6
+ import { toExports } from "unimport";
7
+ import { existsSync } from "node:fs";
8
+ import { lookupNodeModuleSubpath, parseNodeModulePath, resolvePath } from "mlly";
9
+ import { resolveAlias as resolveAlias$1 } from "pathe/utils";
10
+
11
+ //#region src/cli/scan/writeTypesAndFiles.ts
12
+ async function writeTypesAndFiles(silgi) {
13
+ silgi.hook("prepare:types", (opts) => {
14
+ opts.references.push({ path: "./schema.d.ts" });
15
+ opts.references.push({ path: "./silgi-routes.d.ts" });
16
+ });
17
+ const schemaContent = await prepareSchema(silgi);
18
+ const { declarations, tsConfig } = await silgiGenerateType(silgi);
19
+ const tsConfigPath = resolve(silgi.options.rootDir, silgi.options.typescript.tsconfigPath);
20
+ const typesDir = resolve(silgi.options.build.typesDir);
21
+ let autoImportedTypes = [];
22
+ let autoImportExports = "";
23
+ if (silgi.unimport) {
24
+ await silgi.unimport.init();
25
+ const allImports = await silgi.unimport.getImports();
26
+ autoImportExports = toExports(allImports).replace(/#internal\/nitro/g, relative(typesDir, runtimeDir));
27
+ const resolvedImportPathMap = new Map();
28
+ for (const i of allImports.filter((i$1) => !i$1.type)) {
29
+ if (resolvedImportPathMap.has(i.from)) continue;
30
+ let path = resolveAlias$1(i.from, silgi.options.alias);
31
+ if (isAbsolute(path)) {
32
+ const resolvedPath = await resolvePath(i.from, { url: silgi.options.nodeModulesDirs }).catch(() => null);
33
+ if (resolvedPath) {
34
+ const { dir, name } = parseNodeModulePath(resolvedPath);
35
+ if (!dir || !name) path = resolvedPath;
36
+ else {
37
+ const subpath = await lookupNodeModuleSubpath(resolvedPath);
38
+ path = join(dir, name, subpath || "");
39
+ }
40
+ }
41
+ }
42
+ if (existsSync(path) && !await isDirectory(path)) path = path.replace(/\.[a-z]+$/, "");
43
+ if (isAbsolute(path)) path = relative(typesDir, path);
44
+ resolvedImportPathMap.set(i.from, path);
45
+ }
46
+ autoImportedTypes = [silgi.options.imports && silgi.options.imports.autoImport !== false ? (await silgi.unimport.generateTypeDeclarations({
47
+ exportHelper: false,
48
+ resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
49
+ })).trim() : ""];
50
+ }
51
+ const buildFiles = [];
52
+ buildFiles.push({
53
+ path: join(typesDir, "silgi-imports.d.ts"),
54
+ contents: [...autoImportedTypes, autoImportExports || "export {}"].join("\n")
55
+ });
56
+ buildFiles.push({
57
+ path: join(typesDir, "schema.d.ts"),
58
+ contents: schemaContent.join("\n")
59
+ });
60
+ buildFiles.push({
61
+ path: join(typesDir, "silgi-config.d.ts"),
62
+ contents: declarations.join("\n")
63
+ });
64
+ buildFiles.push({
65
+ path: tsConfigPath,
66
+ contents: JSON.stringify(tsConfig, null, 2)
67
+ });
68
+ for await (const file of buildFiles) if (!silgi.errors.length) await writeFile(resolve(silgi.options.build.dir, file.path), file.contents);
69
+ }
70
+
71
+ //#endregion
72
+ export { writeTypesAndFiles };
@@ -0,0 +1,14 @@
1
+ import { cancel, isCancel } from "@clack/prompts";
2
+
3
+ //#region src/cli/utils/cancel.ts
4
+ function cancelOnCancel({ value, message = "Cancelled", onBeforeExit, exitCode = 0 } = {}) {
5
+ const handleCancel = () => {
6
+ cancel(message);
7
+ onBeforeExit?.();
8
+ process.exit(exitCode);
9
+ };
10
+ if (!value || isCancel(value)) handleCancel();
11
+ }
12
+
13
+ //#endregion
14
+ export { cancelOnCancel };
@@ -0,0 +1,15 @@
1
+ //#region src/cli/utils/common.ts
2
+ const commonArgs = {
3
+ dir: {
4
+ type: "string",
5
+ description: "project root directory"
6
+ },
7
+ _dir: {
8
+ type: "positional",
9
+ default: ".",
10
+ description: "project root directory (prefer using `--dir`)"
11
+ }
12
+ };
13
+
14
+ //#endregion
15
+ export { commonArgs };
@@ -0,0 +1,33 @@
1
+ import { useSilgiCLI } from "silgi";
2
+ import satisfies from "semver/functions/satisfies.js";
3
+ import { version } from "silgi/meta";
4
+
5
+ //#region src/cli/utils/compatibility.ts
6
+ const SEMANTIC_VERSION_RE = /-\d+\.[0-9a-f]+/;
7
+ function normalizeSemanticVersion(version$1) {
8
+ return version$1.replace(SEMANTIC_VERSION_RE, "");
9
+ }
10
+ const SILGI_VERSION_RE = /^v/g;
11
+ /**
12
+ * Check version constraints and return incompatibility issues as an array
13
+ */
14
+ async function checkSilgiCompatibility(constraints, silgi = useSilgiCLI()) {
15
+ const issues = [];
16
+ if (constraints.silgi) {
17
+ const _silgiVersion = version.replace(SILGI_VERSION_RE, "");
18
+ if (!satisfies(normalizeSemanticVersion(_silgiVersion), constraints.silgi, { includePrerelease: true })) issues.push({
19
+ name: "silgi",
20
+ message: `Silgi version \`${constraints.silgi}\` is required but currently using \`${version}\``
21
+ });
22
+ }
23
+ await silgi.callHook("kit:compatibility", constraints, issues);
24
+ issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
25
+ return issues;
26
+ }
27
+ function hasInstalledModule(moduleKey, silgi = useSilgiCLI()) {
28
+ const find = silgi.scanModules.find(({ meta }) => meta.configKey === moduleKey);
29
+ return find?.installed ?? false;
30
+ }
31
+
32
+ //#endregion
33
+ export { checkSilgiCompatibility, hasInstalledModule as hasInstalledModule$1 };
@@ -0,0 +1,11 @@
1
+ import { useSilgiCLI } from "../../core/silgiApp.mjs";
2
+
3
+ //#region src/cli/utils/debug.ts
4
+ function debugMode(name) {
5
+ const silgi = useSilgiCLI();
6
+ if (silgi.options.debug === true || typeof silgi.options.debug === "object" && silgi.options.debug[name]) return true;
7
+ return false;
8
+ }
9
+
10
+ //#endregion
11
+ export { debugMode };
@@ -0,0 +1,56 @@
1
+ import { join, relative, resolve } from "pathe";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import ignore from "ignore";
4
+
5
+ //#region src/cli/utils/ignore.ts
6
+ const NEGATION_RE = /^(!?)(.*)$/;
7
+ function resolveIgnorePatterns(silgi, relativePath) {
8
+ if (!silgi) return [];
9
+ const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
10
+ const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
11
+ if (existsSync(nuxtignoreFile)) {
12
+ const contents = readFileSync(nuxtignoreFile, "utf-8");
13
+ ignorePatterns.push(...contents.trim().split(/\r?\n/));
14
+ }
15
+ if (relativePath) return ignorePatterns.map((p) => {
16
+ const [_, negation = "", pattern] = p.match(NEGATION_RE) || [];
17
+ if (pattern && pattern[0] === "*") return p;
18
+ return negation + relative(relativePath, resolve(silgi.options.rootDir, pattern || p));
19
+ });
20
+ return ignorePatterns;
21
+ }
22
+ /**
23
+ * Return a filter function to filter an array of paths
24
+ */
25
+ function isIgnored(pathname, silgi, _stats) {
26
+ if (!silgi) return false;
27
+ if (!silgi._ignore) {
28
+ silgi._ignore = ignore(silgi.options.ignoreOptions);
29
+ silgi._ignore.add(resolveIgnorePatterns(silgi));
30
+ }
31
+ const relativePath = relative(silgi.options.rootDir, pathname);
32
+ if (relativePath[0] === "." && relativePath[1] === ".") return false;
33
+ return !!(relativePath && silgi._ignore.ignores(relativePath));
34
+ }
35
+ /**
36
+ * This function turns string containing groups '**\/*.{spec,test}.{js,ts}' into an array of strings.
37
+ * For example will '**\/*.{spec,test}.{js,ts}' be resolved to:
38
+ * ['**\/*.spec.js', '**\/*.spec.ts', '**\/*.test.js', '**\/*.test.ts']
39
+ * @param group string containing the group syntax
40
+ * @returns {string[]} array of strings without the group syntax
41
+ */
42
+ function resolveGroupSyntax(group) {
43
+ let groups = [group];
44
+ while (groups.some((group$1) => group$1.includes("{"))) groups = groups.flatMap((group$1) => {
45
+ const [head, ...tail] = group$1.split("{");
46
+ if (tail.length) {
47
+ const [body = "", ...rest] = tail.join("{").split("}");
48
+ return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
49
+ }
50
+ return group$1;
51
+ });
52
+ return groups;
53
+ }
54
+
55
+ //#endregion
56
+ export { isIgnored };
@@ -0,0 +1,58 @@
1
+ import { consola as consola$1 } from "consola";
2
+ import { resolve } from "pathe";
3
+ import { createUnimport } from "unimport";
4
+ import { promises } from "node:fs";
5
+ import { createJiti } from "dev-jiti";
6
+
7
+ //#region src/cli/utils/readScanFile.ts
8
+ async function readScanFile(silgi) {
9
+ const path = resolve(silgi.options.silgi.serverDir, "scan.ts");
10
+ const context = await promises.readFile(path, { encoding: "utf-8" });
11
+ silgi.unimport = createUnimport(silgi.options.imports || {});
12
+ await silgi.unimport.init();
13
+ const injectedResult = await silgi.unimport.injectImports(context, path);
14
+ if (!injectedResult) throw new Error("Failed to inject imports");
15
+ const jiti = createJiti(silgi.options.rootDir, {
16
+ fsCache: true,
17
+ moduleCache: false,
18
+ debug: silgi.options.debug === true,
19
+ alias: silgi.options.alias
20
+ });
21
+ try {
22
+ const scanFile = await jiti.evalModule(injectedResult.code, {
23
+ filename: path,
24
+ async: true,
25
+ conditions: silgi.options.conditions
26
+ }, async (data, name) => {
27
+ return (await silgi.unimport.injectImports(data, name)).code;
28
+ });
29
+ silgi.schemas = scanFile.schemas || {};
30
+ silgi.services = scanFile.services || {};
31
+ silgi.shareds = scanFile.shareds || {};
32
+ silgi.resolvers = scanFile.resolvers || {};
33
+ return {
34
+ context,
35
+ object: {
36
+ schemas: scanFile.schemas,
37
+ services: scanFile.services,
38
+ shareds: scanFile.shareds
39
+ },
40
+ path
41
+ };
42
+ } catch (error) {
43
+ if (silgi.options.debug) console.error("Failed to read scan.ts file:", error);
44
+ else consola$1.withTag("silgi").error(error);
45
+ return {
46
+ context,
47
+ object: {
48
+ schemas: {},
49
+ services: {},
50
+ shareds: {}
51
+ },
52
+ path
53
+ };
54
+ }
55
+ }
56
+
57
+ //#endregion
58
+ export { readScanFile };
@@ -0,0 +1,23 @@
1
+ import { replaceRuntimeValues } from "silgi";
2
+ import { useRuntimeConfig } from "silgi/runtime";
3
+ import { klona } from "klona";
4
+ import { builtinDrivers, createStorage } from "unstorage";
5
+
6
+ //#region src/cli/utils/storage.ts
7
+ async function createStorageCLI(silgi) {
8
+ const storage = createStorage();
9
+ const runtime = useRuntimeConfig();
10
+ const mounts = klona({
11
+ ...silgi.options.storage,
12
+ ...silgi.options.devStorage
13
+ });
14
+ for (const [path, opts] of Object.entries(mounts)) if (opts.driver) {
15
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
16
+ const processedOpts = replaceRuntimeValues({ ...opts }, runtime);
17
+ storage.mount(path, driver(processedOpts));
18
+ } else silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
19
+ return storage;
20
+ }
21
+
22
+ //#endregion
23
+ export { createStorageCLI };
@@ -0,0 +1,30 @@
1
+ import { SilgiRuntimeConfig } from "silgi/types";
2
+
3
+ //#region src/core/context.d.ts
4
+ declare function updateRuntimeStorage(runtime: any): void;
5
+ /** Direct access to the silgi context with asyncLocalStorage - see https://github.com/unjs/unctx. */
6
+
7
+ /**
8
+ * Get access to silgi instance.
9
+ *
10
+ * Throws an error if silgi instance is unavailable.
11
+ * @example
12
+ * ```js
13
+ * const runtime = useRuntime()
14
+ * ```
15
+ */
16
+ declare function useRuntime(): SilgiRuntimeConfig;
17
+ /**
18
+ * Get access to Runtime instance.
19
+ *
20
+ * Returns null if Runtime instance is unavailable.
21
+ * @example
22
+ * ```js
23
+ * const runtime = tryUseRuntime()
24
+ * if (runtime) {
25
+ * // Do something
26
+ * }
27
+ * ```
28
+ */
29
+ //#endregion
30
+ export { updateRuntimeStorage as updateRuntimeStorage$1, useRuntime as useRuntime$1 };
@@ -0,0 +1,32 @@
1
+ import { createContext } from "unctx";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+
4
+ //#region src/core/context.ts
5
+ /** async local storage for the name of the current silgi instance */
6
+ const asyncRuntimeStorage = createContext({
7
+ asyncContext: true,
8
+ AsyncLocalStorage
9
+ });
10
+ function updateRuntimeStorage(runtime) {
11
+ if (asyncRuntimeStorage.tryUse()) {
12
+ asyncRuntimeStorage.unset();
13
+ asyncRuntimeStorage.set(runtime);
14
+ } else asyncRuntimeStorage.set(runtime);
15
+ }
16
+ /**
17
+ * Get access to silgi instance.
18
+ *
19
+ * Throws an error if silgi instance is unavailable.
20
+ * @example
21
+ * ```js
22
+ * const runtime = useRuntime()
23
+ * ```
24
+ */
25
+ function useRuntime() {
26
+ const instance = asyncRuntimeStorage.tryUse();
27
+ if (!instance) throw new Error("Runtime instance is unavailable!");
28
+ return instance;
29
+ }
30
+
31
+ //#endregion
32
+ export { updateRuntimeStorage, useRuntime };
@@ -0,0 +1,6 @@
1
+ import { Silgi, SilgiConfig } from "silgi/types";
2
+
3
+ //#region src/core/createSilgi.d.ts
4
+ declare function createSilgi(config: SilgiConfig): Promise<Silgi>;
5
+ //#endregion
6
+ export { createSilgi as createSilgi$1 };
@@ -0,0 +1,152 @@
1
+ import { silgiCtx } from "./unctx.mjs";
2
+ import { createStorage, useSilgiStorage } from "./utils/storage.mjs";
3
+ import { createConsola } from "consola";
4
+ import { createHooks } from "hookable";
5
+ import { getServicePath } from "silgi/kit";
6
+ import { sharedRuntimeConfig, useRuntimeConfig } from "silgi/runtime";
7
+ import { defu } from "defu";
8
+ import { toJsonSchema } from "@standard-community/standard-json";
9
+ import { addRoute, createRouter } from "rou3";
10
+
11
+ //#region src/core/createSilgi.ts
12
+ async function runSilgiPlugins(silgi) {
13
+ for (const plugin of silgi.plugins) try {
14
+ await plugin(silgi);
15
+ } catch (error) {
16
+ silgi.captureError(silgi, error, { tags: ["plugin"] });
17
+ throw error;
18
+ }
19
+ }
20
+ async function createSilgi(config) {
21
+ const hooks = createHooks();
22
+ const silgi = {
23
+ router: void 0,
24
+ _middlewareRouter: void 0,
25
+ routerPrefixs: [],
26
+ schemas: config.schemas ?? {},
27
+ services: config.services ?? {},
28
+ resolvers: config.resolvers ?? [],
29
+ middlewares: config.middlewares ?? {},
30
+ globalMiddlewares: config.globalMiddlewares ?? [],
31
+ shared: config.shared ?? {},
32
+ plugins: config.plugins ?? [],
33
+ framework: config.framework ?? {},
34
+ storage: config.options.putStorage ?? void 0,
35
+ options: config.options ?? {},
36
+ hooks,
37
+ callHook: hooks.callHook,
38
+ addHooks: hooks.addHooks,
39
+ hook: hooks.hook,
40
+ ready: () => {
41
+ return hooks.callHook("ready", silgi);
42
+ },
43
+ envOptions: config.envOptions ?? {},
44
+ close: () => hooks.callHook("close", silgi),
45
+ logger: createConsola(defu(config.options?.consolaOptions ?? {}, { tag: "silgi" })).withTag("silgi"),
46
+ captureError: config.captureError ?? (() => {}),
47
+ websocket: config.websocket ?? void 0
48
+ };
49
+ sharedRuntimeConfig(silgi.options.runtimeConfig);
50
+ if (!silgi.router) silgi.router = createRouter();
51
+ for (const [_route, object] of Object.entries(silgi.services)) {
52
+ const { method, type } = getServicePath(_route);
53
+ if (!object) continue;
54
+ const path = String(object.path);
55
+ const routeParts = path.split("/").filter(Boolean);
56
+ if (routeParts.length > 0) {
57
+ const prefix = `/${routeParts[0]}`;
58
+ if (!silgi.routerPrefixs.includes(prefix)) silgi.routerPrefixs.push(`${type}:${prefix}`);
59
+ }
60
+ let routeWithParams = path;
61
+ let pathParamNames = {};
62
+ let queryParamNames = {};
63
+ if (object.pathParams) {
64
+ const jsonSchema = await toJsonSchema(object.pathParams);
65
+ if (jsonSchema && jsonSchema.properties) {
66
+ pathParamNames = Object.keys(jsonSchema.properties).reduce((acc, key) => {
67
+ const prop = jsonSchema.properties?.[key];
68
+ if (typeof prop === "object" && prop !== null && "type" in prop) acc[key] = prop.type ?? "string";
69
+ else acc[key] = "string";
70
+ return acc;
71
+ }, {});
72
+ const paramNames = Object.keys(jsonSchema.properties);
73
+ if (paramNames.length > 0) {
74
+ const routeParts$1 = routeWithParams.split("/");
75
+ const lastParts = routeParts$1.slice(-paramNames.length);
76
+ const alreadyHasParams = paramNames.every((name, idx) => lastParts[idx] === `:${name}`);
77
+ if (!alreadyHasParams) {
78
+ routeWithParams = routeWithParams.replace(/\/+$/, "");
79
+ for (const param of paramNames) routeWithParams += `/:${param}`;
80
+ }
81
+ }
82
+ }
83
+ }
84
+ if (object.queryParams) {
85
+ const jsonSchema = await toJsonSchema(object.queryParams);
86
+ if (jsonSchema && jsonSchema.properties) queryParamNames = Object.keys(jsonSchema.properties).reduce((acc, key) => {
87
+ const prop = jsonSchema.properties?.[key];
88
+ if (typeof prop === "object" && prop !== null && "type" in prop) acc[key] = prop.type ?? "string";
89
+ else acc[key] = "string";
90
+ return acc;
91
+ }, {});
92
+ }
93
+ addRoute(silgi.router, method, routeWithParams, {
94
+ method,
95
+ route: routeWithParams,
96
+ service: object,
97
+ queryParams: queryParamNames,
98
+ pathParams: pathParamNames
99
+ });
100
+ }
101
+ if (!silgi._middlewareRouter) silgi._middlewareRouter = createRouter();
102
+ for (const [route, routeObject] of Object.entries(silgi.middlewares)) {
103
+ let _key = "";
104
+ let _route = "";
105
+ if (route.includes(":")) {
106
+ const [methodPart, ...routeParts] = route.split(":");
107
+ _key = (methodPart ?? "").toUpperCase();
108
+ if (_key === "GLOBAL") _key = "";
109
+ _route = routeParts.join(":");
110
+ }
111
+ if (_route === "global") {
112
+ for (const method of routeObject.methods?.length ? routeObject.methods : ["ALL"]) silgi.globalMiddlewares.push({
113
+ middleware: routeObject.setup,
114
+ method: method === "ALL" ? "" : method.toUpperCase(),
115
+ route: _route
116
+ });
117
+ continue;
118
+ }
119
+ const methods = routeObject.methods?.length ? routeObject.methods : ["ALL"];
120
+ for (const method of methods) {
121
+ const globalMethod = method === "ALL" ? "" : method.toUpperCase();
122
+ addRoute(silgi._middlewareRouter, globalMethod, _route, {
123
+ middleware: routeObject.setup,
124
+ method,
125
+ route: _route
126
+ });
127
+ }
128
+ }
129
+ silgi.hooks.addHooks(silgi.options.hooks);
130
+ await runSilgiPlugins(silgi);
131
+ if (!silgi.storage) silgi.storage = await createStorage(silgi);
132
+ silgi.shared.storage = (...data) => {
133
+ return useSilgiStorage(...data);
134
+ };
135
+ silgi.shared.useRuntimeConfig = useRuntimeConfig;
136
+ if (silgiCtx.tryUse()) {
137
+ silgiCtx.unset();
138
+ silgiCtx.set(silgi);
139
+ } else {
140
+ silgiCtx.set(silgi);
141
+ silgi.hook("close", () => silgiCtx.unset());
142
+ }
143
+ hooks.hookOnce("close", async () => {
144
+ hooks.removeAllHooks();
145
+ await silgi.storage.dispose();
146
+ });
147
+ silgi.logger.info("Silgi Start");
148
+ return silgi;
149
+ }
150
+
151
+ //#endregion
152
+ export { createSilgi };
@@ -0,0 +1,65 @@
1
+ //#region src/core/error.d.ts
2
+ /**
3
+ * Silgi Runtime Error
4
+ * @class
5
+ * @extends Error
6
+ * @property {number} statusCode - An integer indicating the HTTP response status code.
7
+ * @property {string} statusMessage - A string representing the HTTP status message.
8
+ * @property {boolean} fatal - Indicates if the error is a fatal error.
9
+ * @property {boolean} unhandled - Indicates if the error was unhandled and auto-captured.
10
+ * @property {DataT} data - An extra data that will be included in the response.
11
+ * This can be used to pass additional information about the error.
12
+ */
13
+ declare class SilgiError<DataT = unknown> extends Error {
14
+ static __silgi_error__: boolean;
15
+ statusCode: number;
16
+ fatal: boolean;
17
+ unhandled: boolean;
18
+ statusMessage?: string;
19
+ data?: DataT;
20
+ cause?: unknown;
21
+ constructor(message: string, opts?: {
22
+ cause?: unknown;
23
+ });
24
+ toJSON(): Pick<SilgiError<DataT>, "message" | "statusCode" | "statusMessage" | "data">;
25
+ }
26
+ /**
27
+ * Creates a new `Error` that can be used to handle both internal and runtime errors.
28
+ *
29
+ * @param input {string | (Partial<SilgiError> & { status?: number; statusText?: string })} - The error message or an object containing error properties.
30
+ * If a string is provided, it will be used as the error `message`.
31
+ *
32
+ * @example
33
+ * // String error where `statusCode` defaults to `500`
34
+ * throw createError("An error occurred");
35
+ * // Object error
36
+ * throw createError({
37
+ * statusCode: 400,
38
+ * statusMessage: "Bad Request",
39
+ * message: "Invalid input",
40
+ * data: { field: "email" }
41
+ * });
42
+ *
43
+ *
44
+ * @return {SilgiError} - An instance of SilgiError.
45
+ *
46
+ * @remarks
47
+ * - Typically, `message` contains a brief, human-readable description of the error, while `statusMessage` is specific to HTTP responses and describes
48
+ * the status text related to the response status code.
49
+ * - In a client-server context, using a short `statusMessage` is recommended because it can be accessed on the client side. Otherwise, a `message`
50
+ * passed to `createError` on the server will not propagate to the client.
51
+ * - Consider avoiding putting dynamic user input in the `message` to prevent potential security issues.
52
+ */
53
+ declare function createError<DataT = unknown>(input: string | (Partial<SilgiError<DataT>> & {
54
+ status?: number;
55
+ statusText?: string;
56
+ })): SilgiError<DataT>;
57
+ /**
58
+ * Checks if the given input is an instance of SilgiError.
59
+ *
60
+ * @param input {*} - The input to check.
61
+ * @return {boolean} - Returns true if the input is an instance of SilgiError, false otherwise.
62
+ */
63
+ declare function isError<DataT = unknown>(input: any): input is SilgiError<DataT>;
64
+ //#endregion
65
+ export { SilgiError as SilgiError$1, createError as createError$1, isError as isError$1 };