silgi 0.10.0 → 0.10.2

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