silgi 0.7.1 → 0.7.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.
Files changed (83) hide show
  1. package/dist/_chunks/index.mjs +5 -0
  2. package/dist/cli/{utils/compatibility.mjs → compatibility.mjs} +1 -1
  3. package/dist/cli/config/index.d.mts +11 -0
  4. package/dist/cli/config/index.d.ts +11 -0
  5. package/dist/{core/config/types.mjs → cli/config/index.mjs} +19 -2
  6. package/dist/cli/index.mjs +3 -3
  7. package/dist/cli/loader.mjs +581 -0
  8. package/dist/cli/prepare.mjs +1488 -0
  9. package/dist/core/index.d.mts +2 -10
  10. package/dist/core/index.d.ts +2 -10
  11. package/dist/core/index.mjs +943 -16
  12. package/dist/ecosystem/nitro/index.mjs +62 -1
  13. package/dist/ecosystem/nuxt/module.mjs +1 -1
  14. package/dist/kit/index.mjs +299 -10
  15. package/dist/meta/index.d.mts +1 -1
  16. package/dist/meta/index.d.ts +1 -1
  17. package/dist/meta/index.mjs +1 -1
  18. package/package.json +5 -1
  19. package/dist/cli/build/framework/h3.mjs +0 -46
  20. package/dist/cli/build/framework/index.mjs +0 -7
  21. package/dist/cli/build/framework/nitro.mjs +0 -28
  22. package/dist/cli/build/framework/nuxt.mjs +0 -9
  23. package/dist/cli/build/prepare.mjs +0 -7
  24. package/dist/cli/build/scanURIs.mjs +0 -27
  25. package/dist/cli/build/template/framework.mjs +0 -91
  26. package/dist/cli/build/template/schema.mjs +0 -115
  27. package/dist/cli/build/template/silgi.mjs +0 -149
  28. package/dist/cli/build/types.mjs +0 -130
  29. package/dist/cli/commands/prepare.mjs +0 -49
  30. package/dist/cli/common.mjs +0 -13
  31. package/dist/cli/core/app.mjs +0 -89
  32. package/dist/cli/core/scan.mjs +0 -40
  33. package/dist/cli/core/silgi.mjs +0 -77
  34. package/dist/cli/core/storage.mjs +0 -11
  35. package/dist/cli/core/templates.mjs +0 -29
  36. package/dist/cli/module/exportScan.mjs +0 -69
  37. package/dist/cli/module/install.mjs +0 -52
  38. package/dist/cli/module/scan.mjs +0 -141
  39. package/dist/cli/utils/generateRouterDTS.mjs +0 -84
  40. package/dist/cli/utils/ignore.mjs +0 -46
  41. package/dist/cli/utils/readCoreFile.mjs +0 -47
  42. package/dist/cli/utils/scan.mjs +0 -147
  43. package/dist/cli/utils/storage.mjs +0 -21
  44. package/dist/cli/utils/uri.mjs +0 -71
  45. package/dist/core/config/defaults.mjs +0 -96
  46. package/dist/core/config/loader.mjs +0 -98
  47. package/dist/core/config/resolvers/compatibility.mjs +0 -90
  48. package/dist/core/config/resolvers/imports.mjs +0 -96
  49. package/dist/core/config/resolvers/paths.mjs +0 -194
  50. package/dist/core/config/resolvers/storage.mjs +0 -25
  51. package/dist/core/config/resolvers/url.mjs +0 -7
  52. package/dist/core/createSilgi.mjs +0 -84
  53. package/dist/core/error.mjs +0 -227
  54. package/dist/core/fetch/ofetch.mjs +0 -35
  55. package/dist/core/parser.mjs +0 -136
  56. package/dist/core/silgi.mjs +0 -114
  57. package/dist/core/silgiApp.mjs +0 -15
  58. package/dist/core/unctx.mjs +0 -27
  59. package/dist/core/uris/uri.mjs +0 -33
  60. package/dist/core/uris/utils.mjs +0 -127
  61. package/dist/core/utils/event.mjs +0 -5
  62. package/dist/core/utils/global.mjs +0 -12
  63. package/dist/core/utils/merge.mjs +0 -25
  64. package/dist/core/utils/schema.mjs +0 -5
  65. package/dist/core/utils/service.mjs +0 -5
  66. package/dist/core/utils/shared.mjs +0 -5
  67. package/dist/core/utils/storage.mjs +0 -70
  68. package/dist/ecosystem/nitro/module.mjs +0 -62
  69. package/dist/kit/esm.mjs +0 -10
  70. package/dist/kit/fs.mjs +0 -25
  71. package/dist/kit/isFramework.mjs +0 -25
  72. package/dist/kit/logger.mjs +0 -8
  73. package/dist/kit/module.mjs +0 -73
  74. package/dist/kit/path.mjs +0 -34
  75. package/dist/kit/preset.mjs +0 -6
  76. package/dist/kit/resolve.mjs +0 -78
  77. package/dist/kit/template.mjs +0 -47
  78. package/dist/kit/utils.mjs +0 -20
  79. package/dist/package.json.mjs +0 -5
  80. package/dist/schema/common.mjs +0 -43
  81. package/dist/schema/index.mjs +0 -9
  82. package/dist/schema/internal.mjs +0 -22
  83. /package/dist/cli/{commands/init.mjs → init.mjs} +0 -0
