silgi 0.19.10 → 0.19.12

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