silgi 0.24.16 → 0.24.18

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.
@@ -5,18 +5,19 @@ import { existsSync, promises, readFileSync, writeFileSync, mkdirSync } from 'no
5
5
  import { readdir, readFile } from 'node:fs/promises';
6
6
  import consola, { consola as consola$1 } from 'consola';
7
7
  import { createHooks, createDebugger } from 'hookable';
8
- import { useSilgiCLI as useSilgiCLI$1, replaceRuntimeValues, silgiCLICtx as silgiCLICtx$1, autoImportTypes } from 'silgi';
8
+ import { useSilgiCLI, replaceRuntimeValues, silgiCLICtx, autoImportTypes } from 'silgi';
9
9
  import { runtimeDir } from 'silgi/runtime/meta';
10
10
  import { scanExports, createUnimport, toExports } from 'unimport';
11
- import { withoutTrailingSlash, withLeadingSlash, isRelative, withTrailingSlash } from 'ufo';
11
+ import { c as createRouteRules } from '../_chunks/routeRules.mjs';
12
12
  import * as p from '@clack/prompts';
13
13
  import * as dotenv from 'dotenv';
14
14
  import { resolveModuleExportNames, findTypeExports, findExports, resolvePath, parseNodeModulePath, lookupNodeModuleSubpath } from 'mlly';
15
15
  import { createJiti } from 'dev-jiti';
16
- import { h as hasInstalledModule } from './silgi.DWfN_DdY.mjs';
16
+ import { h as hasInstalledModule } from './compatibility.mjs';
17
17
  import { fileURLToPath } from 'node:url';
18
18
  import defu, { defu as defu$1 } from 'defu';
19
19
  import { resolveModuleURL } from 'exsolve';
20
+ import { isRelative, withTrailingSlash } from 'ufo';
20
21
  import { generateTypes, resolveSchema } from 'untyped';
21
22
  import { globby } from 'globby';
22
23
  import ignore from 'ignore';
@@ -25,9 +26,8 @@ import { klona } from 'klona';
25
26
  import { useSilgiRuntimeConfig, initRuntimeConfig } from 'silgi/runtime';
26
27
  import { createStorage, builtinDrivers } from 'unstorage';
27
28
  import { peerDependencies } from 'silgi/meta';
28
- import { l as loadOptions, s as silgiGenerateType } from './silgi.BIBmUBIR.mjs';
29
+ import { l as loadOptions, s as silgiGenerateType } from './types.mjs';
29
30
  import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
30
- import { createContext } from 'unctx';
31
31
 