@@ -0,0 +1,1488 @@
1
+ import { defineCommand } from 'citty';
2
+ import { join, resolve, isAbsolute, relative, dirname, basename, extname } from 'pathe';
3
+ import { version } from 'silgi/meta';
4
+ import { runtimeDir } from 'silgi/runtime/meta';
5
+ import { promises, existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
6
+ import { readdir } from 'node:fs/promises';
7
+ import { resolvePath, parseNodeModulePath, lookupNodeModuleSubpath, resolve as resolve$1 } from 'mlly';
8
+ import { resolveAlias } from 'pathe/utils';
9
+ import { silgiGenerateType, useSilgiCLI, SchemaParser, silgiCLICtx } from 'silgi/core';
10
+ import { relativeWithDot, isDirectory, writeFile, resolveAlias as resolveAlias$1, resolvePath as resolvePath$1, normalizeTemplate, useLogger } from 'silgi/kit';
11
+ import { toExports, scanExports, createUnimport } from 'unimport';
12
+ import { createJiti } from 'dev-jiti';
13
+ import { readPackageJSON } from 'pkg-types';
14
+ import { hash } from 'ohash';
15
+ import { consola } from 'consola';
16
+ import { createHooks, createDebugger } from 'hookable';
17
+ import { pascalCase } from 'scule';
18
+ import { h as hasInstalledModule } from './compatibility.mjs';
19
+ import { pathToFileURL, fileURLToPath } from 'node:url';
20
+ import { isRelative, withTrailingSlash } from 'ufo';
21
+ import { globby } from 'globby';
22
+ import ignore from 'ignore';
23
+ import { klona } from 'klona';
24
+ import { createStorage, builtinDrivers } from 'unstorage';
25
+ import { l as loadOptions } from './loader.mjs';
26
+ import 'semver/functions/satisfies.js';
27
+ import 'c12';
28
+ import 'compatx';
29
+ import 'klona/full';
30
+ import 'std-env';
31
+ import 'consola/utils';
32
+ import 'escape-string-regexp';
33
+
34
+ async function h3Framework(silgi, skip = false) {
35
+ if (silgi.options.preset !== "h3" && skip === false)
36
+ return;
37
+ if (silgi.options.preset === "h3") {
38
+ silgi.hook("after:prepare:schema.ts", (data) => {
39
+ data.unshift("type FrameworkContextExtends = NitroApp");
40
+ });
41
+ }
42
+ silgi.hook("prepare:schema.ts", (data) => {
43
+ data.importItems.nitropack = {
44
+ import: [
45
+ { name: "NitroApp", type: true }
46
+ ],
47
+ from: "nitropack/types"
48
+ };
49
+ data.importItems.h3 = {
50
+ import: [
51
+ { name: "H3Event", type: true }
52
+ ],
53
+ from: "h3"
54
+ };
55
+ data.events.push({
56
+ key: "H3Event",
57
+ value: "H3Event",
58
+ extends: true,
59
+ isSilgiContext: false
60
+ });
61
+ });
62
+ silgi.hook("prepare:createDTSFramework", (data) => {
63
+ data.importItems["silgi/types"] = {
64
+ import: [
65
+ { name: "ModuleRuntimeContext", type: true }
66
+ ],
67
+ from: "silgi/types"
68
+ };
69
+ data.customContent?.push(
70
+ "",
71
+ 'declare module "h3" {',
72
+ " interface H3EventContext extends ModuleRuntimeContext {}",
73
+ "}",
74
+ ""
75
+ );
76
+ });
77
+ }
78
+
79
+ async function nitroFramework(silgi, skip = false) {
80
+ if (silgi.options.preset !== "nitro" && skip === false)
81
+ return;
82
+ silgi.hook("prepare:schema.ts", (data) => {
83
+ data.importItems.nitropack = {
84
+ import: [
85
+ { name: "NitroApp", type: true }
86
+ ],
87
+ from: "nitropack/types"
88
+ };
89
+ });
90
+ silgi.hook("after:prepare:schema.ts", (data) => {
91
+ data.unshift("type FrameworkContextExtends = NitroApp");
92
+ });
93
+ silgi.options.plugins.push({
94
+ packageImport: "silgi/runtime/internal/nitro",
95
+ path: join(runtimeDir, "internal/nitro")
96
+ });
97
+ silgi.hook("prepare:core.ts", (_data) => {
98
+ });
99
+ await h3Framework(silgi, true);
100
+ }
101
+
102
+ async function nuxtFramework(silgi, skip = false) {
103
+ if (silgi.options.preset !== "nuxt" && skip === false)
104
+ return;
105
+ await nitroFramework(silgi, true);
106
+ }
107
+
108
+ const frameworkSetup = [h3Framework, nitroFramework, nuxtFramework];
109
+
110
+ async function prepare$1(_silgi) {
111
+ }
112
+
113
+ async function generateSilgiStorageBaseType(silgi) {
114
+ silgi.hook("prepare:schema.ts", async (options) => {
115
+ if (silgi.options.storage) {
116
+ for (const [key, _value] of Object.entries(silgi.options.storage)) {
117
+ options.storeBase.push(key);
118
+ }
119
+ }
120
+ });
121
+ }
122
+
123
+ async function generateRouterDTS(silgi) {
124
+ silgi.hook("finish:types", async (data) => {
125
+ const uris = data.object.uris;
126
+ const subPath = "srn";
127
+ const groupedPaths = /* @__PURE__ */ new Map();
128
+ Object.entries(uris || {}).forEach(([key, params]) => {
129
+ const [service, resource, method, action] = key.split("/");
130
+ const basePath = params ? `${subPath}/${service}/${resource}/${action}/${params}` : `${subPath}/${service}/${resource}/${action}`;
131
+ const fullPath = `${subPath}/${service}/${resource}/${action}`;
132
+ if (!groupedPaths.has(basePath)) {
133
+ groupedPaths.set(basePath, /* @__PURE__ */ new Map());
134
+ }
135
+ groupedPaths.get(basePath)?.set(method.toLowerCase(), fullPath);
136
+ });
137
+ const keys = [
138
+ " keys: {",
139
+ Array.from(groupedPaths.entries()).map(([basePath, methods]) => {
140
+ return ` '/${basePath}': {${Array.from(methods.entries()).map(([method, path]) => `
141
+ ${method}: '/${path}'`).join(",")}
142
+ }`;
143
+ }).join(",\n"),
144
+ " }",
145
+ ""
146
+ ].join("\n");
147
+ const groupedRoutes = Object.entries(uris || {}).reduce((acc, [key, _params]) => {
148
+ const [service, resource, method, action] = key.split("/");
149
+ const routePath = `${subPath}/${service}/${resource}/${action}`;
150
+ if (!acc[routePath]) {
151
+ acc[routePath] = {};
152
+ }
153
+ acc[routePath][method] = {
154
+ input: `ExtractInputFromURI<'${key}'>`,
155
+ output: `ExtractOutputFromURI<'${key}'>`,
156
+ params: `ExtractRouterParamsFromURI<'${key}'>['params']`
157
+ };
158
+ return acc;
159
+ }, {});
160
+ const routerTypes = Object.entries(groupedRoutes).map(([path, methods]) => {
161
+ const methodEntries = Object.entries(methods).map(([method, { input, output, params }]) => {
162
+ return ` '${method}': {
163
+ input: ${input},
164
+ output: ${output}
165
+ params: ${params}
166
+ }`;
167
+ }).join(",\n");
168
+ return ` '/${path}': {
169
+ ${methodEntries}
170
+ }`;
171
+ });
172
+ const nitro = [
173
+ "declare module 'nitropack/types' {",
174
+ " interface InternalApi extends RouterTypes {}",
175
+ "}"
176
+ ];
177
+ const content = [
178
+ keys.slice(0, -1),
179
+ // son satırdaki boş satırı kaldır
180
+ ...routerTypes
181
+ ].join(",\n");
182
+ const context = [
183
+ "import type { ExtractInputFromURI, ExtractOutputFromURI, ExtractRouterParamsFromURI } from 'silgi/types'",
184
+ "",
185
+ "export interface RouterTypes {",
186
+ content,
187
+ "}",
188
+ "",
189
+ "declare module 'silgi/types' {",
190
+ " interface SilgiRouterTypes extends RouterTypes {",
191
+ " }",
192
+ "}",
193
+ "",
194
+ silgi.options.preset === "h3" || silgi.options.preset === "nitro" ? nitro.join("\n") : "",
195
+ "",
196
+ "export {}"
197
+ ].join("\n");
198
+ const outputPath = resolve(silgi.options.build.typesDir, "silgi-routes.d.ts");
199
+ await promises.writeFile(outputPath, context);
200
+ });
201
+ }
202
+
203
+ async function readCoreFile(silgi) {
204
+ const path = resolve(silgi.options.silgi.serverDir, "core.ts");
205
+ const context = await promises.readFile(path, { encoding: "utf-8" });
206
+ const injectedResult = await silgi.unimport.injectImports(context, path);
207
+ if (!injectedResult) {
208
+ throw new Error("Failed to inject imports");
209
+ }
210
+ const jiti = createJiti(silgi.options.rootDir, {
211
+ fsCache: false,
212
+ moduleCache: false,
213
+ debug: silgi.options.debug,
214
+ alias: silgi.options.alias
215
+ });
216
+ const coreFile = await jiti.evalModule(
217
+ injectedResult.code,
218
+ {
219
+ filename: path,
220
+ async: true,
221
+ conditions: silgi.options.conditions
222
+ },
223
+ async (data, name) => {
224
+ return (await silgi.unimport.injectImports(data, name)).code;
225
+ }
226
+ );
227
+ silgi.uris = coreFile.uris;
228
+ silgi.schemas = coreFile.schemas;
229
+ silgi.services = coreFile.services;
230
+ silgi.shareds = coreFile.shareds;
231
+ silgi.modulesURIs = coreFile.modulesURIs;
232
+ return {
233
+ context,
234
+ object: {
235
+ schemas: coreFile.schemas,
236
+ uris: coreFile.uris,
237
+ services: coreFile.services,
238
+ shareds: coreFile.shareds,
239
+ modulesURIs: coreFile.modulesURIs
240
+ },
241
+ path
242
+ };
243
+ }
244
+
245
+ function traverseObject(silgi, obj, currentPath = []) {
246
+ const uriMap = /* @__PURE__ */ new Map();
247
+ function traverse(node, path = []) {
248
+ if (!node || typeof node !== "object")
249
+ return;
250
+ if (path.length === 4) {
251
+ const basePath = path.join("/");
252
+ let paramString = "";
253
+ if (node.router) {
254
+ let params = null;
255
+ if (node.router?._def?.typeName !== void 0) {
256
+ try {
257
+ const shape = node.router?.shape?.params?.shape;
258
+ params = shape ? Object.keys(shape) : null;
259
+ } catch {
260
+ params = null;
261
+ }
262
+ }
263
+ if (params?.length) {
264
+ paramString = params.map((p) => `:${p}`).join("/");
265
+ }
266
+ }
267
+ uriMap.set(basePath, paramString);
268
+ return;
269
+ }
270
+ for (const key in node) {
271
+ if (!["_type", "fields"].includes(key)) {
272
+ traverse(node[key], [...path, key]);
273
+ }
274
+ }
275
+ }
276
+ traverse(obj, currentPath);
277
+ return uriMap;
278
+ }
279
+ function scanActionModulesUris(silgi, obj, currentPath = []) {
280
+ const uriMap = {};
281
+ function traverse(node, path = []) {
282
+ if (!node || typeof node !== "object")
283
+ return;
284
+ if (path.length === 4) {
285
+ const basePath = path.join("/");
286
+ let moduleName = "";
287
+ if (node.modules?.yoga) {
288
+ let rootFieldName = null;
289
+ if (node.modules?.yoga?.rootFieldName) {
290
+ moduleName = "yoga";
291
+ rootFieldName = node.modules?.yoga?.rootFieldName;
292
+ }
293
+ if (!rootFieldName) {
294
+ return;
295
+ }
296
+ uriMap[moduleName] ??= {};
297
+ if (uriMap[moduleName].rootFieldName) {
298
+ silgi.logger.withTag("scanActionModulesUris").error(`Hata ${moduleName} ${rootFieldName} ${basePath} bu zaten burada kullanilmis.`);
299
+ }
300
+ uriMap[moduleName].rootFieldName ??= {};
301
+ uriMap[moduleName].rootFieldName[rootFieldName] = basePath;
302
+ }
303
+ return;
304
+ }
305
+ for (const key in node) {
306
+ if (!["_type", "fields"].includes(key)) {
307
+ traverse(node[key], [...path, key]);
308
+ }
309
+ }
310
+ }
311
+ traverse(obj, currentPath);
312
+ return uriMap;
313
+ }
314
+
315
+ async function scanUris(silgi) {
316
+ const { context, object, path } = await readCoreFile(silgi);
317
+ const uriMap = traverseObject(silgi, object.schemas, []);
318
+ const modulesURIs = scanActionModulesUris(silgi, object.services, []);
319
+ const uriContent = Array.from(uriMap.entries()).map(([uri, params]) => ` '${uri}': '${params}',`).join("\n");
320
+ let newContext = "";
321
+ if (uriMap.size > 0) {
322
+ newContext = context.replace(
323
+ /export const uris = \{[^}]*\}/,
324
+ `export const uris = {
325
+ ${uriContent}
326
+ }`
327
+ ).replace(
328
+ /export const modulesURIs = \{[^}]*\}/,
329
+ `export const modulesURIs = ${JSON.stringify(modulesURIs, null, 2)}`
330
+ );
331
+ } else {
332
+ newContext = context;
333
+ }
334
+ await promises.writeFile(path, newContext);
335
+ }
336
+
337
+ async function createCoreFramework(silgi) {
338
+ const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
339
+ if (silgi.options.preset !== "nitro" && silgi.options.preset !== "h3")
340
+ return;
341
+ const importItems = {
342
+ "silgi/types": {
343
+ import: [
344
+ { name: "ModuleRuntimeContext", type: true }
345
+ ],
346
+ from: "silgi/types"
347
+ }
348
+ };
349
+ await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
350
+ if (typeof id !== "string") {
351
+ return;
352
+ }
353
+ const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
354
+ if (!pkg?.name) {
355
+ return;
356
+ }
357
+ if (importItems[pkg.name]) {
358
+ importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
359
+ }
360
+ }));
361
+ const customImports = [];
362
+ const functions = [];
363
+ await silgi.callHook("prepare:createCoreFramework", {
364
+ importItems,
365
+ customImports,
366
+ functions
367
+ });
368
+ const content = [
369
+ ...functions.map((f) => f.params?.length ? ` await ${f.name}(framework, ${f.params.join(",")})` : ` await ${f.name}(framework)`)
370
+ ];
371
+ return {
372
+ content,
373
+ importItems,
374
+ customImports
375
+ };
376
+ }
377
+ async function createDTSFramework(silgi) {
378
+ const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
379
+ const importItems = {
380
+ "silgi/types": {
381
+ import: [
382
+ { name: "ModuleRuntimeContext", type: true }
383
+ ],
384
+ from: "silgi/types"
385
+ }
386
+ };
387
+ await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
388
+ if (typeof id !== "string") {
389
+ return;
390
+ }
391
+ const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
392
+ if (!pkg?.name) {
393
+ return;
394
+ }
395
+ if (importItems[pkg.name]) {
396
+ importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
397
+ }
398
+ }));
399
+ const customImports = [];
400
+ const customContent = [];
401
+ await silgi.callHook("prepare:createDTSFramework", {
402
+ importItems,
403
+ customImports,
404
+ customContent
405
+ });
406
+ const content = [
407
+ ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
408
+ const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
409
+ return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
410
+ }),
411
+ "",
412
+ ...customImports,
413
+ "",
414
+ ...customContent,
415
+ ""
416
+ ];
417
+ return {
418
+ content,
419
+ importItems
420
+ };
421
+ }
422
+
423
+ async function schemaTemplate(silgi) {
424
+ const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
425
+ const importItems = {
426
+ "silgi/types": {
427
+ import: [
428
+ { name: "URIsTypes", type: true },
429
+ { name: "Namespaces", type: true },
430
+ { name: "ModuleRuntimeContext", type: true }
431
+ ],
432
+ from: "silgi/types"
433
+ }
434
+ };
435
+ await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
436
+ if (typeof id !== "string") {
437
+ return;
438
+ }
439
+ const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
440
+ if (!pkg?.name) {
441
+ return;
442
+ }
443
+ if (importItems[pkg.name]) {
444
+ importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
445
+ }
446
+ }));
447
+ const data = {
448
+ importItems,
449
+ customImports: [],
450
+ configs: [],
451
+ contexts: [],
452
+ methods: [],
453
+ shareds: [],
454
+ events: [],
455
+ storeBase: [],
456
+ hooks: [],
457
+ runtimeHooks: []
458
+ };
459
+ const storeBase = [];
460
+ await silgi.callHook("prepare:schema.ts", data);
461
+ const silgiExport = relativeWithDot(silgi.options.build.typesDir, `${silgi.options.silgi.serverDir}/core.ts`);
462
+ let addSilgiContext = false;
463
+ const importsContent = [
464
+ ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
465
+ const path = isAbsolute(from) ? relativeWithDot(silgi.options.build.typesDir, from) : from;
466
+ return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${path}'`;
467
+ }),
468
+ "",
469
+ ...data.customImports,
470
+ ""
471
+ ];
472
+ const importData = [
473
+ "interface InferredNamespaces {",
474
+ ...(silgi.options.namespaces || []).map((key) => ` ${key}: string,`),
475
+ "}",
476
+ "",
477
+ `type SchemaExtends = Namespaces<typeof import('${silgiExport}')['schemas']>`,
478
+ "",
479
+ `type SilgiURIsMerge = URIsTypes<typeof import('${silgiExport}')['uris']>`,
480
+ "",
481
+ `type SilgiModuleContextExtends = ${data.contexts.length ? data.contexts.map(({ value }) => value).join(" & ") : "{}"}`,
482
+ "",
483
+ data.events.length ? `interface SilgiModuleEventsExtends extends ${data.events.map((item) => item.extends ? item.value : "").join(", ")} {
484
+ ${data.events.map((item) => {
485
+ if (item.isSilgiContext) {
486
+ addSilgiContext = true;
487
+ }
488
+ return !item.extends && !addSilgiContext ? ` ${item.key}: ${item.value}` : item.isSilgiContext ? " context: ModuleRuntimeContext" : "";
489
+ }).join(",\n")}
490
+ }` : "interface SilgiModuleEventsExtends {}",
491
+ "",
492
+ data.shareds.length ? `type SilgiModuleSharedExtends = ${data.shareds.map(({ value }) => value).join(" & ")}` : "type SilgiModuleSharedExtends = {}",
493
+ "",
494
+ "interface SilgiModuleMethodsExtends {",
495
+ ...(data.methods || []).map(({ key, value }) => ` ${key}: ${value},`),
496
+ "}",
497
+ "",
498
+ "interface SilgiModuleOptionsExtends {",
499
+ ...(data.configs || []).map(({ key, value }) => ` ${key}: ${value},`),
500
+ "}",
501
+ "",
502
+ "interface SilgiStorageBaseExtends {",
503
+ ...(storeBase || []).map((value) => ` ${value}: ''`),
504
+ "}",
505
+ "",
506
+ `type ModuleHooksExtend = ${data.hooks?.length ? data.hooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
507
+ "",
508
+ `type SilgiRuntimeHooksExtends = ${data.runtimeHooks?.length ? data.runtimeHooks.map(({ value }) => `${value}`).join(" & ") : "{}"}`,
509
+ "",
510
+ "declare module 'silgi/types' {",
511
+ " interface FrameworkContext extends FrameworkContextExtends {}",
512
+ " interface SilgiSchema extends SchemaExtends {}",
513
+ " interface SilgiNamespaces extends InferredNamespaces {}",
514
+ " interface SilgiStorageBase extends SilgiStorageBaseExtends {}",
515
+ " interface SilgiModules extends SilgiModuleOptionsExtends {}",
516
+ " interface SilgiURIs extends SilgiURIsMerge {}",
517
+ " interface ModuleRuntimeContext extends SilgiModuleContextExtends {}",
518
+ " interface SilgiEvent extends SilgiModuleEventsExtends {}",
519
+ " interface SilgiDefaultShared extends SilgiModuleSharedExtends {}",
520
+ " interface ModuleRuntimeMethods extends SilgiModuleMethodsExtends {}",
521
+ " interface ModuleOptions extends SilgiModuleOptionsExtends {}",
522
+ " interface ModuleRuntimeHooks extends SilgiRuntimeHooksExtends {}",
523
+ " interface ModuleHooks extends ModuleHooksExtend {}",
524
+ "}",
525
+ "",
526
+ "export {}"
527
+ ];
528
+ await silgi.callHook("after:prepare:schema.ts", importData);
529
+ importData.unshift(...importsContent);
530
+ return importData;
531
+ }
532
+
533
+ async function silgiCoreFile(data, frameworkContext, silgi) {
534
+ const relativeRootDir = relativeWithDot(silgi.options.rootDir, silgi.options.serverDir);
535
+ let importItems = {
536
+ "silgi/core": {
537
+ import: [
538
+ { name: "createSilgi" }
539
+ ],
540
+ from: "silgi/core"
541
+ },
542
+ "silgi/types": {
543
+ import: [
544
+ { name: "ModuleOptions", type: true },
545
+ { name: "SilgiOptions", type: true },
546
+ { name: "FrameworkContext", type: true },
547
+ { name: "DeepPartial", type: true },
548
+ { name: "BuildConfig", type: true }
549
+ ],
550
+ from: "silgi/types"
551
+ },
552
+ "#silgi/vfs": {
553
+ import: [],
554
+ from: "./vfs"
555
+ }
556
+ };
557
+ importItems = { ...data._importItems, ...importItems };
558
+ await Promise.all([...silgi.options.modules, ...silgi.options._modules].map(async (id) => {
559
+ if (typeof id !== "string") {
560
+ return;
561
+ }
562
+ const pkg = await readPackageJSON(id, { url: silgi.options.modulesDir }).catch(() => null);
563
+ if (!pkg?.name) {
564
+ return;
565
+ }
566
+ if (importItems[pkg.name]) {
567
+ importItems[pkg.name].from = isAbsolute(id) ? relativeWithDot(relativeRootDir, id) : id;
568
+ }
569
+ }));
570
+ const customImports = data._customImports || [];
571
+ const uris = [];
572
+ const services = [];
573
+ const shareds = [];
574
+ const schemas = [];
575
+ const buildSilgiExtraContent = [];
576
+ const _silgiOptions = {};
577
+ const _silgiConfigs = [];
578
+ for (const module of silgi.scanModules) {
579
+ _silgiOptions[module.meta.configKey] = {
580
+ ...module.options
581
+ };
582
+ }
583
+ await silgi.callHook("prepare:core.ts", {
584
+ importItems,
585
+ customImports,
586
+ uris,
587
+ services,
588
+ shareds,
589
+ schemas,
590
+ buildSilgiExtraContent,
591
+ _silgiOptions,
592
+ _silgiConfigs
593
+ });
594
+ if (importItems["#silgi/vfs"].import.length === 0) {
595
+ delete importItems["#silgi/vfs"];
596
+ }
597
+ if (services.length > 0) {
598
+ importItems["silgi/core"].import.push({ name: "mergeServices" });
599
+ }
600
+ if (shareds.length > 0) {
601
+ importItems["silgi/core"].import.push({ name: "mergeShared" });
602
+ }
603
+ if (schemas.length > 0) {
604
+ importItems["silgi/core"].import.push({ name: "mergeSchemas" });
605
+ }
606
+ const plugins = [];
607
+ for (const plugin of silgi.options.plugins) {
608
+ const pluginImportName = `_${hash(plugin.packageImport)}`;
609
+ customImports.push(`import ${pluginImportName} from '${plugin.packageImport}'`);
610
+ plugins.push(pluginImportName);
611
+ }
612
+ const importsContent = [
613
+ ...Object.entries(importItems).map(([_name, { from, import: imports }]) => {
614
+ return `import { ${imports.map(({ type, name }) => type ? `type ${name}` : name).join(", ")} } from '${from}'`;
615
+ }),
616
+ "",
617
+ ...customImports,
618
+ ""
619
+ ];
620
+ const importData = [
621
+ "export const uris = {}",
622
+ "",
623
+ "export const modulesURIs = {}",
624
+ "",
625
+ schemas.length > 0 ? "export const schemas = mergeSchemas([" : "export const schemas = {",
626
+ ...schemas.map((name) => {
627
+ return ` ${name},`;
628
+ }),
629
+ schemas.length > 0 ? "])" : "}",
630
+ "",
631
+ services.length > 0 ? "export const services = mergeServices([" : "export const services = {",
632
+ ...services.map((name) => {
633
+ return ` ${name},`;
634
+ }),
635
+ services.length > 0 ? "])" : "}",
636
+ "",
637
+ shareds.length > 0 ? "export const shareds = mergeShared([" : "export const shareds = {",
638
+ ...shareds.map((name) => {
639
+ return ` ${name},`;
640
+ }),
641
+ shareds.length > 0 ? "])" : "}",
642
+ "",
643
+ `export const _silgiOptions: DeepPartial<ModuleOptions> = ${JSON.stringify(_silgiOptions, null, 2)}`,
644
+ "",
645
+ "export async function buildSilgi(framework: FrameworkContext, moduleOptions?: Partial<ModuleOptions>,buildOptions?: Partial<BuildConfig>, ) {",
646
+ " const silgi = await createSilgi({",
647
+ " framework,",
648
+ " shared: shareds as any,",
649
+ " services: services as any,",
650
+ " schemas: schemas as any,",
651
+ " uris,",
652
+ " modulesURIs,",
653
+ ` plugins: [${plugins.join(", ")}],`,
654
+ _silgiConfigs.length > 0 ? ` ${_silgiConfigs.map((config) => Object.entries(config).map(([key, value]) => `${key}: ${value}`)).join(",\n ")},` : "",
655
+ " ...buildOptions,",
656
+ " options: {",
657
+ ` present: '${silgi.options.preset}',`,
658
+ " ..._silgiOptions,",
659
+ " ...moduleOptions,",
660
+ " },",
661
+ " })",
662
+ "",
663
+ ...frameworkContext,
664
+ "",
665
+ ...buildSilgiExtraContent,
666
+ "",
667
+ " return silgi",
668
+ "}",
669
+ ""
670
+ ];
671
+ await silgi.callHook("after:prepare:core.ts", importData);
672
+ importData.unshift(...importsContent);
673
+ return importData;
674
+ }
675
+
676
+ async function writeTypesAndFiles(silgi) {
677
+ const data = await createCoreFramework(silgi);
678
+ await generateSilgiStorageBaseType(silgi);
679
+ await generateRouterDTS(silgi);
680
+ silgi.hook("prepare:types", (opts) => {
681
+ opts.references.push({ path: "./schema.d.ts" });
682
+ opts.references.push({ path: "./silgi-routes.d.ts" });
683
+ opts.references.push({ path: "./framework.d.ts" });
684
+ });
685
+ const schemaContent = await schemaTemplate(silgi);
686
+ const coreContent = await silgiCoreFile({
687
+ _importItems: data?.importItems ?? {},
688
+ _customImports: data?.customImports ?? []
689
+ }, data?.content ?? [], silgi);
690
+ const frameworkDTS = await createDTSFramework(silgi);
691
+ const { declarations, tsConfig } = await silgiGenerateType(silgi);
692
+ const tsConfigPath = resolve(
693
+ silgi.options.typescript.generateTsConfig ? silgi.options.build.dir : silgi.options.rootDir,
694
+ silgi.options.typescript.tsconfigPath
695
+ );
696
+ const typesDir = resolve(silgi.options.build.typesDir);
697
+ const silgiDir = resolve(silgi.options.silgi.serverDir);
698
+ let autoImportedTypes = [];
699
+ let autoImportExports = "";
700
+ if (silgi.unimport) {
701
+ await silgi.unimport.init();
702
+ const allImports = await silgi.unimport.getImports();
703
+ autoImportExports = toExports(allImports).replace(
704
+ /#internal\/nitro/g,
705
+ relative(typesDir, runtimeDir)
706
+ );
707
+ const resolvedImportPathMap = /* @__PURE__ */ new Map();
708
+ for (const i of allImports.filter((i2) => !i2.type)) {
709
+ if (resolvedImportPathMap.has(i.from)) {
710
+ continue;
711
+ }
712
+ let path = resolveAlias(i.from, silgi.options.alias);
713
+ if (isAbsolute(path)) {
714
+ const resolvedPath = await resolvePath(i.from, {
715
+ url: silgi.options.nodeModulesDirs
716
+ }).catch(() => null);
717
+ if (resolvedPath) {
718
+ const { dir, name } = parseNodeModulePath(resolvedPath);
719
+ if (!dir || !name) {
720
+ path = resolvedPath;
721
+ } else {
722
+ const subpath = await lookupNodeModuleSubpath(resolvedPath);
723
+ path = join(dir, name, subpath || "");
724
+ }
725
+ }
726
+ }
727
+ if (existsSync(path) && !await isDirectory(path)) {
728
+ path = path.replace(/\.[a-z]+$/, "");
729
+ }
730
+ if (isAbsolute(path)) {
731
+ path = relative(typesDir, path);
732
+ }
733
+ resolvedImportPathMap.set(i.from, path);
734
+ }
735
+ autoImportedTypes = [
736
+ silgi.options.imports && silgi.options.imports.autoImport !== false ? (await silgi.unimport.generateTypeDeclarations({
737
+ exportHelper: false,
738
+ resolvePath: (i) => resolvedImportPathMap.get(i.from) ?? i.from
739
+ })).trim() : ""
740
+ ];
741
+ }
742
+ const buildFiles = [];
743
+ buildFiles.push({
744
+ path: join(typesDir, "silgi-routes.d.ts"),
745
+ // contents: uris.join('\n'),
746
+ contents: ""
747
+ });
748
+ buildFiles.push({
749
+ path: join(silgiDir, "core.ts"),
750
+ contents: coreContent.join("\n")
751
+ });
752
+ buildFiles.push({
753
+ path: join(typesDir, "schema.d.ts"),
754
+ contents: schemaContent.join("\n")
755
+ });
756
+ buildFiles.push({
757
+ path: join(typesDir, "silgi-imports.d.ts"),
758
+ contents: [...autoImportedTypes, autoImportExports || "export {}"].join(
759
+ "\n"
760
+ )
761
+ });
762
+ buildFiles.push({
763
+ path: join(typesDir, "silgi.d.ts"),
764
+ contents: declarations.join("\n")
765
+ });
766
+ buildFiles.push({
767
+ path: tsConfigPath,
768
+ contents: JSON.stringify(tsConfig, null, 2)
769
+ });
770
+ buildFiles.push({
771
+ path: join(typesDir, "framework.d.ts"),
772
+ contents: frameworkDTS.content.join("\n")
773
+ });
774
+ for await (const file of buildFiles) {
775
+ await writeFile(
776
+ resolve(silgi.options.build.dir, file.path),
777
+ file.contents
778
+ );
779
+ }
780
+ await scanUris(silgi);
781
+ const readCore = await readCoreFile(silgi);
782
+ silgi.uris = readCore.object.uris;
783
+ silgi.modulesURIs = readCore.object.modulesURIs;
784
+ silgi.schemas = readCore.object.schemas;
785
+ silgi.shareds = readCore.object.shareds;
786
+ await silgi.hooks.callHook("finish:types", readCore);
787
+ }
788
+
789
+ const commonArgs = {
790
+ dir: {
791
+ type: "string",
792
+ description: "project root directory"
793
+ },
794
+ _dir: {
795
+ type: "positional",
796
+ default: ".",
797
+ description: "project root directory (prefer using `--dir`)"
798
+ }
799
+ };
800
+
801
+ async function registerModuleExportScan(silgi) {
802
+ silgi.hook("prepare:schema.ts", async (options) => {
803
+ for (const module of silgi.scanModules) {
804
+ const exports = module.meta.exports;
805
+ if (!exports?.length)
806
+ continue;
807
+ const configKey = module.meta.configKey;
808
+ const moduleName = module.meta.name || module.meta._packageName;
809
+ options.importItems[configKey] = {
810
+ import: [],
811
+ from: module.meta._packageName ? moduleName : relativeWithDot(silgi.options.build.typesDir, module.entryPath)
812
+ };
813
+ const exportedTypes = exports.filter((exp) => exp.type).map((exp) => exp.name);
814
+ if (exportedTypes.includes("ModuleOptions")) {
815
+ const importName = pascalCase(`${configKey}Config`);
816
+ options.importItems[configKey].import.push({
817
+ name: `ModuleOptions as ${importName}`,
818
+ type: true
819
+ });
820
+ options.configs.push({ key: configKey, value: importName });
821
+ }
822
+ if (exportedTypes.includes("ModuleRuntimeContext")) {
823
+ const importName = pascalCase(`${configKey}Context`);
824
+ options.importItems[configKey].import.push({
825
+ name: `ModuleRuntimeContext as ${importName}`,
826
+ type: true
827
+ });
828
+ options.contexts.push({ key: configKey, value: importName });
829
+ }
830
+ if (exportedTypes.includes("ModuleRuntimeMethods")) {
831
+ const importName = pascalCase(`${configKey}Method`);
832
+ options.importItems[configKey].import.push({
833
+ name: `ModuleRuntimeMethods as ${importName}`,
834
+ type: true
835
+ });
836
+ options.methods.push({ key: configKey, value: importName });
837
+ }
838
+ if (exportedTypes.includes("ModuleRuntimeShared")) {
839
+ const importName = pascalCase(`${configKey}Shared`);
840
+ options.importItems[configKey].import.push({
841
+ name: `ModuleRuntimeShared as ${importName}`,
842
+ type: true
843
+ });
844
+ options.shareds.push({ key: configKey, value: importName });
845
+ }
846
+ if (exportedTypes.includes("ModuleHooks")) {
847
+ const importName = pascalCase(`${configKey}Hooks`);
848
+ options.importItems[configKey].import.push({
849
+ name: `ModuleHooks as ${importName}`,
850
+ type: true
851
+ });
852
+ options.hooks.push({ key: configKey, value: importName });
853
+ }
854
+ if (exportedTypes.includes("ModuleRuntimeHooks")) {
855
+ const importName = pascalCase(`${configKey}RuntimeHooks`);
856
+ options.importItems[configKey].import.push({
857
+ name: `ModuleRuntimeHooks as ${importName}`,
858
+ type: true
859
+ });
860
+ options.runtimeHooks.push({ key: configKey, value: importName });
861
+ }
862
+ }
863
+ });
864
+ }
865
+
866
+ async function loadSilgiModuleInstance(silgiModule) {
867
+ if (typeof silgiModule === "string") {
868
+ throw new TypeError(`Could not load \`${silgiModule}\`. Is it installed?`);
869
+ }
870
+ if (typeof silgiModule !== "function") {
871
+ throw new TypeError(`Nuxt module should be a function: ${silgiModule}`);
872
+ }
873
+ return { silgiModule };
874
+ }
875
+ async function installModules(silgi) {
876
+ const jiti = createJiti(silgi.options.rootDir, {
877
+ alias: silgi.options.alias
878
+ });
879
+ for (const module of silgi.scanModules) {
880
+ if (hasInstalledModule(module.meta.configKey)) {
881
+ silgi.logger.info(`Module ${module.meta.configKey} installed`);
882
+ }
883
+ try {
884
+ const silgiModule = await jiti.import(module.entryPath, {
885
+ default: true,
886
+ conditions: silgi.options.conditions
887
+ });
888
+ if (silgiModule.name !== "silgiNormalizedModule") {
889
+ silgi.scanModules = silgi.scanModules.filter((m) => m.entryPath !== module.entryPath);
890
+ continue;
891
+ }
892
+ await installModule(silgiModule, silgi);
893
+ } catch (err) {
894
+ silgi.logger.error(err);
895
+ }
896
+ }
897
+ }
898
+ async function installModule(moduleToInstall, silgi = useSilgiCLI(), inlineOptions) {
899
+ const { silgiModule } = await loadSilgiModuleInstance(moduleToInstall);
900
+ const res = await silgiModule({}, silgi) ?? {};
901
+ if (res === false) {
902
+ return false;
903
+ }
904
+ const metaData = await silgiModule.getMeta?.();
905
+ const installedModule = silgi.scanModules.find((m) => m.meta.configKey === metaData?.configKey);
906
+ if (installedModule) {
907
+ installedModule.installed = true;
908
+ } else {
909
+ throw new Error(`Module ${metaData?.name} not found`);
910
+ }
911
+ }
912
+
913
+ const logger$1 = consola;
914
+ async function _resolveSilgiModule(mod, silgi) {
915
+ let _url;
916
+ let buildTimeModuleMeta = {};
917
+ const jiti = createJiti(silgi.options.rootDir, {
918
+ alias: silgi.options.alias
919
+ });
920
+ if (typeof mod === "string") {
921
+ const paths = /* @__PURE__ */ new Set();
922
+ mod = resolveAlias$1(mod, silgi.options.alias);
923
+ if (isRelative(mod)) {
924
+ mod = resolve(silgi.options.rootDir, mod);
925
+ }
926
+ paths.add(join(mod, "module"));
927
+ paths.add(mod);
928
+ for (const path of paths) {
929
+ try {
930
+ 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 });
931
+ mod = await jiti.import(src, {
932
+ default: true,
933
+ conditions: silgi.options.conditions
934
+ });
935
+ _url = fileURLToPath(new URL(src));
936
+ const moduleMetadataPath = new URL("module.json", src);
937
+ if (existsSync(moduleMetadataPath)) {
938
+ buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
939
+ } else {
940
+ if (typeof mod === "function") {
941
+ const meta = await mod.getMeta?.();
942
+ const _exports = await scanExports(_url, true);
943
+ buildTimeModuleMeta = {
944
+ ...meta,
945
+ exports: _exports.map(({ from, ...rest }) => rest)
946
+ };
947
+ }
948
+ }
949
+ break;
950
+ } catch (error) {
951
+ const code = error.code;
952
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
953
+ continue;
954
+ }
955
+ logger$1.error(`Error while importing module \`${mod}\`: ${error}`);
956
+ throw error;
957
+ }
958
+ }
959
+ }
960
+ if (!buildTimeModuleMeta) {
961
+ throw new Error(`Module ${mod} is not a valid Silgi module`);
962
+ }
963
+ if (typeof mod === "function") {
964
+ if (silgi.scanModules.some((m) => m.meta?.configKey === buildTimeModuleMeta.configKey)) {
965
+ throw new Error(`Module with key \`${buildTimeModuleMeta.configKey}\` already exists`);
966
+ }
967
+ silgi.scanModules.push({
968
+ meta: buildTimeModuleMeta,
969
+ entryPath: _url,
970
+ installed: false,
971
+ options: await mod.getOptions?.() || {}
972
+ });
973
+ }
974
+ }
975
+ async function scanModules$1(silgi) {
976
+ const _modules = [
977
+ ...silgi.options._modules,
978
+ ...silgi.options.modules
979
+ ];
980
+ for await (const mod of _modules) {
981
+ await _resolveSilgiModule(mod, silgi);
982
+ }
983
+ const moduleMap = new Map(
984
+ silgi.scanModules.map((m) => [m.meta?.configKey, m])
985
+ );
986
+ const graph = createDependencyGraph(silgi.scanModules);
987
+ const sortedKeys = topologicalSort(graph);
988
+ const modules = sortedKeys.map((key) => moduleMap.get(key)).filter((module) => Boolean(module));
989
+ silgi.scanModules = modules;
990
+ }
991
+ function createDependencyGraph(modules) {
992
+ const graph = /* @__PURE__ */ new Map();
993
+ modules.forEach((module) => {
994
+ const key = module.meta?.configKey;
995
+ if (key) {
996
+ graph.set(key, /* @__PURE__ */ new Set());
997
+ }
998
+ });
999
+ modules.forEach((module) => {
1000
+ const key = module.meta?.configKey;
1001
+ const deps = module.meta?.dependencies || [];
1002
+ if (key && deps.length > 0) {
1003
+ const modulesDeps = graph.get(key) || /* @__PURE__ */ new Set();
1004
+ deps.forEach((dep) => {
1005
+ if (graph.has(dep)) {
1006
+ modulesDeps.add(dep);
1007
+ }
1008
+ });
1009
+ graph.set(key, modulesDeps);
1010
+ }
1011
+ });
1012
+ return graph;
1013
+ }
1014
+ function topologicalSort(graph) {
1015
+ const visited = /* @__PURE__ */ new Set();
1016
+ const temp = /* @__PURE__ */ new Set();
1017
+ const order = [];
1018
+ function visit(node) {
1019
+ if (temp.has(node))
1020
+ throw new Error(`Circular dependency detected: ${node}`);
1021
+ if (visited.has(node))
1022
+ return;
1023
+ temp.add(node);
1024
+ const deps = graph.get(node) || /* @__PURE__ */ new Set();
1025
+ for (const dep of deps) {
1026
+ visit(dep);
1027
+ }
1028
+ temp.delete(node);
1029
+ visited.add(node);
1030
+ order.unshift(node);
1031
+ }
1032
+ for (const [node, deps] of graph.entries()) {
1033
+ if (deps.size === 0 && !visited.has(node))
1034
+ visit(node);
1035
+ }
1036
+ for (const node of graph.keys()) {
1037
+ if (!visited.has(node))
1038
+ visit(node);
1039
+ }
1040
+ return order;
1041
+ }
1042
+
1043
+ function resolveIgnorePatterns(silgi, relativePath) {
1044
+ if (!silgi) {
1045
+ return [];
1046
+ }
1047
+ const ignorePatterns = silgi.options.ignore.flatMap((s) => resolveGroupSyntax(s));
1048
+ const nuxtignoreFile = join(silgi.options.rootDir, ".nuxtignore");
1049
+ if (existsSync(nuxtignoreFile)) {
1050
+ const contents = readFileSync(nuxtignoreFile, "utf-8");
1051
+ ignorePatterns.push(...contents.trim().split(/\r?\n/));
1052
+ }
1053
+ return ignorePatterns;
1054
+ }
1055
+ function isIgnored(pathname, silgi, _stats) {
1056
+ if (!silgi) {
1057
+ return false;
1058
+ }
1059
+ if (!silgi._ignore) {
1060
+ silgi._ignore = ignore(silgi.options.ignoreOptions);
1061
+ silgi._ignore.add(resolveIgnorePatterns(silgi));
1062
+ }
1063
+ const relativePath = relative(silgi.options.rootDir, pathname);
1064
+ if (relativePath[0] === "." && relativePath[1] === ".") {
1065
+ return false;
1066
+ }
1067
+ return !!(relativePath && silgi._ignore.ignores(relativePath));
1068
+ }
1069
+ function resolveGroupSyntax(group) {
1070
+ let groups = [group];
1071
+ while (groups.some((group2) => group2.includes("{"))) {
1072
+ groups = groups.flatMap((group2) => {
1073
+ const [head, ...tail] = group2.split("{");
1074
+ if (tail.length) {
1075
+ const [body = "", ...rest] = tail.join("{").split("}");
1076
+ return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
1077
+ }
1078
+ return group2;
1079
+ });
1080
+ }
1081
+ return groups;
1082
+ }
1083
+
1084
+ async function scanFiles$1(silgi) {
1085
+ const filePaths = /* @__PURE__ */ new Set();
1086
+ const scannedPaths = [];
1087
+ const dir = silgi.options.serverDir;
1088
+ const files = (await globby(dir, { cwd: silgi.options.rootDir, ignore: silgi.options.ignore })).sort();
1089
+ if (files.length) {
1090
+ const siblings = await readdir(dirname(dir)).catch(() => []);
1091
+ const directory = basename(dir);
1092
+ if (!siblings.includes(directory)) {
1093
+ const directoryLowerCase = directory.toLowerCase();
1094
+ const caseCorrected = siblings.find((sibling) => sibling.toLowerCase() === directoryLowerCase);
1095
+ if (caseCorrected) {
1096
+ const original = relative(silgi.options.serverDir, dir);
1097
+ const corrected = relative(silgi.options.serverDir, join(dirname(dir), caseCorrected));
1098
+ consola.warn(`Components not scanned from \`~/${corrected}\`. Did you mean to name the directory \`~/${original}\` instead?`);
1099
+ }
1100
+ }
1101
+ }
1102
+ for (const _file of files) {
1103
+ const filePath = resolve(dir, _file);
1104
+ if (scannedPaths.find((d) => filePath.startsWith(withTrailingSlash(d))) || isIgnored(filePath, silgi)) {
1105
+ continue;
1106
+ }
1107
+ if (filePaths.has(filePath)) {
1108
+ continue;
1109
+ }
1110
+ filePaths.add(filePath);
1111
+ if (silgi.options.extensions.includes(extname(filePath))) {
1112
+ const parser = new SchemaParser({
1113
+ debug: false
1114
+ });
1115
+ const readfile = readFileSync(filePath, "utf-8");
1116
+ const { exportVariables, parseInterfaceDeclarations } = parser.parseExports(readfile, filePath);
1117
+ const createServices = exportVariables("createService", filePath);
1118
+ if (createServices.length > 0) {
1119
+ for (const createService of createServices) {
1120
+ const { exportName, path } = createService;
1121
+ silgi.hook("prepare:core.ts", (options) => {
1122
+ options.services.push(exportName);
1123
+ });
1124
+ silgi.hook("prepare:core.ts", (options) => {
1125
+ options.importItems[path] ??= {
1126
+ import: [],
1127
+ from: relativeWithDot(silgi.options.silgi.serverDir, path)
1128
+ };
1129
+ options.importItems[path].import.push({
1130
+ name: exportName
1131
+ });
1132
+ });
1133
+ }
1134
+ }
1135
+ const createSchemas = exportVariables("createSchema", filePath);
1136
+ if (createSchemas.length > 0) {
1137
+ for (const createSchema of createSchemas) {
1138
+ const { exportName, path } = createSchema;
1139
+ silgi.hook("prepare:core.ts", (options) => {
1140
+ options.schemas.push(exportName);
1141
+ });
1142
+ silgi.hook("prepare:core.ts", (options) => {
1143
+ options.importItems[path] ??= {
1144
+ import: [],
1145
+ from: relativeWithDot(silgi.options.silgi.serverDir, path)
1146
+ };
1147
+ options.importItems[path].import.push({
1148
+ name: exportName
1149
+ });
1150
+ });
1151
+ }
1152
+ }
1153
+ const createShareds = exportVariables("createShared", filePath);
1154
+ if (createShareds.length > 0) {
1155
+ for (const createShared of createShareds) {
1156
+ const { exportName, path } = createShared;
1157
+ silgi.hook("prepare:core.ts", (options) => {
1158
+ options.shareds.push(exportName);
1159
+ });
1160
+ silgi.hook("prepare:core.ts", (options) => {
1161
+ options.importItems[path] ??= {
1162
+ import: [],
1163
+ // Relative path kaldirmamiz gerekiyor bunlar hooklarin bittigi yerde karar verilmeli.
1164
+ from: relativeWithDot(silgi.options.silgi.serverDir, path)
1165
+ };
1166
+ options.importItems[path].import.push({
1167
+ name: exportName
1168
+ });
1169
+ });
1170
+ }
1171
+ }
1172
+ const sharedsTypes = parseInterfaceDeclarations("ExtendShared", filePath);
1173
+ if (sharedsTypes.length > 0) {
1174
+ for (const sharedType of sharedsTypes) {
1175
+ const { exportName, path } = sharedType;
1176
+ silgi.hook("prepare:schema.ts", (options) => {
1177
+ options.shareds.push({
1178
+ key: exportName,
1179
+ value: exportName
1180
+ });
1181
+ });
1182
+ silgi.hook("prepare:schema.ts", (options) => {
1183
+ options.importItems[path] ??= {
1184
+ import: [],
1185
+ from: path
1186
+ };
1187
+ options.importItems[path].import.push({
1188
+ name: exportName,
1189
+ type: true
1190
+ });
1191
+ });
1192
+ }
1193
+ }
1194
+ const contextTypes = parseInterfaceDeclarations("ExtendContext", filePath);
1195
+ if (contextTypes.length > 0) {
1196
+ for (const contextType of contextTypes) {
1197
+ const { exportName, path } = contextType;
1198
+ silgi.hook("prepare:schema.ts", (options) => {
1199
+ options.contexts.push({
1200
+ key: exportName,
1201
+ value: exportName
1202
+ });
1203
+ });
1204
+ silgi.hook("prepare:schema.ts", (options) => {
1205
+ options.importItems[path] ??= {
1206
+ import: [],
1207
+ from: path
1208
+ };
1209
+ options.importItems[path].import.push({
1210
+ name: exportName,
1211
+ type: true
1212
+ });
1213
+ });
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+
1220
+ async function createStorageCLI(silgi) {
1221
+ const storage = createStorage();
1222
+ const mounts = klona({
1223
+ ...silgi.options.storage,
1224
+ ...silgi.options.devStorage
1225
+ });
1226
+ for (const [path, opts] of Object.entries(mounts)) {
1227
+ if (opts.driver) {
1228
+ const driver = await import(builtinDrivers[opts.driver] || opts.driver).then((r) => r.default || r);
1229
+ storage.mount(path, driver(opts));
1230
+ } else {
1231
+ silgi.logger.warn(`No \`driver\` set for storage mount point "${path}".`);
1232
+ }
1233
+ }
1234
+ return storage;
1235
+ }
1236
+
1237
+ const vueShim = {
1238
+ filename: "types/vue-shim.d.ts",
1239
+ getContents: ({ app }) => {
1240
+ if (!app.options.typescript.shim) {
1241
+ return "";
1242
+ }
1243
+ return [
1244
+ "declare module '*.vue' {",
1245
+ " import { DefineComponent } from 'vue'",
1246
+ " const component: DefineComponent<{}, {}, any>",
1247
+ " export default component",
1248
+ "}"
1249
+ ].join("\n");
1250
+ }
1251
+ };
1252
+ const pluginsDeclaration = {
1253
+ filename: "types/plugins.d.ts",
1254
+ getContents: async () => {
1255
+ return `
1256
+ declare module 'nuxt' {
1257
+ interface NuxtApp {
1258
+ $myPlugin: any;
1259
+ }
1260
+ }
1261
+ `;
1262
+ }
1263
+ };
1264
+
1265
+ const defaultTemplates = {
1266
+ __proto__: null,
1267
+ pluginsDeclaration: pluginsDeclaration,
1268
+ vueShim: vueShim
1269
+ };
1270
+
1271
+ const postTemplates = [
1272
+ pluginsDeclaration.filename
1273
+ ];
1274
+ const logger = useLogger("silgi");
1275
+ async function generateApp(app, options = {}) {
1276
+ app.templates = Object.values(defaultTemplates).concat(app.options.build.templates);
1277
+ await app.callHook("app:templates", app);
1278
+ app.templates = app.templates.map((tmpl) => normalizeTemplate(tmpl, app.options.silgi.vfsDir));
1279
+ const filteredTemplates = {
1280
+ pre: [],
1281
+ post: []
1282
+ };
1283
+ for (const template of app.templates) {
1284
+ if (options.filter && !options.filter(template)) {
1285
+ continue;
1286
+ }
1287
+ const key = template.filename && postTemplates.includes(template.filename) ? "post" : "pre";
1288
+ filteredTemplates[key].push(template);
1289
+ }
1290
+ const templateContext = { app };
1291
+ const writes = [];
1292
+ const indexImports = [];
1293
+ const dirs = /* @__PURE__ */ new Set();
1294
+ const changedTemplates = [];
1295
+ async function processTemplate(template) {
1296
+ const fullPath = template.dst || resolve(app.options.silgi.vfsDir, template.filename);
1297
+ const start = performance.now();
1298
+ const contents = await compileTemplate(template, templateContext).catch((e) => {
1299
+ logger.error(`Could not compile template \`${template.filename}\`.`);
1300
+ logger.error(e);
1301
+ throw e;
1302
+ });
1303
+ template.modified = true;
1304
+ if (template.modified) {
1305
+ changedTemplates.push(template);
1306
+ }
1307
+ const perf = performance.now() - start;
1308
+ const setupTime = Math.round(perf * 100) / 100;
1309
+ if (app.options.debug || setupTime > 500) {
1310
+ logger.info(`Compiled \`${template.filename}\` in ${setupTime}ms`);
1311
+ }
1312
+ if (template.modified && template.write) {
1313
+ dirs.add(dirname(fullPath));
1314
+ if (!fullPath.endsWith(".d.ts")) {
1315
+ indexImports.push(relativeWithDot(app.options.silgi.serverDir, fullPath));
1316
+ }
1317
+ writes.push(() => writeFileSync(fullPath, contents, "utf8"));
1318
+ }
1319
+ }
1320
+ await Promise.allSettled(filteredTemplates.pre.map(processTemplate));
1321
+ await Promise.allSettled(filteredTemplates.post.map(processTemplate));
1322
+ for (const dir of dirs) {
1323
+ mkdirSync(dir, { recursive: true });
1324
+ }
1325
+ for (const write of writes) {
1326
+ write();
1327
+ }
1328
+ writeFileSync(resolve(app.options.silgi.serverDir, "index.ts"), `${indexImports.map((i) => `export * from '${i}'`).join("\n")}
1329
+ `, "utf8");
1330
+ if (changedTemplates.length) {
1331
+ await app.callHook("app:templatesGenerated", app, changedTemplates, options);
1332
+ }
1333
+ }
1334
+ async function compileTemplate(template, ctx) {
1335
+ delete ctx.utils;
1336
+ if (template.src) {
1337
+ try {
1338
+ return await promises.readFile(template.src, "utf-8");
1339
+ } catch (err) {
1340
+ logger.error(`[nuxt] Error reading template from \`${template.src}\``);
1341
+ throw err;
1342
+ }
1343
+ }
1344
+ if (template.getContents) {
1345
+ return template.getContents({
1346
+ ...ctx,
1347
+ options: template.options
1348
+ });
1349
+ }
1350
+ throw new Error(`[nuxt] Invalid template. Templates must have either \`src\` or \`getContents\`: ${JSON.stringify(template)}`);
1351
+ }
1352
+
1353
+ const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
1354
+ async function scanAndSyncOptions(silgi) {
1355
+ const scannedModules = await scanModules(silgi);
1356
+ silgi.options.modules = silgi.options.modules || [];
1357
+ for (const modPath of scannedModules) {
1358
+ if (!silgi.options.modules.includes(modPath)) {
1359
+ silgi.options.modules.push(modPath);
1360
+ }
1361
+ }
1362
+ }
1363
+ async function scanModules(silgi) {
1364
+ const files = await scanFiles(silgi, "silgi/modules");
1365
+ return files.map((f) => f.fullPath);
1366
+ }
1367
+ async function scanFiles(silgi, name) {
1368
+ const files = await Promise.all(
1369
+ silgi.options.scanDirs.map((dir) => scanDir(silgi, dir, name))
1370
+ ).then((r) => r.flat());
1371
+ return files;
1372
+ }
1373
+ async function scanDir(silgi, dir, name) {
1374
+ const fileNames = await globby(join(name, GLOB_SCAN_PATTERN), {
1375
+ cwd: dir,
1376
+ dot: true,
1377
+ ignore: silgi.options.ignore,
1378
+ absolute: true
1379
+ });
1380
+ return fileNames.map((fullPath) => {
1381
+ return {
1382
+ fullPath,
1383
+ path: relative(join(dir, name), fullPath)
1384
+ };
1385
+ }).sort((a, b) => a.path.localeCompare(b.path));
1386
+ }
1387
+
1388
+ async function createSilgiCLI(config = {}, opts = {}) {
1389
+ const options = await loadOptions(config, opts);
1390
+ const hooks = createHooks();
1391
+ const silgi = {
1392
+ modulesURIs: {},
1393
+ scannedURIs: /* @__PURE__ */ new Map(),
1394
+ services: {},
1395
+ uris: {},
1396
+ shareds: {},
1397
+ schemas: {},
1398
+ unimport: void 0,
1399
+ options,
1400
+ hooks,
1401
+ // vfs: {}
1402
+ _requiredModules: {},
1403
+ logger: consola.withTag("silgi"),
1404
+ close: () => silgi.hooks.callHook("close", silgi),
1405
+ storage: void 0,
1406
+ scanModules: [],
1407
+ templates: [],
1408
+ callHook: hooks.callHook,
1409
+ addHooks: hooks.addHooks,
1410
+ hook: hooks.hook,
1411
+ async updateConfig(_config) {
1412
+ }
1413
+ };
1414
+ if (silgiCLICtx.tryUse()) {
1415
+ silgiCLICtx.unset();
1416
+ silgiCLICtx.set(silgi);
1417
+ } else {
1418
+ silgiCLICtx.set(silgi);
1419
+ silgi.hook("close", () => silgiCLICtx.unset());
1420
+ }
1421
+ if (silgi.options.debug) {
1422
+ createDebugger(silgi.hooks, { tag: "silgi" });
1423
+ silgi.options.plugins.push({
1424
+ path: join(runtimeDir, "internal/debug"),
1425
+ packageImport: "silgi/runtime/internal/debug"
1426
+ });
1427
+ }
1428
+ await scanAndSyncOptions(silgi);
1429
+ await scanModules$1(silgi);
1430
+ await scanFiles$1(silgi);
1431
+ silgi.storage = await createStorageCLI(silgi);
1432
+ silgi.hooks.hook("close", async () => {
1433
+ await silgi.storage.dispose();
1434
+ });
1435
+ if (silgi.options.logLevel !== void 0) {
1436
+ silgi.logger.level = silgi.options.logLevel;
1437
+ }
1438
+ silgi.hooks.addHooks(silgi.options.hooks);
1439
+ await installModules(silgi);
1440
+ await silgi.hooks.callHook("scanFiles:done", silgi);
1441
+ await generateApp(silgi);
1442
+ if (silgi.options.imports) {
1443
+ silgi.unimport = createUnimport(silgi.options.imports);
1444
+ await silgi.unimport.init();
1445
+ }
1446
+ await registerModuleExportScan(silgi);
1447
+ return silgi;
1448
+ }
1449
+
1450
+ const prepare = defineCommand({
1451
+ meta: {
1452
+ name: "prepare",
1453
+ description: "Generate types for the project",
1454
+ version: version
1455
+ },
1456
+ args: {
1457
+ ...commonArgs,
1458
+ preset: {
1459
+ type: "string",
1460
+ description: "The build preset to use (you can also use `SILGI_PRESET` environment variable)."
1461
+ },
1462
+ stub: {
1463
+ type: "boolean",
1464
+ description: "Run in silgi development mode"
1465
+ }
1466
+ },
1467
+ async run({ args }) {
1468
+ const rootDir = resolve(args.dir || args._dir || ".");
1469
+ const silgi = await createSilgiCLI({
1470
+ rootDir,
1471
+ dev: args.stub,
1472
+ stub: args.stub,
1473
+ typescript: { internalPaths: args.stub }
1474
+ });
1475
+ await prepare$1();
1476
+ for (const framework of frameworkSetup) {
1477
+ await framework(silgi);
1478
+ }
1479
+ await writeTypesAndFiles(silgi);
1480
+ await silgi.callHook("read:core.ts", async () => {
1481
+ const data = await readCoreFile(silgi);
1482
+ return data;
1483
+ });
1484
+ await silgi.close();
1485
+ }
1486
+ });
1487
+
1488
+ export { prepare as default };