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