silgi 0.30.2 → 0.30.4

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.
@@ -0,0 +1,2374 @@
1
+ import consola, { consola as consola$1 } from 'consola';
2
+ import { createHooks, createDebugger } from 'hookable';
3
+ import { resolve, join, relative, dirname, basename, extname, isAbsolute } from 'pathe';
4
+ import { useSilgiCLI, replaceRuntimeValues, silgiCLICtx, autoImportTypes } from 'silgi';
5
+ import { isPresents, addTemplate, addCoreFile, relativeWithDot, hash, resolveAlias, directoryToURL, hasError, removeExtension, addImports, baseHeaderBannerComment, writeFile, parseServices, normalizeTemplate, useLogger, resolveSilgiPath, hasSilgiModule, genEnsureSafeVar, toArray, isDirectory } from 'silgi/kit';
6
+ import { runtimeDir } from 'silgi/runtime/meta';
7
+ import { scanExports, createUnimport, toExports } from 'unimport';
8
+ import { c as createRouteRules } from '../_chunks/routeRules.mjs';
9
+ import * as p from '@clack/prompts';
10
+ import { existsSync, promises, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
11
+ import * as dotenv from 'dotenv';
12
+ import { findTypeExports, findExports, resolvePath, parseNodeModulePath, lookupNodeModuleSubpath } from 'mlly';
13
+ import { createJiti } from 'dev-jiti';
14
+ import { h as hasInstalledModule } from './compatibility.mjs';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { defu } from 'defu';
17
+ import { resolveModuleURL } from 'exsolve';
18
+ import { isRelative, withTrailingSlash } from 'ufo';
19
+ import { readdir, readFile } from 'node:fs/promises';
20
+ import { globby } from 'globby';
21
+ import ignore from 'ignore';
22
+ import { parseSync } from '@oxc-parser/wasm';
23
+ import { genImport, genTypeImport, genObjectFromRawEntries, genObjectFromRaw, genObjectFromValues, genAugmentation } from 'knitwork';
24
+ import { klona } from 'klona';
25
+ import { useSilgiRuntimeConfig, initRuntimeConfig } from 'silgi/runtime';
26
+ import { createStorage, builtinDrivers } from 'unstorage';
27
+ import { snakeCase } from 'scule';
28
+ import { l as loadOptions, s as silgiGenerateType } from './types.mjs';
29
+ import { generateDTS } from 'apiful/openapi';
30
+ import { u as useSilgiCLI$1 } from '../_chunks/silgiApp.mjs';
31
+ import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
32
+ import { generateTypes, resolveSchema } from 'untyped';
33
+
34
+ async function setupDotenv(options) {
35
+ const targetEnvironment = options.env ?? process.env;
36
+ const environment = await loadDotenv({
37
+ cwd: options.cwd,
38
+ fileName: options.fileName ?? ".env",
39
+ env: targetEnvironment,
40
+ interpolate: options.interpolate ?? true
41
+ });
42
+ for (const key in environment) {
43
+ if (!key.startsWith("_") && targetEnvironment[key] === void 0) {
44
+ targetEnvironment[key] = environment[key];
45
+ }
46
+ }
47
+ return environment;
48
+ }
49
+ async function loadDotenv(options) {
50
+ const environment = /* @__PURE__ */ Object.create(null);
51
+ const dotenvFile = resolve(options.cwd, options.fileName);
52
+ if (existsSync(dotenvFile)) {
53
+ const parsed = dotenv.parse(await promises.readFile(dotenvFile, "utf8"));
54
+ Object.assign(environment, parsed);
55
+ }
56
+ if (!options.env?._applied) {
57
+ Object.assign(environment, options.env);
58
+ environment._applied = true;
59
+ }
60
+ if (options.interpolate) {
61
+ interpolate(environment);
62
+ }
63
+ return environment;
64
+ }
65
+ function interpolate(target, source = {}, parse = (v) => v) {
66
+ function getValue(key) {
67
+ return source[key] === void 0 ? target[key] : source[key];
68
+ }
69
+ function interpolate2(value, parents = []) {
70
+ if (typeof value !== "string") {
71
+ return value;
72
+ }
73
+ const matches = value.match(/(.?\$\{?[\w:]*\}?)/g) || [];
74
+ return parse(
75
+ matches.reduce((newValue, match) => {
76
+ const parts = /(.?)\$\{?([\w:]+)?\}?/.exec(match) || [];
77
+ const prefix = parts[1];
78
+ let value2, replacePart;
79
+ if (prefix === "\\") {
80
+ replacePart = parts[0] || "";
81
+ value2 = replacePart.replace(String.raw`\$`, "$");
82
+ } else {
83
+ const key = parts[2];
84
+ replacePart = (parts[0] || "").slice(prefix.length);
85
+ if (parents.includes(key)) {
86
+ console.warn(
87
+ `Please avoid recursive environment variables ( loop: ${parents.join(
88
+ " > "
89
+ )} > ${key} )`
90
+ );
91
+ return "";
92
+ }
93
+ value2 = getValue(key);
94
+ value2 = interpolate2(value2, [...parents, key]);
95
+ }
96
+ return value2 === void 0 ? newValue : newValue.replace(replacePart, value2);
97
+ }, value)
98
+ );
99
+ }
100
+ for (const key in target) {
101
+ target[key] = interpolate2(getValue(key));
102
+ }
103
+ }
104
+
105
+ let initialized = false;
106
+ async function prepareEnv(silgiConfig) {
107
+ if (initialized)
108
+ return;
109
+ initialized = true;
110
+ const customEnvironments = silgiConfig.environments;
111
+ const environment = silgiConfig.activeEnvironment ? silgiConfig.activeEnvironment : await p.select({
112
+ message: "Select an environment",
113
+ options: customEnvironments?.length > 0 ? customEnvironments.map((env) => ({
114
+ label: env.fileName,
115
+ value: env.fileName
116
+ })) : [
117
+ { label: "Development (.env)", value: ".env" },
118
+ { label: "Docker (.env.docker)", value: "docker" },
119
+ { label: "Staging (.env.staging)", value: "staging" },
120
+ { label: "Testing (.env.testing)", value: "testing" },
121
+ { label: "Production (.env.prod)", value: "prod" }
122
+ ]
123
+ });
124
+ const findEnv = customEnvironments?.find((env) => env.fileName === environment);
125
+ if (findEnv) {
126
+ await setupDotenv({
127
+ cwd: findEnv.cwd || silgiConfig.rootDir,
128
+ interpolate: findEnv.interpolate,
129
+ fileName: findEnv.fileName,
130
+ env: findEnv.env
131
+ });
132
+ } else {
133
+ await setupDotenv({
134
+ cwd: silgiConfig.rootDir,
135
+ interpolate: true,
136
+ fileName: environment === ".env" ? ".env" : `.env.${environment}`
137
+ });
138
+ }
139
+ }
140
+
141
+ async function emptyFramework(silgi) {
142
+ if (silgi.options.preset === "npm-package" || !silgi.options.preset) {
143
+ silgi.hook("after:schema.ts", (data) => {
144
+ data.unshift("type FrameworkContextExtends = {}");
145
+ });
146
+ }
147
+ }
148
+
149
+ async function h3Framework(silgi, skip = false) {
150
+ if (!isPresents(["h3"]) && skip === false)
151
+ return;
152
+ if (isPresents(["h3"])) {
153
+ silgi.hook("after:schema.ts", (data) => {
154
+ data.unshift("type FrameworkContextExtends = NitroApp");
155
+ });
156
+ }
157
+ silgi.hook("before:schema.ts", (data) => {
158
+ data.addImportItemType([
159
+ {
160
+ imports: [
161
+ {
162
+ name: "H3Event"
163
+ }
164
+ ],
165
+ specifier: "h3"
166
+ },
167
+ {
168
+ imports: [
169
+ {
170
+ name: "NitroApp"
171
+ }
172
+ ],
173
+ specifier: "nitropack/types"
174
+ }
175
+ ]);
176
+ data.events.push({
177
+ key: "H3Event",
178
+ value: "H3Event",
179
+ extends: true,
180
+ isSilgiContext: false
181
+ });
182
+ });
183
+ silgi.hook("prepare:types", (opts) => {
184
+ addTemplate({
185
+ filename: "types/h3.d.ts",
186
+ where: ".silgi",
187
+ getContents: () => {
188
+ return [
189
+ "import type { SilgiRuntimeContext } from 'silgi/types'",
190
+ "",
191
+ 'declare module "h3" {',
192
+ " interface H3EventContext extends SilgiRuntimeContext {}",
193
+ "}",
194
+ ""
195
+ ].join("\n");
196
+ }
197
+ });
198
+ opts.references.push({ path: "./h3.d.ts" });
199
+ });
200
+ addCoreFile({
201
+ before: ({ silgiConfigs }) => {
202
+ silgiConfigs.push({
203
+ captureError: `(silgi, error, context = {}) => {
204
+ const promise = silgi.hooks
205
+ .callHookParallel('error', silgi, error, context)
206
+ .catch((error_) => {
207
+ console.error('Error while capturing another error', error_)
208
+ })
209
+
210
+ if (context.event && isEvent(context.event)) {
211
+ const errors = context.event.context.nitro?.errors
212
+ if (errors) {
213
+ errors.push({ error, context })
214
+ }
215
+ if (context.event.waitUntil) {
216
+ context.event.waitUntil(promise)
217
+ }
218
+ }
219
+ }`
220
+ });
221
+ }
222
+ });
223
+ if (silgi.options.imports !== false) {
224
+ silgi.options.imports.presets ??= [];
225
+ }
226
+ }
227
+
228
+ async function nitroFramework(silgi, skip = false) {
229
+ if (!isPresents(["nitro"]) && skip === false)
230
+ return;
231
+ silgi.hook("before:schema.ts", (data) => {
232
+ data.addImportItemType({
233
+ imports: [
234
+ {
235
+ name: "NitroApp"
236
+ }
237
+ ],
238
+ specifier: "nitropack/types"
239
+ });
240
+ });
241
+ silgi.hook("after:schema.ts", (data) => {
242
+ data.unshift("type FrameworkContextExtends = NitroApp");
243
+ });
244
+ silgi.options.plugins.push({
245
+ packageImport: "silgi/runtime/internal/nitro",
246
+ path: join(runtimeDir, "internal/nitro")
247
+ });
248
+ silgi.hook("prepare:types", (opts) => {
249
+ addTemplate({
250
+ filename: "types/nitro.d.ts",
251
+ where: ".silgi",
252
+ getContents: () => {
253
+ return [
254
+ "import type { NitroRuntimeConfig } from 'nitropack/types'",
255
+ "",
256
+ 'declare module "silgi/types" {',
257
+ " interface SilgiRuntimeConfig extends NitroRuntimeConfig {}",
258
+ "}",
259
+ ""
260
+ ].join("\n");
261
+ }
262
+ });
263
+ opts.references.push({ path: "./nitro.d.ts" });
264
+ });
265
+ if (silgi.options.imports !== false) {
266
+ silgi.options.imports.presets ??= [];
267
+ }
268
+ await h3Framework(silgi, true);
269
+ }
270
+
271
+ async function nuxtFramework(silgi, skip = false) {
272
+ if (silgi.options.preset !== "nuxt" && skip === false)
273
+ return;
274
+ await nitroFramework(silgi, true);
275
+ }
276
+
277
+ const frameworkSetup = [
278
+ emptyFramework,
279
+ h3Framework,
280
+ nitroFramework,
281
+ nuxtFramework
282
+ ];
283
+
284
+ async function registerModuleExportScan(silgi) {
285
+ silgi.hook("before:schema.ts", async (options) => {
286
+ for (const module of silgi.scanModules) {
287
+ const moduleReExports = [];
288
+ if (!module.entryPath) {
289
+ continue;
290
+ }
291
+ const moduleTypes = await promises.readFile(module.entryPath.replace(/\.mjs$/, "Types.d.ts"), "utf8").catch(() => "");
292
+ const normalisedModuleTypes = moduleTypes.replace(/export\s*\{.*?\}/gs, (match) => match.replace(/\b(type|interface)\b/g, ""));
293
+ for (const e of findTypeExports(normalisedModuleTypes)) {
294
+ moduleReExports.push(e);
295
+ }
296
+ for (const e of findExports(normalisedModuleTypes)) {
297
+ moduleReExports.push(e);
298
+ }
299
+ const hasTypeExport = (name) => moduleReExports.find((exp) => exp.names?.includes(name));
300
+ const configKey = module.meta.configKey;
301
+ const moduleName = module.meta.name || module.meta._packageName;
302
+ const specifier = module.meta._packageName ? moduleName : relativeWithDot(silgi.options.build.typesDir, module.entryPath);
303
+ if (hasTypeExport("ModuleOptions")) {
304
+ const importName = hash(`${configKey}ModuleOptions`);
305
+ options.addImportItemType({
306
+ imports: [
307
+ {
308
+ as: importName,
309
+ name: "ModuleOptions"
310
+ }
311
+ ],
312
+ specifier
313
+ });
314
+ options.options.push({ key: configKey, value: importName });
315
+ }
316
+ if (hasTypeExport("ModuleRuntimeOptions")) {
317
+ const importName = hash(`${configKey}ModuleRuntimeOptions`);
318
+ options.addImportItemType({
319
+ imports: [
320
+ {
321
+ as: importName,
322
+ name: "ModuleRuntimeOptions"
323
+ }
324
+ ],
325
+ specifier
326
+ });
327
+ options.runtimeOptions.push({ key: configKey, value: importName });
328
+ }
329
+ if (hasTypeExport("ModuleRuntimeShareds")) {
330
+ const importName = hash(`${configKey}ModuleRuntimeShareds`);
331
+ options.addImportItemType({
332
+ imports: [
333
+ {
334
+ as: importName,
335
+ name: "ModuleRuntimeShareds"
336
+ }
337
+ ],
338
+ specifier
339
+ });
340
+ options.shareds.push({ key: configKey, value: importName });
341
+ }
342
+ if (hasTypeExport("ModuleEvents")) {
343
+ const importName = hash(`${configKey}ModuleEvents`);
344
+ options.addImportItemType({
345
+ imports: [
346
+ {
347
+ as: importName,
348
+ name: "ModuleEvents"
349
+ }
350
+ ],
351
+ specifier
352
+ });
353
+ options.events.push({ key: configKey, value: importName });
354
+ }
355
+ if (hasTypeExport("ModuleRuntimeContexts")) {
356
+ const importName = hash(`${configKey}ModuleRuntimeContexts`);
357
+ options.addImportItemType({
358
+ imports: [
359
+ {
360
+ as: importName,
361
+ name: "ModuleRuntimeContexts"
362
+ }
363
+ ],
364
+ specifier
365
+ });
366
+ options.contexts.push({ key: configKey, value: importName });
367
+ }
368
+ if (hasTypeExport("ModuleHooks")) {
369
+ const importName = hash(`${configKey}ModuleHooks`);
370
+ options.addImportItemType({
371
+ imports: [
372
+ {
373
+ as: importName,
374
+ name: "ModuleHooks"
375
+ }
376
+ ],
377
+ specifier
378
+ });
379
+ options.hooks.push({ key: configKey, value: importName });
380
+ }
381
+ if (hasTypeExport("ModuleRuntimeHooks")) {
382
+ const importName = hash(`${configKey}RuntimeHooks`);
383
+ options.addImportItemType({
384
+ imports: [
385
+ {
386
+ as: importName,
387
+ name: "ModuleRuntimeHooks"
388
+ }
389
+ ],
390
+ specifier
391
+ });
392
+ options.runtimeHooks.push({ key: configKey, value: importName });
393
+ }
394
+ if (hasTypeExport("ModuleRuntimeActions")) {
395
+ const importName = hash(`${configKey}ModuleRuntimeActions`);
396
+ options.addImportItemType({
397
+ imports: [
398
+ {
399
+ as: importName,
400
+ name: "ModuleRuntimeActions"
401
+ }
402
+ ],
403
+ specifier
404
+ });
405
+ options.actions.push({ key: configKey, value: importName });
406
+ }
407
+ if (hasTypeExport("ModuleRuntimeMethods")) {
408
+ const importName = hash(`${configKey}ModuleRuntimeMethods`);
409
+ options.addImportItemType({
410
+ imports: [
411
+ {
412
+ as: importName,
413
+ name: "ModuleRuntimeMethods"
414
+ }
415
+ ],
416
+ specifier
417
+ });
418
+ options.methods.push({ key: configKey, value: importName });
419
+ }
420
+ if (hasTypeExport("ModuleRuntimeRouteRules")) {
421
+ const importName = hash(`${configKey}ModuleRuntimeRouteRules`);
422
+ options.addImportItemType({
423
+ imports: [
424
+ {
425
+ as: importName,
426
+ name: "ModuleRuntimeRouteRules"
427
+ }
428
+ ],
429
+ specifier
430
+ });
431
+ options.routeRules.push({ key: configKey, value: importName });
432
+ }
433
+ if (hasTypeExport("ModuleRuntimeRouteRulesConfig")) {
434
+ const importName = hash(`${configKey}ModuleRuntimeRouteRulesConfig`);
435
+ options.addImportItemType({
436
+ imports: [
437
+ {
438
+ as: importName,
439
+ name: "ModuleRuntimeRouteRulesConfig"
440
+ }
441
+ ],
442
+ specifier
443
+ });
444
+ options.routeRulesConfig.push({ key: configKey, value: importName });
445
+ }
446
+ }
447
+ });
448
+ }
449
+
450
+ async function loadSilgiModuleInstance(silgiModule) {
451
+ if (typeof silgiModule === "string") {
452
+ throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
453
+ }
454
+ if (typeof silgiModule !== "function") {
455
+ throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
456
+ }
457
+ return { silgiModule };
458
+ }
459
+ async function installModules(silgi, prepare = false) {
460
+ silgi.options.isPreparingModules = prepare;
461
+ const jiti = createJiti(silgi.options.rootDir, {
462
+ alias: silgi.options.alias,
463
+ fsCache: true,
464
+ moduleCache: true
465
+ });
466
+ for (const module of silgi.scanModules) {
467
+ if (hasInstalledModule(module.meta.configKey) && !silgi.options.dev) {
468
+ silgi.logger.info(`Module ${module.meta.configKey} installed`);
469
+ }
470
+ try {
471
+ const silgiModule = module.entryPath !== void 0 ? await jiti.import(module.entryPath, {
472
+ default: true,
473
+ conditions: silgi.options.conditions
474
+ }) : module.module;
475
+ if (silgiModule.name !== "silgiNormalizedModule") {
476
+ silgi.scanModules = silgi.scanModules.filter((m) => m.entryPath !== module.entryPath);
477
+ continue;
478
+ }
479
+ await installModule(silgiModule, silgi, prepare);
480
+ } catch (err) {
481
+ silgi.logger.error(err);
482
+ }
483
+ }
484
+ silgi.options.isPreparingModules = false;
485
+ }
486
+ async function installModule(moduleToInstall, silgi = useSilgiCLI(), inlineOptions, prepare = false) {
487
+ const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
488
+ const res = await silgiModule(inlineOptions || {}, silgi) ?? {};
489
+ if (res === false) {
490
+ return false;
491
+ }
492
+ const metaData = await silgiModule.getMeta?.();
493
+ if (prepare) {
494
+ return metaData;
495
+ }
496
+ const installedModule = silgi.scanModules.find((m) => m.meta.configKey === metaData?.configKey);
497
+ if (installedModule) {
498
+ installedModule.installed = true;
499
+ } else {
500
+ throw new Error(`Module ${metaData?.name} not found`);
501
+ }
502
+ }
503
+
504
+ const MissingModuleMatcher = /Cannot find module\s+['"]?([^'")\s]+)['"]?/i;
505
+ async function _resolveSilgiModule(silgiModule, silgi) {
506
+ let resolvedModulePath;
507
+ let buildTimeModuleMeta = {};
508
+ const jiti = createJiti(silgi.options.rootDir, {
509
+ alias: silgi.options.alias,
510
+ fsCache: true,
511
+ moduleCache: true
512
+ });
513
+ if (typeof silgiModule === "string") {
514
+ silgiModule = resolveAlias(silgiModule, silgi.options.alias);
515
+ if (isRelative(silgiModule)) {
516
+ silgiModule = resolve(silgi.options.rootDir, silgiModule);
517
+ }
518
+ try {
519
+ const src = resolveModuleURL(silgiModule, {
520
+ from: silgi.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
521
+ suffixes: ["silgi", "silgi/index", "module", "module/index", "", "index"],
522
+ extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
523
+ // Maybe add https://github.com/unjs/exsolve/blob/dfff3e9bbc4a3a173a2d56b9b9ff731ab15598be/src/resolve.ts#L7
524
+ // conditions: silgi.options.conditions,
525
+ });
526
+ resolvedModulePath = fileURLToPath(src);
527
+ const resolvedSilgiModule = await jiti.import(src, { default: true });
528
+ if (typeof resolvedSilgiModule !== "function") {
529
+ throw new TypeError(`Nuxt module should be a function: ${silgiModule}.`);
530
+ }
531
+ silgiModule = await jiti.import(src, {
532
+ default: true,
533
+ conditions: silgi.options.conditions
534
+ });
535
+ const moduleMetadataPath = new URL("module.json", src);
536
+ if (existsSync(moduleMetadataPath)) {
537
+ buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
538
+ } else {
539
+ if (typeof silgiModule === "function") {
540
+ const meta = await silgiModule.getMeta?.();
541
+ const _exports = await scanExports(resolvedModulePath, true);
542
+ buildTimeModuleMeta = {
543
+ ...meta,
544
+ exports: _exports.map(({ from, ...rest }) => rest)
545
+ };
546
+ }
547
+ }
548
+ } catch (error) {
549
+ const code = error.code;
550
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
551
+ throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
552
+ }
553
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
554
+ const module = MissingModuleMatcher.exec(error.message)?.[1];
555
+ if (module && !module.includes(silgiModule)) {
556
+ throw new TypeError(`Error while importing module \`${silgiModule}\`: ${error}`);
557
+ }
558
+ }
559
+ }
560
+ }
561
+ if (!buildTimeModuleMeta) {
562
+ throw new Error(`Module ${silgiModule} is not a valid Silgi module`);
563
+ }
564
+ if (typeof silgiModule === "function") {
565
+ if (!buildTimeModuleMeta.configKey) {
566
+ const meta = await silgiModule.getMeta?.();
567
+ buildTimeModuleMeta = {
568
+ ...meta,
569
+ exports: []
570
+ };
571
+ }
572
+ if (silgi.scanModules.some((m) => m.meta?.configKey === buildTimeModuleMeta.configKey)) {
573
+ throw new Error(`Module with key \`${buildTimeModuleMeta.configKey}\` already exists`);
574
+ }
575
+ const options = await silgiModule.getOptions?.() || {};
576
+ if (options) {
577
+ silgi.options._c12.config[buildTimeModuleMeta.configKey] = defu(
578
+ silgi.options._c12.config[buildTimeModuleMeta.configKey] || {},
579
+ options || {}
580
+ );
581
+ } else {
582
+ throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
583
+ }
584
+ silgi.scanModules.push({
585
+ meta: buildTimeModuleMeta,
586
+ entryPath: resolvedModulePath || void 0,
587
+ installed: false,
588
+ options,
589
+ module: silgiModule
590
+ });
591
+ }
592
+ }
593
+ async function scanModules$1(silgi) {
594
+ const _modules = [
595
+ ...silgi.options._modules,
596
+ ...silgi.options.modules
597
+ ];
598
+ for await (const mod of _modules) {
599
+ await _resolveSilgiModule(mod, silgi);
600
+ }
601
+ const moduleMap = new Map(
602
+ silgi.scanModules.map((m) => [m.meta?.configKey, m])
603
+ );
604
+ const graphData = createDependencyGraph(silgi.scanModules);
605
+ const sortedKeys = topologicalSort(graphData);
606
+ const modules = sortedKeys.map((key) => moduleMap.get(key)).filter((module) => Boolean(module));
607
+ silgi.scanModules = modules;
608
+ }
609
+ function createDependencyGraph(modules) {
610
+ const graph = /* @__PURE__ */ new Map();
611
+ const inDegree = /* @__PURE__ */ new Map();
612
+ modules.forEach((module) => {
613
+ const key = module.meta?.configKey;
614
+ if (key) {
615
+ graph.set(key, /* @__PURE__ */ new Set());
616
+ inDegree.set(key, 0);
617
+ }
618
+ });
619
+ modules.forEach((module) => {
620
+ const key = module.meta?.configKey;
621
+ if (!key) {
622
+ return;
623
+ }
624
+ const requiredDeps = module.meta?.requiredDependencies || [];
625
+ const beforeDeps = module.meta?.beforeDependencies || [];
626
+ const afterDeps = module.meta?.afterDependencies || [];
627
+ const processedDeps = /* @__PURE__ */ new Set();
628
+ requiredDeps.forEach((dep) => {
629
+ if (!graph.has(dep)) {
630
+ throw new Error(`Required dependency "${dep}" for module "${key}" is missing`);
631
+ }
632
+ graph.get(dep)?.add(key);
633
+ inDegree.set(key, (inDegree.get(key) || 0) + 1);
634
+ processedDeps.add(dep);
635
+ });
636
+ beforeDeps.forEach((dep) => {
637
+ if (!graph.has(dep)) {
638
+ return;
639
+ }
640
+ graph.get(key)?.add(dep);
641
+ inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
642
+ });
643
+ afterDeps.forEach((dep) => {
644
+ if (processedDeps.has(dep)) {
645
+ return;
646
+ }
647
+ if (!graph.has(dep)) {
648
+ return;
649
+ }
650
+ graph.get(dep)?.add(key);
651
+ inDegree.set(key, (inDegree.get(key) || 0) + 1);
652
+ });
653
+ });
654
+ return { graph, inDegree };
655
+ }
656
+ function findCyclicDependencies(graph) {
657
+ const visited = /* @__PURE__ */ new Set();
658
+ const recursionStack = /* @__PURE__ */ new Set();
659
+ const cycles = [];
660
+ function dfs(node, path = []) {
661
+ visited.add(node);
662
+ recursionStack.add(node);
663
+ path.push(node);
664
+ for (const neighbor of graph.get(node) || []) {
665
+ if (recursionStack.has(neighbor)) {
666
+ const cycleStart = path.indexOf(neighbor);
667
+ if (cycleStart !== -1) {
668
+ cycles.push([...path.slice(cycleStart), neighbor]);
669
+ }
670
+ } else if (!visited.has(neighbor)) {
671
+ dfs(neighbor, [...path]);
672
+ }
673
+ }
674
+ recursionStack.delete(node);
675
+ path.pop();
676
+ }
677
+ for (const node of graph.keys()) {
678
+ if (!visited.has(node)) {
679
+ dfs(node, []);
680
+ }
681
+ }
682
+ return cycles;
683
+ }
684
+ function topologicalSort(graphData) {
685
+ const { graph, inDegree } = graphData;
686
+ const order = [];
687
+ const queue = [];
688
+ for (const [node, degree] of inDegree.entries()) {
689
+ if (degree === 0) {
690
+ queue.push(node);
691
+ }
692
+ }
693
+ while (queue.length > 0) {
694
+ const node = queue.shift();
695
+ order.push(node);
696
+ const neighbors = Array.from(graph.get(node) || []);
697
+ for (const neighbor of neighbors) {
698
+ const newDegree = (inDegree.get(neighbor) || 0) - 1;
699
+ inDegree.set(neighbor, newDegree);
700
+ if (newDegree === 0) {
701
+ queue.push(neighbor);
702
+ }
703
+ }
704
+ }
705
+ if (order.length !== graph.size) {
706
+ const cycles = findCyclicDependencies(graph);
707
+ if (cycles.length > 0) {
708
+ const cycleStr = cycles.map((cycle) => ` ${cycle.join(" -> ")}`).join("\n");
709
+ throw new Error(`Circular dependencies detected:
710
+ ${cycleStr}`);
711
+ } else {
712
+ const unresolvedModules = Array.from(graph.keys()).filter((key) => !order.includes(key));
713
+ throw new Error(`Unable to resolve dependencies for modules: ${unresolvedModules.join(", ")}`);
714
+ }
715
+ }
716
+ return order;
717
+ }
718
+
719
+ function resolveIgnorePatterns(silgi, relativePath) {
720
+ if (!silgi) {
721
+ return [];
722
+ }
723
+ const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
724
+ const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
725
+ if (existsSync(nuxtignoreFile)) {
726
+ const contents = readFileSync(nuxtignoreFile, "utf-8");
727
+ ignorePatterns.push(...contents.trim().split(/\r?\n/));
728
+ }
729
+ return ignorePatterns;
730
+ }
731
+ function isIgnored(pathname, silgi, _stats) {
732
+ if (!silgi) {
733
+ return false;
734
+ }
735
+ if (!silgi._ignore) {
736
+ silgi._ignore = ignore(silgi.options.ignoreOptions);
737
+ silgi._ignore.add(resolveIgnorePatterns(silgi));
738
+ }
739
+ const relativePath = relative(silgi.options.rootDir, pathname);
740
+ if (relativePath[0] === "." && relativePath[1] === ".") {
741
+ return false;
742
+ }
743
+ return !!(relativePath && silgi._ignore.ignores(relativePath));
744
+ }
745
+ function resolveGroupSyntax(group) {
746
+ let groups = [group];
747
+ while (groups.some((group2) => group2.includes("{"))) {
748
+ groups = groups.flatMap((group2) => {
749
+ const [head, ...tail] = group2.split("{");
750
+ if (tail.length) {
751
+ const [body = "", ...rest] = tail.join("{").split("}");
752
+ return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
753
+ }
754
+ return group2;
755
+ });
756
+ }
757
+ return groups;
758
+ }
759
+
760
+ const safeFiles = [
761
+ "silgi/configs",
762
+ "silgi",
763
+ "silgi/rules",
764
+ "silgi/scan",
765
+ "silgi/vfs"
766
+ ];
767
+ class SchemaParser {
768
+ options = {
769
+ debug: false
770
+ };
771
+ /**
772
+ *
773
+ */
774
+ constructor(options) {
775
+ this.options = {
776
+ ...this.options,
777
+ ...options
778
+ };
779
+ }
780
+ parseExports(content, filePath) {
781
+ const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
782
+ if (this.options.debug)
783
+ writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
784
+ return {
785
+ exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
786
+ parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
787
+ // parsePlugin: (path: string) => this.parsePlugin(ast, path),
788
+ };
789
+ }
790
+ parseVariableDeclaration(ast, path) {
791
+ const silgi = useSilgiCLI();
792
+ if (ast.program.body.length === 0) {
793
+ if (safeFiles.find((i) => path.includes(i)))
794
+ return [];
795
+ silgi.errors.push({
796
+ type: "Parser",
797
+ path
798
+ });
799
+ consola.warn("This file has a problem:", path);
800
+ }
801
+ const variableDeclarations = ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
802
+ return variableDeclarations;
803
+ }
804
+ parseTSInterfaceDeclaration(ast, path = "") {
805
+ const silgi = useSilgiCLI();
806
+ if (ast.program.body.length === 0) {
807
+ if (safeFiles.find((i) => path.includes(i)))
808
+ return [];
809
+ silgi.errors.push({
810
+ type: "Parser",
811
+ path
812
+ });
813
+ consola.warn("This file has a problem:", path);
814
+ }
815
+ const interfaceDeclarations = ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
816
+ return interfaceDeclarations;
817
+ }
818
+ parseTypeDeclarations(ast, find = "", path = "") {
819
+ const data = [];
820
+ const variableDeclarations = this.parseVariableDeclaration(ast, path);
821
+ for (const item of variableDeclarations) {
822
+ for (const declaration of item.declaration.declarations) {
823
+ if (declaration.init?.callee?.name === find) {
824
+ const options = {};
825
+ if (declaration.init.arguments) {
826
+ for (const argument of declaration.init.arguments) {
827
+ for (const propertie of argument.properties) {
828
+ if (propertie.key.name === "name")
829
+ options.pluginName = propertie.value.value;
830
+ }
831
+ }
832
+ }
833
+ for (const key in declaration.init.properties) {
834
+ const property = declaration.init.properties[key];
835
+ if (property.type === "ObjectProperty") {
836
+ if (property.key.name === "options") {
837
+ for (const key2 in property.value.properties) {
838
+ const option = property.value.properties[key2];
839
+ if (option.type === "ObjectProperty") {
840
+ options[option.key.name] = option.value.value;
841
+ }
842
+ }
843
+ }
844
+ }
845
+ }
846
+ options.type = false;
847
+ data.push({
848
+ exportName: declaration.id.name,
849
+ options,
850
+ // object: declaration.init,
851
+ path
852
+ });
853
+ }
854
+ }
855
+ }
856
+ return data;
857
+ }
858
+ parseInterfaceDeclarations(ast, find = "", path = "") {
859
+ const data = [];
860
+ for (const item of this.parseTSInterfaceDeclaration(ast, path)) {
861
+ if (!item?.declaration?.extends)
862
+ continue;
863
+ for (const declaration of item?.declaration?.extends) {
864
+ if (declaration.expression.name === find) {
865
+ const options = {};
866
+ options.type = true;
867
+ data.push({
868
+ exportName: item.declaration.id.name,
869
+ options,
870
+ // object: declaration.init,
871
+ path
872
+ });
873
+ }
874
+ }
875
+ }
876
+ return data;
877
+ }
878
+ // private parsePlugin(ast: any, path: string = '') {
879
+ // const data = {
880
+ // export: [],
881
+ // name: '',
882
+ // path: '',
883
+ // } as DataTypePlugin
884
+ // for (const item of this.parseVariableDeclaration(ast)) {
885
+ // for (const declaration of item.declaration.declarations) {
886
+ // if (declaration.init.callee?.name === 'defineSilgiModule') {
887
+ // if (declaration.init.arguments) {
888
+ // for (const argument of declaration.init.arguments) {
889
+ // for (const propertie of argument.properties) {
890
+ // if (propertie.key.name === 'name')
891
+ // data.name = propertie.value.value
892
+ // }
893
+ // }
894
+ // }
895
+ // data.export.push({
896
+ // name: data.name,
897
+ // as: camelCase(`${data.name}DefineSilgiModule`),
898
+ // type: false,
899
+ // })
900
+ // }
901
+ // }
902
+ // }
903
+ // for (const item of this.parseTSInterfaceDeclaration(ast)) {
904
+ // if (!item?.declaration?.extends)
905
+ // continue
906
+ // for (const declaration of item?.declaration?.extends) {
907
+ // if (declaration.expression.name === 'ModuleOptions') {
908
+ // data.export.push({
909
+ // name: item.declaration.id.name,
910
+ // as: camelCase(`${data.name}ModuleOptions`),
911
+ // type: true,
912
+ // })
913
+ // }
914
+ // // TODO add other plugins
915
+ // }
916
+ // }
917
+ // data.path = path
918
+ // return data
919
+ // }
920
+ }
921
+
922
+ async function scanExportFile(silgi) {
923
+ const filePaths = /* @__PURE__ */ new Set();
924
+ const scannedPaths = [];
925
+ const dir = silgi.options.serverDir;
926
+ const files = (await globby(dir, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
927
+ if (files.length) {
928
+ const siblings = await readdir(dirname(dir)).catch(() => []);
929
+ const directory = basename(dir);
930
+ if (!siblings.includes(directory)) {
931
+ const directoryLowerCase = directory.toLowerCase();
932
+ const caseCorrected = siblings.find((sibling) => sibling.toLowerCase() === directoryLowerCase);
933
+ if (caseCorrected) {
934
+ const original = relative(silgi.options.serverDir, dir);
935
+ const corrected = relative(silgi.options.serverDir, join(dirname(dir), caseCorrected));
936
+ consola$1.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`);
937
+ }
938
+ }
939
+ }
940
+ for (const _file of files) {
941
+ const filePath = resolve(dir, _file);
942
+ if (scannedPaths.find((d) => filePath.startsWith(withTrailingSlash(d))) || isIgnored(filePath, silgi)) {
943
+ continue;
944
+ }
945
+ if (filePaths.has(filePath)) {
946
+ continue;
947
+ }
948
+ filePaths.add(filePath);
949
+ if (silgi.options.extensions.includes(extname(filePath))) {
950
+ const parser = new SchemaParser({
951
+ debug: false
952
+ });
953
+ const readfile = await readFile(filePath, "utf-8");
954
+ const { exportVariables, parseInterfaceDeclarations } = parser.parseExports(readfile, filePath);
955
+ const createServices = exportVariables("createService", filePath);
956
+ if (hasError("Parser", silgi)) {
957
+ return;
958
+ }
959
+ const scanTS = [];
960
+ const schemaTS = [];
961
+ if (createServices.length > 0) {
962
+ scanTS.push(...createServices.map(({ exportName, path }) => {
963
+ const randomString = hash(basename(path) + exportName);
964
+ const _name = `_v${randomString}`;
965
+ return { exportName, path, _name, type: "service" };
966
+ }));
967
+ }
968
+ const createSchemas = exportVariables("createSchema", filePath);
969
+ if (hasError("Parser", silgi)) {
970
+ return;
971
+ }
972
+ if (createSchemas.length > 0) {
973
+ scanTS.push(...createSchemas.map(({ exportName, path }) => {
974
+ const randomString = hash(basename(path) + exportName);
975
+ const _name = `_v${randomString}`;
976
+ return { exportName, path, _name, type: "schema" };
977
+ }));
978
+ }
979
+ const createShareds = exportVariables("createShared", filePath);
980
+ if (hasError("Parser", silgi)) {
981
+ return;
982
+ }
983
+ if (createShareds.length > 0) {
984
+ scanTS.push(...createShareds.map(({ exportName, path }) => {
985
+ const randomString = hash(basename(path) + exportName);
986
+ const _name = `_v${randomString}`;
987
+ return { exportName, path, _name, type: "shared" };
988
+ }));
989
+ }
990
+ const sharedsTypes = parseInterfaceDeclarations("ExtendShared", filePath);
991
+ if (hasError("Parser", silgi)) {
992
+ return;
993
+ }
994
+ if (sharedsTypes.length > 0) {
995
+ schemaTS.push(...sharedsTypes.map(({ exportName, path }) => {
996
+ const randomString = hash(basename(path) + exportName);
997
+ const _name = `_v${randomString}`;
998
+ return { exportName, path, _name, type: "shared" };
999
+ }));
1000
+ }
1001
+ const contextTypes = parseInterfaceDeclarations("ExtendContext", filePath);
1002
+ if (hasError("Parser", silgi)) {
1003
+ return;
1004
+ }
1005
+ if (contextTypes.length > 0) {
1006
+ schemaTS.push(...contextTypes.map(({ exportName, path }) => {
1007
+ const randomString = hash(basename(path) + exportName);
1008
+ const _name = `_v${randomString}`;
1009
+ return { exportName, path, _name, type: "context" };
1010
+ }));
1011
+ }
1012
+ silgi.hook("before:scan.ts", (options) => {
1013
+ for (const { exportName, path, _name, type } of scanTS) {
1014
+ if (!path.includes("vfs")) {
1015
+ silgi.options.devServer.watch.push(path);
1016
+ }
1017
+ if (type === "service") {
1018
+ options.services.push(_name);
1019
+ }
1020
+ if (type === "shared") {
1021
+ options.shareds.push(_name);
1022
+ }
1023
+ if (type === "schema") {
1024
+ options.schemas.push(_name);
1025
+ }
1026
+ options.addImportItem({
1027
+ specifier: removeExtension(relativeWithDot(silgi.options.silgi.serverDir, path)),
1028
+ imports: [
1029
+ {
1030
+ name: exportName,
1031
+ as: _name
1032
+ }
1033
+ ]
1034
+ });
1035
+ }
1036
+ });
1037
+ silgi.hook("before:schema.ts", (options) => {
1038
+ for (const { exportName, path, _name, type } of schemaTS) {
1039
+ if (!path.includes("vfs")) {
1040
+ silgi.options.devServer.watch.push(path);
1041
+ }
1042
+ if (type === "shared") {
1043
+ options.shareds.push({
1044
+ key: _name,
1045
+ value: _name
1046
+ });
1047
+ }
1048
+ if (type === "context") {
1049
+ options.contexts.push({
1050
+ key: _name,
1051
+ value: _name
1052
+ });
1053
+ }
1054
+ options.addImportItem({
1055
+ imports: [
1056
+ {
1057
+ name: exportName,
1058
+ as: _name
1059
+ }
1060
+ ],
1061
+ specifier: removeExtension(relativeWithDot(silgi.options.build.typesDir, path))
1062
+ });
1063
+ }
1064
+ });
1065
+ }
1066
+ }
1067
+ }
1068
+
1069
+ function buildUriMap(silgi, currentPath = []) {
1070
+ const uriMap = /* @__PURE__ */ new Map();
1071
+ function traverse(node, path = []) {
1072
+ if (!node || typeof node !== "object")
1073
+ return;
1074
+ if (path.length === 4) {
1075
+ const basePath = path.join("/");
1076
+ let pathString = "";
1077
+ if (node.pathParams) {
1078
+ let paths = null;
1079
+ if (node.pathParams?._def?.typeName !== void 0) {
1080
+ try {
1081
+ const shape = node.pathParams?.shape;
1082
+ paths = shape ? Object.keys(shape) : null;
1083
+ } catch {
1084
+ paths = null;
1085
+ }
1086
+ }
1087
+ if (paths?.length) {
1088
+ pathString = paths.map((p) => `:${p}`).join("/");
1089
+ }
1090
+ }
1091
+ uriMap.set(basePath, pathString);
1092
+ return;
1093
+ }
1094
+ for (const key in node) {
1095
+ if (!["_type", "fields"].includes(key)) {
1096
+ traverse(node[key], [...path, key]);
1097
+ }
1098
+ }
1099
+ }
1100
+ traverse(silgi.schemas, currentPath);
1101
+ silgi.uris = defu(silgi.uris, Object.fromEntries(uriMap));
1102
+ return uriMap;
1103
+ }
1104
+
1105
+ async function readScanFile(silgi) {
1106
+ const path = resolve(silgi.options.silgi.serverDir, "scan.ts");
1107
+ const context = await promises.readFile(path, { encoding: "utf-8" });
1108
+ silgi.unimport = createUnimport(silgi.options.imports || {});
1109
+ await silgi.unimport.init();
1110
+ const injectedResult = await silgi.unimport.injectImports(context, path);
1111
+ if (!injectedResult) {
1112
+ throw new Error("Failed to inject imports");
1113
+ }
1114
+ const jiti = createJiti(silgi.options.rootDir, {
1115
+ fsCache: true,
1116
+ moduleCache: false,
1117
+ debug: silgi.options.debug === true,
1118
+ alias: silgi.options.alias
1119
+ });
1120
+ try {
1121
+ globalThis._silgi_runtime = silgi.options.runtimeConfig;
1122
+ injectedResult.code = `globalThis._silgi_runtime = ${JSON.stringify(silgi.options.runtimeConfig)};
1123
+ ${injectedResult.code}`;
1124
+ injectedResult.code = injectedResult.code.replace(/runtimeConfig: \{\}/, `runtimeConfig: ${JSON.stringify(silgi.options.runtimeConfig)}`);
1125
+ const scanFile = await jiti.evalModule(
1126
+ injectedResult.code,
1127
+ {
1128
+ filename: path,
1129
+ async: true,
1130
+ conditions: silgi.options.conditions
1131
+ },
1132
+ async (data, name) => {
1133
+ return (await silgi.unimport.injectImports(data, name)).code;
1134
+ }
1135
+ );
1136
+ silgi.uris = defu(silgi.uris, scanFile.uris) || {};
1137
+ silgi.schemas = defu(scanFile.schemas, scanFile.uris) || {};
1138
+ silgi.services = defu(scanFile.services, scanFile.uris) || {};
1139
+ silgi.shareds = defu(scanFile.shareds, scanFile.shareds) || {};
1140
+ silgi.modulesURIs = defu(scanFile.modulesURIs, scanFile.modulesURIs) || {};
1141
+ return {
1142
+ context,
1143
+ object: {
1144
+ schemas: scanFile.schemas,
1145
+ uris: scanFile.uris,
1146
+ services: scanFile.services,
1147
+ shareds: scanFile.shareds,
1148
+ modulesURIs: scanFile.modulesURIs
1149
+ },
1150
+ path
1151
+ };
1152
+ } catch (error) {
1153
+ if (silgi.options.debug) {
1154
+ console.error("Failed to read scan.ts file:", error);
1155
+ } else {
1156
+ consola$1.withTag("silgi").error(error);
1157
+ }
1158
+ return {
1159
+ context,
1160
+ object: {
1161
+ schemas: {},
1162
+ uris: {},
1163
+ services: {},
1164
+ shareds: {},
1165
+ modulesURIs: {}
1166
+ },
1167
+ path
1168
+ };
1169
+ }
1170
+ }
1171
+
1172
+ async function prepareScanFile(silgi) {
1173
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
1174
+ imports: [
1175
+ {
1176
+ specifier: "silgi",
1177
+ imports: [
1178
+ {
1179
+ name: "createSilgi"
1180
+ },
1181
+ {
1182
+ name: "createShared"
1183
+ }
1184
+ ]
1185
+ },
1186
+ {
1187
+ specifier: "./configs",
1188
+ imports: [
1189
+ {
1190
+ name: "cliConfigs"
1191
+ }
1192
+ ]
1193
+ }
1194
+ ],
1195
+ typeImports: [
1196
+ {
1197
+ specifier: "silgi/types",
1198
+ imports: [
1199
+ {
1200
+ name: "SilgiRuntimeOptions"
1201
+ },
1202
+ {
1203
+ name: "FrameworkContext"
1204
+ }
1205
+ ]
1206
+ }
1207
+ ]
1208
+ });
1209
+ const scanned = {
1210
+ uris: {},
1211
+ services: [],
1212
+ shareds: [],
1213
+ schemas: [],
1214
+ modulesURIs: {},
1215
+ addImportItem,
1216
+ addImportItemType
1217
+ };
1218
+ if (silgi.uris) {
1219
+ defu(scanned.uris, silgi.uris);
1220
+ }
1221
+ if (silgi.modulesURIs) {
1222
+ scanned.shareds.push(
1223
+ `createShared({
1224
+ modulesURIs,
1225
+ })`
1226
+ );
1227
+ defu(scanned.modulesURIs, silgi.modulesURIs);
1228
+ }
1229
+ await silgi.callHook("before:scan.ts", scanned);
1230
+ if (scanned.services.length > 0) {
1231
+ addImportItem({
1232
+ specifier: "silgi",
1233
+ imports: {
1234
+ name: "mergeServices"
1235
+ }
1236
+ });
1237
+ }
1238
+ if (scanned.shareds.length > 0) {
1239
+ addImportItem({
1240
+ specifier: "silgi",
1241
+ imports: {
1242
+ name: "mergeShared"
1243
+ }
1244
+ });
1245
+ }
1246
+ if (scanned.schemas.length > 0) {
1247
+ addImportItem({
1248
+ specifier: "silgi",
1249
+ imports: {
1250
+ name: "mergeSchemas"
1251
+ }
1252
+ });
1253
+ }
1254
+ const importsContent = [
1255
+ ...genImports.map(({ specifier, imports, options }) => {
1256
+ return genImport(specifier, imports, options);
1257
+ }),
1258
+ ...genTypeImports.map(({ specifier, imports }) => {
1259
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
1260
+ }),
1261
+ ""
1262
+ ];
1263
+ const importData = [
1264
+ `export const uris = ${JSON.stringify(scanned.uris, null, 2)}`,
1265
+ "",
1266
+ `export const modulesURIs = ${JSON.stringify(scanned.modulesURIs, null, 2)}`,
1267
+ "",
1268
+ scanned.schemas.length > 0 ? "export const schemas = mergeSchemas([" : "export const schemas = {",
1269
+ ...scanned.schemas.map((name) => {
1270
+ return ` ${name},`;
1271
+ }),
1272
+ scanned.schemas.length > 0 ? "])" : "}",
1273
+ "",
1274
+ scanned.services.length > 0 ? "export const services = mergeServices([" : "export const services = {",
1275
+ ...scanned.services.map((name) => {
1276
+ return ` ${name},`;
1277
+ }),
1278
+ scanned.services.length > 0 ? "])" : "}",
1279
+ "",
1280
+ scanned.shareds.length > 0 ? "export const shareds = mergeShared([" : "export const shareds = {",
1281
+ ...scanned.shareds.map((name) => {
1282
+ return ` ${name},`;
1283
+ }),
1284
+ scanned.shareds.length > 0 ? "])" : "}",
1285
+ ""
1286
+ ];
1287
+ await silgi.callHook("after:scan.ts", importData);
1288
+ importData.unshift(...importsContent);
1289
+ importData.unshift(...baseHeaderBannerComment);
1290
+ return importData;
1291
+ }
1292
+
1293
+ async function writeScanFiles(silgi) {
1294
+ const data = await prepareScanFile(silgi);
1295
+ if (!silgi.errors.length) {
1296
+ await writeFile(
1297
+ resolve(silgi.options.silgi.serverDir, "scan.ts"),
1298
+ data.join("\n")
1299
+ );
1300
+ }
1301
+ await readScanFile(silgi);
1302
+ buildUriMap(silgi);
1303
+ parseServices(silgi);
1304
+ silgi.hook("before:scan.ts", (file) => {
1305
+ file.uris = {
1306
+ ...file.uris,
1307
+ ...silgi.uris
1308
+ };
1309
+ file.modulesURIs = {
1310
+ ...file.modulesURIs,
1311
+ ...silgi.modulesURIs
1312
+ };
1313
+ });
1314
+ }
1315
+
1316
+ async function createStorageCLI(silgi) {
1317
+ const storage = createStorage();
1318
+ const runtime = useSilgiRuntimeConfig();
1319
+ const mounts = klona({
1320
+ ...silgi.options.storage,
1321
+ ...silgi.options.devStorage
1322
+ });
1323
+ for (const [path, opts] of Object.entries(mounts)) {
1324
+ if (opts.driver) {
1325
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
1326
+ const processedOpts = replaceRuntimeValues({ ...opts }, runtime);
1327
+ storage.mount(path, driver(processedOpts));
1328
+ } else {
1329
+ silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
1330
+ }
1331
+ }
1332
+ return storage;
1333
+ }
1334
+
1335
+ const vueShim = {
1336
+ filename: "delete/testtest.d.ts",
1337
+ where: ".silgi",
1338
+ getContents: ({ app }) => {
1339
+ if (!app.options.typescript.shim) {
1340
+ return "";
1341
+ }
1342
+ return [
1343
+ "declare module '*.vue' {",
1344
+ " import { DefineComponent } from 'vue'",
1345
+ " const component: DefineComponent<{}, {}, any>",
1346
+ " export default component",
1347
+ "}"
1348
+ ].join("\n");
1349
+ }
1350
+ };
1351
+ const pluginsDeclaration = {
1352
+ filename: "delete/testtest1.d.ts",
1353
+ where: ".silgi",
1354
+ getContents: async () => {
1355
+ return `
1356
+ declare module 'nuxt' {
1357
+ interface NuxtApp {
1358
+ $myPlugin: any;
1359
+ }
1360
+ }
1361
+ `;
1362
+ }
1363
+ };
1364
+
1365
+ const defaultTemplates = {
1366
+ __proto__: null,
1367
+ pluginsDeclaration: pluginsDeclaration,
1368
+ vueShim: vueShim
1369
+ };
1370
+
1371
+ const postTemplates = [
1372
+ pluginsDeclaration.filename
1373
+ ];
1374
+ const logger = useLogger("silgi");
1375
+ async function generateApp(app, options = {}) {
1376
+ app.templates = Object.values(defaultTemplates).concat(app.options.build.templates);
1377
+ await app.callHook("app:templates", app);
1378
+ app.templates = app.templates.map((tmpl) => {
1379
+ const dir = tmpl.where === ".silgi" ? app.options.build.dir : tmpl.where === "server" ? app.options.silgi.serverDir : tmpl.where === "client" ? app.options.silgi.clientDir : app.options.silgi.vfsDir;
1380
+ return normalizeTemplate(tmpl, dir);
1381
+ });
1382
+ const filteredTemplates = {
1383
+ pre: [],
1384
+ post: []
1385
+ };
1386
+ for (const template of app.templates) {
1387
+ if (options.filter && !options.filter(template)) {
1388
+ continue;
1389
+ }
1390
+ const key = template.filename && postTemplates.includes(template.filename) ? "post" : "pre";
1391
+ filteredTemplates[key].push(template);
1392
+ }
1393
+ const templateContext = { app };
1394
+ const writes = [];
1395
+ const dirs = /* @__PURE__ */ new Set();
1396
+ const changedTemplates = [];
1397
+ async function processTemplate(template) {
1398
+ const dir = template.where === ".silgi" ? app.options.build.dir : template.where === "server" ? app.options.silgi.serverDir : template.where === "client" ? app.options.silgi.clientDir : app.options.silgi.vfsDir;
1399
+ const fullPath = template.dst || resolve(dir, template.filename);
1400
+ const start = performance.now();
1401
+ const contents = await compileTemplate(template, templateContext).catch((e) => {
1402
+ logger.error(`Could not compile template \`${template.filename}\`.`);
1403
+ logger.error(e);
1404
+ throw e;
1405
+ });
1406
+ template.modified = true;
1407
+ if (template.modified) {
1408
+ changedTemplates.push(template);
1409
+ }
1410
+ const perf = performance.now() - start;
1411
+ const setupTime = Math.round(perf * 100) / 100;
1412
+ if (app.options.debug || setupTime > 500) {
1413
+ logger.info(`Compiled \`${template.filename}\` in ${setupTime}ms`);
1414
+ }
1415
+ if (template.modified && template.write) {
1416
+ dirs.add(dirname(fullPath));
1417
+ if (template.skipIfExists && existsSync(fullPath)) {
1418
+ return;
1419
+ }
1420
+ writes.push(() => writeFileSync(fullPath, contents, "utf8"));
1421
+ }
1422
+ }
1423
+ await Promise.allSettled(filteredTemplates.pre.map(processTemplate));
1424
+ await Promise.allSettled(filteredTemplates.post.map(processTemplate));
1425
+ for (const dir of dirs) {
1426
+ mkdirSync(dir, { recursive: true });
1427
+ }
1428
+ for (const write of writes) {
1429
+ if (!app.errors.length) {
1430
+ write();
1431
+ }
1432
+ }
1433
+ if (changedTemplates.length) {
1434
+ await app.callHook("app:templatesGenerated", app, changedTemplates, options);
1435
+ }
1436
+ }
1437
+ async function compileTemplate(template, ctx) {
1438
+ delete ctx.utils;
1439
+ if (template.src) {
1440
+ try {
1441
+ return await promises.readFile(template.src, "utf-8");
1442
+ } catch (err) {
1443
+ logger.error(`[nuxt] Error reading template from \`${template.src}\``);
1444
+ throw err;
1445
+ }
1446
+ }
1447
+ if (template.getContents) {
1448
+ return template.getContents({
1449
+ ...ctx,
1450
+ options: template.options
1451
+ });
1452
+ }
1453
+ throw new Error(`[nuxt] Invalid template. Templates must have either \`src\` or \`getContents\`: ${JSON.stringify(template)}`);
1454
+ }
1455
+
1456
+ function useCLIRuntimeConfig(silgi) {
1457
+ const safeRuntimeConfig = JSON.parse(JSON.stringify(silgi.options.runtimeConfig));
1458
+ silgi.hook("prepare:configs.ts", (data) => {
1459
+ data.runtimeConfig = safeRuntimeConfig;
1460
+ silgi.options.envOptions = silgi.options.envOptions;
1461
+ });
1462
+ addTemplate({
1463
+ filename: "env.example",
1464
+ write: true,
1465
+ where: ".silgi",
1466
+ getContents() {
1467
+ const flattenedConfig = flattenObject(safeRuntimeConfig);
1468
+ const groupedVars = {};
1469
+ Object.entries(flattenedConfig).forEach(([key, { value, originalPath }]) => {
1470
+ const shouldExclude = silgi.options.codegen.env.safeList.some((safePath) => {
1471
+ if (safePath.length !== originalPath.length)
1472
+ return false;
1473
+ return safePath.every((segment, index) => segment.toLowerCase() === originalPath[index].toLowerCase());
1474
+ });
1475
+ if (shouldExclude)
1476
+ return;
1477
+ if (originalPath.length > 0) {
1478
+ const firstKey = originalPath[0];
1479
+ const categoryName = extractCategoryFromCamel(firstKey);
1480
+ if (!groupedVars[categoryName]) {
1481
+ groupedVars[categoryName] = {};
1482
+ }
1483
+ groupedVars[categoryName][key] = value;
1484
+ } else {
1485
+ if (!groupedVars.OTHER) {
1486
+ groupedVars.OTHER = {};
1487
+ }
1488
+ groupedVars.OTHER[key] = value;
1489
+ }
1490
+ });
1491
+ return Object.entries(groupedVars).map(([category, vars]) => {
1492
+ const varsContent = Object.entries(vars).map(([key, value]) => `${key}=${value}`).join("\n");
1493
+ return `# ${category}
1494
+ ${varsContent}`;
1495
+ }).join("\n\n");
1496
+ }
1497
+ });
1498
+ const _sharedRuntimeConfig = initRuntimeConfig(silgi.options.envOptions, silgi.options.runtimeConfig);
1499
+ silgi.options.runtimeConfig = safeRuntimeConfig;
1500
+ return _sharedRuntimeConfig;
1501
+ }
1502
+ function extractCategoryFromCamel(str) {
1503
+ if (/^[a-z]+[A-Z]/.test(str)) {
1504
+ const matches = str.match(/^([a-z]+)([A-Z][a-z0-9]*)?/);
1505
+ if (matches && matches[2]) {
1506
+ return `${matches[1].toUpperCase()}_${matches[2].toUpperCase()}`;
1507
+ }
1508
+ }
1509
+ return str.toUpperCase();
1510
+ }
1511
+ function flattenObject(obj, prefix = "SILGI", originalPath = []) {
1512
+ return Object.entries(obj).reduce((acc, [key, value]) => {
1513
+ const formattedKey = snakeCase(key).toUpperCase();
1514
+ const newKey = `${prefix}_${formattedKey}`;
1515
+ const newPath = [...originalPath, key];
1516
+ if (typeof value === "object" && value !== null) {
1517
+ Object.assign(acc, flattenObject(value, newKey, newPath));
1518
+ } else {
1519
+ acc[newKey] = { value, originalPath: newPath };
1520
+ }
1521
+ return acc;
1522
+ }, {});
1523
+ }
1524
+
1525
+ const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
1526
+ async function scanAndSyncOptions(silgi) {
1527
+ const scannedModules = await scanModules(silgi);
1528
+ silgi.options.modules = silgi.options.modules || [];
1529
+ for (const modPath of scannedModules) {
1530
+ if (!silgi.options.modules.includes(modPath)) {
1531
+ silgi.options.modules.push(modPath);
1532
+ }
1533
+ }
1534
+ }
1535
+ async function scanModules(silgi) {
1536
+ const files = await scanFiles(silgi, "silgi/modules");
1537
+ return files.map((f) => f.fullPath);
1538
+ }
1539
+ async function scanFiles(silgi, name) {
1540
+ const files = await Promise.all(
1541
+ silgi.options.scanDirs.map((dir) => scanDir(silgi, dir, name))
1542
+ ).then((r) => r.flat());
1543
+ return files;
1544
+ }
1545
+ async function scanDir(silgi, dir, name) {
1546
+ const fileNames = await globby(join(name, GLOB_SCAN_PATTERN), {
1547
+ cwd: dir,
1548
+ dot: true,
1549
+ ignore: silgi.options.ignore,
1550
+ absolute: true
1551
+ });
1552
+ return fileNames.map((fullPath) => {
1553
+ return {
1554
+ fullPath,
1555
+ path: relative(join(dir, name), fullPath)
1556
+ };
1557
+ }).sort((a, b) => a.path.localeCompare(b.path));
1558
+ }
1559
+
1560
+ async function createSilgiCLI(config = {}, opts = {}) {
1561
+ const options = await loadOptions(config, opts);
1562
+ const hooks = createHooks();
1563
+ const silgi = {
1564
+ modulesURIs: {},
1565
+ scannedURIs: /* @__PURE__ */ new Map(),
1566
+ services: {},
1567
+ uris: {},
1568
+ shareds: {},
1569
+ schemas: {},
1570
+ unimport: void 0,
1571
+ options,
1572
+ hooks,
1573
+ errors: [],
1574
+ _requiredModules: {},
1575
+ logger: opts.consola || consola$1.withTag("silgi"),
1576
+ close: () => silgi.hooks.callHook("close", silgi),
1577
+ storage: void 0,
1578
+ scanModules: [],
1579
+ templates: [],
1580
+ callHook: hooks.callHook,
1581
+ addHooks: hooks.addHooks,
1582
+ hook: hooks.hook,
1583
+ async updateConfig(_config) {
1584
+ },
1585
+ routeRules: void 0,
1586
+ adapters: {}
1587
+ };
1588
+ if (silgi.options.adapters && Object.keys(silgi.options.adapters)?.length > 0) {
1589
+ for (const [key, value] of Object.entries(silgi.options.adapters)) {
1590
+ silgi.adapters[key] = value;
1591
+ }
1592
+ }
1593
+ await prepareEnv(options);
1594
+ const routeRules = createRouteRules();
1595
+ routeRules.importRules(options.routeRules ?? {});
1596
+ silgi.routeRules = routeRules;
1597
+ if (silgiCLICtx.tryUse()) {
1598
+ silgiCLICtx.unset();
1599
+ silgiCLICtx.set(silgi);
1600
+ } else {
1601
+ silgiCLICtx.set(silgi);
1602
+ silgi.hook("close", () => silgiCLICtx.unset());
1603
+ }
1604
+ await silgi.hooks.callHook("ready", silgi);
1605
+ if (silgi.options.debug) {
1606
+ createDebugger(silgi.hooks, { tag: "silgi" });
1607
+ silgi.options.plugins.push({
1608
+ path: join(runtimeDir, "internal/debug"),
1609
+ packageImport: "silgi/runtime/internal/debug"
1610
+ });
1611
+ }
1612
+ for (const framework of frameworkSetup) {
1613
+ await framework(silgi);
1614
+ }
1615
+ await scanAndSyncOptions(silgi);
1616
+ await scanModules$1(silgi);
1617
+ await scanExportFile(silgi);
1618
+ await installModules(silgi, true);
1619
+ useCLIRuntimeConfig(silgi);
1620
+ await writeScanFiles(silgi);
1621
+ silgi.storage = await createStorageCLI(silgi);
1622
+ silgi.hooks.hook("close", async () => {
1623
+ await silgi.storage.dispose();
1624
+ });
1625
+ if (silgi.options.logLevel !== void 0) {
1626
+ silgi.logger.level = silgi.options.logLevel;
1627
+ }
1628
+ silgi.hooks.addHooks(silgi.options.hooks);
1629
+ await installModules(silgi);
1630
+ await silgi.hooks.callHook("scanFiles:done", silgi);
1631
+ await generateApp(silgi);
1632
+ if (silgi.options.imports) {
1633
+ silgi.options.imports.dirs ??= [];
1634
+ silgi.options.imports.dirs = silgi.options.imports.dirs.map((dir) => {
1635
+ if (typeof dir === "string") {
1636
+ if (dir.startsWith("!")) {
1637
+ return `!${resolveSilgiPath(dir.slice(1), options, silgi.options.rootDir)}`;
1638
+ }
1639
+ return resolveSilgiPath(dir, options, silgi.options.rootDir);
1640
+ }
1641
+ return dir;
1642
+ });
1643
+ silgi.options.imports.presets.push({
1644
+ from: "silgi/types",
1645
+ imports: autoImportTypes.map((type) => type),
1646
+ type: true
1647
+ });
1648
+ silgi.options.imports.presets.push({
1649
+ from: "silgi/types",
1650
+ imports: autoImportTypes.map((type) => type),
1651
+ type: true
1652
+ });
1653
+ silgi.options.imports.presets.push({
1654
+ from: "silgi/runtime/internal/ofetch",
1655
+ imports: ["createSilgiFetch", "silgi$fetch"]
1656
+ });
1657
+ silgi.unimport = createUnimport(silgi.options.imports);
1658
+ await silgi.unimport.init();
1659
+ }
1660
+ await registerModuleExportScan(silgi);
1661
+ await writeScanFiles(silgi);
1662
+ return silgi;
1663
+ }
1664
+
1665
+ async function generateApiFul(silgi) {
1666
+ const config = silgi.options.apiFul;
1667
+ if (!hasSilgiModule("openapi")) {
1668
+ silgi.logger.info("Silgi OpenAPI module not found, if you want to use it, please install it @silgi/openapi");
1669
+ return;
1670
+ }
1671
+ if (!config.services || hasSilgiModule("openapi")) {
1672
+ config.services ??= {};
1673
+ config.services = {
1674
+ silgi: {
1675
+ schema: join(silgi.options.build.dir, "openapi.json")
1676
+ }
1677
+ };
1678
+ }
1679
+ const resolvedOpenAPIServices = Object.fromEntries(
1680
+ Object.entries(config?.services ?? {}).filter(([, service]) => Boolean(service.schema))
1681
+ );
1682
+ if (Object.keys(resolvedOpenAPIServices).length === 0) {
1683
+ consola$1.info("No OpenAPI schemas found, skipping generation");
1684
+ return;
1685
+ }
1686
+ for (const service of Object.values(resolvedOpenAPIServices)) {
1687
+ if (typeof service.schema === "string" && !service.schema.startsWith("http")) {
1688
+ service.schema = resolve(silgi.options.rootDir, service.schema);
1689
+ }
1690
+ }
1691
+ const types = await generateDTS(resolvedOpenAPIServices);
1692
+ silgi.hook("prepare:types", (opts) => {
1693
+ opts.references.push({ path: "./apiful.d.ts" });
1694
+ });
1695
+ addTemplate({
1696
+ filename: "types/apiful.d.ts",
1697
+ where: ".silgi",
1698
+ write: true,
1699
+ getContents: () => types
1700
+ });
1701
+ }
1702
+
1703
+ async function prepare(_silgi) {
1704
+ }
1705
+
1706
+ async function exportRules(silgi) {
1707
+ try {
1708
+ if (!silgi?.routeRules?.exportRules) {
1709
+ throw new Error("Invalid silgi configuration: routeRules or exportRules is undefined");
1710
+ }
1711
+ const exportedRules = silgi.routeRules.exportRules();
1712
+ if (!exportedRules || typeof exportedRules !== "object") {
1713
+ throw new Error("No valid route rules to export");
1714
+ }
1715
+ const content = `/* eslint-disable */
1716
+ // @ts-nocheck
1717
+ // This file is auto-generated at build time by Silgi
1718
+ // Contains route rules with preserved functions
1719
+ // DO NOT MODIFY THIS FILE DIRECTLY
1720
+
1721
+ export const routeRules = ${genObjectFromRawEntries(
1722
+ Object.entries(exportedRules).map(([key, value]) => {
1723
+ if (typeof value === "function") {
1724
+ return [key, genObjectFromRaw(value)];
1725
+ }
1726
+ return [key, genObjectFromValues(value)];
1727
+ })
1728
+ )}
1729
+ `;
1730
+ const serverDir = silgi.options.silgi.serverDir;
1731
+ if (!serverDir) {
1732
+ throw new Error("Server directory not defined in configuration");
1733
+ }
1734
+ const file = join(serverDir, "rules.ts");
1735
+ if (!silgi.errors.length) {
1736
+ await writeFile(file, content);
1737
+ }
1738
+ } catch (error) {
1739
+ console.error("\u274C Failed to prepare build:", error instanceof Error ? error.message : String(error));
1740
+ throw error;
1741
+ }
1742
+ }
1743
+
1744
+ function debugMode(name) {
1745
+ const silgi = useSilgiCLI$1();
1746
+ if (silgi.options.debug === true || typeof silgi.options.debug === "object" && silgi.options.debug[name]) {
1747
+ return true;
1748
+ }
1749
+ return false;
1750
+ }
1751
+
1752
+ async function prepareCommands(silgi = useSilgiCLI$1()) {
1753
+ const commands = [];
1754
+ await silgi.callHook("prepare:commands", commands);
1755
+ if (debugMode("command")) {
1756
+ addTemplate({
1757
+ filename: "cli.json",
1758
+ where: ".silgi",
1759
+ write: true,
1760
+ getContents: () => JSON.stringify(commands, null, 2)
1761
+ });
1762
+ }
1763
+ silgi.hook("prepare:types", async ({ references }) => {
1764
+ const allTags = commands.reduce((acc, commandGroup) => {
1765
+ Object.values(commandGroup).forEach((command) => {
1766
+ if (command.tags) {
1767
+ command.tags.forEach((tag) => acc.add(tag));
1768
+ }
1769
+ });
1770
+ return acc;
1771
+ }, /* @__PURE__ */ new Set());
1772
+ const data = [
1773
+ genAugmentation("silgi/types", {
1774
+ SilgiCommands: {
1775
+ ...Object.fromEntries(Array.from(allTags.values()).map((tag) => [tag, "string"]))
1776
+ }
1777
+ }),
1778
+ "",
1779
+ "export {}"
1780
+ ];
1781
+ addTemplate({
1782
+ filename: "types/commands.d.ts",
1783
+ write: true,
1784
+ where: ".silgi",
1785
+ getContents: () => data.join("\n")
1786
+ });
1787
+ references.push({
1788
+ path: "./commands.d.ts"
1789
+ });
1790
+ });
1791
+ silgi.options.commands = commands;
1792
+ }
1793
+
1794
+ async function prepareConfigs(silgi) {
1795
+ const _data = {
1796
+ runtimeConfig: {}
1797
+ };
1798
+ for (const module of silgi.scanModules) {
1799
+ if (module.meta.cliToRuntimeOptionsKeys && module.meta.cliToRuntimeOptionsKeys?.length > 0) {
1800
+ for (const key of module.meta.cliToRuntimeOptionsKeys) {
1801
+ _data[module.meta.configKey] = {
1802
+ ..._data[module.meta.configKey],
1803
+ [key]: module.options[key]
1804
+ };
1805
+ }
1806
+ } else {
1807
+ _data[module.meta.configKey] = {};
1808
+ }
1809
+ }
1810
+ await silgi.callHook("prepare:configs.ts", _data);
1811
+ const importData = [
1812
+ "import type { SilgiRuntimeOptions, SilgiRuntimeConfig, SilgiOptions } from 'silgi/types'",
1813
+ "import { useSilgiRuntimeConfig } from 'silgi/runtime'",
1814
+ "",
1815
+ `export const runtimeConfig: Partial<SilgiRuntimeConfig> = ${genObjectFromRawEntries(
1816
+ Object.entries(_data.runtimeConfig).map(([key, value]) => [key, genEnsureSafeVar(value)]),
1817
+ ""
1818
+ )}`,
1819
+ "",
1820
+ "const runtime = useSilgiRuntimeConfig(undefined, runtimeConfig)",
1821
+ ""
1822
+ ];
1823
+ delete _data.runtimeConfig;
1824
+ importData.push(`export const cliConfigs: Partial<SilgiRuntimeOptions & SilgiOptions> = ${genObjectFromRawEntries(
1825
+ Object.entries(_data).map(
1826
+ ([key, value]) => [key, genEnsureSafeVar(value)]
1827
+ ).concat(
1828
+ [
1829
+ ["runtimeConfig", "runtime"]
1830
+ ]
1831
+ )
1832
+ )}`);
1833
+ importData.unshift(...baseHeaderBannerComment);
1834
+ return importData;
1835
+ }
1836
+
1837
+ async function prepareCoreFile(silgi) {
1838
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
1839
+ imports: [
1840
+ {
1841
+ specifier: "silgi/runtime",
1842
+ imports: [
1843
+ {
1844
+ name: "mergeDeep"
1845
+ }
1846
+ ]
1847
+ },
1848
+ {
1849
+ specifier: "silgi",
1850
+ imports: [
1851
+ {
1852
+ name: "createSilgi"
1853
+ }
1854
+ ]
1855
+ },
1856
+ {
1857
+ specifier: "./scan",
1858
+ imports: [
1859
+ {
1860
+ name: "uris"
1861
+ },
1862
+ {
1863
+ name: "services"
1864
+ },
1865
+ {
1866
+ name: "shareds"
1867
+ },
1868
+ {
1869
+ name: "schemas"
1870
+ },
1871
+ {
1872
+ name: "modulesURIs"
1873
+ }
1874
+ ]
1875
+ },
1876
+ {
1877
+ specifier: "./configs",
1878
+ imports: [
1879
+ {
1880
+ name: "cliConfigs"
1881
+ }
1882
+ ]
1883
+ },
1884
+ {
1885
+ specifier: "./rules",
1886
+ imports: [
1887
+ {
1888
+ name: "routeRules"
1889
+ }
1890
+ ]
1891
+ }
1892
+ ],
1893
+ typeImports: [
1894
+ {
1895
+ specifier: "silgi/types",
1896
+ imports: [
1897
+ {
1898
+ name: "SilgiRuntimeOptions"
1899
+ },
1900
+ {
1901
+ name: "BuildSilgi"
1902
+ }
1903
+ ]
1904
+ }
1905
+ ]
1906
+ });
1907
+ const before = [];
1908
+ const after = [];
1909
+ const _data = {
1910
+ silgiConfigs: [],
1911
+ addImportItem,
1912
+ addImportItemType,
1913
+ addBuildFunction: (data) => {
1914
+ for (const item of toArray(data)) {
1915
+ if (item.where === "after") {
1916
+ if (item.custom) {
1917
+ after.push(item.custom);
1918
+ } else {
1919
+ after.push(item.params?.length ? ` await ${item.name}(option, ${item.params.join(",")})` : ` await ${item.name}(option)`);
1920
+ }
1921
+ }
1922
+ if (item.where === "before") {
1923
+ if (item.custom) {
1924
+ before.push(item.custom);
1925
+ } else {
1926
+ before.push(item.params?.length ? ` await ${item.name}(option, ${item.params.join(",")})` : ` await ${item.name}(option)`);
1927
+ }
1928
+ }
1929
+ }
1930
+ }
1931
+ };
1932
+ await silgi.callHook("before:core.ts", _data);
1933
+ const plugins = [];
1934
+ for (const plugin of silgi.options.plugins) {
1935
+ const pluginImportName = hash(plugin.packageImport);
1936
+ addImportItem({
1937
+ specifier: plugin.packageImport,
1938
+ imports: pluginImportName
1939
+ });
1940
+ plugins.push(pluginImportName);
1941
+ }
1942
+ const importsContent = [
1943
+ ...genImports.map(({ specifier, imports, options }) => {
1944
+ return genImport(specifier, imports, options);
1945
+ }),
1946
+ ...genTypeImports.map(({ specifier, imports }) => {
1947
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
1948
+ }),
1949
+ ""
1950
+ ];
1951
+ const importData = [
1952
+ "",
1953
+ "export async function buildSilgi(option: BuildSilgi) {",
1954
+ "",
1955
+ "// buildSilgiBefore",
1956
+ ...before,
1957
+ "",
1958
+ "const silgi = await createSilgi({",
1959
+ " framework: option.framework,",
1960
+ " shared: shareds,",
1961
+ " services: services,",
1962
+ " schemas: schemas,",
1963
+ " uris,",
1964
+ " modulesURIs,",
1965
+ ` plugins: [${plugins.join(", ")}],`,
1966
+ "",
1967
+ _data.silgiConfigs.length > 0 ? _data.silgiConfigs.map((item) => {
1968
+ const code = genObjectFromRawEntries(Object.entries(item));
1969
+ return ` ${code.slice(1, -1).trim()},`;
1970
+ }).filter(Boolean).join("\n") : "",
1971
+ "",
1972
+ " options: mergeDeep(cliConfigs, {",
1973
+ " runtimeConfig: {} as SilgiRuntimeOptions,",
1974
+ " routeRules: routeRules as any,",
1975
+ ` present: '${silgi.options.preset}',`,
1976
+ " ...option.modules,",
1977
+ " ...option.options,",
1978
+ " }) as any,",
1979
+ " })",
1980
+ "",
1981
+ "// buildSilgiAfter",
1982
+ ...after,
1983
+ "",
1984
+ " return silgi",
1985
+ "}",
1986
+ ""
1987
+ ];
1988
+ await silgi.callHook("after:core.ts", importData);
1989
+ importData.unshift(...importsContent);
1990
+ importData.unshift(...baseHeaderBannerComment);
1991
+ return importData;
1992
+ }
1993
+
1994
+ async function writeCoreFile(silgi) {
1995
+ const coreContent = await prepareCoreFile(silgi);
1996
+ const configs = await prepareConfigs(silgi);
1997
+ const silgiDir = resolve(silgi.options.silgi.serverDir);
1998
+ const buildFiles = [];
1999
+ buildFiles.push({
2000
+ path: join(silgiDir, "core.ts"),
2001
+ contents: coreContent.join("\n")
2002
+ });
2003
+ buildFiles.push({
2004
+ path: join(silgiDir, "configs.ts"),
2005
+ contents: configs.join("\n")
2006
+ });
2007
+ for await (const file of buildFiles) {
2008
+ if (!silgi.errors.length) {
2009
+ await writeFile(
2010
+ resolve(silgi.options.build.dir, file.path),
2011
+ file.contents
2012
+ );
2013
+ }
2014
+ }
2015
+ }
2016
+
2017
+ async function generateRouterDTS(silgi) {
2018
+ const uris = silgi.uris;
2019
+ const subPath = "srn";
2020
+ const groupedPaths = /* @__PURE__ */ new Map();
2021
+ Object.entries(uris || {}).forEach(([key, params]) => {
2022
+ const [service, resource, method, action] = key.split("/");
2023
+ const basePath = params ? `${subPath}/${service}/${resource}/${action}/${params}` : `${subPath}/${service}/${resource}/${action}`;
2024
+ const fullPath = `${subPath}/${service}/${resource}/${action}`;
2025
+ if (!groupedPaths.has(basePath)) {
2026
+ groupedPaths.set(basePath, /* @__PURE__ */ new Map());
2027
+ }
2028
+ groupedPaths.get(basePath)?.set(method.toLowerCase(), fullPath);
2029
+ });
2030
+ const keys = [
2031
+ " keys: {",
2032
+ Array.from(groupedPaths.entries()).map(([basePath, methods]) => {
2033
+ return ` '/${basePath}': {${Array.from(methods.entries()).map(([method, path]) => `
2034
+ ${method}: '/${path}'`).join(",")}
2035
+ }`;
2036
+ }).join(",\n"),
2037
+ " }",
2038
+ ""
2039
+ ].join("\n");
2040
+ const groupedRoutes = Object.entries(uris || {}).reduce((acc, [key, _params]) => {
2041
+ const [service, resource, method, action] = key.split("/");
2042
+ const routePath = `${subPath}/${service}/${resource}/${action}`;
2043
+ if (!acc[routePath]) {
2044
+ acc[routePath] = {};
2045
+ }
2046
+ acc[routePath][method] = {
2047
+ input: `ExtractInputFromURI<'${key}'>`,
2048
+ output: `ExtractOutputFromURI<'${key}'>`,
2049
+ queryParams: `ExtractQueryParamsFromURI<'${key}'>`,
2050
+ pathParams: `ExtractPathParamsFromURI<'${key}'>`
2051
+ };
2052
+ return acc;
2053
+ }, {});
2054
+ const routerTypes = Object.entries(groupedRoutes).map(([path, methods]) => {
2055
+ const methodEntries = Object.entries(methods).map(([method, { input, output, queryParams, pathParams }]) => {
2056
+ return ` '${method}': {
2057
+ input: ${input},
2058
+ output: ${output},
2059
+ queryParams: ${queryParams},
2060
+ pathParams: ${pathParams}
2061
+ }`;
2062
+ }).join(",\n");
2063
+ return ` '/${path}': {
2064
+ ${methodEntries}
2065
+ }`;
2066
+ });
2067
+ const nitro = [
2068
+ "declare module 'nitropack/types' {",
2069
+ " interface InternalApi extends RouterTypes {}",
2070
+ "}"
2071
+ ];
2072
+ const content = [
2073
+ keys.slice(0, -1),
2074
+ // son satırdaki boş satırı kaldır
2075
+ ...routerTypes
2076
+ ].join(",\n");
2077
+ const context = [
2078
+ "import type { ExtractInputFromURI, ExtractOutputFromURI, ExtractQueryParamsFromURI, ExtractPathParamsFromURI } from 'silgi/types'",
2079
+ "",
2080
+ "export interface RouterTypes {",
2081
+ content,
2082
+ "}",
2083
+ "",
2084
+ "declare module 'silgi/types' {",
2085
+ " interface SilgiRouterTypes extends RouterTypes {",
2086
+ " }",
2087
+ "}",
2088
+ "",
2089
+ silgi.options.preset === "h3" || silgi.options.preset === "nitro" ? nitro.join("\n") : "",
2090
+ "",
2091
+ "export {}"
2092
+ ];
2093
+ return context;
2094
+ }
2095
+
2096
+ async function prepareSchema(silgi) {
2097
+ const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
2098
+ imports: [
2099
+ {
2100
+ specifier: relativeWithDot(
2101
+ silgi.options.build.typesDir,
2102
+ `${silgi.options.silgi.serverDir}/scan`
2103
+ ),
2104
+ imports: [
2105
+ {
2106
+ name: "modulesURIs"
2107
+ }
2108
+ ]
2109
+ }
2110
+ ],
2111
+ typeImports: [
2112
+ {
2113
+ specifier: "silgi/types",
2114
+ imports: [
2115
+ {
2116
+ name: "URIsTypes"
2117
+ },
2118
+ {
2119
+ name: "Namespaces"
2120
+ },
2121
+ {
2122
+ name: "SilgiRuntimeContext"
2123
+ }
2124
+ ]
2125
+ }
2126
+ ]
2127
+ });
2128
+ const data = {
2129
+ addImportItem,
2130
+ addImportItemType,
2131
+ options: [],
2132
+ contexts: [],
2133
+ actions: [],
2134
+ shareds: [
2135
+ {
2136
+ key: "modulesURIs",
2137
+ value: "{ modulesURIs: typeof modulesURIs }"
2138
+ }
2139
+ ],
2140
+ events: [],
2141
+ hooks: [],
2142
+ runtimeHooks: [],
2143
+ runtimeOptions: [],
2144
+ methods: [],
2145
+ routeRules: [],
2146
+ routeRulesConfig: []
2147
+ };
2148
+ await silgi.callHook("before:schema.ts", data);
2149
+ const silgiScanTS = relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/scan`);
2150
+ let addSilgiContext = false;
2151
+ const importsContent = [
2152
+ ...genImports.map(({ specifier, imports, options }) => {
2153
+ return genImport(specifier, imports, options);
2154
+ }),
2155
+ ...genTypeImports.map(({ specifier, imports }) => {
2156
+ return genTypeImport(specifier, Array.isArray(imports) ? imports : [imports]);
2157
+ }),
2158
+ ""
2159
+ ];
2160
+ const importData = [
2161
+ generateTypes(
2162
+ await resolveSchema(
2163
+ {
2164
+ ...silgi.options.namespaces?.reduce((acc, key) => ({ ...acc, [key]: "" }), {}) || {}
2165
+ }
2166
+ ),
2167
+ {
2168
+ interfaceName: "InferredNamespaces",
2169
+ addExport: false,
2170
+ addDefaults: false,
2171
+ allowExtraKeys: false,
2172
+ indentation: 0
2173
+ }
2174
+ ),
2175
+ "",
2176
+ `type SchemaExtends = Namespaces<typeof import('${silgiScanTS}')['schemas']>`,
2177
+ "",
2178
+ `type SilgiURIsMerge = URIsTypes<typeof import('${silgiScanTS}')['uris']>`,
2179
+ "",
2180
+ `type SilgiModuleContextExtends = ${data.contexts.length ? data.contexts.map(({ value }) => value).join(" & ") : "{}"}`,
2181
+ "",
2182
+ data.events.length ? `interface SilgiModuleEventsExtends extends ${data.events.map((item) => item.extends ? item.value : "").join(", ")} {
2183
+ ${data.events.map((item) => {
2184
+ if (item.isSilgiContext) {
2185
+ addSilgiContext = true;
2186
+ }
2187
+ return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: SilgiRuntimeContext" : "";
2188
+ }).join(",\n")}
2189
+ }` : "interface SilgiModuleEventsExtends {}",
2190
+ "",
2191
+ `type RuntimeActionExtends = ${data.actions?.length ? data.actions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2192
+ "",
2193
+ `type RuntimeMethodExtends = ${data.methods?.length ? data.methods.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2194
+ "",
2195
+ `type RuntimeRouteRulesExtends = ${data.routeRules?.length ? data.routeRules.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2196
+ "",
2197
+ `type RuntimeRouteRulesConfigExtends = ${data.routeRulesConfig?.length ? data.routeRulesConfig.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2198
+ "",
2199
+ `type SilgiModuleSharedExtends = ${data.shareds.length ? data.shareds.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2200
+ "",
2201
+ `type SilgiModuleOptionExtend = ${data.options?.length ? data.options.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2202
+ "",
2203
+ `type SilgiRuntimeOptionExtends = ${data.runtimeOptions?.length ? data.runtimeOptions.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2204
+ "",
2205
+ silgi.options.typescript.generateRuntimeConfigTypes ? generateTypes(
2206
+ await resolveSchema(
2207
+ {
2208
+ ...Object.fromEntries(
2209
+ Object.entries(silgi.options.runtimeConfig).filter(
2210
+ ([key]) => !["app", "nitro", "nuxt"].includes(key)
2211
+ )
2212
+ )
2213
+ }
2214
+ ),
2215
+ {
2216
+ interfaceName: "SilgiRuntimeConfigExtends",
2217
+ addExport: false,
2218
+ addDefaults: false,
2219
+ allowExtraKeys: false,
2220
+ indentation: 0
2221
+ }
2222
+ ) : "",
2223
+ "",
2224
+ generateTypes(
2225
+ await resolveSchema(
2226
+ {
2227
+ ...silgi.options.storages?.reduce((acc, key) => ({ ...acc, [key]: "" }), {}) || {},
2228
+ // 'redis': {} -> 'redis': string
2229
+ ...Object.entries(silgi.options.storage).map(([key]) => ({
2230
+ [key]: ""
2231
+ })).reduce((acc, obj) => ({ ...acc, ...obj }), {})
2232
+ }
2233
+ ),
2234
+ {
2235
+ interfaceName: "SilgiStorageBaseExtends",
2236
+ addExport: false,
2237
+ addDefaults: false,
2238
+ allowExtraKeys: false,
2239
+ indentation: 0
2240
+ }
2241
+ ),
2242
+ "",
2243
+ `type ModuleHooksExtend = ${data.hooks?.length ? data.hooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2244
+ "",
2245
+ `type SilgiRuntimeHooksExtends = ${data.runtimeHooks?.length ? data.runtimeHooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
2246
+ "",
2247
+ genAugmentation("silgi/types", {
2248
+ FrameworkContext: [{}, { extends: ["FrameworkContextExtends"] }],
2249
+ SilgiSchema: [{}, { extends: ["SchemaExtends"] }],
2250
+ SilgiNamespaces: [{}, { extends: ["InferredNamespaces"] }],
2251
+ SilgiStorageBase: [{}, { extends: ["SilgiStorageBaseExtends"] }],
2252
+ SilgiURIs: [{}, { extends: ["SilgiURIsMerge"] }],
2253
+ SilgiRuntimeContext: [{}, { extends: ["SilgiModuleContextExtends"] }],
2254
+ SilgiEvents: [{}, { extends: ["SilgiModuleEventsExtends"] }],
2255
+ SilgiRuntimeSharedsExtend: [{}, { extends: ["SilgiModuleSharedExtends"] }],
2256
+ SilgiRuntimeActions: [{}, { extends: ["RuntimeActionExtends"] }],
2257
+ SilgiRuntimeOptions: [{}, { extends: ["SilgiRuntimeOptionExtends"] }],
2258
+ SilgiRuntimeHooks: [{}, { extends: ["SilgiRuntimeHooksExtends"] }],
2259
+ SilgiRuntimeConfig: [{}, { extends: ["SilgiRuntimeConfigExtends"] }],
2260
+ SilgiHooks: [{}, { extends: ["ModuleHooksExtend"] }],
2261
+ SilgiRuntimeMethods: [{}, { extends: ["RuntimeMethodExtends"] }],
2262
+ SilgiRuntimeRouteRules: [{}, { extends: ["RuntimeRouteRulesExtends"] }],
2263
+ SilgiRuntimeRouteRulesConfig: [{}, { extends: ["RuntimeRouteRulesConfigExtends"] }],
2264
+ SilgiModuleOptions: [{}, { extends: ["SilgiModuleOptionExtend"] }]
2265
+ }).replace(/,\s*/g, "\n"),
2266
+ "",
2267
+ "export {}"
2268
+ ];
2269
+ await silgi.callHook("after:schema.ts", importData);
2270
+ importData.unshift(...importsContent);
2271
+ return importData;
2272
+ }
2273
+
2274
+ async function writeTypesAndFiles(silgi) {
2275
+ const routerDTS = await generateRouterDTS(silgi);
2276
+ silgi.hook("prepare:types", (opts) => {
2277
+ opts.references.push({ path: "./schema.d.ts" });
2278
+ opts.references.push({ path: "./silgi-routes.d.ts" });
2279
+ });
2280
+ const schemaContent = await prepareSchema(silgi);
2281
+ const { declarations, tsConfig } = await silgiGenerateType(silgi);
2282
+ const tsConfigPath = resolve(
2283
+ silgi.options.rootDir,
2284
+ silgi.options.typescript.tsconfigPath
2285
+ );
2286
+ const typesDir = resolve(silgi.options.build.typesDir);
2287
+ let autoImportedTypes = [];
2288
+ let autoImportExports = "";
2289
+ if (silgi.unimport) {
2290
+ await silgi.unimport.init();
2291
+ const allImports = await silgi.unimport.getImports();
2292
+ autoImportExports = toExports(allImports).replace(
2293
+ /#internal\/nitro/g,
2294
+ relative(typesDir, runtimeDir)
2295
+ );
2296
+ const resolvedImportPathMap = /* @__PURE__ */ new Map();
2297
+ for (const i of allImports.filter((i2) => !i2.type)) {
2298
+ if (resolvedImportPathMap.has(i.from)) {
2299
+ continue;
2300
+ }
2301
+ let path = resolveAlias$1(i.from, silgi.options.alias);
2302
+ if (isAbsolute(path)) {
2303
+ const resolvedPath = await resolvePath(i.from, {
2304
+ url: silgi.options.nodeModulesDirs
2305
+ }).catch(() => null);
2306
+ if (resolvedPath) {
2307
+ const { dir, name } = parseNodeModulePath(resolvedPath);
2308
+ if (!dir || !name) {
2309
+ path = resolvedPath;
2310
+ } else {
2311
+ const subpath = await lookupNodeModuleSubpath(resolvedPath);
2312
+ path = join(dir, name, subpath || "");
2313
+ }
2314
+ }
2315
+ }
2316
+ if (existsSync(path) && !await isDirectory(path)) {
2317
+ path = path.replace(/\.[a-z]+$/, "");
2318
+ }
2319
+ if (isAbsolute(path)) {
2320
+ path = relative(typesDir, path);
2321
+ }
2322
+ resolvedImportPathMap.set(i.from, path);
2323
+ }
2324
+ autoImportedTypes = [
2325
+ silgi.options.imports && silgi.options.imports.autoImport !== false ? (await silgi.unimport.generateTypeDeclarations({
2326
+ exportHelper: false,
2327
+ resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
2328
+ })).trim() : ""
2329
+ ];
2330
+ }
2331
+ const buildFiles = [];
2332
+ buildFiles.push({
2333
+ path: join(typesDir, "silgi-routes.d.ts"),
2334
+ contents: routerDTS.join("\n")
2335
+ });
2336
+ buildFiles.push({
2337
+ path: join(typesDir, "silgi-imports.d.ts"),
2338
+ contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
2339
+ "\n"
2340
+ )
2341
+ });
2342
+ buildFiles.push({
2343
+ path: join(typesDir, "schema.d.ts"),
2344
+ contents: schemaContent.join("\n")
2345
+ });
2346
+ buildFiles.push({
2347
+ path: join(typesDir, "silgi.d.ts"),
2348
+ contents: declarations.join("\n")
2349
+ });
2350
+ buildFiles.push({
2351
+ path: tsConfigPath,
2352
+ contents: JSON.stringify(tsConfig, null, 2)
2353
+ });
2354
+ for await (const file of buildFiles) {
2355
+ if (!silgi.errors.length) {
2356
+ await writeFile(
2357
+ resolve(silgi.options.build.dir, file.path),
2358
+ file.contents
2359
+ );
2360
+ }
2361
+ }
2362
+ }
2363
+
2364
+ async function build(silgi) {
2365
+ await prepare();
2366
+ await generateApiFul(silgi);
2367
+ await prepareCommands(silgi);
2368
+ await writeCoreFile(silgi);
2369
+ await exportRules(silgi);
2370
+ await writeTypesAndFiles(silgi);
2371
+ await generateApp(silgi);
2372
+ }
2373
+
2374
+ export { build as b, createSilgiCLI as c, prepareEnv as p };