silgi 0.3.13 → 0.4.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 (69) hide show
  1. package/README.md +1 -31
  2. package/cli.d.ts +1 -0
  3. package/config.d.ts +1 -0
  4. package/core.d.ts +1 -0
  5. package/dist/_chunks/index.mjs +233 -0
  6. package/dist/cli/compatibility.mjs +42 -0
  7. package/dist/cli/index.mjs +3 -184
  8. package/dist/cli/prepare.mjs +1346 -0
  9. package/dist/config/index.d.mts +5 -0
  10. package/dist/config/index.d.ts +5 -0
  11. package/dist/core/index.d.mts +136 -0
  12. package/dist/core/index.d.ts +136 -0
  13. package/dist/core/index.mjs +1444 -0
  14. package/dist/ecosystem/nitro/index.mjs +21 -29
  15. package/dist/ecosystem/nuxt/module.mjs +4 -25
  16. package/dist/kit/index.d.mts +90 -0
  17. package/dist/kit/index.d.ts +90 -0
  18. package/dist/kit/index.mjs +316 -0
  19. package/dist/meta/index.d.mts +3 -0
  20. package/dist/meta/index.d.ts +3 -0
  21. package/dist/meta/index.mjs +1 -0
  22. package/dist/presets/_all.gen.d.ts +2 -0
  23. package/dist/presets/_all.gen.mjs +8 -0
  24. package/dist/presets/_resolve.d.ts +8 -0
  25. package/dist/presets/_resolve.mjs +58 -0
  26. package/dist/presets/_types.gen.d.ts +5 -0
  27. package/dist/presets/_types.gen.mjs +1 -0
  28. package/dist/presets/h3/preset.d.ts +2 -0
  29. package/dist/presets/h3/preset.mjs +22 -0
  30. package/dist/presets/index.d.mts +1 -0
  31. package/dist/presets/index.d.ts +2 -0
  32. package/dist/presets/index.mjs +1 -0
  33. package/dist/presets/nitro/preset.d.ts +2 -0
  34. package/dist/presets/nitro/preset.mjs +26 -0
  35. package/dist/presets/npmpackage/preset.d.ts +2 -0
  36. package/dist/presets/npmpackage/preset.mjs +23 -0
  37. package/dist/runtime/index.d.ts +1 -0
  38. package/dist/runtime/index.mjs +1 -0
  39. package/dist/runtime/internal/debug.d.ts +2 -0
  40. package/dist/runtime/internal/debug.mjs +5 -0
  41. package/dist/runtime/internal/nitro.d.ts +2 -0
  42. package/dist/runtime/internal/nitro.mjs +45 -0
  43. package/dist/runtime/internal/plugin.d.ts +3 -0
  44. package/dist/runtime/internal/plugin.mjs +4 -0
  45. package/dist/shared/silgi.40ZJYm8F.d.mts +11 -0
  46. package/dist/shared/silgi.40ZJYm8F.d.ts +11 -0
  47. package/dist/shared/{silgi.ClpvycKI.d.mts → silgi.D8h2AAVk.d.ts} +451 -437
  48. package/dist/shared/{silgi.ClpvycKI.d.ts → silgi.DSHNePNA.d.mts} +451 -437
  49. package/dist/types/index.d.mts +42 -0
  50. package/dist/types/index.d.ts +42 -0
  51. package/dist/types/index.mjs +1 -0
  52. package/kit.d.ts +1 -0
  53. package/meta.d.ts +1 -0
  54. package/package.json +89 -39
  55. package/presets.d.ts +1 -0
  56. package/runtime-meta.d.ts +4 -0
  57. package/runtime-meta.mjs +32 -0
  58. package/runtime.d.ts +1 -0
  59. package/types.d.ts +1 -0
  60. package/bin/silgi.mjs +0 -3
  61. package/dist/chunks/generate.mjs +0 -1257
  62. package/dist/cli/config.d.mts +0 -1633
  63. package/dist/cli/config.d.ts +0 -1633
  64. package/dist/index.d.mts +0 -198
  65. package/dist/index.d.ts +0 -198
  66. package/dist/index.mjs +0 -503
  67. package/dist/shared/silgi.D2yb1XAa.mjs +0 -842
  68. /package/dist/{chunks → cli}/init.mjs +0 -0
  69. /package/dist/{cli/config.mjs → config/index.mjs} +0 -0
