silgi 0.24.13 → 0.24.15

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