silgi 0.33.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { BaseError, ErrorCategory, ErrorFactory, ErrorMetadata, 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 } from './core/index.mjs';
1
+ export { SilgiError, autoImportTypes, createError, createRoute, createSchema, createService, createShared, createSilgi, createSilgiCore, createStorage, deepMergeObjects, getEvent, getEventContext, handleResponse, isError, replaceRuntimeValues, silgiCLICtx, silgiCtx, silgiFetch, storageMount, tryUseSilgi, tryUseSilgiCLI, useSilgi, useSilgiCLI, useSilgiStorage } from './core/index.mjs';
2
2
  import 'silgi/types';
3
3
  import '@standard-schema/spec';
4
4
  import 'unstorage';
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
- export { ErrorCategory, ErrorFactory, ErrorSeverity, HttpStatus, SilgiError, autoImportTypes, createSchema, createService, createShared, createSilgi, createStorage, getEvent, getEventContext, isBaseError, mergeSchemas, mergeServices, mergeShared, parseURI, replaceRuntimeValues, silgi, silgiCtx, storageMount, tryUseSilgi, useSilgi, useSilgiStorage } from './core/index.mjs';
1
+ export { SilgiError, autoImportTypes, createError, createRoute, createSchema, createService, createShared, createSilgi, createSilgiCore, createStorage, deepMergeObjects, getEvent, getEventContext, handleResponse, isError, replaceRuntimeValues, silgiCtx, silgiFetch, storageMount, tryUseSilgi, useSilgi, useSilgiStorage } from './core/index.mjs';
2
2
  export { s as silgiCLICtx, t as tryUseSilgiCLI, u as useSilgiCLI } from './_chunks/silgiApp.mjs';
3
3
  import 'consola';
4
4
  import 'defu';
5
5
  import 'hookable';
6
- import './_chunks/routeRules.mjs';
7
- import 'ufo';
6
+ import 'rou3';
8
7
  import 'unctx';
9
8
  import 'node:buffer';
10
9
  import 'klona';
11
10
  import 'silgi/runtime';
12
11
  import 'unstorage';
12
+ import 'srvx';
13
13
  import 'silgi/kit';
@@ -1,4 +1,4 @@
1
- import { Commands, SilgiCLIHooks, GenImport, DefineFrameworkOptions, SilgiCLI, ModuleOptionsCustom, ModuleDefinition, SilgiModule, ServiceParseModule, SilgiPreset, SilgiPresetMeta, SilgiTemplate, ResolvedSilgiTemplate, SilgiEvents } from 'silgi/types';
1
+ import { Commands, SilgiCLIHooks, GenImport, DefineFrameworkOptions, SilgiCLI, ModuleOptionsCustom, ModuleDefinition, SilgiModule, SilgiPreset, SilgiPresetMeta, SilgiTemplate, ResolvedSilgiTemplate, SilgiEvent } from 'silgi/types';
2
2
  import { PresetName } from 'silgi/presets';
3
3
  import { Buffer } from 'node:buffer';
4
4
  import { ConsolaOptions, ConsolaInstance } from 'consola';
@@ -224,32 +224,6 @@ declare function defineSilgiModule<TOptions extends ModuleOptionsCustom>(): {
224
224
  with: <TOptionsDefaults extends Partial<TOptions>>(definition: ModuleDefinition<TOptions, TOptionsDefaults, true> | SilgiModule<TOptions, TOptionsDefaults, true>) => SilgiModule<TOptions, TOptionsDefaults, true>;
225
225
  };
226
226
 
227
- /**
228
- *
229
- *
230
- * @example
231
- * srnResorce: 'coreApi.basket.post.createBasket'
232
- * const { namespace, serviceName, action, method } = cliResorceParse(srnResorce)
233
- *
234
- * namespace: 'coreApi'
235
- * serviceName: 'basket'
236
- * action: 'post'
237
- * method: 'createBasket'
238
- *
239
- */
240
-
241
- declare function serviceParseModule(params: ServiceParseModule): ServiceParseModule;
242
- declare function parseServices(silgi: SilgiCLI,
243
- /**
244
- * url: /coreApi/basket/post/createBasket
245
- * pathLength: 4 or [1, 2, 3, 4] to support multiple path depths
246
- * 1: coreApi
247
- * 2: basket
248
- * 3: post
249
- * 4: createBasket
250
- */
251
- pathLength?: number | number[], servicesObject?: Record<string, any>, currentPath?: string[]): Record<string, Record<string, any>>;
252
-
253
227
  declare function prettyPath(p: string, highlight?: boolean): string;
