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
@@ -1,1348 +1,30 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { createContext, getContext } from 'unctx';
3
- import { toJsonSchema } from '@standard-community/standard-json';
4
- import consola, { createConsola } from 'consola';
5
- import { defu } from 'defu';
6
- import { createHooks } from 'hookable';
7
- import { createRouter, addRoute, findRoute, findAllRoutes } from 'rou3';
8
- import { getServicePath } from 'silgi/kit';
9
- import { useRuntimeConfig, sharedRuntimeConfig } from 'silgi/runtime';
10
- import { Buffer } from 'node:buffer';
11
- import { klona } from 'klona';
12
- import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
13
- import { isDevelopment } from 'std-env';
14
- import { FastURL, FastResponse } from 'srvx';
15
- export { s as silgiCLICtx, t as tryUseSilgiCLI, u as useSilgiCLI } from '../_chunks/silgiApp.mjs';
16
-
17
- const asyncRuntimeStorage = createContext({
18
- asyncContext: true,
19
- AsyncLocalStorage
20
- });
21
- function updateRuntimeStorage(runtime) {
22
- if (asyncRuntimeStorage.tryUse()) {
23
- asyncRuntimeStorage.unset();
24
- asyncRuntimeStorage.set(runtime);
25
- } else {
26
- asyncRuntimeStorage.set(runtime);
27
- }
28
- }
29
- function useRuntime() {
30
- const instance = asyncRuntimeStorage.tryUse();
31
- if (!instance) {
32
- throw new Error("Runtime instance is unavailable!");
33
- }
34
- return instance;
35
- }
36
-
37
- const silgiCtx = getContext("silgi");
38
- function useSilgi() {
39
- const instance = silgiCtx.tryUse();
40
- if (!instance) {
41
- throw new Error("Silgi instance is unavailable!");
42
- }
43
- return instance;
44
- }
45
- function normalizeResult(result) {
46
- if (Array.isArray(result)) {
47
- return [...result];
48
- }
49
- if (result && typeof result === "object") {
50
- if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
51
- return Object.values(result);
52
- }
53
- return { ...result };
54
- }
55
- return result;
56
- }
57
- function tryUseSilgi() {
58
- return silgiCtx.tryUse();
59
- }
60
-
61
- const EmptyObject = /* @__PURE__ */ (() => {
62
- const C = function() {
63
- };
64
- C.prototype = /* @__PURE__ */ Object.create(null);
65
- return C;
66
- })();
67
-
68
- function hasProp(obj, prop) {
69
- try {
70
- return prop in obj;
71
- } catch {
72
- return false;
73
- }
74
- }
75
- function isJSONSerializable(value, _type) {
76
- if (value === null || value === void 0) {
77
- return true;
78
- }
79
- if (_type !== "object") {
80
- return _type === "boolean" || _type === "number" || _type === "string";
81
- }
82
- if (typeof value.toJSON === "function") {
83
- return true;
84
- }
85
- if (Array.isArray(value)) {
86
- return true;
87
- }
88
- if (typeof value.pipe === "function" || typeof value.pipeTo === "function") {
89
- return false;
90
- }
91
- if (value instanceof EmptyObject) {
92
- return true;
93
- }
94
- const proto = Object.getPrototypeOf(value);
95
- return proto === Object.prototype || proto === null;
96
- }
97
-
98
- const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
99
- function sanitizeStatusMessage(statusMessage = "") {
100
- return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
101
- }
102
- function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
103
- if (!statusCode) {
104
- return defaultStatusCode;
105
- }
106
- if (typeof statusCode === "string") {
107
- statusCode = Number.parseInt(statusCode, 10);
108
- }
109
- if (statusCode < 100 || statusCode > 999) {
110
- return defaultStatusCode;
111
- }
112
- return statusCode;
113
- }
114
-
115
- class SilgiError extends Error {
116
- static __silgi_error__ = true;
117
- statusCode = 500;
118
- fatal = false;
119
- unhandled = false;
120
- statusMessage;
121
- data;
122
- cause;
123
- constructor(message, opts = {}) {
124
- super(message, opts);
125
- if (opts.cause && !this.cause) {
126
- this.cause = opts.cause;
127
- }
128
- if (isDevelopment && opts.cause && opts.cause instanceof Error && opts.cause.stack && this.stack) {
129
- this.stack += `
130
- Caused by: ${opts.cause.stack}`;
131
- consola.warn(opts.cause);
132
- }
133
- }
134
- toJSON() {
135
- const obj = {
136
- message: this.message,
137
- statusCode: sanitizeStatusCode(this.statusCode, 500)
138
- };
139
- if (this.statusMessage) {
140
- obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
141
- }
142
- if (this.data !== void 0) {
143
- obj.data = this.data;
144
- }
145
- return obj;
146
- }
147
- }
148
- function createError(input) {
149
- if (typeof input === "string") {
150
- return new SilgiError(input);
151
- }
152
- const cause = input.cause;
153
- const err = new SilgiError(input.message ?? input.statusMessage ?? "", {
154
- cause: cause || input
155
- });
156
- if (hasProp(input, "stack")) {
157
- try {
158
- Object.defineProperty(err, "stack", {
159
- get() {
160
- return input.stack;
161
- }
162
- });
163
- } catch {
164
- try {
165
- err.stack = input.stack;
166
- } catch {
167
- }
168
- }
169
- }
170
- if (input.data) {
171
- err.data = input.data;
172
- }
173
- const statusCode = input.statusCode ?? input.status ?? cause?.statusCode ?? cause?.status;
174
- if (typeof statusCode === "number") {
175
- err.statusCode = sanitizeStatusCode(statusCode);
176
- }
177
- const statusMessage = input.statusMessage ?? input.statusText ?? cause?.statusMessage ?? cause?.statusText;
178
- if (statusMessage) {
179
- err.statusMessage = sanitizeStatusMessage(statusMessage);
180
- }
181
- const fatal = input.fatal ?? cause?.fatal;
182
- if (fatal !== void 0) {
183
- err.fatal = fatal;
184
- }
185
- const unhandled = input.unhandled ?? cause?.unhandled;
186
- if (unhandled !== void 0) {
187
- err.unhandled = unhandled;
188
- }
189
- return err;
190
- }
191
- function isError(input) {
192
- return input?.constructor?.__silgi_error__ === true;
193
- }
194
-
195
- function replaceRuntimeValues(obj, runtime) {
196
- if (!obj || typeof obj !== "object")
197
- return obj;
198
- for (const key in obj) {
199
- if (typeof obj[key] === "string" && obj[key].startsWith("runtime.")) {
200
- const runtimePath = obj[key].substring(8).split(".");
201
- let value = runtime;
202
- for (const segment of runtimePath) {
203
- if (value === void 0 || value === null)
204
- break;
205
- value = value[segment];
206
- }
207
- if (value !== void 0)
208
- obj[key] = value;
209
- } else if (typeof obj[key] === "object" && obj[key] !== null) {
210
- obj[key] = replaceRuntimeValues(obj[key], runtime);
211
- }
212
- }
213
- return obj;
214
- }
215
-
216
- async function createStorage(silgi) {
217
- const storage = createStorage$1();
218
- const runtime = useRuntimeConfig();
219
- const mounts = klona({
220
- ...silgi.options.storage,
221
- ...silgi.options.devStorage
222
- });
223
- for (const [path, opts] of Object.entries(mounts)) {
224
- if (opts.driver) {
225
- const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
226
- const processedOpts = replaceRuntimeValues({ ...opts }, runtime);
227
- storage.mount(path, driver(processedOpts));
228
- } else {
229
- silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
230
- }
231
- }
232
- return storage;
233
- }
234
- function useSilgiStorage(base = "/memory:cache") {
235
- const silgi = useSilgi();
236
- return base ? prefixStorage(silgi.storage, base) : silgi.storage;
237
- }
238
- async function generateStorageKey(params) {
239
- const {
240
- url,
241
- input,
242
- keyGenerator,
243
- requestId,
244
- storageOptions
245
- } = params;
246
- const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
247
- const parts = [
248
- cacheScopePrefix,
249
- // Always include scope prefix first
250
- url.raw
251
- ].filter(Boolean);
252
- if (storageOptions?.scope === "request") {
253
- if (!requestId) {
254
- throw createError({
255
- statusCode: 400,
256
- statusMessage: "Request ID is required for request-scoped cache",
257
- data: {
258
- requestId,
259
- url,
260
- input,
261
- storageOptions,
262
- keyGenerator
263
- }
264
- });
265
- }
266
- parts.push(requestId);
267
- }
268
- if (keyGenerator) {
269
- const customKey = await Promise.resolve(keyGenerator(input));
270
- parts.push(customKey);
271
- } else {
272
- parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
273
- }
274
- return Buffer.from(parts.join(":")).toString("base64");
275
- }
276
-
277
- async function runSilgiPlugins(silgi) {
278
- for (const plugin of silgi.plugins) {
279
- try {
280
- await plugin(silgi);
281
- } catch (error) {
282
- silgi.captureError(silgi, error, { tags: ["plugin"] });
283
- throw error;
284
- }
285
- }
286
- }
287
- async function createSilgi(config) {
288
- const hooks = createHooks();
289
- const silgi = {
290
- router: void 0,
291
- _middlewareRouter: void 0,
292
- routerPrefixs: [],
293
- schemas: config.schemas ?? {},
294
- services: config.services ?? {},
295
- resolvers: config.resolvers ?? [],
296
- middlewares: config.middlewares ?? {},
297
- globalMiddlewares: config.globalMiddlewares ?? [],
298
- shared: config.shared ?? {},
299
- plugins: config.plugins ?? [],
300
- framework: config.framework ?? {},
301
- storage: config.options.putStorage ?? void 0,
302
- options: config.options ?? {},
303
- hooks,
304
- callHook: hooks.callHook,
305
- addHooks: hooks.addHooks,
306
- hook: hooks.hook,
307
- ready: () => {
308
- return hooks.callHook("ready", silgi);
309
- },
310
- envOptions: config.envOptions ?? {},
311
- close: () => hooks.callHook("close", silgi),
312
- logger: createConsola(defu(config.options?.consolaOptions ?? {}, {
313
- tag: "silgi"
314
- })).withTag("silgi"),
315
- captureError: config.captureError ?? (() => {
316
- }),
317
- websocket: config.websocket ?? void 0
318
- };
319
- sharedRuntimeConfig(silgi.options.runtimeConfig);
320
- if (!silgi.router) {
321
- silgi.router = createRouter();
322
- }
323
- for (const [_route, object] of Object.entries(silgi.services)) {
324
- const { method, type } = getServicePath(_route);
325
- if (!object)
326
- continue;
327
- const path = String(object.path);
328
- const routeParts = path.split("/").filter(Boolean);
329
- if (routeParts.length > 0) {
330
- const prefix = `/${routeParts[0]}`;
331
- if (!silgi.routerPrefixs.includes(prefix)) {
332
- silgi.routerPrefixs.push(`${type}:${prefix}`);
333
- }
334
- }
335
- let routeWithParams = path;
336
- let pathParamNames = {};
337
- let queryParamNames = {};
338
- if (object.pathParams) {
339
- const jsonSchema = await toJsonSchema(object.pathParams);
340
- if (jsonSchema && jsonSchema.properties) {
341
- pathParamNames = Object.keys(jsonSchema.properties).reduce((acc, key) => {
342
- const prop = jsonSchema.properties?.[key];
343
- if (typeof prop === "object" && prop !== null && "type" in prop) {
344
- acc[key] = prop.type ?? "string";
345
- } else {
346
- acc[key] = "string";
347
- }
348
- return acc;
349
- }, {});
350
- const paramNames = Object.keys(jsonSchema.properties);
351
- if (paramNames.length > 0) {
352
- const routeParts2 = routeWithParams.split("/");
353
- const lastParts = routeParts2.slice(-paramNames.length);
354
- const alreadyHasParams = paramNames.every((name, idx) => lastParts[idx] === `:${name}`);
355
- if (!alreadyHasParams) {
356
- routeWithParams = routeWithParams.replace(/\/+$/, "");
357
- for (const param of paramNames) {
358
- routeWithParams += `/:${param}`;
359
- }
360
- }
361
- }
362
- }
363
- }
364
- if (object.queryParams) {
365
- const jsonSchema = await toJsonSchema(object.queryParams);
366
- if (jsonSchema && jsonSchema.properties) {
367
- queryParamNames = Object.keys(jsonSchema.properties).reduce((acc, key) => {
368
- const prop = jsonSchema.properties?.[key];
369
- if (typeof prop === "object" && prop !== null && "type" in prop) {
370
- acc[key] = prop.type ?? "string";
371
- } else {
372
- acc[key] = "string";
373
- }
374
- return acc;
375
- }, {});
376
- }
377
- }
378
- addRoute(silgi.router, method, routeWithParams, {
379
- method,
380
- route: routeWithParams,
381
- service: object,
382
- queryParams: queryParamNames,
383
- pathParams: pathParamNames
384
- });
385
- }
386
- if (!silgi._middlewareRouter) {
387
- silgi._middlewareRouter = createRouter();
388
- }
389
- for (const [route, routeObject] of Object.entries(silgi.middlewares)) {
390
- let _route = "";
391
- if (route.includes(":")) {
392
- const [methodPart, ...routeParts] = route.split(":");
393
- methodPart.toUpperCase();
394
- _route = routeParts.join(":");
395
- }
396
- if (_route === "global") {
397
- for (const method of routeObject.methods?.length ? routeObject.methods : ["ALL"]) {
398
- silgi.globalMiddlewares.push({
399
- middleware: routeObject.setup,
400
- method: method === "ALL" ? "" : method.toUpperCase(),
401
- route: _route
402
- });
403
- }
404
- continue;
405
- }
406
- const methods = routeObject.methods?.length ? routeObject.methods : ["ALL"];
407
- for (const method of methods) {
408
- const globalMethod = method === "ALL" ? "" : method.toUpperCase();
409
- addRoute(silgi._middlewareRouter, globalMethod, _route, {
410
- middleware: routeObject.setup,
411
- method,
412
- route: _route
413
- });
414
- }
415
- }
416
- silgi.hooks.addHooks(silgi.options.hooks);
417
- await runSilgiPlugins(silgi);
418
- if (!silgi.storage) {
419
- silgi.storage = await createStorage(silgi);
420
- }
421
- silgi.shared.storage = (...data) => {
422
- return useSilgiStorage(...data);
423
- };
424
- silgi.shared.useRuntimeConfig = useRuntimeConfig;
425
- if (silgiCtx.tryUse()) {
426
- silgiCtx.unset();
427
- silgiCtx.set(silgi);
428
- } else {
429
- silgiCtx.set(silgi);
430
- silgi.hook("close", () => silgiCtx.unset());
431
- }
432
- hooks.hookOnce("close", async () => {
433
- hooks.removeAllHooks();
434
- await silgi.storage.dispose();
435
- });
436
- silgi.logger.info("Silgi Start");
437
- return silgi;
438
- }
439
-
440
- class SilgiHttpEvent {
441
- static __is_event__ = true;
442
- req;
443
- url;
444
- context;
445
- _res;
446
- constructor(req, context) {
447
- this.context = context || new EmptyObject();
448
- this.context.protocol = "HTTP";
449
- this.req = req;
450
- const _url = req._url;
451
- this.url = _url && _url instanceof URL ? _url : new FastURL(req.url);
452
- }
453
- _chain;
454
- get res() {
455
- if (!this._res) {
456
- this._res = new SilgiEventResponse();
457
- }
458
- return this._res;
459
- }
460
- get runtime() {
461
- return this.req.runtime;
462
- }
463
- toString() {
464
- return `[${this.req.method}] ${this.req.url}`;
465
- }
466
- toJSON() {
467
- return this.toString();
468
- }
469
- }
470
- class SilgiEventResponse {
471
- status;
472
- statusText;
473
- _headers;
474
- get headers() {
475
- if (!this._headers) {
476
- this._headers = new Headers();
477
- }
478
- return this._headers;
479
- }
480
- }
481
-
482
- const kNotFound = /* @__PURE__ */ Symbol.for("silgi.notFound");
483
- const kHandled = /* @__PURE__ */ Symbol.for("silgi.handled");
484
- function handleResponse(val, event, config) {
485
- if (val && val instanceof Promise) {
486
- return val.catch((error) => error).then((resolvedVal) => handleResponse(resolvedVal, event, config));
487
- }
488
- const response = prepareResponse(val, event, config);
489
- if (response instanceof Promise) {
490
- return handleResponse(response, event, config);
491
- }
492
- const { onBeforeResponse } = config;
493
- return onBeforeResponse ? Promise.resolve(onBeforeResponse(event, response)).then(() => response) : response;
494
- }
495
- function prepareResponse(val, event, config, nested) {
496
- if (val === kHandled) {
497
- return new FastResponse(null);
498
- }
499
- if (val === kNotFound) {
500
- val = createError({
501
- statusCode: 404,
502
- statusMessage: `Cannot find any route matching [${event.req.method}] ${event.url}`
503
- });
504
- }
505
- if (val && val instanceof Error) {
506
- const error = createError(val);
507
- const { onError } = config;
508
- return onError && !nested ? Promise.resolve(onError(error, event)).catch((error2) => error2).then((newVal) => prepareResponse(newVal ?? val, event, config, true)) : errorResponse(error, config.debug);
509
- }
510
- const eventHeaders = event.res._headers;
511
- if (!(val instanceof Response)) {
512
- const res = prepareResponseBody(val, event, config);
513
- const status = event.res.status;
514
- return new FastResponse(
515
- nullBody(event.req.method, status) ? null : res.body,
516
- {
517
- status,
518
- statusText: event.res.statusText,
519
- headers: res.headers && eventHeaders ? mergeHeaders(res.headers, eventHeaders) : res.headers || eventHeaders
520
- }
521
- );
522
- }
523
- if (!eventHeaders) {
524
- return val;
525
- }
526
- return new FastResponse(
527
- nullBody(event.req.method, val.status) ? null : val.body,
528
- {
529
- status: val.status,
530
- statusText: val.statusText,
531
- headers: mergeHeaders(eventHeaders, val.headers)
532
- }
533
- );
534
- }
535
- function nullBody(method, status) {
536
- return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
537
- }
538
- function mergeHeaders(base, merge) {
539
- const mergedHeaders = new Headers(base);
540
- for (const [name, value] of merge) {
541
- if (name === "set-cookie") {
542
- mergedHeaders.append(name, value);
543
- } else {
544
- mergedHeaders.set(name, value);
545
- }
546
- }
547
- return mergedHeaders;
548
- }
549
- const emptyHeaders = new Headers({ "content-length": "0" });
550
- const jsonHeaders = new Headers({
551
- "content-type": "application/json;charset=UTF-8"
552
- });
553
- function prepareResponseBody(val, event, config) {
554
- if (val === null || val === void 0) {
555
- return { body: "", headers: emptyHeaders };
556
- }
557
- const valType = typeof val;
558
- if (valType === "string") {
559
- return { body: val };
560
- }
561
- if (val instanceof Uint8Array) {
562
- event.res.headers.set("content-length", val.byteLength.toString());
563
- return { body: val };
564
- }
565
- if (isJSONSerializable(val, valType)) {
566
- return {
567
- body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
568
- headers: jsonHeaders
569
- };
570
- }
571
- if (valType === "bigint") {
572
- return { body: val.toString(), headers: jsonHeaders };
573
- }
574
- if (val instanceof Blob) {
575
- const headers = {
576
- "content-type": val.type,
577
- "content-length": val.size.toString()
578
- };
579
- if ("name" in val) {
580
- const filename = encodeURIComponent(val.name);
581
- headers["content-disposition"] = `filename="${filename}"; filename*=UTF-8''${filename}`;
582
- }
583
- return { body: val.stream(), headers };
584
- }
585
- if (valType === "symbol") {
586
- return { body: val.toString() };
587
- }
588
- if (valType === "function") {
589
- return { body: `${val.name}()` };
590
- }
591
- return { body: val };
592
- }
593
- function errorResponse(error, debug) {
594
- return new FastResponse(
595
- JSON.stringify(
596
- {
597
- statusCode: error.statusCode,
598
- statusMessage: error.statusMessage,
599
- data: error.data,
600
- stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
601
- },
602
- null,
603
- 2
604
- ),
605
- {
606
- status: error.statusCode,
607
- statusText: error.statusMessage,
608
- headers: {
609
- "content-type": "application/json; charset=utf-8"
610
- }
611
- }
612
- );
613
- }
614
-
615
- async function parseRequestInput(req) {
616
- const contentType = req.headers.get("content-type") || "";
617
- if (contentType.startsWith("application/json")) {
618
- const text = await req.text();
619
- if (!text)
620
- return void 0;
621
- try {
622
- return JSON.parse(text);
623
- } catch {
624
- throw createError({
625
- statusCode: 400,
626
- statusMessage: "Invalid JSON",
627
- data: text
628
- });
629
- }
630
- }
631
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
632
- const text = await req.text();
633
- return Object.fromEntries(new URLSearchParams(text));
634
- }
635
- if (contentType.startsWith("text/")) {
636
- return await req.text();
637
- }
638
- if (contentType.startsWith("application/octet-stream")) {
639
- const buffer = await req.arrayBuffer();
640
- if (typeof File !== "undefined") {
641
- return new File([buffer], "uploaded.bin", { type: contentType });
642
- }
643
- if (typeof Buffer !== "undefined") {
644
- return Buffer.from(buffer);
645
- }
646
- return new Uint8Array(buffer);
647
- }
648
- return await req.text();
649
- }
650
-
651
- const plusRegex = /\+/g;
652
- function parseQuery(input) {
653
- const params = new EmptyObject();
654
- if (!input || input === "?") {
655
- return params;
656
- }
657
- const inputLength = input.length;
658
- let key = "";
659
- let value = "";
660
- let startingIndex = -1;
661
- let equalityIndex = -1;
662
- let shouldDecodeKey = false;
663
- let shouldDecodeValue = false;
664
- let keyHasPlus = false;
665
- let valueHasPlus = false;
666
- let hasBothKeyValuePair = false;
667
- let c = 0;
668
- for (let i = 0; i < inputLength + 1; i++) {
669
- c = i === inputLength ? 38 : input.charCodeAt(i);
670
- switch (c) {
671
- case 38: {
672
- hasBothKeyValuePair = equalityIndex > startingIndex;
673
- if (!hasBothKeyValuePair) {
674
- equalityIndex = i;
675
- }
676
- key = input.slice(startingIndex + 1, equalityIndex);
677
- if (hasBothKeyValuePair || key.length > 0) {
678
- if (keyHasPlus) {
679
- key = key.replace(plusRegex, " ");
680
- }
681
- if (shouldDecodeKey) {
682
- try {
683
- key = decodeURIComponent(key);
684
- } catch {
685
- }
686
- }
687
- if (hasBothKeyValuePair) {
688
- value = input.slice(equalityIndex + 1, i);
689
- if (valueHasPlus) {
690
- value = value.replace(plusRegex, " ");
691
- }
692
- if (shouldDecodeValue) {
693
- try {
694
- value = decodeURIComponent(value);
695
- } catch {
696
- }
697
- }
698
- }
699
- const currentValue = params[key];
700
- if (currentValue === void 0) {
701
- params[key] = value;
702
- } else {
703
- if (Array.isArray(currentValue)) {
704
- currentValue.push(value);
705
- } else {
706
- params[key] = [currentValue, value];
707
- }
708
- }
709
- }
710
- value = "";
711
- startingIndex = i;
712
- equalityIndex = i;
713
- shouldDecodeKey = false;
714
- shouldDecodeValue = false;
715
- keyHasPlus = false;
716
- valueHasPlus = false;
717
- break;
718
- }
719
- case 61: {
720
- if (equalityIndex <= startingIndex) {
721
- equalityIndex = i;
722
- } else {
723
- shouldDecodeValue = true;
724
- }
725
- break;
726
- }
727
- case 43: {
728
- if (equalityIndex > startingIndex) {
729
- valueHasPlus = true;
730
- } else {
731
- keyHasPlus = true;
732
- }
733
- break;
734
- }
735
- case 37: {
736
- if (equalityIndex > startingIndex) {
737
- shouldDecodeValue = true;
738
- } else {
739
- shouldDecodeKey = true;
740
- }
741
- break;
742
- }
743
- }
744
- }
745
- return params;
746
- }
747
-
748
- function getQuery(event) {
749
- return parseQuery(event.url.search.slice(1));
750
- }
751
- function getRouterParams(event, opts = {}) {
752
- let params = event.context.params || {};
753
- if (opts.decode) {
754
- params = { ...params };
755
- for (const key in params) {
756
- params[key] = decodeURIComponent(params[key]);
757
- }
758
- }
759
- return params;
760
- }
761
-
762
- function createResolver(resolver) {
763
- return resolver;
764
- }
765
- function getUrlPrefix(path, method) {
766
- const parse = path.includes("://") ? new FastURL(path) : new URL(path, "http://localhost");
767
- const cleanedPath = parse.pathname + parse.search + parse.hash;
768
- const segments = cleanedPath.split("/").filter(Boolean);
769
- if (segments.length < 2) {
770
- throw createError({
771
- statusCode: 400,
772
- statusMessage: "Invalid URL format",
773
- data: { cleanedPath }
774
- });
775
- }
776
- const prefix = `/${segments[0]}`;
777
- const namespace = segments[1];
778
- return {
779
- namespaceName: namespace,
780
- prefixName: prefix,
781
- raw: path,
782
- path: cleanedPath,
783
- methodName: method || "GET"
784
- };
785
- }
786
-
787
- async function orchestrate(route, event) {
788
- const silgiCtx = useSilgi();
789
- const silgiURL = getUrlPrefix(route.route || event.req.url, route.method);
790
- const input = route.service?.rules?.readBeforeBody === false ? {} : await parseRequestInput(event.req);
791
- const hookContext = { earlyReturnValue: false };
792
- const routerParams = input.path || getRouterParams(event);
793
- const queryParams = input.query || getQuery(event);
794
- const inputData = {
795
- args: input,
796
- query: queryParams,
797
- path: routerParams
798
- };
799
- try {
800
- if (!route.service) {
801
- throw createError({
802
- statusCode: 404,
803
- statusMessage: "Service not found"
804
- });
805
- }
806
- const cachePromise = cacheExecute(input, route, silgiURL, event);
807
- const beforeHookPromise = silgiCtx.callHook("fetch:before", {
808
- url: silgiURL,
809
- input,
810
- event,
811
- route,
812
- hookContext
813
- });
814
- const cacheData = await cachePromise;
815
- await beforeHookPromise;
816
- if (hookContext.earlyReturnValue !== false) {
817
- return hookContext.earlyReturnValue;
818
- }
819
- if (cacheData?.success) {
820
- await silgiCtx.callHook("fetch:after", {
821
- event,
822
- url: silgiURL,
823
- input,
824
- result: cacheData.data,
825
- success: true,
826
- cached: true,
827
- // modules: setup.modules,
828
- route,
829
- hookContext
830
- });
831
- return cacheData.data;
832
- }
833
- silgiCtx.shared.$fetch = silgiFetch;
834
- silgiCtx.shared.silgi = silgiCtx;
835
- const result = await route.service?.handler?.(
836
- // input
837
- inputData,
838
- // shared
839
- silgiCtx.shared,
840
- // event
841
- event
842
- );
843
- await silgiCtx.callHook("fetch:after", {
844
- event,
845
- url: silgiURL,
846
- input: inputData,
847
- result,
848
- success: true,
849
- route,
850
- hookContext
851
- });
852
- if (route.service?.storage && cacheData?.cachedKey) {
853
- await useSilgiStorage(route.service.storage.base).setItem(
854
- cacheData.cachedKey,
855
- result,
856
- // Cast to StorageValue if needed
857
- route.service.storage.options
858
- );
859
- }
860
- return result;
861
- } catch (err) {
862
- await silgiCtx.callHook("fetch:error", {
863
- event,
864
- input: inputData,
865
- error: err instanceof Error ? err : new Error(String(err)),
866
- url: silgiURL,
867
- route,
868
- hookContext
869
- });
870
- silgiCtx.captureError(
871
- silgiCtx,
872
- createError({
873
- message: err instanceof Error ? err.message : String(err),
874
- statusCode: 500,
875
- statusMessage: "Internal Server Error",
876
- cause: err
877
- }),
878
- {
879
- event,
880
- tags: ["execute"]
881
- }
882
- );
883
- throw err;
884
- }
885
- }
886
- async function cacheExecute(input, route, silgiURL, event) {
887
- if (!route.service || !route.service.storage)
888
- return;
889
- const cacheKey = route.service.storage ? await generateStorageKey({
890
- url: silgiURL,
891
- input,
892
- keyGenerator: route.service.storage.key,
893
- storageOptions: route.service.storage,
894
- requestId: event?.requestId
895
- }) : null;
896
- if (cacheKey) {
897
- const cachedResult = await useSilgiStorage(route.service.storage.base).getItem(cacheKey);
898
- if (cachedResult !== null) {
899
- return {
900
- success: true,
901
- data: normalizeResult(cachedResult),
902
- cached: true,
903
- cachedKey: cacheKey
904
- };
905
- }
906
- }
907
- return {
908
- success: false,
909
- data: null,
910
- cached: false,
911
- cachedKey: cacheKey
912
- };
913
- }
914
-
915
- function getHeader(name, headers) {
916
- if (!headers) {
917
- return;
918
- }
919
- if (headers instanceof Headers) {
920
- return headers.get(name);
921
- }
922
- const lName = name.toLowerCase();
923
- if (Array.isArray(headers)) {
924
- return headers.find(
925
- (h) => h[0] === name || lName === h[0].toLowerCase()
926
- )?.[1];
927
- }
928
- return headers[name] || headers[lName];
929
- }
930
- function substitutePathParams(path, pathParams) {
931
- if (!pathParams)
932
- return path;
933
- return path.replace(/:(\w+)/g, (_, key) => {
934
- if (key in pathParams) {
935
- return encodeURIComponent(pathParams[key]);
936
- }
937
- return `:${key}`;
938
- });
939
- }
940
- function withDuplexIfBody(options) {
941
- if (!options)
942
- return options;
943
- if (options.body && !("duplex" in options)) {
944
- return { ...options, duplex: "half" };
945
- }
946
- return options;
947
- }
948
- async function silgiFetch(_request, options, context) {
949
- let request;
950
- if (typeof _request === "string") {
951
- _request = substitutePathParams(_request, options?.pathParams);
952
- let url = _request;
953
- if (url[0] === "/") {
954
- const host = getHeader("Host", options?.headers) || ".";
955
- const proto = getHeader("X-Forwarded-Proto", options?.headers) === "https" ? "https" : "http";
956
- url = `${proto}://${host}${url}`;
957
- }
958
- request = new Request(url, withDuplexIfBody(options));
959
- } else if (options || _request instanceof URL) {
960
- request = new Request(_request, withDuplexIfBody(options));
961
- } else {
962
- request = _request;
963
- }
964
- const silgiEvent = new SilgiHttpEvent(request, context);
965
- let handlerRes;
966
- try {
967
- handlerRes = handler(silgiEvent);
968
- } catch (error) {
969
- handlerRes = Promise.reject(error);
970
- }
971
- return handleResponse(handlerRes, silgiEvent, {});
972
- }
973
- async function middleware(event) {
974
- const silgiContext = useSilgi();
975
- event._chain = Promise.resolve(await silgiContext.callHook("request:on", event));
976
- let _chain = void 0;
977
- const _middleware = silgiContext.globalMiddlewares;
978
- if (_middleware) {
979
- _chain = _chain || Promise.resolve();
980
- for (const m of _middleware) {
981
- _chain = _chain.then(async (_previous) => {
982
- if (_previous !== void 0 && _previous !== kNotFound) {
983
- return _previous;
984
- }
985
- if (!(m.method === event.req.method) || !m.middleware) {
986
- return;
987
- }
988
- try {
989
- await silgiContext.callHook("middleware:global:on", event, m.middleware);
990
- } catch (error) {
991
- if (isError(error)) {
992
- throw error;
993
- }
994
- throw createError({
995
- message: "Middleware error",
996
- statusCode: 500,
997
- statusMessage: "Middleware error",
998
- cause: error
999
- });
1000
- }
1001
- return m.middleware.handler?.(event, silgiContext);
1002
- });
1003
- }
1004
- }
1005
- const _mRouter = silgiContext._middlewareRouter;
1006
- if (_mRouter) {
1007
- const matches = findAllRoutes(_mRouter, event.req.method, event.url.pathname);
1008
- if (matches.length > 0) {
1009
- _chain = _chain || Promise.resolve();
1010
- for (const match of matches) {
1011
- _chain = _chain.then(async (_previous) => {
1012
- if (_previous !== void 0 && _previous !== kNotFound) {
1013
- return _previous;
1014
- }
1015
- if (!(match.data.method === event.req.method) || !match.data.middleware) {
1016
- return;
1017
- }
1018
- event.context.params = match.params;
1019
- event.context.matchedRoute = match.data;
1020
- try {
1021
- await silgiContext.callHook("middleware:router:on", event, match.data.middleware);
1022
- } catch (error) {
1023
- if (isError(error)) {
1024
- throw error;
1025
- }
1026
- throw createError({
1027
- message: "Middleware error",
1028
- statusCode: 500,
1029
- statusMessage: "Middleware error",
1030
- cause: error
1031
- });
1032
- }
1033
- return match.data.middleware.handler?.(event, silgiContext);
1034
- });
1035
- }
1036
- }
1037
- }
1038
- event._chain = _chain;
1039
- if (event._chain) {
1040
- const data = await event._chain;
1041
- if (data !== void 0 && data !== kNotFound) {
1042
- return data;
1043
- }
1044
- }
1045
- }
1046
- async function handler(event) {
1047
- await middleware(event);
1048
- const silgiContext = useSilgi();
1049
- if (silgiContext.router) {
1050
- const match = findRoute(silgiContext.router, event.req.method, event.url.pathname);
1051
- if (match) {
1052
- if (event._chain) {
1053
- return event._chain.then(async (_previous) => {
1054
- if (_previous !== void 0 && _previous !== kNotFound) {
1055
- return _previous;
1056
- }
1057
- event.context.params = match.params;
1058
- event.context.matchedRoute = match.data;
1059
- return orchestrate(match.data, event);
1060
- });
1061
- } else {
1062
- event.context.params = match.params;
1063
- event.context.matchedRoute = match.data;
1064
- return orchestrate(match.data, event);
1065
- }
1066
- }
1067
- }
1068
- return event._chain ? event._chain.then(
1069
- (_previous) => _previous === void 0 ? kNotFound : _previous
1070
- ) : kNotFound;
1071
- }
1072
- function getWebsocket(silgi = useSilgi()) {
1073
- return {
1074
- ...silgi.options.websocket,
1075
- resolve: async (request) => {
1076
- request.method || "GET";
1077
- const event = new SilgiHttpEvent(request, {});
1078
- const silgiContext = useSilgi();
1079
- const handler2 = silgiContext.router && findRoute(silgiContext.router, event.req.method, event.url.pathname);
1080
- return handler2?.data.service?.websocket || {};
1081
- }
1082
- };
1083
- }
1084
-
1085
- function storageMount(silgi) {
1086
- const _silgi = silgi || useSilgi();
1087
- return (base, driver) => {
1088
- const existingStorage = _silgi.storage.getMount(base);
1089
- if (existingStorage) {
1090
- return existingStorage.driver;
1091
- }
1092
- const storage = _silgi.storage.mount(base, driver);
1093
- return storage;
1094
- };
1095
- }
1096
-
1097
- class EventStream {
1098
- _event;
1099
- _transformStream = new TransformStream();
1100
- _writer;
1101
- _encoder = new TextEncoder();
1102
- _writerIsClosed = false;
1103
- _paused = false;
1104
- _unsentData;
1105
- _disposed = false;
1106
- _handled = false;
1107
- constructor(event, opts = {}) {
1108
- this._event = event;
1109
- this._writer = this._transformStream.writable.getWriter();
1110
- this._writer.closed.then(() => {
1111
- this._writerIsClosed = true;
1112
- });
1113
- if (opts.autoclose !== false) {
1114
- this._event?.runtime?.node?.res?.once("close", () => this.close());
1115
- }
1116
- }
1117
- async push(message) {
1118
- if (typeof message === "string") {
1119
- await this._sendEvent({ data: message });
1120
- return;
1121
- }
1122
- if (Array.isArray(message)) {
1123
- if (message.length === 0) {
1124
- return;
1125
- }
1126
- if (typeof message[0] === "string") {
1127
- const msgs = [];
1128
- for (const item of message) {
1129
- msgs.push({ data: item });
1130
- }
1131
- await this._sendEvents(msgs);
1132
- return;
1133
- }
1134
- await this._sendEvents(message);
1135
- return;
1136
- }
1137
- await this._sendEvent(message);
1138
- }
1139
- async _sendEvent(message) {
1140
- if (this._writerIsClosed) {
1141
- return;
1142
- }
1143
- if (this._paused && !this._unsentData) {
1144
- this._unsentData = formatEventStreamMessage(message);
1145
- return;
1146
- }
1147
- if (this._paused) {
1148
- this._unsentData += formatEventStreamMessage(message);
1149
- return;
1150
- }
1151
- await this._writer.write(this._encoder.encode(formatEventStreamMessage(message))).catch();
1152
- }
1153
- async _sendEvents(messages) {
1154
- if (this._writerIsClosed) {
1155
- return;
1156
- }
1157
- const payload = formatEventStreamMessages(messages);
1158
- if (this._paused && !this._unsentData) {
1159
- this._unsentData = payload;
1160
- return;
1161
- }
1162
- if (this._paused) {
1163
- this._unsentData += payload;
1164
- return;
1165
- }
1166
- await this._writer.write(this._encoder.encode(payload)).catch();
1167
- }
1168
- pause() {
1169
- this._paused = true;
1170
- }
1171
- get isPaused() {
1172
- return this._paused;
1173
- }
1174
- async resume() {
1175
- this._paused = false;
1176
- await this.flush();
1177
- }
1178
- async flush() {
1179
- if (this._writerIsClosed) {
1180
- return;
1181
- }
1182
- if (this._unsentData?.length) {
1183
- await this._writer.write(this._encoder.encode(this._unsentData));
1184
- this._unsentData = void 0;
1185
- }
1186
- }
1187
- /**
1188
- * Close the stream and the connection if the stream is being sent to the client
1189
- */
1190
- async close() {
1191
- if (this._disposed) {
1192
- return;
1193
- }
1194
- if (!this._writerIsClosed) {
1195
- try {
1196
- await this._writer.close();
1197
- } catch {
1198
- }
1199
- }
1200
- this._disposed = true;
1201
- }
1202
- /**
1203
- * Triggers callback when the writable stream is closed.
1204
- * It is also triggered after calling the `close()` method.
1205
- */
1206
- onClosed(cb) {
1207
- this._writer.closed.then(cb);
1208
- }
1209
- async send() {
1210
- setEventStreamHeaders(this._event);
1211
- this._event.res.status = 200;
1212
- this._handled = true;
1213
- return this._transformStream.readable;
1214
- }
1215
- }
1216
- function formatEventStreamMessage(message) {
1217
- let result = "";
1218
- if (message.id) {
1219
- result += `id: ${message.id}
1220
- `;
1221
- }
1222
- if (message.event) {
1223
- result += `event: ${message.event}
1224
- `;
1225
- }
1226
- if (typeof message.retry === "number" && Number.isInteger(message.retry)) {
1227
- result += `retry: ${message.retry}
1228
- `;
1229
- }
1230
- result += `data: ${message.data}
1231
-
1232
- `;
1233
- return result;
1234
- }
1235
- function formatEventStreamMessages(messages) {
1236
- let result = "";
1237
- for (const msg of messages) {
1238
- result += formatEventStreamMessage(msg);
1239
- }
1240
- return result;
1241
- }
1242
- function setEventStreamHeaders(event) {
1243
- event.res.headers.set("content-type", "text/event-stream");
1244
- event.res.headers.set(
1245
- "cache-control",
1246
- "private, no-cache, no-store, no-transform, must-revalidate, max-age=0"
1247
- );
1248
- event.res.headers.set("x-accel-buffering", "no");
1249
- if (!isHttp2Request(event)) {
1250
- event.res.headers.set("connection", "keep-alive");
1251
- }
1252
- }
1253
- function isHttp2Request(event) {
1254
- const rawHeaders = event.req.headers;
1255
- if (typeof rawHeaders.get === "function") {
1256
- try {
1257
- return rawHeaders.has(":path") || rawHeaders.has(":method");
1258
- } catch {
1259
- return false;
1260
- }
1261
- }
1262
- return ":path" in rawHeaders || ":method" in rawHeaders;
1263
- }
1264
-
1265
- function createEventStream(event, opts) {
1266
- return new EventStream(event, opts);
1267
- }
1268
-
1269
- function getEvent(event) {
1270
- if (event?.event) {
1271
- return getEvent(event.event);
1272
- }
1273
- return event;
1274
- }
1275
- function getEventContext(event) {
1276
- const _event = getEvent(event);
1277
- return _event.context;
1278
- }
1279
-
1280
- function deepMerge(target, source) {
1281
- if (typeof target !== "object" || target === null)
1282
- return source;
1283
- if (typeof source !== "object" || source === null)
1284
- return source;
1285
- const result = Array.isArray(target) ? [...target] : { ...target };
1286
- for (const key of Object.keys(source)) {
1287
- if (key in target) {
1288
- result[key] = deepMerge(target[key], source[key]);
1289
- } else {
1290
- result[key] = source[key];
1291
- }
1292
- }
1293
- return result;
1294
- }
1295
- function deepMergeObjects(schemas) {
1296
- let merged = {};
1297
- for (const schema of schemas) {
1298
- merged = deepMerge(merged, schema);
1299
- }
1300
- return merged;
1301
- }
1302
-
1303
- function createMiddleware(params) {
1304
- return {
1305
- [`${params.key}:${params.path}`]: {
1306
- setup: params.setup,
1307
- methods: params.methods?.length ? params.methods : ["ALL"],
1308
- key: params.key,
1309
- path: params.path
1310
- }
1311
- };
1312
- }
1313
-
1314
- function createSchema(params) {
1315
- const { key, ...object } = params;
1316
- return {
1317
- [key]: object
1318
- };
1319
- }
1320
-
1321
- function defineServiceSetup(setup) {
1322
- return setup;
1323
- }
1324
- function createService(params) {
1325
- const method = params.method || "ALL";
1326
- return {
1327
- [`http:${method}:${params.path}`]: params
1328
- };
1329
- }
1330
- function createWebSocket(params) {
1331
- const method = params.method || "ALL";
1332
- return {
1333
- [`websocket:${method}:${params.path}`]: params
1334
- };
1335
- }
1336
-
1337
- function createShared(shared) {
1338
- return shared;
1339
- }
1340
-
1
+ import { silgiCLICtx, tryUseSilgiCLI, useSilgiCLI } from "./silgiApp.mjs";
2
+ import { updateRuntimeStorage, useRuntime } from "./context.mjs";
3
+ import { silgiCtx, tryUseSilgi, useSilgi } from "./unctx.mjs";
4
+ import { SilgiError, createError, isError } from "./error.mjs";
5
+ import { replaceRuntimeValues } from "./utils/runtime.mjs";
6
+ import { createStorage, useSilgiStorage } from "./utils/storage.mjs";
7
+ import { createSilgi } from "./createSilgi.mjs";
8
+ import { SilgiHttpEvent } from "./event.mjs";
9
+ import { handleResponse, kHandled, kNotFound } from "./response.mjs";
10
+ import { createResolver$1 as createResolver, getUrlPrefix } from "./utils/resolver.mjs";
11
+ import { getWebsocket, handler, middleware, silgiFetch } from "./silgi.mjs";
12
+ import { storageMount } from "./storage.mjs";
13
+ import { createEventStream } from "./utils/event-stream.mjs";
14
+ import { getEvent, getEventContext } from "./utils/event.mjs";
15
+ import { deepMergeObjects } from "./utils/merge.mjs";
16
+ import { createMiddleware } from "./utils/middleware.mjs";
17
+ import { createSchema } from "./utils/schema.mjs";
18
+ import { createService, createWebSocket, defineServiceSetup } from "./utils/service.mjs";
19
+ import { createShared } from "./utils/shared.mjs";
20
+
21
+ //#region src/core/index.ts
1341
22
  const autoImportTypes = [
1342
- "ExtractInputFromURI",
1343
- "ExtractOutputFromURI",
1344
- "ExtractPathParamsFromURI",
1345
- "ExtractQueryParamsFromURI"
23
+ "ExtractInputFromURI",
24
+ "ExtractOutputFromURI",
25
+ "ExtractPathParamsFromURI",
26
+ "ExtractQueryParamsFromURI"
1346
27
  ];
1347
28
 
1348
- export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createEventStream, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, createWebSocket, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, getWebsocket, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, updateRuntimeStorage, useRuntime, useSilgi, useSilgiStorage };
29
+ //#endregion
30
+ export { SilgiError, SilgiHttpEvent, autoImportTypes, createError, createEventStream, createMiddleware, createResolver, createSchema, createService, createShared, createSilgi, createStorage, createWebSocket, deepMergeObjects, defineServiceSetup, getEvent, getEventContext, getUrlPrefix, getWebsocket, handleResponse, handler, isError, kHandled, kNotFound, middleware, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, updateRuntimeStorage, useRuntime, useSilgi, useSilgiCLI, useSilgiStorage };