silgi 0.24.21 → 0.24.23

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