254
228
  declare function resolveSilgiPath(path: string, silgiCLIOptions: SilgiCLI['options'], base?: string): string;
255
229
 
@@ -301,11 +275,11 @@ declare function addTemplate<T>(_template: SilgiTemplate<T> | string): ResolvedS
301
275
  */
302
276
  declare function normalizeTemplate<T>(template: SilgiTemplate<T> | string, buildDir?: string): ResolvedSilgiTemplate<T>;
303
277
 
304
- declare function useRequest<T extends IncomingMessage>(event: SilgiEvents): T | (IncomingMessage & {
278
+ declare function useRequest<T extends IncomingMessage>(event: SilgiEvent): T | (IncomingMessage & {
305
279
  originalUrl?: string;
306
280
  });
307
- declare function useResponse<T extends ServerResponse>(event: SilgiEvents): ServerResponse;
308
- declare function getIpAddress(event: SilgiEvents): string | boolean;
281
+ declare function useResponse<T extends ServerResponse>(event: SilgiEvent): ServerResponse;
282
+ declare function getIpAddress(event: SilgiEvent): string | boolean;
309
283
  /**
310
284
  * Extract the client's IP address from request headers with high accuracy
311
285
  * @param req - The incoming HTTP request
@@ -337,5 +311,5 @@ declare function isPresents(names: PresetName[]): boolean;
337
311
  declare function isRuntimePresents(names: PresetName[]): boolean;
338
312
  declare function removeExtension(filePath: string): string;
339
313
 
340
- export { MODE_RE, MigrationStatus, addCommands, addCoreFile, addImports, addNPMPackage, addTemplate, baseHeaderBannerComment, createFunction, createFunctionConfigs, createResolver, defineFramework, defineSilgiModule, defineSilgiPreset, directoryToURL, filterInPlace, formatFunctions, genEnsureSafeVar, generateMigration, getAllEntries, getIpAddress, getMigration, hasError, hasInstalledModule, hasSilgiModule, hash, ipAddress, isDirectory, isH3, isNitro, isNuxt, isPresents, isRuntimePresents, listMigrations, migrationDown, migrationUp, normalizeTemplate, parseServices, prettyPath, processFilePath, relativeWithDot, removeExtension, resolveAlias, resolvePath, resolveSilgiModule, resolveSilgiPath, serviceParseModule, toArray, tryResolveModule, useLogger, useRequest, useResponse, writeFile };
314
+ export { MODE_RE, MigrationStatus, addCommands, addCoreFile, addImports, addNPMPackage, addTemplate, baseHeaderBannerComment, createFunction, createFunctionConfigs, createResolver, defineFramework, defineSilgiModule, defineSilgiPreset, directoryToURL, filterInPlace, formatFunctions, genEnsureSafeVar, generateMigration, getAllEntries, getIpAddress, getMigration, hasError, hasInstalledModule, hasSilgiModule, hash, ipAddress, isDirectory, isH3, isNitro, isNuxt, isPresents, isRuntimePresents, listMigrations, migrationDown, migrationUp, normalizeTemplate, prettyPath, processFilePath, relativeWithDot, removeExtension, resolveAlias, resolvePath, resolveSilgiModule, resolveSilgiPath, toArray, tryResolveModule, useLogger, useRequest, useResponse, writeFile };
341
315
  export type { FunctionConfig, JsonPatch, MigrationData, MigrationInfo, MigrationOptions, MigrationResult };
@@ -16,7 +16,6 @@ import { existsSync, promises } from 'node:fs';
16
16
  import * as rfc6902 from 'rfc6902';
17
17
  import { defu } from 'defu';
18
18
  import { c as checkSilgiCompatibility } from '../cli/compatibility.mjs';
19
- import { withLeadingSlash } from 'ufo';
20
19
  import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
21
20
  import 'unctx';
22
21
  import 'semver/functions/satisfies.js';
@@ -807,59 +806,6 @@ ${issues.toString()}`);
807
806
  return silgiNormalizedModule;
808
807
  }
809
808
 
810
- function serviceParseModule(params) {
811
- return params;
812
- }
813
- const parseRouteRules = serviceParseModule(({
814
- node,
815
- basePath,
816
- silgi,
817
- pathLength
818
- }) => {
819
- const routeRules = node.routeRules;
820
- if (!routeRules)
821
- return;
822
- let removeMethod = "";
823
- removeMethod = withLeadingSlash(basePath);
824
- if (pathLength === 1 || pathLength === 2 || pathLength === 3) {
825
- if (routeRules.doubleSplat === void 0) {
826
- routeRules.doubleSplat = true;
827
- }
828
- }
829
- if (routeRules.splat)
830
- removeMethod = `${removeMethod}/*`;
831
- else if (routeRules.doubleSplat)
832
- removeMethod = `${removeMethod}/**`;
833
- removeMethod = removeMethod.replace(/\/{2,}/g, "/");
834
- delete routeRules.splat;
835
- delete routeRules.doubleSplat;
836
- silgi.routeRules.addRule(removeMethod, routeRules);
837
- });
838
- function parseServices(silgi, pathLength = [4, 3, 2, 1], servicesObject, currentPath = []) {
839
- const modulesURIs = {};
840
- silgi.options.serviceParseModules.push(parseRouteRules);
841
- const pathLengths = Array.isArray(pathLength) ? pathLength : [pathLength];
842
- function traverse(node, path = []) {
843
- if (!node || typeof node !== "object")
844
- return;
845
- if (pathLengths.includes(path.length)) {
846
- const basePath = path.join("/");
847
- for (const handler of silgi.options.serviceParseModules) {
848
- handler({ node, basePath, silgi, modulesURIs, pathLength: path.length });
849
- }
850
- }
851
- for (const key in node) {
852
- if (!["_type", "fields"].includes(key)) {
853
- traverse(node[key], [...path, key]);
854
- }
855
- }
856
- }
857
- traverse(servicesObject || silgi.services, currentPath);
858
- silgi.options.serviceParseModules = [];
859
- silgi.modulesURIs = defu(modulesURIs, silgi.modulesURIs);
860
- return modulesURIs;
861
- }
862
-
863
809
  function defineSilgiPreset(preset, meta) {
864
810
  if (meta?.url && typeof preset !== "function") ;
865
811
  return { ...preset, _meta: meta };
@@ -1067,4 +1013,4 @@ function isValidIp(ip) {
1067
1013
  return false;
1068
1014
  }
1069
1015
 
1070
- export { MODE_RE, MigrationStatus, addCommands, addCoreFile, addImports, addNPMPackage, addTemplate, baseHeaderBannerComment, createFunction, createFunctionConfigs, createResolver, defineFramework, defineSilgiModule, defineSilgiPreset, directoryToURL, filterInPlace, formatFunctions, genEnsureSafeVar, generateMigration, getAllEntries, getIpAddress, getMigration, hasError, hasInstalledModule, hasSilgiModule, hash, ipAddress, isDirectory$1 as isDirectory, isH3, isNitro, isNuxt, isPresents, isRuntimePresents, listMigrations, migrationDown, migrationUp, normalizeTemplate, parseServices, prettyPath, processFilePath, relativeWithDot, removeExtension, resolveAlias, resolvePath, resolveSilgiModule, resolveSilgiPath, serviceParseModule, toArray, tryResolveModule, useLogger, useRequest, useResponse, writeFile };
1016
+ export { MODE_RE, MigrationStatus, addCommands, addCoreFile, addImports, addNPMPackage, addTemplate, baseHeaderBannerComment, createFunction, createFunctionConfigs, createResolver, defineFramework, defineSilgiModule, defineSilgiPreset, directoryToURL, filterInPlace, formatFunctions, genEnsureSafeVar, generateMigration, getAllEntries, getIpAddress, getMigration, hasError, hasInstalledModule, hasSilgiModule, hash, ipAddress, isDirectory$1 as isDirectory, isH3, isNitro, isNuxt, isPresents, isRuntimePresents, listMigrations, migrationDown, migrationUp, normalizeTemplate, prettyPath, processFilePath, relativeWithDot, removeExtension, resolveAlias, resolvePath, resolveSilgiModule, resolveSilgiPath, toArray, tryResolveModule, useLogger, useRequest, useResponse, writeFile };
@@ -1,10 +1,10 @@
1
- import type { EnvOptions, SilgiEvents, SilgiRuntimeConfig } from 'silgi/types';
1
+ import type { EnvOptions, SilgiEvent, SilgiRuntimeConfig } from 'silgi/types';
2
2
  /**
3
3
  * Access 'resolved' Nuxt runtime configuration, with values updated from environment.
4
4
  *
5
5
  * This mirrors the runtime behavior of Nitro.
6
6
  */
7
- export declare function useSilgiRuntimeConfig<T extends SilgiRuntimeConfig>(event?: SilgiEvents, inlineRuntimeConfig?: Record<string, any>): SilgiRuntimeConfig;
7
+ export declare function useSilgiRuntimeConfig<T extends SilgiRuntimeConfig>(event?: SilgiEvent, inlineRuntimeConfig?: Record<string, any>): SilgiRuntimeConfig;
8
8
  export declare function initRuntimeConfig(envOptions?: EnvOptions, inlineRuntimeConfig?: Record<string, any>): Readonly<Record<string, any>>;
9
9
  export declare function updateRuntimeConfig(runtimeConfig: Record<string, unknown>): void;
10
10
  export declare function applyEnv(obj: Record<string, any>, opts: EnvOptions, parentKey?: string): Record<string, any>;
@@ -0,0 +1,4 @@
1
+ import type { NextApiRequest, NextApiResponse } from 'next';
2
+ import type { Silgi } from 'silgi/types';
3
+ export declare function addNextApp(silgiContext?: Silgi): (req: NextApiRequest | Request, res?: NextApiResponse) => Promise<void | NextApiResponse<any> | Response>;
4
+ export default addNextApp;
@@ -0,0 +1,72 @@
1
+ import { createError, handleResponse, isError, useSilgi } from "silgi";
2
+ import { getQuery, withoutHost } from "ufo";
3
+ export function addNextApp(silgiContext = useSilgi()) {
4
+ return async (req, res) => {
5
+ if (!silgiContext) {
6
+ throw new Error("Silgi context is not defined");
7
+ }
8
+ let operation;
9
+ try {
10
+ const silgiConnect = silgi({
11
+ req,
12
+ res,
13
+ context: {},
14
+ url: new URL(req.url || "", "http://localhost")
15
+ });
16
+ const query = getQuery(req.url || "");
17
+ const body = req.body;
18
+ let newPath = withoutHost(req.url || "").replace(/\/srn/, "");
19
+ if (newPath.includes("?")) {
20
+ newPath = `${newPath}&method=${req.method}`;
21
+ } else {
22
+ newPath = `${newPath}?method=${req.method}`;
23
+ }
24
+ operation = parseURI(newPath, silgiContext.uris);
25
+ if (!operation) {
26
+ throw createError({
27
+ statusCode: 400,
28
+ statusMessage: "Invalid URI"
29
+ });
30
+ }
31
+ await silgiContext.callHook("event:init", req, {
32
+ path: newPath,
33
+ queryParams: query,
34
+ operation
35
+ });
36
+ const data = await silgiConnect.execute(newPath, {
37
+ ...body
38
+ }, void 0, query);
39
+ return handleResponse(data, {
40
+ req,
41
+ res,
42
+ context: {},
43
+ url: new URL(req.url || "", "http://localhost")
44
+ }, {
45
+ debug: false
46
+ });
47
+ } catch (err) {
48
+ if (isError(err)) {
49
+ }
50
+ await silgiContext.callHook("execute:error", {
51
+ error: err instanceof Error ? err : new Error(String(err)),
52
+ timestamp: Date.now(),
53
+ operation
54
+ // event: event as never,
55
+ });
56
+ silgiContext.captureError(
57
+ silgiContext,
58
+ createError({
59
+ message: err instanceof Error ? err.message : String(err),
60
+ statusCode: 500,
61
+ statusMessage: "Internal Server Error"
62
+ }),
63
+ {
64
+ event,
65
+ operation,
66
+ tags: ["execute"]
67
+ }
68
+ );
69
+ }
70
+ };
71
+ }
72
+ export default addNextApp;
@@ -1,3 +1,3 @@
1
1
  import type { Silgi } from 'silgi/types';
2
- export declare function addNitroApp(silgiCtx?: Silgi): Promise<void>;
2
+ export declare function addNitroApp(silgiContext?: Silgi): Promise<void>;
3
3
  export default addNitroApp;
@@ -1,66 +1,92 @@
1
- import { createError, defineEventHandler, getQuery, H3Error, readBody } from "h3";
2
- import { ErrorFactory, HttpStatus, parseURI, silgi, SilgiError, useSilgi } from "silgi";
3
- export async function addNitroApp(silgiCtx = useSilgi()) {
4
- const nitro = silgiCtx.framework;
5
- nitro.router.use("/srn/**", defineEventHandler(async (event) => {
6
- let operation;
7
- try {
8
- const silgiConnect = silgi(event);
9
- const query = getQuery(event);
10
- const body = await readBody(event).catch(() => ({}));
11
- let newPath = event.path;
12
- if (event.path.includes("?")) {
13
- newPath = `${event.path}&method=${event.method}`;
14
- } else {
15
- newPath = `${event.path}?method=${event.method}`;
16
- }
17
- operation = parseURI(newPath, silgiCtx.uris);
18
- if (!operation) {
19
- throw ErrorFactory.create({ message: "Invalid URI", httpStatus: HttpStatus.BAD_REQUEST });
20
- }
21
- await silgiCtx.callHook("event:init", event, {
22
- path: newPath,
23
- queryParams: query,
24
- operation
25
- });
26
- const data = await silgiConnect.execute(newPath, {
27
- ...body
28
- }, void 0, query);
29
- if (data) {
30
- return data;
31
- }
32
- } catch (err) {
33
- if (err instanceof H3Error) {
34
- throw err;
35
- }
36
- if (SilgiError.isError(err)) {
37
- throw createError({
38
- statusCode: err.httpStatus,
39
- message: err.message,
40
- data: {
41
- code: err.code,
42
- category: err.category,
43
- severity: err.severity,
44
- context: err.context
1
+ import {
2
+ createError as createH3Error,
3
+ defineEventHandler,
4
+ H3Error,
5
+ readBody
6
+ } from "h3";
7
+ import {
8
+ createError,
9
+ isError,
10
+ silgiFetch,
11
+ useSilgi
12
+ } from "silgi";
13
+ import { getUrlPrefix } from "../../core/utils/route.ts";
14
+ export async function addNitroApp(silgiContext = useSilgi()) {
15
+ const nitro = silgiContext.framework;
16
+ const prefixs = silgiContext.routerPrefixs;
17
+ for (const prefix of prefixs) {
18
+ nitro.router.use(`${prefix}/**`, defineEventHandler(async (event) => {
19
+ const silgiURL = getUrlPrefix(event.path, event.method);
20
+ try {
21
+ const resolvedRoute = await silgiFetch(
22
+ event.path,
23
+ {
24
+ method: event.method.toUpperCase(),
25
+ body: event.method.toUpperCase() === "GET" ? void 0 : await readBody(event).catch(() => void 0)
26
+ }
27
+ );
28
+ if (!resolvedRoute.ok) {
29
+ await silgiContext.callHook("execute:error", {
30
+ error: new Error(resolvedRoute.statusText),
31
+ url: silgiURL,
32
+ event
33
+ });
34
+ silgiContext.captureError(
35
+ silgiContext,
36
+ createError({
37
+ message: resolvedRoute.statusText,
38
+ statusCode: resolvedRoute.status,
39
+ statusMessage: resolvedRoute.statusText
40
+ }),
41
+ {
42
+ event,
43
+ url: silgiURL,
44
+ tags: ["execute"]
45
+ }
46
+ );
47
+ throw createError({
48
+ statusCode: resolvedRoute.status,
49
+ statusMessage: resolvedRoute.statusText
50
+ });
51
+ }
52
+ return resolvedRoute;
53
+ } catch (err) {
54
+ if (err instanceof H3Error) {
55
+ throw err;
56
+ }
57
+ if (isError(err)) {
58
+ throw createH3Error({
59
+ statusCode: 500,
60
+ statusMessage: "Internal Server Error",
61
+ cause: err
62
+ });
63
+ }
64
+ await silgiContext.callHook("execute:error", {
65
+ error: err instanceof Error ? err : new Error(String(err)),
66
+ url: silgiURL,
67
+ event
68
+ });
69
+ silgiContext.captureError(
70
+ silgiContext,
71
+ createError({
72
+ message: err instanceof Error ? err.message : String(err),
73
+ statusCode: 500,
74
+ statusMessage: "Internal Server Error",
75
+ cause: err
76
+ }),
77
+ {
78
+ event,
79
+ url: silgiURL,
80
+ tags: ["execute"]
45
81
  }
82
+ );
83
+ throw createError({
84
+ statusCode: 500,
85
+ message: "Internal Server Error",
86
+ cause: err
46
87
  });
47
88
  }
48
- await silgiCtx.callHook("execute:error", {
49
- error: err instanceof Error ? err : new Error(String(err)),
50
- timestamp: Date.now(),
51
- operation,
52
- event
53
- });
54
- silgiCtx.captureError(silgiCtx, SilgiError.from(err), {
55
- event,
56
- operation,
57
- tags: ["execute"]
58
- });
59
- throw createError({
60
- statusCode: 500,
61
- message: "Internal Server Error"
62
- });
63
- }
64
- }));
89
+ }));
90
+ }
65
91
  }
66
92
  export default addNitroApp;