silgi 0.3.13 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +1 -31
  2. package/cli.d.ts +1 -0
  3. package/config.d.ts +1 -0
  4. package/core.d.ts +1 -0
  5. package/dist/_chunks/index.mjs +233 -0
  6. package/dist/cli/compatibility.mjs +42 -0
  7. package/dist/cli/index.mjs +3 -184
  8. package/dist/cli/prepare.mjs +1350 -0
  9. package/dist/config/index.d.mts +5 -0
  10. package/dist/config/index.d.ts +5 -0
  11. package/dist/core/index.d.mts +136 -0
  12. package/dist/core/index.d.ts +136 -0
  13. package/dist/core/index.mjs +1444 -0
  14. package/dist/ecosystem/nitro/index.mjs +21 -29
  15. package/dist/ecosystem/nuxt/module.mjs +4 -25
  16. package/dist/kit/index.d.mts +90 -0
  17. package/dist/kit/index.d.ts +90 -0
  18. package/dist/kit/index.mjs +316 -0
  19. package/dist/meta/index.d.mts +3 -0
  20. package/dist/meta/index.d.ts +3 -0
  21. package/dist/meta/index.mjs +1 -0
  22. package/dist/presets/_all.gen.d.ts +2 -0
  23. package/dist/presets/_all.gen.mjs +10 -0
  24. package/dist/presets/_resolve.d.ts +8 -0
  25. package/dist/presets/_resolve.mjs +58 -0
  26. package/dist/presets/_types.gen.d.ts +5 -0
  27. package/dist/presets/_types.gen.mjs +1 -0
  28. package/dist/presets/h3/preset.d.ts +2 -0
  29. package/dist/presets/h3/preset.mjs +22 -0
  30. package/dist/presets/index.d.mts +1 -0
  31. package/dist/presets/index.d.ts +2 -0
  32. package/dist/presets/index.mjs +1 -0
  33. package/dist/presets/nitro/preset.d.ts +2 -0
  34. package/dist/presets/nitro/preset.mjs +26 -0
  35. package/dist/presets/npmpackage/preset.d.ts +2 -0
  36. package/dist/presets/npmpackage/preset.mjs +23 -0
  37. package/dist/presets/nuxt/preset.d.ts +2 -0
  38. package/dist/presets/nuxt/preset.mjs +26 -0
  39. package/dist/runtime/index.d.ts +1 -0
  40. package/dist/runtime/index.mjs +1 -0
  41. package/dist/runtime/internal/debug.d.ts +2 -0
  42. package/dist/runtime/internal/debug.mjs +5 -0
  43. package/dist/runtime/internal/nitro.d.ts +2 -0
  44. package/dist/runtime/internal/nitro.mjs +45 -0
  45. package/dist/runtime/internal/plugin.d.ts +3 -0
  46. package/dist/runtime/internal/plugin.mjs +4 -0
  47. package/dist/shared/silgi.40ZJYm8F.d.mts +11 -0
  48. package/dist/shared/silgi.40ZJYm8F.d.ts +11 -0
  49. package/dist/shared/{silgi.ClpvycKI.d.ts → silgi.CzUPBllI.d.mts} +452 -438
  50. package/dist/shared/{silgi.ClpvycKI.d.mts → silgi.D_LzzCtJ.d.ts} +452 -438
  51. package/dist/types/index.d.mts +42 -0
  52. package/dist/types/index.d.ts +42 -0
  53. package/dist/types/index.mjs +1 -0
  54. package/kit.d.ts +1 -0
  55. package/meta.d.ts +1 -0
  56. package/package.json +89 -39
  57. package/presets.d.ts +1 -0
  58. package/runtime-meta.d.ts +4 -0
  59. package/runtime-meta.mjs +32 -0
  60. package/runtime.d.ts +1 -0
  61. package/types.d.ts +1 -0
  62. package/bin/silgi.mjs +0 -3
  63. package/dist/chunks/generate.mjs +0 -1257
  64. package/dist/cli/config.d.mts +0 -1633
  65. package/dist/cli/config.d.ts +0 -1633
  66. package/dist/index.d.mts +0 -198
  67. package/dist/index.d.ts +0 -198
  68. package/dist/index.mjs +0 -503
  69. package/dist/shared/silgi.D2yb1XAa.mjs +0 -842
  70. /package/dist/{chunks → cli}/init.mjs +0 -0
  71. /package/dist/{cli/config.mjs → config/index.mjs} +0 -0
