silgi 0.9.35 → 0.10.1

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