@@ -0,0 +1,1444 @@
1
+ import { watchConfig, loadConfig } from 'c12';
2
+ import { resolveCompatibilityDatesFromEnv, formatDate, resolveCompatibilityDates } from 'compatx';
3
+ import { klona } from 'klona/full';
4
+ import { isDebug, isTest, isDevelopment } from 'std-env';
5
+ import consola, { createConsola } from 'consola';
6
+ import { colors } from 'consola/utils';
7
+ import { relative, join, resolve, isAbsolute, dirname } from 'pathe';
8
+ import escapeRE from 'escape-string-regexp';
9
+ import { resolveModuleExportNames, resolvePath as resolvePath$1 } from 'mlly';
10
+ import { existsSync, lstatSync, promises, writeFileSync } from 'node:fs';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { findWorkspaceDir, readPackageJSON } from 'pkg-types';
13
+ import { resolveSilgiPath, resolveAlias, resolvePath, relativeWithDot, resolveSilgiModule } from 'silgi/kit';
14
+ import { runtimeDir, pkgDir } from 'silgi/runtime/meta';
15
+ import { isRelative, withLeadingSlash, withTrailingSlash } from 'ufo';
16
+ import defu$1, { defu } from 'defu';
17
+ import { isEvent } from 'h3';
18
+ import { createHooks } from 'hookable';
19
+ import { defineUntypedSchema, applyDefaults } from 'untyped';
20
+ import { getContext } from 'unctx';
21
+ import { Buffer } from 'node:buffer';
22
+ import { klona as klona$1 } from 'klona';
23
+ import { createStorage as createStorage$1, builtinDrivers, prefixStorage } from 'unstorage';
24
+ import memoryDriver from 'unstorage/drivers/memory';
25
+ import { parseSync } from '@oxc-parser/wasm';
26
+
27
+ const SilgiCLIDefaults = {
28
+ // General
29
+ debug: isDebug,
30
+ // timing: isDebug,
31
+ logLevel: isTest ? 1 : 3,
32
+ // runtimeConfig: { app: {}, silgi: {} },
33
+ appConfig: {},
34
+ appConfigFiles: [],
35
+ // Dirs
36
+ scanDirs: [],
37
+ build: {
38
+ dir: ".silgi",
39
+ typesDir: "{{ build.dir }}/types"
40
+ },
41
+ output: {
42
+ dir: "{{ rootDir }}/.output",
43
+ serverDir: "{{ output.dir }}/server",
44
+ publicDir: "{{ output.dir }}/public"
45
+ },
46
+ serverDir: "{{ rootDir }}/server",
47
+ clientDir: "{{ rootDir }}/client",
48
+ silgi: {
49
+ serverDir: "{{ serverDir }}/silgi",
50
+ clientDir: "{{ clientDir }}/silgi",
51
+ publicDir: "{{ silgi.serverDir }}/public",
52
+ utilsDir: "{{ silgi.serverDir }}/utils",
53
+ composablesDir: "{{ silgi.serverDir }}/composables",
54
+ typesDir: "{{ silgi.serverDir }}/types",
55
+ servicesDir: "{{ silgi.serverDir }}/services"
56
+ },
57
+ // Modules
58
+ _modules: [],
59
+ modules: [],
60
+ // Features
61
+ // experimental: {},
62
+ future: {},
63
+ storage: {},
64
+ devStorage: {},
65
+ // bundledStorage: [],
66
+ // publicAssets: [],
67
+ // serverAssets: [],
68
+ plugins: [],
69
+ // tasks: {},
70
+ // scheduledTasks: {},
71
+ imports: {
72
+ exclude: [],
73
+ dirs: [],
74
+ presets: [],
75
+ virtualImports: ["#imports"]
76
+ },
77
+ // virtual: {},
78
+ // compressPublicAssets: false,
79
+ ignore: [],
80
+ // Dev
81
+ dev: false,
82
+ // devServer: { watch: [] },
83
+ watchOptions: { ignoreInitial: true },
84
+ // devProxy: {},
85
+ // Logging
86
+ // logging: {
87
+ // compressedSizes: true,
88
+ // buildSuccess: true,
89
+ // },
90
+ // Routing
91
+ // baseURL: process.env.NITRO_APP_BASE_URL || '/',
92
+ // handlers: [],
93
+ // devHandlers: [],
94
+ // errorHandler: undefined,
95
+ // routeRules: {},
96
+ // Advanced
97
+ typescript: {
98
+ strict: false,
99
+ generateTsConfig: true,
100
+ // generateRuntimeConfigTypes: true,
101
+ tsconfigPath: "types/silgi.tsconfig.json",
102
+ internalPaths: false,
103
+ tsConfig: {},
104
+ customConditions: []
105
+ },
106
+ conditions: [],
107
+ nodeModulesDirs: [],
108
+ // hooks: {},
109
+ commands: {},
110
+ // Framework
111
+ framework: {
112
+ name: "h3",
113
+ version: ""
114
+ },
115
+ extensions: [".js", ".jsx", ".mjs", ".ts", ".tsx", ".vue"]
116
+ };
117
+
118
+ const fallbackCompatibilityDate = "2025-02-04";
119
+ async function resolveCompatibilityOptions(options) {
120
+ options.compatibilityDate = resolveCompatibilityDatesFromEnv(
121
+ options.compatibilityDate
122
+ );
123
+ if (!options.compatibilityDate.default) {
124
+ options.compatibilityDate.default = await _resolveDefault(options);
125
+ }
126
+ }
127
+ let _fallbackInfoShown = false;
128
+ let _promptedUserToUpdate = false;
129
+ async function _resolveDefault(options) {
130
+ const _todayDate = formatDate(/* @__PURE__ */ new Date());
131
+ const consola$1 = consola.withTag("silgi");
132
+ consola$1.warn(`No valid compatibility date is specified.`);
133
+ const onFallback = () => {
134
+ if (!_fallbackInfoShown) {
135
+ consola$1.info(
136
+ [
137
+ `Using \`${fallbackCompatibilityDate}\` as fallback.`,
138
+ ` Please specify compatibility date to avoid unwanted behavior changes:`,
139
+ ` - Add \`compatibilityDate: '${_todayDate}'\` to the config file.`,
140
+ ` - Or set \`COMPATIBILITY_DATE=${_todayDate}\` environment variable.`,
141
+ ``
142
+ ].join("\n")
143
+ );
144
+ _fallbackInfoShown = true;
145
+ }
146
+ return fallbackCompatibilityDate;
147
+ };
148
+ const shallUpdate = !_promptedUserToUpdate && await consola$1.prompt(
149
+ `Do you want to auto update config file to set ${colors.cyan(`compatibilityDate: '${_todayDate}'`)}?`,
150
+ {
151
+ type: "confirm",
152
+ default: true
153
+ }
154
+ );
155
+ _promptedUserToUpdate = true;
156
+ if (!shallUpdate) {
157
+ return onFallback();
158
+ }
159
+ const { updateConfig } = await import('c12/update');
160
+ const updateResult = await updateConfig({
161
+ configFile: "silgi.config",
162
+ cwd: options.rootDir,
163
+ async onCreate({ configFile }) {
164
+ const shallCreate = await consola$1.prompt(
165
+ `Do you want to initialize a new config in ${colors.cyan(relative(".", configFile))}?`,
166
+ {
167
+ type: "confirm",
168
+ default: true
169
+ }
170
+ );
171
+ if (shallCreate !== true) {
172
+ return false;
173
+ }
174
+ return _getDefaultNitroConfig();
175
+ },
176
+ async onUpdate(config) {
177
+ config.compatibilityDate = _todayDate;
178
+ }
179
+ }).catch((error) => {
180
+ consola$1.error(`Failed to update config: ${error.message}`);
181
+ return null;
182
+ });
183
+ if (updateResult?.configFile) {
184
+ consola$1.success(
185
+ `Compatibility date set to \`${_todayDate}\` in \`${relative(".", updateResult.configFile)}\``
186
+ );
187
+ return _todayDate;
188
+ }
189
+ return onFallback();
190
+ }
191
+ function _getDefaultNitroConfig() {
192
+ return (
193
+ /* js */
194
+ `
195
+ import { defineSilgiConfig } from 'silgi/config'
196
+
197
+ export default defineSilgiConfig({})
198
+ `
199
+ );
200
+ }
201
+
202
+ async function resolveImportsOptions(options) {
203
+ if (options.imports === false) {
204
+ return;
205
+ }
206
+ options.imports.presets ??= [];
207
+ options.imports.presets.push(...getSilgiImportsPreset());
208
+ const h3Exports = await resolveModuleExportNames("h3", {
209
+ url: import.meta.url
210
+ });
211
+ options.imports.presets ??= [];
212
+ options.imports.presets.push({
213
+ from: "h3",
214
+ imports: h3Exports.filter((n) => !/^[A-Z]/.test(n) && n !== "use")
215
+ });
216
+ options.imports.dirs ??= [];
217
+ options.imports.dirs.push(
218
+ ...options.scanDirs.map((dir) => join(dir, "utils/**/*"))
219
+ );
220
+ if (Array.isArray(options.imports.exclude) && options.imports.exclude.length === 0) {
221
+ options.imports.exclude.push(/[/\\]\.git[/\\]/);
222
+ options.imports.exclude.push(options.build.dir);
223
+ const scanDirsInNodeModules = options.scanDirs.map((dir) => dir.match(/(?<=\/)node_modules\/(.+)$/)?.[1]).filter(Boolean);
224
+ options.imports.exclude.push(
225
+ scanDirsInNodeModules.length > 0 ? new RegExp(
226
+ `node_modules\\/(?!${scanDirsInNodeModules.map((dir) => escapeRE(dir)).join("|")})`
227
+ ) : /[/\\]node_modules[/\\]/
228
+ );
229
+ }
230
+ }
231
+ function getSilgiImportsPreset() {
232
+ return [
233
+ // TODO: buraya bizim importlarimiz gelecek.
234
+ // {
235
+ // from: 'nitropack/runtime',
236
+ // imports: ['useNitroApp'],
237
+ // },
238
+ // {
239
+ // from: 'nitropack/runtime',
240
+ // imports: ['useRuntimeConfig', 'useAppConfig'],
241
+ // },
242
+ // {
243
+ // from: 'nitropack/runtime',
244
+ // imports: ['defineNitroPlugin', 'nitroPlugin'],
245
+ // },
246
+ // {
247
+ // from: 'nitropack/runtime/internal/cache',
248
+ // imports: [
249
+ // 'defineCachedFunction',
250
+ // 'defineCachedEventHandler',
251
+ // 'cachedFunction',
252
+ // 'cachedEventHandler',
253
+ // ],
254
+ // },
255
+ // {
256
+ // from: 'nitropack/runtime/internal/storage',
257
+ // imports: ['useStorage'],
258
+ // },
259
+ // {
260
+ // from: 'nitropack/runtime/internal/renderer',
261
+ // imports: ['defineRenderHandler'],
262
+ // },
263
+ // {
264
+ // from: 'nitropack/runtime/internal/meta',
265
+ // imports: ['defineRouteMeta'],
266
+ // },
267
+ // {
268
+ // from: 'nitropack/runtime/internal/route-rules',
269
+ // imports: ['getRouteRules'],
270
+ // },
271
+ // {
272
+ // from: 'nitropack/runtime/internal/context',
273
+ // imports: ['useEvent'],
274
+ // },
275
+ // {
276
+ // from: 'nitropack/runtime/internal/task',
277
+ // imports: ['defineTask', 'runTask'],
278
+ // },
279
+ // {
280
+ // from: 'nitropack/runtime/internal/error/utils',
281
+ // imports: ['defineNitroErrorHandler'],
282
+ // },
283
+ ];
284
+ }
285
+
286
+ async function resolvePathOptions(options) {
287
+ options.rootDir = resolve(options.rootDir || ".");
288
+ options.workspaceDir = await findWorkspaceDir(options.rootDir).catch(
289
+ () => options.rootDir
290
+ );
291
+ options.srcDir = resolve(options.srcDir || options.rootDir);
292
+ for (const key of ["srcDir"]) {
293
+ options[key] = resolve(options.rootDir, options[key]);
294
+ }
295
+ options.build.dir = resolve(options.rootDir, options.build.dir);
296
+ options.build.typesDir = resolveSilgiPath(
297
+ options.build.typesDir || SilgiCLIDefaults.build.typesDir,
298
+ options,
299
+ options.rootDir
300
+ );
301
+ if (options.preset === "npm-package") {
302
+ const packageJsonPath = resolve(options.rootDir, "package.json");
303
+ const packageJson = await readPackageJSON(packageJsonPath);
304
+ if (packageJson.name === undefined) {
305
+ throw new Error("Package name is undefined");
306
+ }
307
+ options.alias ||= {};
308
+ options.alias[packageJson.name] = join(options.rootDir, "src/module.ts");
309
+ options.alias[`${packageJson.name}/runtime/`] = join(options.rootDir, "src/runtime/");
310
+ options.alias = {
311
+ ...options.alias,
312
+ "silgi/runtime": join(runtimeDir),
313
+ "#internal/silgi": join(runtimeDir),
314
+ "silgi/runtime/*": join(runtimeDir, "*"),
315
+ "#internal/silgi/*": join(runtimeDir, "*")
316
+ };
317
+ }
318
+ if (options.typescript?.internalPaths) {
319
+ options.alias = {
320
+ ...options.alias,
321
+ "silgi/runtime": join(runtimeDir),
322
+ "#internal/silgi": join(runtimeDir),
323
+ "silgi/runtime/*": join(runtimeDir, "*"),
324
+ "#internal/silgi/*": join(runtimeDir, "*")
325
+ };
326
+ options.typescript.customConditions = [
327
+ ...options.typescript.customConditions,
328
+ "silgiTypes"
329
+ ];
330
+ options.conditions ||= [];
331
+ options.conditions.push("silgi");
332
+ }
333
+ options.alias = {
334
+ ...options.alias,
335
+ "~/": join(options.srcDir, "/"),
336
+ "@/": join(options.srcDir, "/"),
337
+ "~~/": join(options.rootDir, "/"),
338
+ "@@/": join(options.rootDir, "/")
339
+ };
340
+ if (options.alias && typeof options.alias === "object") {
341
+ ((options.typescript.tsConfig ??= {}).compilerOptions ??= {}).paths ??= {};
342
+ const paths = options.typescript.tsConfig.compilerOptions.paths;
343
+ for (const [key, value] of Object.entries(options.alias)) {
344
+ if (typeof paths === "object") {
345
+ paths[key] = [value];
346
+ }
347
+ }
348
+ }
349
+ if (options.typescript.tsConfig.compilerOptions?.paths && typeof options.typescript.tsConfig.compilerOptions.paths === "object") {
350
+ ((options.typescript.tsConfig ??= {}).compilerOptions ??= {}).paths ??= {};
351
+ const paths = options.typescript.tsConfig.compilerOptions.paths;
352
+ for (const [key, value] of Object.entries(options.alias)) {
353
+ if (typeof paths === "object") {
354
+ paths[key] = [value];
355
+ }
356
+ }
357
+ }
358
+ options.modulesDir = [resolve(options.rootDir, "node_modules")];
359
+ options.output.dir = resolveSilgiPath(
360
+ options.output.dir || SilgiCLIDefaults.output.dir,
361
+ options,
362
+ options.rootDir
363
+ );
364
+ options.output.publicDir = resolveSilgiPath(
365
+ options.output.publicDir || SilgiCLIDefaults.output.publicDir,
366
+ options,
367
+ options.rootDir
368
+ );
369
+ options.output.serverDir = resolveSilgiPath(
370
+ options.output.serverDir || SilgiCLIDefaults.output.serverDir,
371
+ options,
372
+ options.rootDir
373
+ );
374
+ options.serverDir = resolveSilgiPath(
375
+ options.serverDir || SilgiCLIDefaults.serverDir,
376
+ options,
377
+ options.rootDir
378
+ );
379
+ options.clientDir = resolveSilgiPath(
380
+ options.clientDir || SilgiCLIDefaults.clientDir,
381
+ options,
382
+ options.rootDir
383
+ );
384
+ options.silgi.serverDir = resolveSilgiPath(
385
+ options.silgi.serverDir || SilgiCLIDefaults.silgi.serverDir,
386
+ options,
387
+ options.rootDir
388
+ );
389
+ options.silgi.clientDir = resolveSilgiPath(
390
+ options.silgi.clientDir || SilgiCLIDefaults.silgi.clientDir,
391
+ options,
392
+ options.rootDir
393
+ );
394
+ options.silgi.publicDir = resolveSilgiPath(
395
+ options.silgi.publicDir || SilgiCLIDefaults.silgi.publicDir,
396
+ options,
397
+ options.rootDir
398
+ );
399
+ options.silgi.utilsDir = resolveSilgiPath(
400
+ options.silgi.utilsDir || SilgiCLIDefaults.silgi.utilsDir,
401
+ options,
402
+ options.rootDir
403
+ );
404
+ options.silgi.composablesDir = resolveSilgiPath(
405
+ options.silgi.composablesDir || SilgiCLIDefaults.silgi.composablesDir,
406
+ options,
407
+ options.rootDir
408
+ );
409
+ options.silgi.typesDir = resolveSilgiPath(
410
+ options.silgi.typesDir || SilgiCLIDefaults.silgi.typesDir,
411
+ options,
412
+ options.rootDir
413
+ );
414
+ options.silgi.servicesDir = resolveSilgiPath(
415
+ options.silgi.servicesDir || SilgiCLIDefaults.silgi.servicesDir,
416
+ options,
417
+ options.rootDir
418
+ );
419
+ options.nodeModulesDirs.push(resolve(options.workspaceDir, "node_modules"));
420
+ options.nodeModulesDirs.push(resolve(options.rootDir, "node_modules"));
421
+ options.nodeModulesDirs.push(resolve(pkgDir, "node_modules"));
422
+ options.nodeModulesDirs.push(resolve(pkgDir, ".."));
423
+ options.nodeModulesDirs = [
424
+ ...new Set(
425
+ options.nodeModulesDirs.map((dir) => resolve(options.rootDir, dir))
426
+ )
427
+ ];
428
+ options.scanDirs.unshift(options.srcDir);
429
+ options.scanDirs = options.scanDirs.map(
430
+ (dir) => resolve(options.srcDir, dir)
431
+ );
432
+ options.scanDirs = [...new Set(options.scanDirs)];
433
+ options.appConfigFiles ??= [];
434
+ options.appConfigFiles = options.appConfigFiles.map((file) => _tryResolve(resolveSilgiPath(file, options))).filter(Boolean);
435
+ for (const dir of options.scanDirs) {
436
+ const configFile = _tryResolve("app.config", dir);
437
+ if (configFile && !options.appConfigFiles.includes(configFile)) {
438
+ options.appConfigFiles.push(configFile);
439
+ }
440
+ }
441
+ const modulesRuntimePaths = {};
442
+ if (options.typescript?.internalPaths) {
443
+ for (let i of options.modules) {
444
+ if (typeof i === "string") {
445
+ i = resolveAlias(i, options.alias);
446
+ if (isRelative(i)) {
447
+ i = resolve(options.rootDir, i);
448
+ }
449
+ const src = isAbsolute(i) ? pathToFileURL(await resolvePath(i, { fallbackToOriginal: false, extensions: options.extensions })).href : await resolvePath$1(i, { url: options.modulesDir.map((m) => pathToFileURL(m.replace(/\/node_modules\/?$/, ""))), extensions: options.extensions });
450
+ const cleanPath = src.replace(/(\/(?:src|dist)(?:\/runtime)?(?:\/.*)?$)/, "");
451
+ modulesRuntimePaths[`${i}/runtime`] = `${cleanPath}/src/runtime`;
452
+ }
453
+ }
454
+ for (const [key, value] of Object.entries(modulesRuntimePaths)) {
455
+ options.alias = {
456
+ ...options.alias,
457
+ [`${key}`]: value
458
+ };
459
+ }
460
+ }
461
+ }
462
+ function _tryResolve(path, base = ".", extensions = ["", ".js", ".ts", ".mjs", ".cjs", ".json"]) {
463
+ path = resolve(base, path);
464
+ if (existsSync(path)) {
465
+ return path;
466
+ }
467
+ for (const ext of extensions) {
468
+ const p = path + ext;
469
+ if (existsSync(p)) {
470
+ return p;
471
+ }
472
+ }
473
+ }
474
+
475
+ async function resolveStorageOptions(options) {
476
+ const fsMounts = {
477
+ root: resolve(options.rootDir),
478
+ src: resolve(options.srcDir),
479
+ build: resolve(options.build.dir),
480
+ cache: resolve(options.build.dir, "cache")
481
+ };
482
+ for (const p in fsMounts) {
483
+ options.devStorage[p] = options.devStorage[p] || {
484
+ driver: "fs",
485
+ readOnly: p === "root" || p === "src",
486
+ base: fsMounts[p]
487
+ };
488
+ }
489
+ if (options.dev && options.storage.data === undefined && options.devStorage.data === undefined) {
490
+ options.devStorage.data = {
491
+ driver: "fs",
492
+ base: resolve(options.rootDir, ".data/kv")
493
+ };
494
+ }
495
+ }
496
+
497
+ async function resolveURLOptions(options) {
498
+ options.baseURL = withLeadingSlash(withTrailingSlash(options.baseURL));
499
+ }
500
+
501
+ const configResolvers = [
502
+ resolveCompatibilityOptions,
503
+ resolvePathOptions,
504
+ resolveImportsOptions,
505
+ // resolveRouteRulesOptions,
506
+ // resolveDatabaseOptions,
507
+ // resolveFetchOptions,
508
+ // resolveExportConditionsOptions,
509
+ // resolveRuntimeConfigOptions,
510
+ // resolveOpenAPIOptions,
511
+ resolveURLOptions,
512
+ // resolveAssetsOptions,
513
+ resolveStorageOptions
514
+ // resolveErrorOptions,
515
+ ];
516
+ async function loadOptions(configOverrides = {}, opts = {}) {
517
+ const options = await _loadUserConfig(configOverrides, opts);
518
+ for (const resolver of configResolvers) {
519
+ await resolver(options);
520
+ }
521
+ return options;
522
+ }
523
+ async function _loadUserConfig(configOverrides = {}, opts = {}) {
524
+ let presetOverride = configOverrides.preset || process.env.SILGI_PRESET;
525
+ if (configOverrides.dev) {
526
+ presetOverride = "silgi-dev";
527
+ }
528
+ configOverrides = klona(configOverrides);
529
+ globalThis.defineSilgiConfig = globalThis.defineSilgiConfig || ((c) => c);
530
+ let compatibilityDate = configOverrides.compatibilityDate || opts.compatibilityDate || (process.env.SILGI_COMPATIBILITY_DATE || process.env.SERVER_COMPATIBILITY_DATE || process.env.COMPATIBILITY_DATE);
531
+ const { resolvePreset } = await import('silgi/presets');
532
+ const loadedConfig = await (opts.watch ? watchConfig : loadConfig)({
533
+ name: "silgi",
534
+ cwd: configOverrides.rootDir,
535
+ dotenv: configOverrides.dev,
536
+ extend: { extendKey: ["extends", "preset"] },
537
+ overrides: {
538
+ ...configOverrides,
539
+ preset: presetOverride
540
+ },
541
+ async defaultConfig({ configs }) {
542
+ const getConf = (key) => configs.main?.[key] ?? configs.rc?.[key] ?? configs.packageJson?.[key];
543
+ if (!compatibilityDate) {
544
+ compatibilityDate = getConf("compatibilityDate");
545
+ }
546
+ return {
547
+ // typescript: {
548
+ // generateRuntimeConfigTypes:
549
+ // !framework?.name || framework.name === 'nitro',
550
+ // },
551
+ preset: presetOverride || (await resolvePreset("", {
552
+ static: getConf("static"),
553
+ compatibilityDate: compatibilityDate || fallbackCompatibilityDate
554
+ }))?._meta?.name
555
+ };
556
+ },
557
+ defaults: SilgiCLIDefaults,
558
+ jitiOptions: {
559
+ alias: {
560
+ "silgi": "silgi/config",
561
+ "silgi/config": "silgi/config"
562
+ }
563
+ },
564
+ async resolve(id) {
565
+ const preset = await resolvePreset(id, {
566
+ static: configOverrides.static,
567
+ compatibilityDate: compatibilityDate || fallbackCompatibilityDate
568
+ });
569
+ if (preset) {
570
+ return {
571
+ config: klona(preset)
572
+ };
573
+ }
574
+ },
575
+ ...opts.c12
576
+ });
577
+ delete globalThis.defineSilgiConfig;
578
+ const options = klona(loadedConfig.config);
579
+ options._config = configOverrides;
580
+ options._c12 = loadedConfig;
581
+ const _presetName = (loadedConfig.layers || []).find((l) => l.config?._meta?.name)?.config?._meta?.name || presetOverride;
582
+ options.preset = _presetName;
583
+ options.compatibilityDate = resolveCompatibilityDates(
584
+ compatibilityDate,
585
+ options.compatibilityDate
586
+ );
587
+ return options;
588
+ }
589
+
590
+ function getDirectory(p) {
591
+ try {
592
+ return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
593
+ } catch {
594
+ }
595
+ return p;
596
+ }
597
+
598
+ function renderAttrs(obj) {
599
+ const attrs = [];
600
+ for (const key in obj) {
601
+ attrs.push(renderAttr(key, obj[key]));
602
+ }
603
+ return attrs.join(" ");
604
+ }
605
+ function renderAttr(key, value) {
606
+ return value ? `${key}="${value}"` : "";
607
+ }
608
+ async function silgiGenerateType(silgi) {
609
+ const rootDirWithSlash = withTrailingSlash(silgi.options.rootDir);
610
+ const tsConfigPath = resolve(
611
+ silgi.options.build.dir,
612
+ silgi.options.typescript.tsconfigPath
613
+ );
614
+ const tsconfigDir = dirname(tsConfigPath);
615
+ const include = /* @__PURE__ */ new Set([
616
+ relativeWithDot(tsconfigDir, join(silgi.options.build.typesDir, "silgi.d.ts")).replace(
617
+ /^(?=[^.])/,
618
+ "./"
619
+ ),
620
+ join(relativeWithDot(tsconfigDir, silgi.options.rootDir), "**/*"),
621
+ ...silgi.options.srcDir === silgi.options.rootDir ? [] : [join(relativeWithDot(tsconfigDir, silgi.options.srcDir), "**/*")]
622
+ ]);
623
+ const exclude = /* @__PURE__ */ new Set([
624
+ // nitro generate output: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/nitro.ts#L186
625
+ relativeWithDot(silgi.options.build.dir, resolve(silgi.options.rootDir, "dist"))
626
+ ]);
627
+ for (const dir of silgi.options.modulesDir) {
628
+ exclude.add(relativeWithDot(silgi.options.build.dir, dir));
629
+ }
630
+ const moduleEntryPaths = [];
631
+ for (const m of silgi.scanModules) {
632
+ if (m.entryPath) {
633
+ moduleEntryPaths.push(getDirectory(m.entryPath));
634
+ }
635
+ }
636
+ const modulePaths = await resolveSilgiModule(rootDirWithSlash, moduleEntryPaths);
637
+ for (const path of modulePaths) {
638
+ const relative2 = relativeWithDot(silgi.options.build.dir, path);
639
+ include.add(join(relative2, "runtime"));
640
+ exclude.add(join(relative2, "runtime/server"));
641
+ include.add(join(relative2, "dist/runtime"));
642
+ exclude.add(join(relative2, "dist/runtime/server"));
643
+ }
644
+ const tsConfig = defu(silgi.options.typescript?.tsConfig, {
645
+ compilerOptions: {
646
+ forceConsistentCasingInFileNames: true,
647
+ strict: silgi.options.typescript.strict,
648
+ noEmit: true,
649
+ target: "ESNext",
650
+ module: "ESNext",
651
+ moduleResolution: "Bundler",
652
+ allowJs: true,
653
+ resolveJsonModule: true,
654
+ jsx: "preserve",
655
+ allowSyntheticDefaultImports: true,
656
+ jsxFactory: "h",
657
+ jsxFragmentFactory: "Fragment",
658
+ allowImportingTsExtensions: true,
659
+ customConditions: ["silgiTypes"],
660
+ paths: {
661
+ "#imports": [
662
+ relativeWithDot(tsconfigDir, join(silgi.options.build.typesDir, "silgi-imports"))
663
+ ]
664
+ // ...(silgi.options.typescript?.internalPaths
665
+ // ? {
666
+ // 'silgi/runtime': [
667
+ // relativeWithDot(tsconfigDir, join(runtimeDir, 'index')),
668
+ // ],
669
+ // '#internal/silgi': [
670
+ // relativeWithDot(tsconfigDir, join(runtimeDir, 'index')),
671
+ // ],
672
+ // 'silgi/runtime/*': [
673
+ // relativeWithDot(tsconfigDir, join(runtimeDir, '*')),
674
+ // ],
675
+ // '#internal/silgi/*': [
676
+ // relativeWithDot(tsconfigDir, join(runtimeDir, '*')),
677
+ // ],
678
+ // }
679
+ // : {}),
680
+ }
681
+ },
682
+ include: [...include],
683
+ exclude: [...exclude]
684
+ });
685
+ tsConfig.compilerOptions ||= {};
686
+ tsConfig.compilerOptions.paths ||= {};
687
+ tsConfig.include ||= [];
688
+ for (const alias in tsConfig.compilerOptions.paths) {
689
+ const paths = tsConfig.compilerOptions.paths[alias];
690
+ tsConfig.compilerOptions.paths[alias] = await Promise.all(
691
+ paths.map(async (path) => {
692
+ if (!isAbsolute(path)) {
693
+ return path;
694
+ }
695
+ const stats = await promises.stat(path).catch(
696
+ () => null
697
+ /* file does not exist */
698
+ );
699
+ return relativeWithDot(
700
+ tsconfigDir,
701
+ stats?.isFile() ? path.replace(/\b\.\w+$/g, "") : path
702
+ );
703
+ })
704
+ );
705
+ }
706
+ const references = [];
707
+ await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
708
+ if (typeof id !== "string") {
709
+ return;
710
+ }
711
+ const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
712
+ references.push({ types: pkg?.name || id });
713
+ }));
714
+ const declarations = [];
715
+ await silgi.callHook("prepare:types", { references, declarations, tsConfig });
716
+ tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(silgi.options.build.dir, p) : p))];
717
+ tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(silgi.options.build.dir, p) : p))];
718
+ const _declarations = [
719
+ ...references.map((ref) => {
720
+ if ("path" in ref && isAbsolute(ref.path)) {
721
+ ref.path = relative(silgi.options.build.dir, ref.path);
722
+ }
723
+ return `/// <reference ${renderAttrs(ref)} />`;
724
+ }),
725
+ ...declarations,
726
+ "",
727
+ "export {}",
728
+ ""
729
+ ];
730
+ return {
731
+ declarations: _declarations,
732
+ tsConfig
733
+ };
734
+ }
735
+
736
+ const common = defineUntypedSchema({
737
+ /**
738
+ * Environment to use.
739
+ *
740
+ * @default 'h3'
741
+ */
742
+ environment: {
743
+ $resolve: (val) => val ?? "h3"
744
+ },
745
+ /**
746
+ * Whether Nuxt is running in development mode.
747
+ *
748
+ * Normally, you should not need to set this.
749
+ */
750
+ dev: {
751
+ $resolve: (val) => val ?? Boolean(isDevelopment)
752
+ },
753
+ /**
754
+ * Whether your app is being unit tested.
755
+ */
756
+ test: {
757
+ $resolve: (val) => val ?? Boolean(isTest)
758
+ },
759
+ /**
760
+ * Set to `true` to enable debug mode.
761
+ *
762
+ * At the moment, it prints out hook names and timings on the server, and
763
+ * logs hook arguments as well in the browser.
764
+ *
765
+ */
766
+ debug: {
767
+ $resolve: (val) => val ?? isDebug
768
+ },
769
+ plugins: {
770
+ $resolve: (val) => (val || []).filter(Boolean)
771
+ },
772
+ $schema: {}
773
+ });
774
+
775
+ const internal = defineUntypedSchema({
776
+ /** @private */
777
+ _majorVersion: 4,
778
+ /** @private */
779
+ _generate: false,
780
+ /** @private */
781
+ _prepare: false,
782
+ /** @private */
783
+ _requiredPlugins: {},
784
+ /**
785
+ * @private
786
+ * @type {Array<{ meta: ModuleMeta; timings?: Record<string, number | undefined>; entryPath?: string }>}
787
+ */
788
+ _installedPlugins: [],
789
+ /** @private */
790
+ _plugins: [],
791
+ extensions: [".js", ".mjs", ".ts"]
792
+ });
793
+
794
+ const SilgiConfigSchema = {
795
+ ...common,
796
+ ...internal
797
+ };
798
+
799
+ const silgiCtx = getContext("silgi");
800
+ function useSilgi() {
801
+ const instance = silgiCtx.tryUse();
802
+ if (!instance) {
803
+ throw new Error("Silgi instance is unavailable!");
804
+ }
805
+ return instance;
806
+ }
807
+ function normalizeResult(result) {
808
+ if (Array.isArray(result)) {
809
+ return [...result];
810
+ }
811
+ if (result && typeof result === "object") {
812
+ if (Object.keys(result).every((key) => !Number.isNaN(Number(key)))) {
813
+ return Object.values(result);
814
+ }
815
+ return { ...result };
816
+ }
817
+ return result;
818
+ }
819
+
820
+ var SilgiErrorCode = /* @__PURE__ */ ((SilgiErrorCode2) => {
821
+ SilgiErrorCode2["AUTH_UNAUTHORIZED"] = "AUTH_UNAUTHORIZED";
822
+ SilgiErrorCode2["AUTH_MISSING_CONTEXT"] = "AUTH_MISSING_CONTEXT";
823
+ SilgiErrorCode2["AUTH_INVALID_CONTEXT"] = "AUTH_INVALID_CONTEXT";
824
+ SilgiErrorCode2["AUTH_PERMISSION_DENIED"] = "AUTH_PERMISSION_DENIED";
825
+ SilgiErrorCode2["PLUGIN_ERROR"] = "PLUGIN_ERROR";
826
+ SilgiErrorCode2["METHOD_NOT_FOUND"] = "METHOD_NOT_FOUND";
827
+ SilgiErrorCode2["EXECUTION_ERROR"] = "EXECUTION_ERROR";
828
+ SilgiErrorCode2["CACHE_ERROR"] = "CACHE_ERROR";
829
+ SilgiErrorCode2["PLUGIN_ALREADY_EXISTS"] = "PLUGIN_ALREADY_EXISTS";
830
+ SilgiErrorCode2["PLUGIN_NOT_FOUND"] = "PLUGIN_NOT_FOUND";
831
+ SilgiErrorCode2["PLUGIN_INIT_ERROR"] = "PLUGIN_INIT_ERROR";
832
+ return SilgiErrorCode2;
833
+ })(SilgiErrorCode || {});
834
+ class SilgiError extends Error {
835
+ code;
836
+ details;
837
+ meta;
838
+ timestamp;
839
+ cause;
840
+ constructor(options) {
841
+ super(options.message);
842
+ this.name = "SilgiError";
843
+ this.code = options.code;
844
+ this.details = options.details;
845
+ this.meta = options.meta;
846
+ this.cause = options.cause;
847
+ this.timestamp = Date.now();
848
+ if (Error.captureStackTrace) {
849
+ Error.captureStackTrace(this, this.constructor);
850
+ }
851
+ }
852
+ // Improve error formatting
853
+ toString() {
854
+ let str = `${this.name} [${this.code}]: ${this.message}`;
855
+ if (this.details) {
856
+ str += `
857
+ Details: ${JSON.stringify(this.details, null, 2)}`;
858
+ }
859
+ if (this.meta) {
860
+ str += `
861
+ Meta: ${JSON.stringify(this.meta, null, 2)}`;
862
+ }
863
+ if (this.stack) {
864
+ str += `
865
+ ${this.stack}`;
866
+ }
867
+ return str;
868
+ }
869
+ toJSON() {
870
+ return {
871
+ name: this.name,
872
+ code: this.code,
873
+ message: this.message,
874
+ details: this.details,
875
+ meta: this.meta,
876
+ timestamp: this.timestamp,
877
+ stack: this.stack
878
+ };
879
+ }
880
+ static createFrom(error, code = "UNKNOWN_ERROR") {
881
+ if (error instanceof SilgiError) {
882
+ return error;
883
+ }
884
+ return new SilgiError({
885
+ code,
886
+ message: error instanceof Error ? error.message : String(error),
887
+ cause: error instanceof Error ? error : undefined
888
+ });
889
+ }
890
+ static isSilgiError(error) {
891
+ return error instanceof SilgiError;
892
+ }
893
+ }
894
+
895
+ function uriParseError(message, code) {
896
+ throw new SilgiError({
897
+ code: `URI_PARSE_ERROR_${code}`,
898
+ message
899
+ });
900
+ }
901
+ function parseURI(uri, uris) {
902
+ if (!uri)
903
+ throw uriParseError("URI cannot be empty", "EMPTY_URI");
904
+ else if (!uris)
905
+ throw uriParseError("URIs is not nullable", "NULL_URIS");
906
+ const cleanUri = uri.replace(/^\/*(srn\/)?/, "").replace(/\/*$/, "");
907
+ const [path, queryString] = cleanUri.split("?");
908
+ const parts = path.split("/");
909
+ const query = queryString ? Object.fromEntries(
910
+ queryString.split("&").map((param) => param.split("="))
911
+ ) : undefined;
912
+ const method = query?.method ? query?.method.toLowerCase() : undefined;
913
+ if (method && parts.length < 3 || !method && parts.length < 4)
914
+ throw uriParseError("Invalid URI format lengt", "INVALID_FORMAT");
915
+ const namespaceName = parts[0];
916
+ const serviceName = parts[1];
917
+ const methodName = method || parts[2];
918
+ const actionName = method ? parts[2] : parts[3];
919
+ if (!namespaceName || !serviceName || !methodName || !actionName)
920
+ throw uriParseError("Invalid URI format", "INVALID_FORMAT");
921
+ const hasParameters = parts.length > 4;
922
+ const baseUri = `${namespaceName}/${serviceName}/${methodName}/${actionName}`;
923
+ const template = uris[baseUri];
924
+ if (template === "") {
925
+ if (hasParameters)
926
+ throw uriParseError("No parameters expected for this route", "UNEXPECTED_PARAMS");
927
+ } else if (!template) {
928
+ throw uriParseError("No route found for URI", "ROUTE_NOT_FOUND");
929
+ }
930
+ const routeTemplate = typeof template === "string" ? template : template.pattern;
931
+ const validators = typeof template === "string" ? undefined : template.validators;
932
+ const routerParams = {};
933
+ if (routeTemplate === "") {
934
+ if (parts.length > 4)
935
+ throw uriParseError("No parameters expected for this route", "UNEXPECTED_PARAMS");
936
+ } else {
937
+ const templateParts = routeTemplate.split("/").filter(Boolean);
938
+ const paramValues = parts.slice(4);
939
+ let valueIndex = 0;
940
+ templateParts.forEach((part) => {
941
+ if (part.startsWith(":")) {
942
+ const paramName = part.substring(1);
943
+ const paramValue = paramValues[valueIndex];
944
+ if (validators?.[paramName] && paramValue) {
945
+ if (!validators[paramName](paramValue)) {
946
+ throw uriParseError(`Invalid value for parameter ${paramName}`, "INVALID_PARAM_VALUE");
947
+ }
948
+ }
949
+ routerParams[paramName] = paramValue || undefined;
950
+ valueIndex++;
951
+ } else if (part && part === paramValues[valueIndex]) {
952
+ valueIndex++;
953
+ }
954
+ });
955
+ }
956
+ return {
957
+ namespaceName,
958
+ serviceName,
959
+ methodName,
960
+ actionName,
961
+ raw: cleanUri,
962
+ parts: [namespaceName, serviceName, methodName, actionName],
963
+ routerParams,
964
+ query,
965
+ uri: baseUri
966
+ };
967
+ }
968
+
969
+ async function findAction(silgi, uri) {
970
+ const { parts } = parseURI(uri, silgi.uris);
971
+ let result = silgi.services;
972
+ for (const part of parts) {
973
+ if (result && Object.prototype.hasOwnProperty.call(result, part)) {
974
+ result = Object.assign({}, result[part]);
975
+ } else {
976
+ console.error("Property not found:", part);
977
+ break;
978
+ }
979
+ }
980
+ return result;
981
+ }
982
+ async function scanAction(silgi) {
983
+ for (const [key, _value] of Object.entries(silgi.uris)) {
984
+ const segments = key.split("/").filter(Boolean);
985
+ if (segments.length !== 4) {
986
+ console.error(`Invalid URI format for key "${key}". URI must have exactly 4 segments in format: namespace/service/method/action`);
987
+ continue;
988
+ }
989
+ const [namespace, service, method, action] = segments;
990
+ if (!namespace || !service || !method || !action) {
991
+ console.error(`Invalid URI segments for key "${key}". All segments must be non-empty`);
992
+ continue;
993
+ }
994
+ const handler = await findAction(silgi, key);
995
+ silgi.scannedHandlers.set(key, handler);
996
+ }
997
+ }
998
+
999
+ async function createStorage(silgi) {
1000
+ const storage = createStorage$1();
1001
+ const mounts = klona$1({
1002
+ ...silgi.options.storage,
1003
+ ...silgi.options.devStorage
1004
+ });
1005
+ for (const [path, opts] of Object.entries(mounts)) {
1006
+ if (opts.driver) {
1007
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
1008
+ storage.mount("/memory:cache", memoryDriver());
1009
+ storage.mount(path, driver(opts));
1010
+ } else {
1011
+ silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
1012
+ }
1013
+ }
1014
+ return storage;
1015
+ }
1016
+ function useStorage(base = "/memory:cache") {
1017
+ const silgi = useSilgi();
1018
+ return base ? prefixStorage(silgi.storage, base) : silgi.storage;
1019
+ }
1020
+ async function generateStorageKey(params) {
1021
+ const {
1022
+ operation,
1023
+ input,
1024
+ keyGenerator,
1025
+ requestId,
1026
+ storageOptions
1027
+ } = params;
1028
+ const cacheScopePrefix = storageOptions?.scope === "request" ? "req" : "global";
1029
+ const parts = [
1030
+ cacheScopePrefix,
1031
+ // Always include scope prefix first
1032
+ operation.namespaceName,
1033
+ operation.serviceName,
1034
+ operation.methodName
1035
+ ].filter(Boolean);
1036
+ if (storageOptions?.scope === "request") {
1037
+ if (!requestId) {
1038
+ throw new SilgiError({
1039
+ code: "CACHE_ERROR",
1040
+ message: "Request ID is required for request-scoped cache"
1041
+ });
1042
+ }
1043
+ parts.push(requestId);
1044
+ }
1045
+ if (keyGenerator) {
1046
+ const customKey = await Promise.resolve(keyGenerator(input));
1047
+ parts.push(customKey);
1048
+ } else {
1049
+ parts.push(typeof input === "object" ? JSON.stringify(input) : String(input));
1050
+ }
1051
+ return Buffer.from(parts.join(":")).toString("base64");
1052
+ }
1053
+
1054
+ async function runSilgiPlugins(silgi) {
1055
+ for (const plugin of silgi.plugins) {
1056
+ try {
1057
+ await plugin(silgi);
1058
+ } catch (error) {
1059
+ silgi.captureError(error, { tags: ["plugin"] });
1060
+ throw error;
1061
+ }
1062
+ }
1063
+ }
1064
+ async function createSilgi(config) {
1065
+ const hooks = createHooks();
1066
+ await applyDefaults(SilgiConfigSchema, config.options);
1067
+ const silgi = {
1068
+ schemas: config.schemas,
1069
+ services: config.services,
1070
+ shared: config.shared,
1071
+ uris: config.uris,
1072
+ modulesURIs: config.modulesURIs,
1073
+ scannedHandlers: /* @__PURE__ */ new Map(),
1074
+ plugins: config.plugins ?? [],
1075
+ framework: config.framework,
1076
+ storage: undefined,
1077
+ options: config.options,
1078
+ hooks,
1079
+ callHook: hooks.callHook,
1080
+ addHooks: hooks.addHooks,
1081
+ hook: hooks.hook,
1082
+ ready: () => {
1083
+ return hooks.callHook("ready", silgi);
1084
+ },
1085
+ close: () => hooks.callHook("close", silgi),
1086
+ logger: createConsola(defu$1(config.options.consolaOptions, {
1087
+ tag: "silgi"
1088
+ })).withTag("silgi"),
1089
+ captureError: (error, context = {}) => {
1090
+ const promise = hooks.callHookParallel("error", error, context).catch((error_) => {
1091
+ console.error("Error while capturing another error", error_);
1092
+ });
1093
+ if (context.event && isEvent(context.event)) {
1094
+ const errors = context.event.context.nitro?.errors;
1095
+ if (errors) {
1096
+ errors.push({ error, context });
1097
+ }
1098
+ if (context.event.waitUntil) {
1099
+ context.event.waitUntil(promise);
1100
+ }
1101
+ }
1102
+ }
1103
+ };
1104
+ await runSilgiPlugins(silgi);
1105
+ await scanAction(silgi);
1106
+ silgi.storage = await createStorage(silgi);
1107
+ silgi.shared.storage = (...data) => {
1108
+ return useStorage(...data);
1109
+ };
1110
+ if (silgiCtx.tryUse()) {
1111
+ silgiCtx.unset();
1112
+ silgiCtx.set(silgi);
1113
+ } else {
1114
+ silgiCtx.set(silgi);
1115
+ silgi.hook("close", () => silgiCtx.unset());
1116
+ }
1117
+ silgi.logger.info("Silgi installed");
1118
+ hooks.hookOnce("close", async () => {
1119
+ hooks.removeAllHooks();
1120
+ await silgi.storage.dispose();
1121
+ });
1122
+ return silgi;
1123
+ }
1124
+
1125
+ function createSilgiFetch(options, localFetch) {
1126
+ return (url, opts = {}) => {
1127
+ opts = typeof options === "function" ? options(opts) : { ...options, ...opts };
1128
+ if (!opts.method)
1129
+ opts.method = "get";
1130
+ const $fetch = getFetch(url, opts, localFetch);
1131
+ return $fetch(fillPath(url, opts?.path), opts);
1132
+ };
1133
+ }
1134
+ function getFetch(url, opts, localFetch) {
1135
+ if (import.meta.server && localFetch) {
1136
+ const isLocalFetch = url[0] === "/" && (!opts.baseURL || opts.baseURL[0] === "/");
1137
+ if (isLocalFetch)
1138
+ return localFetch;
1139
+ }
1140
+ return globalThis.$fetch;
1141
+ }
1142
+ function fillPath(path, params = {}) {
1143
+ for (const [k, v] of Object.entries(params))
1144
+ path = path.replace(`{${k}}`, encodeURIComponent(String(v)));
1145
+ return path;
1146
+ }
1147
+
1148
+ class SchemaParser {
1149
+ options = {
1150
+ debug: false
1151
+ };
1152
+ /**
1153
+ *
1154
+ */
1155
+ constructor(options) {
1156
+ this.options = {
1157
+ ...this.options,
1158
+ ...options
1159
+ };
1160
+ }
1161
+ parseExports(content, filePath) {
1162
+ const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
1163
+ if (this.options.debug)
1164
+ writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
1165
+ return {
1166
+ exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
1167
+ parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
1168
+ // parsePlugin: (path: string) => this.parsePlugin(ast, path),
1169
+ };
1170
+ }
1171
+ parseVariableDeclaration(ast) {
1172
+ return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
1173
+ }
1174
+ parseTSInterfaceDeclaration(ast) {
1175
+ return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
1176
+ }
1177
+ parseTypeDeclarations(ast, find = "", path = "") {
1178
+ const data = [];
1179
+ for (const item of this.parseVariableDeclaration(ast)) {
1180
+ for (const declaration of item.declaration.declarations) {
1181
+ if (declaration.init.callee?.name === find) {
1182
+ const options = {};
1183
+ if (declaration.init.arguments) {
1184
+ for (const argument of declaration.init.arguments) {
1185
+ for (const propertie of argument.properties) {
1186
+ if (propertie.key.name === "name")
1187
+ options.pluginName = propertie.value.value;
1188
+ }
1189
+ }
1190
+ }
1191
+ for (const key in declaration.init.properties) {
1192
+ const property = declaration.init.properties[key];
1193
+ if (property.type === "ObjectProperty") {
1194
+ if (property.key.name === "options") {
1195
+ for (const key2 in property.value.properties) {
1196
+ const option = property.value.properties[key2];
1197
+ if (option.type === "ObjectProperty") {
1198
+ options[option.key.name] = option.value.value;
1199
+ }
1200
+ }
1201
+ }
1202
+ }
1203
+ }
1204
+ options.type = false;
1205
+ data.push({
1206
+ exportName: declaration.id.name,
1207
+ options,
1208
+ // object: declaration.init,
1209
+ path
1210
+ });
1211
+ }
1212
+ }
1213
+ }
1214
+ return data;
1215
+ }
1216
+ parseInterfaceDeclarations(ast, find = "", path = "") {
1217
+ const data = [];
1218
+ for (const item of this.parseTSInterfaceDeclaration(ast)) {
1219
+ if (!item?.declaration?.extends)
1220
+ continue;
1221
+ for (const declaration of item?.declaration?.extends) {
1222
+ if (declaration.expression.name === find) {
1223
+ const options = {};
1224
+ options.type = true;
1225
+ data.push({
1226
+ exportName: item.declaration.id.name,
1227
+ options,
1228
+ // object: declaration.init,
1229
+ path
1230
+ });
1231
+ }
1232
+ }
1233
+ }
1234
+ return data;
1235
+ }
1236
+ // private parsePlugin(ast: any, path: string = '') {
1237
+ // const data = {
1238
+ // export: [],
1239
+ // name: '',
1240
+ // path: '',
1241
+ // } as DataTypePlugin
1242
+ // for (const item of this.parseVariableDeclaration(ast)) {
1243
+ // for (const declaration of item.declaration.declarations) {
1244
+ // if (declaration.init.callee?.name === 'defineSilgiModule') {
1245
+ // if (declaration.init.arguments) {
1246
+ // for (const argument of declaration.init.arguments) {
1247
+ // for (const propertie of argument.properties) {
1248
+ // if (propertie.key.name === 'name')
1249
+ // data.name = propertie.value.value
1250
+ // }
1251
+ // }
1252
+ // }
1253
+ // data.export.push({
1254
+ // name: data.name,
1255
+ // as: camelCase(`${data.name}DefineSilgiModule`),
1256
+ // type: false,
1257
+ // })
1258
+ // }
1259
+ // }
1260
+ // }
1261
+ // for (const item of this.parseTSInterfaceDeclaration(ast)) {
1262
+ // if (!item?.declaration?.extends)
1263
+ // continue
1264
+ // for (const declaration of item?.declaration?.extends) {
1265
+ // if (declaration.expression.name === 'SilgiModuleOptions') {
1266
+ // data.export.push({
1267
+ // name: item.declaration.id.name,
1268
+ // as: camelCase(`${data.name}SilgiModuleOptions`),
1269
+ // type: true,
1270
+ // })
1271
+ // }
1272
+ // // TODO add other plugins
1273
+ // }
1274
+ // }
1275
+ // data.path = path
1276
+ // return data
1277
+ // }
1278
+ }
1279
+
1280
+ function silgi(event) {
1281
+ return {
1282
+ execute: (uriString, input) => {
1283
+ return execute(uriString, input, event);
1284
+ }
1285
+ };
1286
+ }
1287
+ async function execute(uriString, input, event) {
1288
+ const silgiCtx = useSilgi();
1289
+ if (event) {
1290
+ silgiCtx.callHook("event:before", event);
1291
+ }
1292
+ let success = false;
1293
+ let cached = false;
1294
+ let error;
1295
+ let result;
1296
+ const operation = parseURI(uriString, silgiCtx.uris);
1297
+ if (!operation) {
1298
+ throw new SilgiError({
1299
+ code: "INVALID_URI",
1300
+ message: `Invalid URI: ${uriString}`
1301
+ });
1302
+ }
1303
+ const hookContext = {
1304
+ operation,
1305
+ input,
1306
+ event
1307
+ };
1308
+ try {
1309
+ await silgiCtx.callHook("method:before", {
1310
+ operation,
1311
+ input,
1312
+ event
1313
+ });
1314
+ const handler = silgiCtx.scannedHandlers.get(operation.uri);
1315
+ if (!handler) {
1316
+ return {
1317
+ success: false,
1318
+ error: {
1319
+ code: "METHOD_NOT_FOUND",
1320
+ message: `Method ${String(operation.methodName)} not found`
1321
+ }
1322
+ };
1323
+ }
1324
+ if (event)
1325
+ await silgiCtx.callHook("event:before", event);
1326
+ const cacheData = await cacheExecute(operation.uri, input, operation, handler, event);
1327
+ await callModules(operation, handler, input, result, event);
1328
+ if (cacheData?.success) {
1329
+ result = cacheData.data;
1330
+ success = cacheData.success;
1331
+ cached = cacheData.cached;
1332
+ } else {
1333
+ const router = {
1334
+ params: operation.routerParams,
1335
+ query: operation.query
1336
+ };
1337
+ silgiCtx.shared.silgi = (_event) => silgi(_event || event);
1338
+ result = await handler?.handler(router, input, silgiCtx.shared, event);
1339
+ success = true;
1340
+ }
1341
+ await silgiCtx.callHook("method:after", {
1342
+ operation,
1343
+ input,
1344
+ event,
1345
+ result,
1346
+ success
1347
+ });
1348
+ if (!cached) {
1349
+ if (success && cacheData?.cachedKey && handler.storage) {
1350
+ await useStorage(handler.storage.base).setItem(cacheData.cachedKey, result, handler.storage.options);
1351
+ }
1352
+ }
1353
+ return { success: true, data: normalizeResult(result), cached };
1354
+ } catch (err) {
1355
+ error = err instanceof Error ? err : new Error("Unknown error");
1356
+ if (error instanceof SilgiError) {
1357
+ return {
1358
+ success: false,
1359
+ error: {
1360
+ code: error.code,
1361
+ message: error.message,
1362
+ details: error.details
1363
+ }
1364
+ };
1365
+ }
1366
+ await silgiCtx.callHook("method:error", {
1367
+ ...hookContext,
1368
+ error,
1369
+ timestamp: Date.now()
1370
+ });
1371
+ return {
1372
+ success: false,
1373
+ error: {
1374
+ code: SilgiErrorCode.EXECUTION_ERROR,
1375
+ message: error.message || String(error)
1376
+ }
1377
+ };
1378
+ }
1379
+ }
1380
+ async function callModules(operation, handler, input, result, event) {
1381
+ useSilgi();
1382
+ if (!handler.modules)
1383
+ return;
1384
+ for (const [moduleKey, config] of Object.entries(handler.modules)) {
1385
+ if (moduleKey) {
1386
+ if (module) ;
1387
+ }
1388
+ }
1389
+ }
1390
+ async function cacheExecute(uriString, input, operation, handler, event) {
1391
+ if (!handler.storage)
1392
+ return;
1393
+ const cacheKey = handler.storage ? await generateStorageKey({
1394
+ operation,
1395
+ input,
1396
+ keyGenerator: handler.storage.key,
1397
+ storageOptions: handler.storage,
1398
+ requestId: event?.requestId
1399
+ }) : null;
1400
+ if (cacheKey) {
1401
+ const cachedResult = await useStorage(handler.storage.base).getItem(cacheKey);
1402
+ if (cachedResult !== null) {
1403
+ return {
1404
+ success: true,
1405
+ data: normalizeResult(cachedResult),
1406
+ cached: true,
1407
+ cachedKey: cacheKey
1408
+ };
1409
+ }
1410
+ }
1411
+ return {
1412
+ success: false,
1413
+ data: null,
1414
+ cached: false,
1415
+ cachedKey: cacheKey
1416
+ };
1417
+ }
1418
+
1419
+ function merge(items) {
1420
+ return Object.assign({}, ...Array.isArray(items) ? items : [items]);
1421
+ }
1422
+ function mergeSchemas(typesOrArray) {
1423
+ return merge(typesOrArray);
1424
+ }
1425
+ function mergeServices(servicesOrArray) {
1426
+ return merge(servicesOrArray);
1427
+ }
1428
+ function mergeShared(sharedOrArray) {
1429
+ return merge(sharedOrArray);
1430
+ }
1431
+
1432
+ function createSchema(silgiType) {
1433
+ return silgiType;
1434
+ }
1435
+
1436
+ function createService(variables) {
1437
+ return variables;
1438
+ }
1439
+
1440
+ function createShared(shared) {
1441
+ return shared;
1442
+ }
1443
+
1444
+ export { SchemaParser, SilgiError, createSchema, createService, createShared, createSilgi, createSilgiFetch, createStorage, loadOptions, mergeSchemas, mergeServices, mergeShared, parseURI, silgi, silgiGenerateType, useSilgi };