@@ -1,1257 +0,0 @@
1
- import { defineCommand } from 'citty';
2
- import { r as relativeWithDot, k as getDirectory, m as resolveSilgiModule, o as resolvePath$1, q as generateUris, v as generateSilgiStorageBaseType, l as loadSilgiConfig } from '../shared/silgi.D2yb1XAa.mjs';
3
- import { createHooks } from 'hookable';
4
- import ignore from 'ignore';
5
- import { isAbsolute, resolve, join, relative, dirname, basename, extname } from 'pathe';
6
- import { promises, existsSync, writeFileSync, readFileSync } from 'node:fs';
7
- import { readPackageJSON } from 'pkg-types';
8
- import { defu } from 'defu';
9
- import { withTrailingSlash } from 'ufo';
10
- import { resolvePath, resolve as resolve$1 } from 'mlly';
11
- import { readdir } from 'node:fs/promises';
12
- import { consola } from 'consola';
13
- import { globby } from 'globby';
14
- import { parseSync } from '@oxc-parser/wasm';
15
- import { createJiti } from 'jiti';
16
- import { pathToFileURL, fileURLToPath } from 'node:url';
17
- import { pascalCase } from 'scule';
18
- import 'node:buffer';
19
- import 'klona';
20
- import 'unstorage';
21
- import 'unstorage/drivers/memory';
22
- import 'unctx';
23
- import 'c12';
24
- import 'untyped';
25
- import 'std-env';
26
- import 'pathe/utils';
27
-
28
- async function _generateH3DTS(silgi) {
29
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
30
- const importedItems = {
31
- silgi: {
32
- import: [
33
- { name: "URIsTypes", type: true },
34
- { name: "Namespaces", type: true },
35
- { name: "SilgiModuleContext", type: true }
36
- ],
37
- from: "silgi"
38
- }
39
- };
40
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
41
- if (typeof id !== "string") {
42
- return;
43
- }
44
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
45
- if (!pkg?.name) {
46
- return;
47
- }
48
- if (importedItems[pkg.name]) {
49
- importedItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
50
- }
51
- }));
52
- const imports = [];
53
- await silgi.callHook("prepare:h3.d.ts", {
54
- importedItems,
55
- imports
56
- });
57
- const importData = [
58
- "// Generated by silgi",
59
- ...Object.entries(importedItems).map(([_name, { from, import: imports2 }]) => {
60
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.buildDir, from) : from;
61
- return `import { ${imports2.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
62
- }),
63
- "",
64
- ...imports,
65
- "",
66
- 'declare module "h3" {',
67
- " interface H3EventContext extends SilgiModuleContext {}",
68
- "}",
69
- ""
70
- ].join("\n");
71
- return {
72
- importData
73
- };
74
- }
75
- async function writeH3DTS(silgi) {
76
- if (silgi.options.environment !== "h3")
77
- return;
78
- silgi.hook("prepare:schema.ts", (options) => {
79
- options.importedItems.h3 ??= {
80
- import: [
81
- { name: "H3Event", type: true }
82
- ],
83
- from: "h3"
84
- };
85
- options.events.push({
86
- key: "H3Event",
87
- value: "H3Event",
88
- extends: true,
89
- isSilgiContext: false
90
- });
91
- });
92
- const { importData } = await _generateH3DTS(silgi);
93
- async function writeFile() {
94
- const GeneratedBy = "// Generated by silgi";
95
- const tsConfigPath = resolve(silgi.options.buildDir, "h3.d.ts");
96
- await promises.mkdir(silgi.options.buildDir, { recursive: true });
97
- await promises.writeFile(tsConfigPath, `${GeneratedBy}
98
- ${importData}`);
99
- }
100
- await writeFile();
101
- }
102
-
103
- async function _generateSchemaFile(silgi) {
104
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
105
- const importedItems = {
106
- silgi: {
107
- import: [
108
- { name: "URIsTypes", type: true },
109
- { name: "Namespaces", type: true },
110
- { name: "SilgiModuleContext", type: true }
111
- ],
112
- from: "silgi"
113
- }
114
- };
115
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
116
- if (typeof id !== "string") {
117
- return;
118
- }
119
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
120
- if (!pkg?.name) {
121
- return;
122
- }
123
- if (importedItems[pkg.name]) {
124
- importedItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
125
- }
126
- }));
127
- const imports = [];
128
- const configs = [];
129
- const contexts = [];
130
- const methods = [];
131
- const shareds = [];
132
- const events = [];
133
- const storeBase = [];
134
- await silgi.callHook("prepare:schema.ts", {
135
- importedItems,
136
- imports,
137
- configs,
138
- contexts,
139
- methods,
140
- shareds,
141
- storeBase,
142
- events
143
- });
144
- const silgiExport = relativeWithDot(silgi.options.buildDir, `${silgi.options.silgiDir}/core.ts`);
145
- let addSilgiContext = false;
146
- const importData = [
147
- ...Object.entries(importedItems).map(([_name, { from, import: imports2 }]) => {
148
- const path = isAbsolute(from) ? relativeWithDot(silgi.options.buildDir, from) : from;
149
- return `import { ${imports2.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
150
- }),
151
- "",
152
- ...imports,
153
- "",
154
- "interface InferredNamespaces {",
155
- ...(silgi.options.namespaces || []).map((key) => ` ${key}: string,`),
156
- "}",
157
- "",
158
- `type SchemaExtends = Namespaces<typeof import('${silgiExport}')['schemas']>`,
159
- "",
160
- `type SilgiURIsMerge = URIsTypes<typeof import('${silgiExport}')['uris']>`,
161
- "",
162
- contexts.length ? `type SilgiModuleContextExtends = ${contexts.map(({ value }) => value).join(" & ")}` : "type SilgiModuleContextExtends = {}",
163
- "",
164
- events.length ? `interface SilgiModuleEventsExtends extends ${events.map((item) => item.extends ? item.value : "").join(", ")} {
165
- ${events.map((item) => {
166
- if (item.isSilgiContext) {
167
- addSilgiContext = true;
168
- }
169
- return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: SilgiModuleContext" : "";
170
- }).join(",\n")}
171
- }` : "interface SilgiModuleEventsExtends {}",
172
- "",
173
- shareds.length ? `type SilgiModuleSharedExtends = ${shareds.map(({ value }) => value).join(" & ")}` : "type SilgiModuleSharedExtends = {}",
174
- "",
175
- "interface SilgiModuleMethodsExtends {",
176
- ...(methods).map(({ key, value }) => ` ${key}: ${value},`),
177
- "}",
178
- "",
179
- "interface SilgiModuleOptionsExtends {",
180
- ...(configs).map(({ key, value }) => ` ${key}: ${value},`),
181
- "}",
182
- "",
183
- "interface SilgiStorageBaseExtends {",
184
- ...(storeBase).map((value) => ` ${value}: ''`),
185
- "}",
186
- "",
187
- "declare module 'silgi' {",
188
- " interface SilgiSchema extends SchemaExtends {}",
189
- "",
190
- " interface SilgiValidationSchema {",
191
- ` validationLibrary: '${silgi.options.validationLibrary}'`,
192
- " }",
193
- "",
194
- " interface SilgiNamespaces extends InferredNamespaces {}",
195
- "",
196
- " interface SilgiStorageBase extends SilgiStorageBaseExtends {}",
197
- "",
198
- " interface SilgiModules extends SilgiModuleOptionsExtends {}",
199
- "",
200
- " interface SilgiURIs extends SilgiURIsMerge {}",
201
- "",
202
- " interface SilgiConfig extends Partial<SilgiModuleOptionsExtends> {}",
203
- "",
204
- " interface SilgiModuleContext extends SilgiModuleContextExtends {}",
205
- "",
206
- " interface SilgiEvent extends SilgiModuleEventsExtends {}",
207
- "",
208
- " interface SilgiDefaultShared extends SilgiModuleSharedExtends {}",
209
- "",
210
- " interface SilgiModuleMethods extends SilgiModuleMethodsExtends {}",
211
- "",
212
- " interface SilgiModuleOptions extends SilgiModuleOptionsExtends {}",
213
- "}",
214
- "",
215
- "export {}"
216
- ].join("\n");
217
- return {
218
- importData,
219
- importedItems
220
- };
221
- }
222
- async function writeSchema(silgi) {
223
- const { importData } = await _generateSchemaFile(silgi);
224
- async function writeFile() {
225
- const GeneratedBy = "// Generated by silgi";
226
- const tsConfigPath = resolve(silgi.options.buildDir, "schema.d.ts");
227
- await promises.mkdir(silgi.options.buildDir, { recursive: true });
228
- await promises.writeFile(tsConfigPath, `${GeneratedBy}
229
- ${importData}`);
230
- }
231
- await writeFile();
232
- }
233
-
234
- async function _generateSilgiFile(silgi) {
235
- const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
236
- const importedItems = {
237
- silgi: {
238
- import: [
239
- { name: "createSilgi" },
240
- { name: "SilgiModuleOptions", type: true },
241
- { name: "SilgiOptions", type: true }
242
- ],
243
- from: "silgi"
244
- }
245
- };
246
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
247
- if (typeof id !== "string") {
248
- return;
249
- }
250
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
251
- if (!pkg?.name) {
252
- return;
253
- }
254
- if (importedItems[pkg.name]) {
255
- importedItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
256
- }
257
- }));
258
- const imports = [];
259
- const uris = [];
260
- const services = [];
261
- const shareds = [];
262
- const schemas = [];
263
- const modules = [];
264
- await silgi.callHook("prepare:core.ts", {
265
- importedItems,
266
- imports,
267
- uris,
268
- services,
269
- shareds,
270
- schemas,
271
- modules
272
- });
273
- if (services.length > 0) {
274
- importedItems.silgi.import.push({ name: "mergeServices" });
275
- }
276
- if (shareds.length > 0) {
277
- importedItems.silgi.import.push({ name: "mergeShared" });
278
- }
279
- if (schemas.length > 0) {
280
- importedItems.silgi.import.push({ name: "mergeSchemas" });
281
- }
282
- const importData = [
283
- ...Object.entries(importedItems).map(([_name, { from, import: imports2 }]) => {
284
- return `import { ${imports2.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${from}'`;
285
- }),
286
- ...imports,
287
- "",
288
- "export const uris = {}",
289
- "",
290
- schemas.length > 0 ? "export const schemas = mergeSchemas([" : "export const schemas = {",
291
- ...schemas.map((name) => {
292
- return ` ${name},`;
293
- }),
294
- schemas.length > 0 ? "])" : "}",
295
- "",
296
- services.length > 0 ? "export const services = mergeServices([" : "export const services = {",
297
- ...services.map((name) => {
298
- return ` ${name},`;
299
- }),
300
- services.length > 0 ? "])" : "}",
301
- "",
302
- shareds.length > 0 ? "export const shareds = mergeShared([" : "export const shareds = {",
303
- ...shareds.map((name) => {
304
- return ` ${name},`;
305
- }),
306
- shareds.length > 0 ? "])" : "}",
307
- "",
308
- "export const silgiOptions: Partial<SilgiOptions> = {}",
309
- "",
310
- "export async function buildSilgi(options?: Partial<SilgiModuleOptions>) {",
311
- " const silgi = await createSilgi({",
312
- " shared: shareds as any,",
313
- " services: services as any,",
314
- " schemas: schemas as any,",
315
- " uris,",
316
- " _initializedModules: {",
317
- ...modules.map((name) => {
318
- return ` ${name},`;
319
- }),
320
- " } as any,",
321
- "",
322
- " options: {",
323
- " ...silgiOptions,",
324
- " ...options,",
325
- " },",
326
- " })",
327
- "",
328
- " return silgi",
329
- "}",
330
- ""
331
- ].join("\n");
332
- return {
333
- importData,
334
- importedItems
335
- };
336
- }
337
- async function writeSilgiFile(silgi) {
338
- const { importData } = await _generateSilgiFile(silgi);
339
- async function writeFile() {
340
- const GeneratedBy = "// Generated by silgi";
341
- const copySilgi = JSON.parse(JSON.stringify(silgi.options));
342
- delete copySilgi.modulesDir;
343
- delete copySilgi.buildDir;
344
- delete copySilgi.silgiDir;
345
- delete copySilgi.serverDir;
346
- delete copySilgi.rootDir;
347
- delete copySilgi.tsconfig;
348
- delete copySilgi.dir;
349
- delete copySilgi.ignore;
350
- delete copySilgi.hooks;
351
- delete copySilgi.alias;
352
- delete copySilgi.extensions;
353
- delete copySilgi.typescript;
354
- delete copySilgi.typeCheck;
355
- delete copySilgi.tsConfig;
356
- delete copySilgi._silgiConfigFile;
357
- delete copySilgi._silgiConfigFiles;
358
- delete copySilgi._requiredModules;
359
- delete copySilgi._modules;
360
- copySilgi._installedModules?.map((m) => {
361
- m.entryPath = "";
362
- m.active = false;
363
- m.packageName = "";
364
- return m;
365
- });
366
- const silgiObject = JSON.stringify(copySilgi, null, 2);
367
- const newImportData = importData.replace("silgiOptions: Partial<SilgiOptions> = {}", `silgiOptions: Partial<SilgiOptions> = ${silgiObject}`);
368
- const tsConfigPath = resolve(silgi.options.silgiDir, "core.ts");
369
- await promises.mkdir(silgi.options.silgiDir, { recursive: true });
370
- await promises.writeFile(tsConfigPath, `${GeneratedBy}
371
- ${newImportData}`);
372
- }
373
- await writeFile();
374
- }
375
-
376
- async function tryResolveModule(id, url = import.meta.url) {
377
- try {
378
- return await resolvePath(id, { url });
379
- } catch {
380
- }
381
- }
382
-
383
- function renderAttrs(obj) {
384
- const attrs = [];
385
- for (const key in obj) {
386
- attrs.push(renderAttr(key, obj[key]));
387
- }
388
- return attrs.join(" ");
389
- }
390
- function renderAttr(key, value) {
391
- return value ? `${key}="${value}"` : "";
392
- }
393
- const EXTENSION_RE = /\b\.\w+$/g;
394
- const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/];
395
- async function _generateTypes(silgi) {
396
- const rootDirWithSlash = withTrailingSlash(silgi.options.rootDir);
397
- const relativeRootDir = relativeWithDot(silgi.options.buildDir, silgi.options.rootDir);
398
- const include = /* @__PURE__ */ new Set([
399
- "./silgi.d.ts",
400
- "./schema.d.ts",
401
- join(relativeRootDir, ".config/silgi.*"),
402
- join(relativeRootDir, "**/*")
403
- ]);
404
- const exclude = /* @__PURE__ */ new Set([
405
- // nitro generate output: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/nitro.ts#L186
406
- relativeWithDot(silgi.options.buildDir, resolve(silgi.options.rootDir, "dist"))
407
- ]);
408
- for (const dir of silgi.options.modulesDir) {
409
- exclude.add(relativeWithDot(silgi.options.buildDir, dir));
410
- }
411
- const moduleEntryPaths = [];
412
- for (const m of silgi.options._installedModules) {
413
- if (m.entryPath) {
414
- moduleEntryPaths.push(getDirectory(m.entryPath));
415
- }
416
- }
417
- const modulePaths = await resolveSilgiModule(rootDirWithSlash, moduleEntryPaths);
418
- for (const path of modulePaths) {
419
- const relative2 = relativeWithDot(silgi.options.buildDir, path);
420
- include.add(join(relative2, "runtime"));
421
- exclude.add(join(relative2, "runtime/server"));
422
- include.add(join(relative2, "dist/runtime"));
423
- exclude.add(join(relative2, "dist/runtime/server"));
424
- }
425
- const tsConfig = defu(silgi.options.typescript?.tsConfig, {
426
- compilerOptions: {
427
- forceConsistentCasingInFileNames: true,
428
- strict: silgi.options.typescript.strict,
429
- noEmit: true,
430
- target: "ESNext",
431
- module: "ESNext",
432
- moduleResolution: "Bundler",
433
- allowJs: true,
434
- resolveJsonModule: true,
435
- jsx: "preserve",
436
- allowSyntheticDefaultImports: true,
437
- jsxFactory: "h",
438
- jsxFragmentFactory: "Fragment",
439
- allowImportingTsExtensions: true
440
- },
441
- include: [...include],
442
- exclude: [...exclude]
443
- });
444
- const aliases = silgi.options.alias;
445
- const basePath = tsConfig.compilerOptions.baseUrl ? resolve(silgi.options.buildDir, tsConfig.compilerOptions.baseUrl) : silgi.options.buildDir;
446
- tsConfig.compilerOptions ||= {};
447
- tsConfig.compilerOptions.paths ||= {};
448
- tsConfig.include ||= [];
449
- for (const alias in aliases) {
450
- if (excludedAlias.some((re) => re.test(alias))) {
451
- continue;
452
- }
453
- let absolutePath = resolve(basePath, aliases[alias]);
454
- let stats = await promises.stat(absolutePath).catch(
455
- () => null
456
- /* file does not exist */
457
- );
458
- if (!stats) {
459
- const resolvedModule = await tryResolveModule(aliases[alias], silgi.options.modulesDir);
460
- if (resolvedModule) {
461
- absolutePath = resolvedModule;
462
- stats = await promises.stat(resolvedModule).catch(() => null);
463
- }
464
- }
465
- const relativePath = relativeWithDot(silgi.options.buildDir, absolutePath);
466
- if (stats?.isDirectory()) {
467
- tsConfig.compilerOptions.paths[alias] = [relativePath];
468
- tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`];
469
- if (!absolutePath.startsWith(rootDirWithSlash)) {
470
- tsConfig.include.push(relativePath);
471
- }
472
- } else {
473
- const path = stats?.isFile() ? relativePath.replace(EXTENSION_RE, "") : aliases[alias];
474
- tsConfig.compilerOptions.paths[alias] = [path];
475
- if (!absolutePath.startsWith(rootDirWithSlash)) {
476
- tsConfig.include.push(path);
477
- }
478
- }
479
- }
480
- const references = [];
481
- await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
482
- if (typeof id !== "string") {
483
- return;
484
- }
485
- const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
486
- references.push({ types: pkg?.name || id });
487
- }));
488
- const declarations = [];
489
- await silgi.callHook("prepare:types", { references, declarations, tsConfig });
490
- tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(silgi.options.buildDir, p) : p))];
491
- tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(silgi.options.buildDir, p) : p))];
492
- const declaration = [
493
- ...references.map((ref) => {
494
- if ("path" in ref && isAbsolute(ref.path)) {
495
- ref.path = relative(silgi.options.buildDir, ref.path);
496
- }
497
- return `/// <reference ${renderAttrs(ref)} />`;
498
- }),
499
- ...declarations,
500
- "",
501
- "export {}",
502
- ""
503
- ].join("\n");
504
- return {
505
- declaration,
506
- tsConfig
507
- };
508
- }
509
- async function writeTsConfig(silgi) {
510
- const { tsConfig, declaration } = await _generateTypes(silgi);
511
- async function writeFile() {
512
- const GeneratedBy = "// Generated by silgi";
513
- const tsConfigPath = resolve(silgi.options.buildDir, "tsconfig.json");
514
- await promises.mkdir(silgi.options.buildDir, { recursive: true });
515
- await promises.writeFile(tsConfigPath, `${GeneratedBy}
516
- ${JSON.stringify(tsConfig, null, 2)}`);
517
- const declarationPath = resolve(silgi.options.buildDir, "silgi.d.ts");
518
- await promises.writeFile(declarationPath, `${GeneratedBy}
519
- ${declaration}`);
520
- }
521
- await writeFile();
522
- }
523
- async function tsconfigExists(silgi) {
524
- const tsConfigPath = resolve(silgi.options.rootDir, "tsconfig.json");
525
- return existsSync(tsConfigPath);
526
- }
527
- async function writeRootTsConfig(silgi) {
528
- if (await tsconfigExists(silgi)) {
529
- return;
530
- }
531
- const GeneratedBy = `// Generated by silgi'
532
- {
533
- "references": [
534
- {
535
- "path": "./.silgi/tsconfig.json"
536
- },
537
- {
538
- "path": "./.silgi/tsconfig.client.json"
539
- }
540
- ],
541
- "files": []
542
- }
543
- `;
544
- const tsConfigPath = resolve(silgi.options.rootDir, "tsconfig.json");
545
- await promises.mkdir(silgi.options.rootDir, { recursive: true });
546
- await promises.writeFile(tsConfigPath, GeneratedBy);
547
- }
548
-
549
- async function generateRouterDTS(silgi) {
550
- silgi.hook("read:core.ts", async (data) => {
551
- silgi.hook("close", async () => {
552
- const { object } = await data();
553
- const uris = object.uris;
554
- const tag = "srn";
555
- const groupedRoutes = Object.entries(uris).reduce((acc, [key, _value]) => {
556
- const [service, resource, method, action] = key.split("/");
557
- const routePath = `${tag}/${service}/${resource}/${action}`;
558
- if (!acc[routePath]) {
559
- acc[routePath] = {};
560
- }
561
- acc[routePath][method] = {
562
- input: `ExtractInputFromURI<'${key}'>`,
563
- output: `ExtractOutputFromURI<'${key}'>`,
564
- params: `ExtractRouterParamsFromURI<'${key}'>['params']`
565
- };
566
- return acc;
567
- }, {});
568
- const routerTypes = Object.entries(groupedRoutes).map(([path, methods]) => {
569
- const methodEntries = Object.entries(methods).map(([method, { input, output, params }]) => {
570
- return ` '${method}': {
571
- input: ${input},
572
- output: ${output}
573
- params: ${params}
574
- }`;
575
- }).join(",\n");
576
- return ` '/${path}': {
577
- ${methodEntries}
578
- }`;
579
- });
580
- const nitro = [
581
- "declare module 'nitropack/types' {",
582
- " interface InternalApi extends RouterTypes {}",
583
- "}"
584
- ];
585
- const context = [
586
- "import type { ExtractInputFromURI, ExtractOutputFromURI, ExtractRouterParamsFromURI } from 'silgi'",
587
- "",
588
- "export interface RouterTypes {",
589
- routerTypes.join(",\n"),
590
- "}",
591
- "",
592
- "declare module 'silgi' {",
593
- " interface SilgiRouterTypes extends RouterTypes {",
594
- " }",
595
- "}",
596
- "",
597
- silgi.options.environment === "h3" || silgi.options.environment === "nitrojs" ? nitro.join("\n") : "",
598
- "",
599
- "export {}"
600
- ].join("\n");
601
- const outputPath = resolve(silgi.options.buildDir, "silgi-routes.d.ts");
602
- await promises.writeFile(outputPath, context);
603
- });
604
- });
605
- }
606
-
607
- async function writeTypes(silgi) {
608
- await writeH3DTS(silgi);
609
- await generateRouterDTS(silgi);
610
- await writeSilgiFile(silgi);
611
- await writeSchema(silgi);
612
- await writeTsConfig(silgi);
613
- await writeRootTsConfig(silgi);
614
- }
615
-
616
- class SchemaParser {
617
- options = {
618
- debug: false
619
- };
620
- /**
621
- *
622
- */
623
- constructor(options) {
624
- this.options = {
625
- ...this.options,
626
- ...options
627
- };
628
- }
629
- parseExports(content, filePath) {
630
- const ast = parseSync(content, { sourceType: "module", sourceFilename: filePath });
631
- if (this.options.debug)
632
- writeFileSync(`${filePath}.ast.json`, JSON.stringify(ast.program, null, 2));
633
- return {
634
- exportVariables: (search, path) => this.parseTypeDeclarations(ast, search, path),
635
- parseInterfaceDeclarations: (search, path) => this.parseInterfaceDeclarations(ast, search, path)
636
- // parsePlugin: (path: string) => this.parsePlugin(ast, path),
637
- };
638
- }
639
- parseVariableDeclaration(ast) {
640
- return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "VariableDeclaration");
641
- }
642
- parseTSInterfaceDeclaration(ast) {
643
- return ast.program.body.filter((i) => i.type === "ExportNamedDeclaration").filter((i) => i.declaration?.type === "TSInterfaceDeclaration");
644
- }
645
- parseTypeDeclarations(ast, find = "", path = "") {
646
- const data = [];
647
- for (const item of this.parseVariableDeclaration(ast)) {
648
- for (const declaration of item.declaration.declarations) {
649
- if (declaration.init.callee?.name === find) {
650
- const options = {};
651
- if (declaration.init.arguments) {
652
- for (const argument of declaration.init.arguments) {
653
- for (const propertie of argument.properties) {
654
- if (propertie.key.name === "name")
655
- options.pluginName = propertie.value.value;
656
- }
657
- }
658
- }
659
- for (const key in declaration.init.properties) {
660
- const property = declaration.init.properties[key];
661
- if (property.type === "ObjectProperty") {
662
- if (property.key.name === "options") {
663
- for (const key2 in property.value.properties) {
664
- const option = property.value.properties[key2];
665
- if (option.type === "ObjectProperty") {
666
- options[option.key.name] = option.value.value;
667
- }
668
- }
669
- }
670
- }
671
- }
672
- options.type = false;
673
- data.push({
674
- exportName: declaration.id.name,
675
- options,
676
- // object: declaration.init,
677
- path
678
- });
679
- }
680
- }
681
- }
682
- return data;
683
- }
684
- parseInterfaceDeclarations(ast, find = "", path = "") {
685
- const data = [];
686
- for (const item of this.parseTSInterfaceDeclaration(ast)) {
687
- if (!item?.declaration?.extends)
688
- continue;
689
- for (const declaration of item?.declaration?.extends) {
690
- if (declaration.expression.name === find) {
691
- const options = {};
692
- options.type = true;
693
- data.push({
694
- exportName: item.declaration.id.name,
695
- options,
696
- // object: declaration.init,
697
- path
698
- });
699
- }
700
- }
701
- }
702
- return data;
703
- }
704
- // private parsePlugin(ast: any, path: string = '') {
705
- // const data = {
706
- // export: [],
707
- // name: '',
708
- // path: '',
709
- // } as DataTypePlugin
710
- // for (const item of this.parseVariableDeclaration(ast)) {
711
- // for (const declaration of item.declaration.declarations) {
712
- // if (declaration.init.callee?.name === 'defineSilgiModule') {
713
- // if (declaration.init.arguments) {
714
- // for (const argument of declaration.init.arguments) {
715
- // for (const propertie of argument.properties) {
716
- // if (propertie.key.name === 'name')
717
- // data.name = propertie.value.value
718
- // }
719
- // }
720
- // }
721
- // data.export.push({
722
- // name: data.name,
723
- // as: camelCase(`${data.name}DefineSilgiModule`),
724
- // type: false,
725
- // })
726
- // }
727
- // }
728
- // }
729
- // for (const item of this.parseTSInterfaceDeclaration(ast)) {
730
- // if (!item?.declaration?.extends)
731
- // continue
732
- // for (const declaration of item?.declaration?.extends) {
733
- // if (declaration.expression.name === 'SilgiModuleOptions') {
734
- // data.export.push({
735
- // name: item.declaration.id.name,
736
- // as: camelCase(`${data.name}SilgiModuleOptions`),
737
- // type: true,
738
- // })
739
- // }
740
- // // TODO add other plugins
741
- // }
742
- // }
743
- // data.path = path
744
- // console.log(data)
745
- // return data
746
- // }
747
- }
748
-
749
- function resolveIgnorePatterns(silgi, relativePath) {
750
- if (!silgi) {
751
- return [];
752
- }
753
- const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
754
- const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
755
- if (existsSync(nuxtignoreFile)) {
756
- const contents = readFileSync(nuxtignoreFile, "utf-8");
757
- ignorePatterns.push(...contents.trim().split(/\r?\n/));
758
- }
759
- return ignorePatterns;
760
- }
761
- function isIgnored(pathname, silgi, _stats) {
762
- if (!silgi) {
763
- return false;
764
- }
765
- if (!silgi._ignore) {
766
- silgi._ignore = ignore(silgi.options.ignoreOptions);
767
- silgi._ignore.add(resolveIgnorePatterns(silgi));
768
- }
769
- const relativePath = relative(silgi.options.rootDir, pathname);
770
- if (relativePath[0] === "." && relativePath[1] === ".") {
771
- return false;
772
- }
773
- return !!(relativePath && silgi._ignore.ignores(relativePath));
774
- }
775
- function resolveGroupSyntax(group) {
776
- let groups = [group];
777
- while (groups.some((group2) => group2.includes("{"))) {
778
- groups = groups.flatMap((group2) => {
779
- const [head, ...tail] = group2.split("{");
780
- if (tail.length) {
781
- const [body = "", ...rest] = tail.join("{").split("}");
782
- return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
783
- }
784
- return group2;
785
- });
786
- }
787
- return groups;
788
- }
789
-
790
- async function scanFiles(silgi) {
791
- const filePaths = /* @__PURE__ */ new Set();
792
- const scannedPaths = [];
793
- const dir = silgi.options.serverDir;
794
- const files = (await globby(dir, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
795
- if (files.length) {
796
- const siblings = await readdir(dirname(dir)).catch(() => []);
797
- const directory = basename(dir);
798
- if (!siblings.includes(directory)) {
799
- const directoryLowerCase = directory.toLowerCase();
800
- const caseCorrected = siblings.find((sibling) => sibling.toLowerCase() === directoryLowerCase);
801
- if (caseCorrected) {
802
- const original = relative(silgi.options.serverDir, dir);
803
- const corrected = relative(silgi.options.serverDir, join(dirname(dir), caseCorrected));
804
- consola.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`);
805
- }
806
- }
807
- }
808
- for (const _file of files) {
809
- const filePath = resolve(dir, _file);
810
- if (scannedPaths.find((d) => filePath.startsWith(withTrailingSlash(d))) || isIgnored(filePath, silgi)) {
811
- continue;
812
- }
813
- if (filePaths.has(filePath)) {
814
- continue;
815
- }
816
- filePaths.add(filePath);
817
- if (silgi.options.extensions.includes(extname(filePath))) {
818
- const parser = new SchemaParser({
819
- debug: false
820
- });
821
- const readfile = readFileSync(filePath, "utf-8");
822
- const { exportVariables, parseInterfaceDeclarations } = parser.parseExports(readfile, filePath);
823
- const createServices = exportVariables("createService", filePath);
824
- if (createServices.length > 0) {
825
- for (const createService of createServices) {
826
- const { exportName, path } = createService;
827
- silgi.hook("prepare:core.ts", (options) => {
828
- options.services.push(exportName);
829
- });
830
- silgi.hook("prepare:core.ts", (options) => {
831
- options.importedItems[path] ??= {
832
- import: [],
833
- from: relativeWithDot(silgi.options.silgiDir, path)
834
- };
835
- options.importedItems[path].import.push({
836
- name: exportName
837
- });
838
- });
839
- }
840
- }
841
- const createSchemas = exportVariables("createSchema", filePath);
842
- if (createSchemas.length > 0) {
843
- for (const createSchema of createSchemas) {
844
- const { exportName, path } = createSchema;
845
- silgi.hook("prepare:core.ts", (options) => {
846
- options.schemas.push(exportName);
847
- });
848
- silgi.hook("prepare:core.ts", (options) => {
849
- options.importedItems[path] ??= {
850
- import: [],
851
- from: relativeWithDot(silgi.options.silgiDir, path)
852
- };
853
- options.importedItems[path].import.push({
854
- name: exportName
855
- });
856
- });
857
- }
858
- }
859
- const createShareds = exportVariables("createShared", filePath);
860
- if (createShareds.length > 0) {
861
- for (const createShared of createShareds) {
862
- const { exportName, path } = createShared;
863
- silgi.hook("prepare:core.ts", (options) => {
864
- options.shareds.push(exportName);
865
- });
866
- silgi.hook("prepare:core.ts", (options) => {
867
- options.importedItems[path] ??= {
868
- import: [],
869
- // Relative path kaldirmamiz gerekiyor bunlar hooklarin bittigi yerde karar verilmeli.
870
- from: relativeWithDot(silgi.options.silgiDir, path)
871
- };
872
- options.importedItems[path].import.push({
873
- name: exportName
874
- });
875
- });
876
- }
877
- }
878
- const sharedsTypes = parseInterfaceDeclarations("ExtendShared", filePath);
879
- if (sharedsTypes.length > 0) {
880
- for (const sharedType of sharedsTypes) {
881
- const { exportName, path } = sharedType;
882
- silgi.hook("prepare:schema.ts", (options) => {
883
- options.shareds.push({
884
- key: exportName,
885
- value: exportName
886
- });
887
- });
888
- silgi.hook("prepare:schema.ts", (options) => {
889
- options.importedItems[path] ??= {
890
- import: [],
891
- from: path
892
- };
893
- options.importedItems[path].import.push({
894
- name: exportName,
895
- type: true
896
- });
897
- });
898
- }
899
- }
900
- const contextTypes = parseInterfaceDeclarations("ExtendContext", filePath);
901
- if (contextTypes.length > 0) {
902
- for (const contextType of contextTypes) {
903
- const { exportName, path } = contextType;
904
- silgi.hook("prepare:schema.ts", (options) => {
905
- options.contexts.push({
906
- key: exportName,
907
- value: exportName
908
- });
909
- });
910
- silgi.hook("prepare:schema.ts", (options) => {
911
- options.importedItems[path] ??= {
912
- import: [],
913
- from: path
914
- };
915
- options.importedItems[path].import.push({
916
- name: exportName,
917
- type: true
918
- });
919
- });
920
- }
921
- }
922
- }
923
- }
924
- }
925
-
926
- async function readSilgiTs(silgi) {
927
- const path = resolve(silgi.options.silgiDir, "core.ts");
928
- const jiti = createJiti(silgi.options.rootDir, {
929
- fsCache: false,
930
- interopDefault: true,
931
- moduleCache: false
932
- });
933
- const context = await promises.readFile(path, "utf-8");
934
- const coreFile = await jiti.import(
935
- path
936
- );
937
- return {
938
- context,
939
- object: {
940
- schemas: coreFile.schemas,
941
- uris: coreFile.uris,
942
- services: coreFile.services,
943
- shareds: coreFile.shareds
944
- },
945
- path
946
- };
947
- }
948
-
949
- const logger = consola;
950
- async function loadCLISilgiModuleInstance(silgiModule, silgi) {
951
- const buildTimeModuleMeta = {};
952
- let resolvedModulePath;
953
- const resolvedModulePaths = [];
954
- const jiti = createJiti(silgi.options.rootDir);
955
- if (typeof silgiModule === "string") {
956
- const paths = /* @__PURE__ */ new Set();
957
- if (!/\.(?:js|ts|mjs)$/.test(silgiModule))
958
- paths.add(`${silgiModule}/module`);
959
- paths.add(silgiModule);
960
- for (const path of paths) {
961
- try {
962
- const src = isAbsolute(path) ? pathToFileURL(await resolvePath$1(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 });
963
- silgiModule = await jiti.import(src, { default: true });
964
- resolvedModulePath = fileURLToPath(new URL(src));
965
- } catch (error) {
966
- const code = error.code;
967
- if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
968
- continue;
969
- }
970
- logger.error(`Error while importing module \`${silgiModule}\`: ${error}`);
971
- throw error;
972
- }
973
- }
974
- }
975
- if (typeof silgiModule === "string") {
976
- throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
977
- }
978
- if (typeof silgiModule !== "function" && !silgi.options.isPackage) {
979
- if (typeof silgiModule === "object" && silgiModule.name === "modules") {
980
- for (const item of silgiModule.modules) {
981
- const path = resolvedModulePath?.replace(/\/module\.(mjs|ts)$/, `/${item}/module.$1`);
982
- if (path) {
983
- resolvedModulePaths?.push({
984
- name: item,
985
- path,
986
- multiple: true
987
- });
988
- }
989
- }
990
- } else {
991
- throw new TypeError(`Silgi module should be a function: ${silgiModule}`);
992
- }
993
- }
994
- if (typeof silgiModule === "function") {
995
- const meta = await silgiModule.getMeta?.();
996
- resolvedModulePaths?.push({
997
- name: meta.configKey || meta.name,
998
- path: resolvedModulePath
999
- });
1000
- }
1001
- for (const module of resolvedModulePaths) {
1002
- const silgiModule2 = await jiti.import(module.path, { default: true });
1003
- await silgiModule2({}, silgi, true);
1004
- }
1005
- return { silgiModule, buildTimeModuleMeta, resolvedModulePath, resolvedModulePaths };
1006
- }
1007
- async function loadCLISilgiModule(jiti, item, module, silgi, packageName) {
1008
- const moduleResolved = await jiti.import(item.path, { default: true });
1009
- if (typeof moduleResolved === "string") {
1010
- throw new TypeError(`Could not load \`${item.name}\`. Is it installed?`);
1011
- }
1012
- if (typeof moduleResolved !== "function") {
1013
- throw new TypeError(`Nuxt module should be a function: ${item.name}`);
1014
- }
1015
- const meta = await moduleResolved?.getMeta?.();
1016
- if (!meta) {
1017
- throw new TypeError(`Could not load \`${item.name}\`.`);
1018
- }
1019
- silgi.hook("prepare:core.ts", async (options) => {
1020
- if (packageName) {
1021
- if (item.multiple) {
1022
- options.imports.push(`import ${item.name} from '${packageName}/${item.name}'`);
1023
- silgi.options._installedModules.push({
1024
- meta,
1025
- entryPath: item.path,
1026
- packageName: `${packageName}/${item.name}`
1027
- });
1028
- } else {
1029
- options.imports.push(`import ${item.name} from '${packageName}'`);
1030
- silgi.options._installedModules.push({
1031
- meta,
1032
- entryPath: item.path,
1033
- packageName
1034
- });
1035
- }
1036
- } else {
1037
- const relativeRootDir = relativeWithDot(silgi.options.silgiDir, item.path);
1038
- options.imports.push(`import ${item.name} from '${relativeRootDir}'`);
1039
- silgi.options._installedModules.push({
1040
- meta,
1041
- entryPath: item.path,
1042
- packageName: item.path
1043
- });
1044
- }
1045
- });
1046
- }
1047
- async function modulesPackagesImport(silgi) {
1048
- const modules = [
1049
- ...silgi.options.modules,
1050
- ...silgi.options._modules
1051
- ];
1052
- const jiti = createJiti(silgi.options.rootDir);
1053
- for (const module of modules) {
1054
- const { resolvedModulePaths } = await loadCLISilgiModuleInstance(module, silgi);
1055
- for (const item of resolvedModulePaths || []) {
1056
- await loadCLISilgiModule(jiti, item, module, silgi, module);
1057
- }
1058
- }
1059
- }
1060
- async function modulesImport(silgi) {
1061
- const isPackage = silgi.options.isPackage ? `${silgi.options.dir.modules}/**/module.ts` : silgi.options.dir.modules;
1062
- const files = (await globby(isPackage, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
1063
- const jiti = createJiti(silgi.options.rootDir);
1064
- for (const file of files) {
1065
- const { resolvedModulePaths } = await loadCLISilgiModuleInstance(file, silgi);
1066
- for (const item of resolvedModulePaths || []) {
1067
- await loadCLISilgiModule(jiti, item, file, silgi);
1068
- }
1069
- }
1070
- }
1071
- async function installCLIModules(silgi) {
1072
- await modulesPackagesImport(silgi);
1073
- await modulesImport(silgi);
1074
- function createDependencyGraph(modules2) {
1075
- const graph2 = /* @__PURE__ */ new Map();
1076
- modules2.forEach((module) => {
1077
- const key = module.meta?.configKey;
1078
- if (key) {
1079
- graph2.set(key, /* @__PURE__ */ new Set());
1080
- }
1081
- });
1082
- modules2.forEach((module) => {
1083
- const key = module.meta?.configKey;
1084
- const deps = module.meta?.dependencies || [];
1085
- if (key && deps.length > 0) {
1086
- const modulesDeps = graph2.get(key) || /* @__PURE__ */ new Set();
1087
- deps.forEach((dep) => {
1088
- if (graph2.has(dep)) {
1089
- modulesDeps.add(dep);
1090
- }
1091
- });
1092
- graph2.set(key, modulesDeps);
1093
- }
1094
- });
1095
- return graph2;
1096
- }
1097
- function topologicalSort(graph2) {
1098
- const visited = /* @__PURE__ */ new Set();
1099
- const temp = /* @__PURE__ */ new Set();
1100
- const order = [];
1101
- function visit(node) {
1102
- if (temp.has(node)) {
1103
- throw new Error(`D\xF6ng\xFCsel ba\u011F\u0131ml\u0131l\u0131k tespit edildi: ${node}`);
1104
- }
1105
- if (visited.has(node))
1106
- return;
1107
- temp.add(node);
1108
- const deps = graph2.get(node) || /* @__PURE__ */ new Set();
1109
- for (const dep of deps) {
1110
- visit(dep);
1111
- }
1112
- temp.delete(node);
1113
- visited.add(node);
1114
- order.push(node);
1115
- }
1116
- for (const [node, deps] of graph2.entries()) {
1117
- if (deps.size === 0 && !visited.has(node)) {
1118
- visit(node);
1119
- }
1120
- }
1121
- for (const node of graph2.keys()) {
1122
- if (!visited.has(node)) {
1123
- visit(node);
1124
- }
1125
- }
1126
- return order;
1127
- }
1128
- const moduleMap = new Map(
1129
- silgi.options._installedModules.map((m) => [m.meta?.configKey, m])
1130
- );
1131
- const graph = createDependencyGraph(silgi.options._installedModules);
1132
- const sortedKeys = topologicalSort(graph);
1133
- const modules = sortedKeys.map((key) => moduleMap.get(key)).filter((module) => Boolean(module));
1134
- silgi.options._installedModules = modules;
1135
- silgi.hook("prepare:core.ts", async (options) => {
1136
- for (const module of silgi.options._installedModules) {
1137
- options.modules.push(module.meta.configKey);
1138
- }
1139
- });
1140
- silgi.hook("prepare:schema.ts", async (options) => {
1141
- for (const module of silgi.options._installedModules) {
1142
- const exports = module.meta.exports;
1143
- if (exports?.interface) {
1144
- let importName;
1145
- options.importedItems[module.meta.configKey] = {
1146
- import: [],
1147
- from: module.packageName
1148
- };
1149
- if (exports.interface.config) {
1150
- importName = pascalCase(`${module.meta.configKey}Config`);
1151
- options.importedItems[module.meta.configKey].import.push({
1152
- name: `SilgiModuleOptions as ${importName}`,
1153
- type: true
1154
- });
1155
- options.configs.push({
1156
- key: module.meta.configKey,
1157
- value: importName
1158
- });
1159
- }
1160
- if (exports.interface.context) {
1161
- importName = pascalCase(`${module.meta.configKey}Context`);
1162
- options.importedItems[module.meta.configKey].import.push({
1163
- name: `SilgiModuleContext as ${importName}`,
1164
- type: true
1165
- });
1166
- options.contexts.push({
1167
- key: module.meta.configKey,
1168
- value: importName
1169
- });
1170
- }
1171
- if (exports.interface.method) {
1172
- importName = pascalCase(`${module.meta.configKey}Method`);
1173
- options.importedItems[module.meta.configKey].import.push({
1174
- name: `SilgiModuleMethods as ${importName}`,
1175
- type: true
1176
- });
1177
- options.methods.push({
1178
- key: module.meta.configKey,
1179
- value: importName
1180
- });
1181
- }
1182
- if (exports.interface.shared) {
1183
- importName = pascalCase(`${module.meta.configKey}Shared`);
1184
- options.importedItems[module.meta.configKey].import.push({
1185
- name: `SilgiModuleShared as ${importName}`,
1186
- type: true
1187
- });
1188
- options.shareds.push({
1189
- key: module.meta.configKey,
1190
- value: importName
1191
- });
1192
- }
1193
- }
1194
- }
1195
- });
1196
- }
1197
-
1198
- async function generate$1(mergeConfig) {
1199
- const hooks = createHooks();
1200
- const silgi = {
1201
- services: {},
1202
- shared: {},
1203
- uris: {},
1204
- _initializedModules: {},
1205
- scannedHandlers: /* @__PURE__ */ new Map(),
1206
- schemas: {},
1207
- storage: undefined,
1208
- hooks,
1209
- callHook: hooks.callHook,
1210
- addHooks: hooks.addHooks,
1211
- hook: hooks.hook,
1212
- ready: () => {
1213
- return hooks.callHook("ready", silgi);
1214
- },
1215
- close: () => hooks.callHook("close", silgi),
1216
- options: mergeConfig,
1217
- _version: "v0",
1218
- hooksNames: null,
1219
- logger: null
1220
- };
1221
- silgi._ignore = ignore(silgi.options.ignoreOptions);
1222
- silgi.hook("prepare:types", (opts) => {
1223
- opts.references.push({ path: resolve(silgi.options.buildDir, "./schema.d.ts") });
1224
- opts.references.push({ path: resolve(silgi.options.buildDir, "./h3.d.ts") });
1225
- opts.references.push({ path: resolve(silgi.options.buildDir, "./silgi-routes.d.ts") });
1226
- });
1227
- await generateUris(silgi);
1228
- await generateSilgiStorageBaseType(silgi);
1229
- await installCLIModules(silgi);
1230
- await scanFiles(silgi);
1231
- await writeTypes(silgi);
1232
- await silgi.callHook("read:core.ts", async () => {
1233
- const data = await readSilgiTs(silgi);
1234
- return data;
1235
- });
1236
- return silgi;
1237
- }
1238
-
1239
- const generate = defineCommand({
1240
- meta: {
1241
- name: "Silgi Generate",
1242
- description: "Generate code",
1243
- version: "0.1.0"
1244
- },
1245
- args: {},
1246
- async run() {
1247
- const mergeConfig = await loadSilgiConfig({
1248
- overrides: {
1249
- dev: true
1250
- }
1251
- });
1252
- const silgi = await generate$1(mergeConfig);
1253
- await silgi.close();
1254
- }
1255
- });
1256
-
1257
- export { generate as default };