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