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