32
32
  async function prepareBuild(silgi) {
33
33
  try {
@@ -70,291 +70,6 @@ export const routeRules = ${genObjectFromRawEntries(
70
70
  async function prepare(_silgi) {
71
71
  }
72
72
 
73
- function patternToRegex(pattern) {
74
- let regexStr = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
75
- regexStr = regexStr.replace(/\*\*/g, ".+");
76
- regexStr = regexStr.replace(/\*/g, "[^/]+");
77
- regexStr = regexStr.replace(/:([^/]+)/g, "([^/]+)");
78
- return new RegExp(`^${regexStr}$`);
79
- }
80
- function extractParams(url, pattern) {
81
- url = withoutTrailingSlash(withLeadingSlash(url));
82
- pattern = withoutTrailingSlash(withLeadingSlash(pattern));
83
- if (!pattern.includes(":"))
84
- return null;
85
- const paramNames = [];
86
- const patternRegex = pattern.replace(/:([^/]+)/g, (_, name) => {
87
- paramNames.push(name);
88
- return "([^/]+)";
89
- });
90
- const regex = new RegExp(`^${patternRegex}$`);
91
- const matches = url.match(regex);
92
- if (!matches)
93
- return null;
94
- const params = {};
95
- paramNames.forEach((name, i) => {
96
- params[name] = matches[i + 1];
97
- });
98
- return Object.keys(params).length > 0 ? params : null;
99
- }
100
- function matchesPattern(url, pattern) {
101
- url = withoutTrailingSlash(withLeadingSlash(url));
102
- pattern = withoutTrailingSlash(withLeadingSlash(pattern));
103
- if (url === pattern)
104
- return true;
105
- if (pattern.endsWith("/**")) {
106
- const basePath = pattern.slice(0, -3);
107
- return url === basePath || url.startsWith(`${basePath}/`);
108
- }
109
- const urlParts = url.split("/");
110
- const patternParts = pattern.split("/");
111
- if (!pattern.includes("**") && urlParts.length !== patternParts.length) {
112
- return false;
113
- }
114
- if (pattern.includes("/**/")) {
115
- const [prefix, ...suffixParts] = pattern.split("/**/");
116
- const suffix = suffixParts.join("/");
117
- return url.startsWith(prefix) && (!suffix || url.endsWith(`/${suffix}`));
118
- }
119
- return patternToRegex(pattern).test(url);
120
- }
121
- function deepClone(obj) {
122
- if (obj === null || typeof obj !== "object")
123
- return obj;
124
- if (typeof obj === "function")
125
- return obj;
126
- if (Array.isArray(obj))
127
- return obj.map(deepClone);
128
- const cloned = {};
129
- for (const key in obj) {
130
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
131
- cloned[key] = deepClone(obj[key]);
132
- }
133
- }
134
- return cloned;
135
- }
136
- function mergeConfigs(...configs) {
137
- const result = {};
138
- for (const config of configs) {
139
- if (!config)
140
- continue;
141
- for (const key in config) {
142
- const value = config[key];
143
- if (value && typeof value === "object" && !Array.isArray(value) && result[key] && typeof result[key] === "object" && typeof result[key] !== "function") {
144
- const resultValue = result[key];
145
- const valueToMerge = value;
146
- result[key] = mergeConfigs(resultValue, valueToMerge);
147
- } else {
148
- result[key] = value;
149
- }
150
- }
151
- }
152
- return result;
153
- }
154
- function createRouteRules() {
155
- let _rules = {};
156
- let _mergedRules = {};
157
- let _rulesModified = false;
158
- function getRules() {
159
- return deepClone(_rules);
160
- }
161
- function importRules(config) {
162
- const normalizedConfig = {};
163
- for (const pattern in config) {
164
- normalizedConfig[withoutTrailingSlash(withLeadingSlash(pattern))] = deepClone(config[pattern]);
165
- }
166
- _rules = normalizedConfig;
167
- _rulesModified = true;
168
- updateMergeRules();
169
- }
170
- function exportRules() {
171
- return deepClone(_rules);
172
- }
173
- function addRule(pattern, config) {
174
- _rules[withoutTrailingSlash(withLeadingSlash(pattern))] = deepClone(config);
175
- _rulesModified = true;
176
- updateMergeRules();
177
- }
178
- function updateRule(pattern, config) {
179
- const normalizedPattern = withoutTrailingSlash(withLeadingSlash(pattern));
180
- if (_rules[normalizedPattern]) {
181
- _rules[normalizedPattern] = { ..._rules[normalizedPattern], ...deepClone(config) };
182
- } else {
183
- _rules[normalizedPattern] = deepClone(config);
184
- }
185
- _rulesModified = true;
186
- updateMergeRules();
187
- }
188
- function removeRule(pattern) {
189
- delete _rules[withoutTrailingSlash(withLeadingSlash(pattern))];
190
- _rulesModified = true;
191
- updateMergeRules();
192
- }
193
- function matchesRule(url, pattern) {
194
- return matchesPattern(withoutTrailingSlash(withLeadingSlash(url)), withoutTrailingSlash(withLeadingSlash(pattern)));
195
- }
196
- function getMatchingPatterns(url) {
197
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
198
- return Object.keys(_rules).filter((pattern) => matchesPattern(normalizedUrl, pattern)).sort((a, b) => {
199
- if (a === url)
200
- return -1;
201
- if (b === url)
202
- return 1;
203
- const aSegments = a.split("/").filter(Boolean).length;
204
- const bSegments = b.split("/").filter(Boolean).length;
205
- if (aSegments !== bSegments)
206
- return bSegments - aSegments;
207
- const aWildcards = (a.match(/\*/g) || []).length;
208
- const bWildcards = (b.match(/\*/g) || []).length;
209
- if (aWildcards !== bWildcards)
210
- return aWildcards - bWildcards;
211
- const aDoubleWildcards = (a.match(/\*\*/g) || []).length;
212
- const bDoubleWildcards = (b.match(/\*\*/g) || []).length;
213
- if (aDoubleWildcards !== bDoubleWildcards)
214
- return aDoubleWildcards - bDoubleWildcards;
215
- return b.length - a.length;
216
- });
217
- }
218
- function getConfig(url) {
219
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
220
- if (_rulesModified) {
221
- updateMergeRules();
222
- }
223
- if (_mergedRules[normalizedUrl]) {
224
- return deepClone(_mergedRules[normalizedUrl]);
225
- }
226
- const patterns = getMatchingPatterns(normalizedUrl);
227
- if (!patterns.length)
228
- return null;
229
- const mergedConfig = {};
230
- for (let i = patterns.length - 1; i >= 0; i--) {
231
- const pattern = patterns[i];
232
- const patternConfig = _mergedRules[pattern] || _rules[pattern];
233
- Object.assign(mergedConfig, deepClone(patternConfig));
234
- }
235
- _mergedRules[normalizedUrl] = deepClone(mergedConfig);
236
- return mergedConfig;
237
- }
238
- function computeMergedConfig(url, patterns) {
239
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
240
- const matchingPatterns = patterns || getMatchingPatterns(normalizedUrl);
241
- if (!matchingPatterns.length)
242
- return {};
243
- const allPatternsHaveCache = matchingPatterns.every((pattern) => !!_mergedRules[pattern]);
244
- if (allPatternsHaveCache) {
245
- return matchingPatterns.reduceRight((result, pattern) => mergeConfigs(result, deepClone(_mergedRules[pattern])), {});
246
- }
247
- return matchingPatterns.reduceRight((result, pattern) => mergeConfigs(result, deepClone(_rules[pattern])), {});
248
- }
249
- function getParams(url, pattern) {
250
- return extractParams(withoutTrailingSlash(withLeadingSlash(url)), withoutTrailingSlash(withLeadingSlash(pattern)));
251
- }
252
- function match(url) {
253
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
254
- const patterns = getMatchingPatterns(normalizedUrl);
255
- if (!patterns.length)
256
- return null;
257
- const bestPattern = patterns[0];
258
- return {
259
- pattern: bestPattern,
260
- config: deepClone(_rules[bestPattern]),
261
- params: getParams(normalizedUrl, bestPattern)
262
- };
263
- }
264
- function clear() {
265
- _rules = {};
266
- clearMergedRules();
267
- _rulesModified = false;
268
- }
269
- function clearMergedRules() {
270
- _mergedRules = {};
271
- _rulesModified = true;
272
- }
273
- function precomputeMergedRules(urls) {
274
- if (_rulesModified) {
275
- updateMergeRules();
276
- }
277
- for (const url of urls) {
278
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
279
- if (!_mergedRules[normalizedUrl]) {
280
- const patterns = getMatchingPatterns(normalizedUrl);
281
- if (patterns.length) {
282
- _mergedRules[normalizedUrl] = computeMergedConfig(normalizedUrl, patterns);
283
- }
284
- }
285
- }
286
- }
287
- function setMergedRule(url, config) {
288
- const normalizedUrl = withoutTrailingSlash(withLeadingSlash(url));
289
- _mergedRules[normalizedUrl] = deepClone(config);
290
- if (url.includes("*") || url.includes(":")) {
291
- _rulesModified = false;
292
- }
293
- }
294
- function getMergedRules() {
295
- return deepClone(_mergedRules);
296
- }
297
- function configure(config) {
298
- importRules(config);
299
- }
300
- function updateMergeRules() {
301
- if (!_rulesModified) {
302
- return _mergedRules;
303
- }
304
- _mergedRules = {};
305
- const rulePatterns = Object.keys(_rules);
306
- for (const pattern of rulePatterns) {
307
- const patterns = getMatchingPatterns(pattern);
308
- _mergedRules[pattern] = computeMergedConfig(pattern, patterns);
309
- }
310
- for (const pattern of rulePatterns) {
311
- if (pattern.includes("/:")) {
312
- const segments = pattern.split("/");
313
- let partialPath = "";
314
- for (const segment of segments) {
315
- if (segment) {
316
- partialPath += `/${segment}`;
317
- if (segment.startsWith(":") && partialPath !== pattern) {
318
- const samplePath = partialPath.replace(/:\w+/g, "sample");
319
- const patterns = getMatchingPatterns(samplePath);
320
- _mergedRules[samplePath] = computeMergedConfig(samplePath, patterns);
321
- }
322
- }
323
- }
324
- }
325
- }
326
- _rulesModified = false;
327
- return _mergedRules;
328
- }
329
- return {
330
- // Public getters that return a cloned version to prevent direct modification
331
- get rules() {
332
- return getRules();
333
- },
334
- get mergedRules() {
335
- return getMergedRules();
336
- },
337
- // API methods
338
- importRules,
339
- exportRules,
340
- addRule,
341
- updateRule,
342
- removeRule,
343
- matchesRule,
344
- getMatchingPatterns,
345
- getConfig,
346
- getParams,
347
- match,
348
- clear,
349
- clearMergedRules,
350
- precomputeMergedRules,
351
- setMergedRule,
352
- getMergedRules,
353
- configure,
354
- updateMergeRules
355
- };
356
- }
357
-
358
73
  async function setupDotenv(options) {
359
74
  const targetEnvironment = options.env ?? process.env;
360
75
  const environment = await loadDotenv({
@@ -826,7 +541,7 @@ async function installModules(silgi, prepare = false) {
826
541
  }
827
542
  silgi.options.isPreparingModules = false;
828
543
  }
829
- async function installModule(moduleToInstall, silgi = useSilgiCLI$1(), inlineOptions, prepare = false) {
544
+ async function installModule(moduleToInstall, silgi = useSilgiCLI(), inlineOptions, prepare = false) {
830
545
  const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
831
546
  const res = await silgiModule(inlineOptions || {}, silgi) ?? {};
832
547
  if (res === false) {
@@ -1174,7 +889,7 @@ class SchemaParser {
1174
889
  };
1175
890
  }
1176
891
  parseVariableDeclaration(ast, path) {
1177
- const silgi = useSilgiCLI$1();
892
+ const silgi = useSilgiCLI();
1178
893
  if (ast.program.body.length === 0) {
1179
894
  if (safeFiles.find((i) => path.includes(i)))
1180
895
  return [];
@@ -1188,7 +903,7 @@ class SchemaParser {
1188
903
  return variableDeclarations;
1189
904
  }
1190
905
  parseTSInterfaceDeclaration(ast, path = "") {
1191
- const silgi = useSilgiCLI$1();
906
+ const silgi = useSilgiCLI();
1192
907
  if (ast.program.body.length === 0) {
1193
908
  if (safeFiles.find((i) => path.includes(i)))
1194
909
  return [];
@@ -1941,12 +1656,12 @@ async function createSilgiCLI(config = {}, opts = {}) {
1941
1656
  const routeRules = createRouteRules();
1942
1657
  routeRules.importRules(options.routeRules ?? {});
1943
1658
  silgi.routeRules = routeRules;
1944
- if (silgiCLICtx$1.tryUse()) {
1945
- silgiCLICtx$1.unset();
1946
- silgiCLICtx$1.set(silgi);
1659
+ if (silgiCLICtx.tryUse()) {
1660
+ silgiCLICtx.unset();
1661
+ silgiCLICtx.set(silgi);
1947
1662
  } else {
1948
- silgiCLICtx$1.set(silgi);
1949
- silgi.hook("close", () => silgiCLICtx$1.unset());
1663
+ silgiCLICtx.set(silgi);
1664
+ silgi.hook("close", () => silgiCLICtx.unset());
1950
1665
  }
1951
1666
  if (silgi.options.debug) {
1952
1667
  createDebugger(silgi.hooks, { tag: "silgi" });
@@ -2658,25 +2373,4 @@ async function writeTypesAndFiles(silgi) {
2658
2373
  }
2659
2374
  }
2660
2375
 
2661
- const silgiCLICtx = createContext();
2662
- function useSilgiCLI() {
2663
- const instance = silgiCLICtx.tryUse();
2664
- if (!instance) {
2665
- throw new Error("Silgi instance is unavailable!");
2666
- }
2667
- return instance;
2668
- }
2669
- async function silgiCLIIClose() {
2670
- const silgi = silgiCLICtx.tryUse();
2671
- if (!silgi) {
2672
- return;
2673
- }
2674
- await silgi.close();
2675
- await silgi.callHook("close", silgi);
2676
- consola.withTag("silgi").success("Process terminated");
2677
- }
2678
- function tryUseSilgiCLI() {
2679
- return silgiCLICtx.tryUse();
2680
- }
2681
-
2682
- export { prepare as a, writeCoreFile as b, createSilgiCLI as c, prepareBuild as d, createRouteRules as e, silgiCLICtx as f, prepareEnv as p, silgiCLIIClose as s, tryUseSilgiCLI as t, useSilgiCLI as u, writeTypesAndFiles as w };
2376
+ export { prepare as a, writeTypesAndFiles as b, createSilgiCLI as c, prepareEnv as d, prepareBuild as p, writeCoreFile as w };
@@ -0,0 +1,271 @@
1
+ import * as unctx from 'unctx';
2
+ import { Silgi, SilgiCLI, SilgiConfig, SilgiEvents, SilgiFunction, SilgiOperation, MergedSilgiSchema, ServiceType, SilgiSchema, RequiredServiceType, SilgiRuntimeSharedsExtend, SilgiRuntimeContext, DefaultNamespaces, BaseSchemaType, SilgiRuntimeShareds, StorageConfig, SilgiStorageBase } from 'silgi/types';
3
+ import { StandardSchemaV1 } from '@standard-schema/spec';
4
+ import { Storage, StorageValue } from 'unstorage';
5
+
6
+ declare const silgiCtx: unctx.UseContext<Silgi>;
7
+ declare function useSilgi(): Silgi;
8
+ /**
9
+ * Get access to Nuxt instance.
10
+ *
11
+ * Returns null if Nuxt instance is unavailable.
12
+ * @example
13
+ * ```js
14
+ * const silgi = tryUseSilgi()
15
+ * if (silgi) {
16
+ * // Do something
17
+ * }
18
+ * ```
19
+ */
20
+ declare function tryUseSilgi(): Silgi | null;
21
+
22
+ declare const silgiCLICtx: unctx.UseContext<SilgiCLI>;
23
+ declare function useSilgiCLI(): SilgiCLI;
24
+ /**
25
+ * Get access to Nuxt instance.
26
+ *
27
+ * Returns null if Nuxt instance is unavailable.
28
+ * @example
29
+ * ```js
30
+ * const silgi = tryUseSilgi()
31
+ * if (silgi) {
32
+ * // Do something
33
+ * }
34
+ * ```
35
+ */
36
+ declare function tryUseSilgiCLI(): SilgiCLI | null;
37
+
38
+ declare function createSilgi(config: SilgiConfig): Promise<Silgi>;
39
+
40
+ declare function silgi(event?: SilgiEvents | Record<string, any>): SilgiFunction;
41
+
42
+ interface RouteTemplateValidator {
43
+ (value: string): boolean;
44
+ }
45
+ interface RouteTemplateConfig {
46
+ pattern: string;
47
+ validators?: Record<string, RouteTemplateValidator>;
48
+ }
49
+ type URITemplate = string | RouteTemplateConfig;
50
+ declare function parseURI(uri: string, uris: Record<string, URITemplate>): SilgiOperation;
51
+
52
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
53
+ declare function mergeSchemas<T extends MergedSilgiSchema[]>(typesOrArray: [...T] | T): UnionToIntersection<T[number]>;
54
+ declare function mergeServices<T extends ServiceType<SilgiSchema>[]>(servicesOrArray: [...T] | T): RequiredServiceType<SilgiSchema>;
55
+ declare function mergeShared<T extends SilgiRuntimeSharedsExtend[]>(sharedOrArray: [...T] | T): UnionToIntersection<T[number]>;
56
+
57
+ declare function getEvent<T extends SilgiEvents>(event?: SilgiEvents): T;
58
+ declare function getEventContext<T extends SilgiRuntimeContext>(event?: SilgiEvents): T;
59
+
60
+ declare function createSchema<T extends Partial<Record<keyof DefaultNamespaces, Record<string, BaseSchemaType<StandardSchemaV1>>>>>(silgiType: T): {
61
+ [K in keyof T]: {
62
+ [P in keyof T[K]]: T[K][P];
63
+ };
64
+ };
65
+
66
+ declare function createService<T extends SilgiSchema>(variables: ServiceType<T>): ServiceType<T>;
67
+
68
+ declare function createShared(shared: Partial<SilgiRuntimeShareds>): SilgiRuntimeShareds;
69
+
70
+ /**
71
+ * Recursively replaces values starting with 'runtime.' with their actual values from runtime config
72
+ */
73
+ declare function replaceRuntimeValues(obj: any, runtime: any): any;
74
+
75
+ declare function createStorage(silgi: Silgi): Promise<Storage<StorageValue>>;
76
+ declare function useSilgiStorage<T extends StorageValue = StorageValue>(base?: StorageConfig<T>['base'] | (string & {})): Storage<T>;
77
+
78
+ declare enum HttpStatus {
79
+ /** [100] Server has received the request headers and client should proceed to send the request body */
80
+ CONTINUE = 100,
81
+ /** [101] Server is switching protocols according to Upgrade header */
82
+ SWITCHING_PROTOCOLS = 101,
83
+ /** [102] Server is processing the request but no response is available yet */
84
+ PROCESSING = 102,
85
+ /** [103] Server is likely to send a final response with the header fields in the informational response */
86
+ EARLY_HINTS = 103,
87
+ /** [200] Request succeeded and response contains requested data */
88
+ OK = 200,
89
+ /** [201] Request succeeded and new resource has been created */
90
+ CREATED = 201,
91
+ /** [202] Request accepted for processing but processing not completed */
92
+ ACCEPTED = 202,
93
+ /** [203] Request processed successfully but response may be from another source */
94
+ NON_AUTHORITATIVE_INFORMATION = 203,
95
+ /** [204] Request processed successfully but response has no content */
96
+ NO_CONTENT = 204,
97
+ /** [205] Server fulfilled the request and client should reset the document view */
98
+ RESET_CONTENT = 205,
99
+ /** [206] Server delivered only part of the resource due to range header */
100
+ PARTIAL_CONTENT = 206,
101
+ /** [207] Response conveys information about multiple resources for XML messages */
102
+ MULTI_STATUS = 207,
103
+ /** [208] Members of DAV binding have already been enumerated and not included again */
104
+ ALREADY_REPORTED = 208,
105
+ /** [226] Server has fulfilled a GET request, response is result of transformations */
106
+ IM_USED = 226,
107
+ /** [300] Multiple options for the resource from which client may choose */
108
+ MULTIPLE_CHOICES = 300,
109
+ /** [301] Resource permanently moved to new URL */
110
+ MOVED_PERMANENTLY = 301,
111
+ /** [302] Resource temporarily moved to different URL */
112
+ FOUND = 302,
113
+ /** [303] Response to request found at another URL using GET */
114
+ SEE_OTHER = 303,
115
+ /** [304] Resource has not been modified since last requested */
116
+ NOT_MODIFIED = 304,
117
+ /** [305] Deprecated. Resource must be accessed through proxy */
118
+ USE_PROXY = 305,
119
+ /** [307] Resource temporarily moved to different URL, keep method */
120
+ TEMPORARY_REDIRECT = 307,
121
+ /** [308] Resource permanently moved to different URL, keep method */
122
+ PERMANENT_REDIRECT = 308,
123
+ /** [400] Request malformed, syntax error or invalid request */
124
+ BAD_REQUEST = 400,
125
+ /** [401] Request requires user authentication or authorization */
126
+ UNAUTHORIZED = 401,
127
+ /** [402] Reserved for future use, payment required */
128
+ PAYMENT_REQUIRED = 402,
129
+ /** [403] Server understood request but refuses to authorize it */
130
+ FORBIDDEN = 403,
131
+ /** [404] Server cannot find the requested resource */
132
+ NOT_FOUND = 404,
133
+ /** [405] Request method (GET, POST, etc.) not supported for this resource */
134
+ METHOD_NOT_ALLOWED = 405,
135
+ /** [406] Resource cannot generate response matching accept headers */
136
+ NOT_ACCEPTABLE = 406,
137
+ /** [407] Client must first authenticate with the proxy */
138
+ PROXY_AUTHENTICATION_REQUIRED = 407,
139
+ /** [408] Server timed out waiting for the request */
140
+ REQUEST_TIMEOUT = 408,
141
+ /** [409] Request conflicts with current state of the server */
142
+ CONFLICT = 409,
143
+ /** [410] Resource requested is no longer available and will not be available again */
144
+ GONE = 410,
145
+ /** [411] Server requires Content-Length header field */
146
+ LENGTH_REQUIRED = 411,
147
+ /** [412] Precondition given in request headers evaluated to false */
148
+ PRECONDITION_FAILED = 412,
149
+ /** [413] Request entity larger than limits defined by server */
150
+ PAYLOAD_TOO_LARGE = 413,
151
+ /** [414] URI requested by client is longer than server can interpret */
152
+ URI_TOO_LONG = 414,
153
+ /** [415] Media format of requested data not supported by server */
154
+ UNSUPPORTED_MEDIA_TYPE = 415,
155
+ /** [416] Range specified by Range header cannot be fulfilled */
156
+ RANGE_NOT_SATISFIABLE = 416,
157
+ /** [417] Expectation indicated by Expect header cannot be met */
158
+ EXPECTATION_FAILED = 417,
159
+ /** [418] April Fools' joke by RFC 2324 - Server refuses to brew coffee in a teapot */
160
+ IM_A_TEAPOT = 418,
161
+ /** [421] Request directed at a server that is not configured to produce a response */
162
+ MISDIRECTED_REQUEST = 421,
163
+ /** [422] Server understands content type but cannot process contained instructions */
164
+ UNPROCESSABLE_ENTITY = 422,
165
+ /** [423] Requested resource is currently locked */
166
+ LOCKED = 423,
167
+ /** [424] Request failed due to failure of a previous request */
168
+ FAILED_DEPENDENCY = 424,
169
+ /** [425] Server is unwilling to risk processing a request that might be replayed */
170
+ TOO_EARLY = 425,
171
+ /** [426] Server requires client to upgrade to a different protocol */
172
+ UPGRADE_REQUIRED = 426,
173
+ /** [428] Origin server requires request to be conditional */
174
+ PRECONDITION_REQUIRED = 428,
175
+ /** [429] User has sent too many requests in a given time period */
176
+ TOO_MANY_REQUESTS = 429,
177
+ /** [431] Server refusing to process request due to oversized headers */
178
+ REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
179
+ /** [451] Server denies access for legal reasons (e.g., censorship) */
180
+ UNAVAILABLE_FOR_LEGAL_REASONS = 451,
181
+ /** [500] Generic server error, no specific message */
182
+ INTERNAL_SERVER_ERROR = 500,
183
+ /** [501] Server does not recognize method or lacks ability to fulfill */
184
+ NOT_IMPLEMENTED = 501,
185
+ /** [502] Bad response received from upstream server */
186
+ BAD_GATEWAY = 502,
187
+ /** [503] Server temporarily unavailable (overloaded/maintenance) */
188
+ SERVICE_UNAVAILABLE = 503,
189
+ /** [504] Gateway server did not get response from upstream server */
190
+ GATEWAY_TIMEOUT = 504,
191
+ /** [505] Server does not support the HTTP protocol version */
192
+ HTTP_VERSION_NOT_SUPPORTED = 505,
193
+ /** [506] Server has a circular reference in content negotiation */
194
+ VARIANT_ALSO_NEGOTIATES = 506,
195
+ /** [507] Server has insufficient storage to complete request */
196
+ INSUFFICIENT_STORAGE = 507,
197
+ /** [508] Server detected an infinite loop while processing request */
198
+ LOOP_DETECTED = 508,
199
+ /** [510] Further extensions needed for server to fulfill request */
200
+ NOT_EXTENDED = 510,
201
+ /** [511] Client needs to authenticate to gain network access */
202
+ NETWORK_AUTHENTICATION_REQUIRED = 511
203
+ }
204
+ declare enum ErrorSeverity {
205
+ DEBUG = "DEBUG",
206
+ INFO = "INFO",
207
+ WARNING = "WARNING",
208
+ ERROR = "ERROR",
209
+ CRITICAL = "CRITICAL"
210
+ }
211
+ declare enum ErrorCategory {
212
+ AUTHENTICATION = "auth",
213
+ AUTHORIZATION = "authorization",
214
+ VALIDATION = "validation",
215
+ BUSINESS = "business",
216
+ INFRASTRUCTURE = "infrastructure",
217
+ EXTERNAL = "external",
218
+ UNKNOWN = "unknown"
219
+ }
220
+ interface ErrorMetadata {
221
+ timestamp: number;
222
+ correlationId?: string;
223
+ requestId?: string;
224
+ userId?: string;
225
+ path?: string;
226
+ source?: string;
227
+ [key: string]: unknown;
228
+ }
229
+ interface BaseError {
230
+ code: number;
231
+ message: string;
232
+ category: ErrorCategory;
233
+ severity: ErrorSeverity;
234
+ httpStatus: HttpStatus;
235
+ metadata?: ErrorMetadata;
236
+ cause?: Error;
237
+ context?: Record<string, unknown>;
238
+ }
239
+ declare class ErrorFactory {
240
+ private static createMetadata;
241
+ static create(options: Partial<BaseError> & {
242
+ message: string;
243
+ }): SilgiError;
244
+ static authenticationError(message: string, context?: Record<string, unknown>): SilgiError;
245
+ static authorizationError(message: string, context?: Record<string, unknown>): SilgiError;
246
+ static validationError(message: string, context?: Record<string, unknown>): SilgiError;
247
+ static notFoundError(message: string, context?: Record<string, unknown>): SilgiError;
248
+ static internalError(message: string, cause?: Error): SilgiError;
249
+ }
250
+ declare class SilgiError extends Error implements BaseError {
251
+ readonly code: number;
252
+ readonly category: ErrorCategory;
253
+ readonly severity: ErrorSeverity;
254
+ readonly httpStatus: HttpStatus;
255
+ readonly metadata: ErrorMetadata;
256
+ readonly context?: Record<string, unknown>;
257
+ readonly cause?: Error;
258
+ constructor(error: BaseError);
259
+ toString(): string;
260
+ toJSON(): Record<string, unknown>;
261
+ static isError(error: unknown): error is SilgiError;
262
+ static from(error: unknown): SilgiError;
263
+ }
264
+ declare function isBaseError(error: unknown): error is BaseError;
265
+
266
+ declare function storageMount<T extends Storage = Storage>(silgi?: Silgi): (base: keyof SilgiStorageBase, driver: Parameters<Storage['mount']>[1]) => T;
267
+
268
+ declare const autoImportTypes: string[];
269
+
270
+ export { ErrorCategory, ErrorFactory, ErrorSeverity, HttpStatus, SilgiError, autoImportTypes, createSchema, createService, createShared, createSilgi, createStorage, getEvent, getEventContext, isBaseError, mergeSchemas, mergeServices, mergeShared, parseURI, replaceRuntimeValues, silgi, silgiCLICtx, silgiCtx, storageMount, tryUseSilgi, tryUseSilgiCLI, useSilgi, useSilgiCLI, useSilgiStorage };
271
+ export type { BaseError, ErrorMetadata };