silgi 0.39.15 → 0.40.0

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/build.mjs CHANGED
@@ -29,9 +29,9 @@ import 'node:fs/promises';
29
29
  import 'oxc-parser';
30
30
  import 'tinyglobby';
31
31
  import 'ignore';
32
+ import 'scule';
32
33
  import 'klona';
33
34
  import 'unstorage';
34
- import 'scule';
35
35
  import './cli/loader.mjs';
36
36
  import 'c12';
37
37
  import 'compatx';
@@ -2,8 +2,8 @@ import { consola } from 'consola';
2
2
  import { createHooks, createDebugger } from 'hookable';
3
3
  import { resolve, join, relative, extname, basename, dirname, isAbsolute } from 'pathe';
4
4
  import { useSilgiCLI, replaceRuntimeValues, silgiCLICtx, autoImportTypes } from 'silgi';
5
- import { isPresents, addTemplate, addCoreFile, genEnsureSafeVar, getServicePath, writeFile, relativeWithDot, hash, removeExtension, resolveAlias, directoryToURL, addImports, baseHeaderBannerComment, normalizeTemplate, useLogger, resolveSilgiPath, hasSilgiModule, toArray, isDirectory } from 'silgi/kit';
6
- import { useRuntimeConfig, initRuntimeConfig, sharedRuntimeConfig } from 'silgi/runtime';
5
+ import { isPresents, addTemplate, addCoreFile, genEnsureSafeVar, getServicePath, writeFile, relativeWithDot, hash, removeExtension, resolveAlias, directoryToURL, baseHeaderBannerComment, addImports, normalizeTemplate, useLogger, resolveSilgiPath, hasSilgiModule, toArray, isDirectory } from 'silgi/kit';
6
+ import { initRuntimeConfig, useRuntimeConfig, sharedRuntimeConfig } from 'silgi/runtime';
7
7
  import { runtimeDir } from 'silgi/runtime/meta';
8
8
  import { scanExports, createUnimport, toExports } from 'unimport';
9
9
  import * as p from '@clack/prompts';
@@ -21,9 +21,9 @@ import { readdir, readFile } from 'node:fs/promises';
21
21
  import { parseAsync } from 'oxc-parser';
22
22
  import { glob } from 'tinyglobby';
23
23
  import ignore from 'ignore';
24
+ import { snakeCase } from 'scule';
24
25
  import { klona } from 'klona';
25
26
  import { createStorage, builtinDrivers } from 'unstorage';
26
- import { snakeCase } from 'scule';
27
27
  import { l as loadOptions } from './loader.mjs';
28
28
  import { generateDTS } from 'apiful/openapi';
29
29
  import { u as useSilgiCLI$1 } from '../_chunks/silgiApp.mjs';
@@ -252,7 +252,7 @@ async function nextJS(silgi, skip = false) {
252
252
  write: true,
253
253
  getContents: () => template.join("\n")
254
254
  });
255
- silgi.hook("scanFiles:done", async (silgi2) => {
255
+ silgi.hook("ready", async (silgi2) => {
256
256
  const routerPrefixs = [];
257
257
  for (const _route in silgi2.services) {
258
258
  const { route } = getServicePath(_route);
@@ -1044,62 +1044,116 @@ ${cycleStr}`);
1044
1044
  return order;
1045
1045
  }
1046
1046
 
1047
- async function readScanFile(silgi) {
1048
- const path = resolve(silgi.options.silgi.serverDir, "scan.ts");
1049
- const context = await promises.readFile(path, { encoding: "utf-8" });
1050
- silgi.unimport = createUnimport(silgi.options.imports || {});
1051
- await silgi.unimport.init();
1052
- const injectedResult = await silgi.unimport.injectImports(context, path);
1053
- if (!injectedResult) {
1054
- throw new Error("Failed to inject imports");
1055
- }
1056
- const jiti = createJiti(silgi.options.rootDir, {
1057
- fsCache: true,
1058
- moduleCache: false,
1059
- debug: silgi.options.debug === true,
1060
- alias: silgi.options.alias
1047
+ function useCLIRuntimeConfig(silgi = useSilgiCLI()) {
1048
+ const safeRuntimeConfig = JSON.parse(JSON.stringify(silgi.options.runtimeConfig));
1049
+ silgi.hook("prepare:configs.ts", (data) => {
1050
+ data.runtimeConfig = safeRuntimeConfig;
1051
+ silgi.options.envOptions = silgi.options.envOptions;
1061
1052
  });
1062
- try {
1063
- const scanFile = await jiti.evalModule(
1064
- injectedResult.code,
1065
- {
1066
- filename: path,
1067
- async: true,
1068
- conditions: silgi.options.conditions
1069
- },
1070
- async (data, name) => {
1071
- return (await silgi.unimport.injectImports(data, name)).code;
1053
+ addTemplate({
1054
+ filename: "env.example",
1055
+ write: true,
1056
+ where: ".silgi",
1057
+ getContents() {
1058
+ const flattenedConfig = flattenObject(safeRuntimeConfig);
1059
+ const groupedVars = {};
1060
+ Object.entries(flattenedConfig).forEach(([key, { value, originalPath }]) => {
1061
+ const shouldExclude = silgi.options.codegen.env.safeList.some((safePath) => {
1062
+ if (safePath.length !== originalPath.length)
1063
+ return false;
1064
+ return safePath.every((segment, index) => segment.toLowerCase() === originalPath[index].toLowerCase());
1065
+ });
1066
+ if (shouldExclude)
1067
+ return;
1068
+ if (originalPath.length > 0) {
1069
+ const firstKey = originalPath[0];
1070
+ const categoryName = extractCategoryFromCamel(firstKey);
1071
+ if (!groupedVars[categoryName]) {
1072
+ groupedVars[categoryName] = {};
1073
+ }
1074
+ groupedVars[categoryName][key] = value;
1075
+ } else {
1076
+ if (!groupedVars.OTHER) {
1077
+ groupedVars.OTHER = {};
1078
+ }
1079
+ groupedVars.OTHER[key] = value;
1080
+ }
1081
+ });
1082
+ return Object.entries(groupedVars).map(([category, vars]) => {
1083
+ const varsContent = Object.entries(vars).map(([key, value]) => `${key}=${value}`).join("\n");
1084
+ return `# ${category}
1085
+ ${varsContent}`;
1086
+ }).join("\n\n");
1087
+ }
1088
+ });
1089
+ const _sharedRuntimeConfig = initRuntimeConfig(silgi.options.envOptions, silgi.options.runtimeConfig);
1090
+ silgi.options.runtimeConfig = safeRuntimeConfig;
1091
+ return _sharedRuntimeConfig;
1092
+ }
1093
+ function extractCategoryFromCamel(str) {
1094
+ if (/^[a-z]+[A-Z]/.test(str)) {
1095
+ const matches = str.match(/^([a-z]+)([A-Z][a-z0-9]*)?/);
1096
+ if (matches && matches[2]) {
1097
+ return `${matches[1].toUpperCase()}_${matches[2].toUpperCase()}`;
1098
+ }
1099
+ }
1100
+ return str.toUpperCase();
1101
+ }
1102
+ function flattenObject(obj, prefix = "SILGI", originalPath = []) {
1103
+ return Object.entries(obj).reduce((acc, [key, value]) => {
1104
+ const formattedKey = snakeCase(key).toUpperCase();
1105
+ const newKey = `${prefix}_${formattedKey}`;
1106
+ const newPath = [...originalPath, key];
1107
+ if (typeof value === "object" && value !== null) {
1108
+ Object.assign(acc, flattenObject(value, newKey, newPath));
1109
+ } else {
1110
+ acc[newKey] = { value, originalPath: newPath };
1111
+ }
1112
+ return acc;
1113
+ }, {});
1114
+ }
1115
+
1116
+ async function prepareConfigs(silgi = useSilgiCLI()) {
1117
+ useCLIRuntimeConfig();
1118
+ const _data = {
1119
+ runtimeConfig: {}
1120
+ };
1121
+ for (const module of silgi.scanModules) {
1122
+ if (module.meta.cliToRuntimeOptionsKeys && module.meta.cliToRuntimeOptionsKeys?.length > 0) {
1123
+ for (const key of module.meta.cliToRuntimeOptionsKeys) {
1124
+ _data[module.meta.configKey] = {
1125
+ ..._data[module.meta.configKey],
1126
+ [key]: module.options[key]
1127
+ };
1072
1128
  }
1073
- );
1074
- silgi.schemas = scanFile.schemas || {};
1075
- silgi.services = scanFile.services || {};
1076
- silgi.shareds = scanFile.shareds || {};
1077
- silgi.routers = scanFile.routers || {};
1078
- return {
1079
- context,
1080
- object: {
1081
- schemas: scanFile.schemas,
1082
- services: scanFile.services,
1083
- shareds: scanFile.shareds
1084
- },
1085
- path
1086
- };
1087
- } catch (error) {
1088
- if (silgi.options.debug) {
1089
- console.error("Failed to read scan.ts file:", error);
1090
1129
  } else {
1091
- consola.withTag("silgi").error(error);
1130
+ _data[module.meta.configKey] = {};
1092
1131
  }
1093
- return {
1094
- context,
1095
- object: {
1096
- schemas: {},
1097
- services: {},
1098
- shareds: {}
1099
- },
1100
- path
1101
- };
1102
1132
  }
1133
+ await silgi.callHook("prepare:configs.ts", _data);
1134
+ const importData = [
1135
+ "import type { SilgiRuntimeOptions, SilgiRuntimeConfig, SilgiOptions } from 'silgi/types'",
1136
+ "import { useRuntimeConfig } from 'silgi/runtime'",
1137
+ "",
1138
+ `export const runtimeConfig: SilgiRuntimeConfig = ${genObjectFromRawEntries(
1139
+ Object.entries(_data.runtimeConfig).map(([key, value]) => [key, genEnsureSafeVar(value)]),
1140
+ ""
1141
+ )}`,
1142
+ "",
1143
+ "export const localConfig = useRuntimeConfig(undefined, runtimeConfig)",
1144
+ ""
1145
+ ];
1146
+ delete _data.runtimeConfig;
1147
+ importData.push(`export const cliConfigs: Partial<SilgiRuntimeOptions & SilgiOptions> = ${genObjectFromRawEntries(
1148
+ Object.entries(_data).map(
1149
+ ([key, value]) => [key, genEnsureSafeVar(value)]
1150
+ )
1151
+ )}`);
1152
+ importData.unshift(...baseHeaderBannerComment);
1153
+ await writeFile(
1154
+ resolve(silgi.options.silgi.serverDir, "configs.ts"),
1155
+ importData.join("\n")
1156
+ );
1103
1157
  }
1104
1158
 
1105
1159
  async function prepareScanFile(silgi) {
@@ -1185,18 +1239,69 @@ async function prepareScanFile(silgi) {
1185
1239
  await silgi.callHook("after:scan.ts", importData);
1186
1240
  importData.unshift(...importsContent);
1187
1241
  importData.unshift(...baseHeaderBannerComment);
1242
+ await writeFile(
1243
+ resolve(silgi.options.silgi.serverDir, "scan.ts"),
1244
+ importData.join("\n")
1245
+ );
1188
1246
  return importData;
1189
1247
  }
1190
1248
 
1191
- async function writeScanFiles(silgi) {
1192
- const data = await prepareScanFile(silgi);
1193
- if (!silgi.errors.length) {
1194
- await writeFile(
1195
- resolve(silgi.options.silgi.serverDir, "scan.ts"),
1196
- data.join("\n")
1249
+ async function readScanFile(silgi) {
1250
+ const path = resolve(silgi.options.silgi.serverDir, "scan.ts");
1251
+ const context = await promises.readFile(path, { encoding: "utf-8" });
1252
+ silgi.unimport = createUnimport(silgi.options.imports || {});
1253
+ await silgi.unimport.init();
1254
+ const injectedResult = await silgi.unimport.injectImports(context, path);
1255
+ if (!injectedResult) {
1256
+ throw new Error("Failed to inject imports");
1257
+ }
1258
+ const jiti = createJiti(silgi.options.rootDir, {
1259
+ fsCache: true,
1260
+ moduleCache: false,
1261
+ debug: silgi.options.debug === true,
1262
+ alias: silgi.options.alias
1263
+ });
1264
+ try {
1265
+ const scanFile = await jiti.evalModule(
1266
+ injectedResult.code,
1267
+ {
1268
+ filename: path,
1269
+ async: true,
1270
+ conditions: silgi.options.conditions
1271
+ },
1272
+ async (data, name) => {
1273
+ return (await silgi.unimport.injectImports(data, name)).code;
1274
+ }
1197
1275
  );
1276
+ silgi.schemas = scanFile.schemas || {};
1277
+ silgi.services = scanFile.services || {};
1278
+ silgi.shareds = scanFile.shareds || {};
1279
+ silgi.routers = scanFile.routers || {};
1280
+ return {
1281
+ context,
1282
+ object: {
1283
+ schemas: scanFile.schemas,
1284
+ services: scanFile.services,
1285
+ shareds: scanFile.shareds
1286
+ },
1287
+ path
1288
+ };
1289
+ } catch (error) {
1290
+ if (silgi.options.debug) {
1291
+ console.error("Failed to read scan.ts file:", error);
1292
+ } else {
1293
+ consola.withTag("silgi").error(error);
1294
+ }
1295
+ return {
1296
+ context,
1297
+ object: {
1298
+ schemas: {},
1299
+ services: {},
1300
+ shareds: {}
1301
+ },
1302
+ path
1303
+ };
1198
1304
  }
1199
- await readScanFile(silgi);
1200
1305
  }
1201
1306
 
1202
1307
  async function createStorageCLI(silgi) {
@@ -1339,75 +1444,6 @@ async function compileTemplate(template, ctx) {
1339
1444
  throw new Error(`[nuxt] Invalid template. Templates must have either \`src\` or \`getContents\`: ${JSON.stringify(template)}`);
1340
1445
  }
1341
1446
 
1342
- function useCLIRuntimeConfig(silgi) {
1343
- const safeRuntimeConfig = JSON.parse(JSON.stringify(silgi.options.runtimeConfig));
1344
- silgi.hook("prepare:configs.ts", (data) => {
1345
- data.runtimeConfig = safeRuntimeConfig;
1346
- silgi.options.envOptions = silgi.options.envOptions;
1347
- });
1348
- addTemplate({
1349
- filename: "env.example",
1350
- write: true,
1351
- where: ".silgi",
1352
- getContents() {
1353
- const flattenedConfig = flattenObject(safeRuntimeConfig);
1354
- const groupedVars = {};
1355
- Object.entries(flattenedConfig).forEach(([key, { value, originalPath }]) => {
1356
- const shouldExclude = silgi.options.codegen.env.safeList.some((safePath) => {
1357
- if (safePath.length !== originalPath.length)
1358
- return false;
1359
- return safePath.every((segment, index) => segment.toLowerCase() === originalPath[index].toLowerCase());
1360
- });
1361
- if (shouldExclude)
1362
- return;
1363
- if (originalPath.length > 0) {
1364
- const firstKey = originalPath[0];
1365
- const categoryName = extractCategoryFromCamel(firstKey);
1366
- if (!groupedVars[categoryName]) {
1367
- groupedVars[categoryName] = {};
1368
- }
1369
- groupedVars[categoryName][key] = value;
1370
- } else {
1371
- if (!groupedVars.OTHER) {
1372
- groupedVars.OTHER = {};
1373
- }
1374
- groupedVars.OTHER[key] = value;
1375
- }
1376
- });
1377
- return Object.entries(groupedVars).map(([category, vars]) => {
1378
- const varsContent = Object.entries(vars).map(([key, value]) => `${key}=${value}`).join("\n");
1379
- return `# ${category}
1380
- ${varsContent}`;
1381
- }).join("\n\n");
1382
- }
1383
- });
1384
- const _sharedRuntimeConfig = initRuntimeConfig(silgi.options.envOptions, silgi.options.runtimeConfig);
1385
- silgi.options.runtimeConfig = safeRuntimeConfig;
1386
- return _sharedRuntimeConfig;
1387
- }
1388
- function extractCategoryFromCamel(str) {
1389
- if (/^[a-z]+[A-Z]/.test(str)) {
1390
- const matches = str.match(/^([a-z]+)([A-Z][a-z0-9]*)?/);
1391
- if (matches && matches[2]) {
1392
- return `${matches[1].toUpperCase()}_${matches[2].toUpperCase()}`;
1393
- }
1394
- }
1395
- return str.toUpperCase();
1396
- }
1397
- function flattenObject(obj, prefix = "SILGI", originalPath = []) {
1398
- return Object.entries(obj).reduce((acc, [key, value]) => {
1399
- const formattedKey = snakeCase(key).toUpperCase();
1400
- const newKey = `${prefix}_${formattedKey}`;
1401
- const newPath = [...originalPath, key];
1402
- if (typeof value === "object" && value !== null) {
1403
- Object.assign(acc, flattenObject(value, newKey, newPath));
1404
- } else {
1405
- acc[newKey] = { value, originalPath: newPath };
1406
- }
1407
- return acc;
1408
- }, {});
1409
- }
1410
-
1411
1447
  const GLOB_SCAN_PATTERN = "**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}";
1412
1448
  async function scanAndSyncOptions(silgi) {
1413
1449
  const scannedModules = await scanModules(silgi);
@@ -1467,10 +1503,9 @@ async function createSilgiCLI(config = {}, opts = {}) {
1467
1503
  addHooks: hooks.addHooks,
1468
1504
  hook: hooks.hook,
1469
1505
  adapters: {},
1470
- useLocalConfig: () => useRuntimeConfig(void 0, options.runtimeConfig, true),
1506
+ useLocalConfig: () => useRuntimeConfig(void 0, options.runtimeConfig),
1471
1507
  meta: {}
1472
1508
  };
1473
- sharedRuntimeConfig(silgi.options.runtimeConfig);
1474
1509
  if (silgiCLICtx.tryUse()) {
1475
1510
  silgiCLICtx.unset();
1476
1511
  silgiCLICtx.set(silgi);
@@ -1478,7 +1513,6 @@ async function createSilgiCLI(config = {}, opts = {}) {
1478
1513
  silgiCLICtx.set(silgi);
1479
1514
  silgi.hook("close", () => silgiCLICtx.unset());
1480
1515
  }
1481
- await silgi.hooks.callHook("ready", silgi);
1482
1516
  if (silgi.options.debug) {
1483
1517
  createDebugger(silgi.hooks, { tag: "silgi" });
1484
1518
  silgi.options.plugins.push({
@@ -1486,25 +1520,28 @@ async function createSilgiCLI(config = {}, opts = {}) {
1486
1520
  packageImport: "silgi/runtime/internal/debug"
1487
1521
  });
1488
1522
  }
1523
+ await scanAndSyncOptions(silgi);
1524
+ await scanSilgiExports();
1525
+ await scanModules$1(silgi);
1526
+ await installModules(silgi, true);
1527
+ await prepareConfigs();
1528
+ sharedRuntimeConfig(silgi.options.runtimeConfig, silgi.options.dev);
1489
1529
  if (silgi.options.adapters && Object.keys(silgi.options.adapters)?.length > 0) {
1490
1530
  for (const [key, value] of Object.entries(silgi.options.adapters)) {
1491
1531
  if (typeof value === "function") {
1492
- const resolved = value();
1532
+ const resolved = value(silgi);
1493
1533
  silgi.adapters[key] = resolved instanceof Promise ? await resolved : resolved;
1494
1534
  } else {
1495
1535
  silgi.adapters[key] = value;
1496
1536
  }
1497
1537
  }
1498
1538
  }
1499
- await scanAndSyncOptions(silgi);
1500
- await scanModules$1(silgi);
1501
- await scanSilgiExports();
1502
- await installModules(silgi, true);
1503
- useCLIRuntimeConfig(silgi);
1539
+ await prepareScanFile(silgi);
1540
+ await readScanFile(silgi);
1541
+ await installModules(silgi);
1504
1542
  for (const framework of frameworkSetup) {
1505
1543
  await framework(silgi);
1506
1544
  }
1507
- await writeScanFiles(silgi);
1508
1545
  silgi.storage = await createStorageCLI(silgi);
1509
1546
  silgi.hooks.hook("close", async () => {
1510
1547
  await silgi.storage.dispose();
@@ -1513,8 +1550,6 @@ async function createSilgiCLI(config = {}, opts = {}) {
1513
1550
  silgi.logger.level = silgi.options.logLevel;
1514
1551
  }
1515
1552
  silgi.hooks.addHooks(silgi.options.hooks);
1516
- await installModules(silgi);
1517
- await silgi.hooks.callHook("scanFiles:done", silgi);
1518
1553
  await generateApp(silgi);
1519
1554
  if (silgi.options.imports) {
1520
1555
  silgi.options.imports.dirs ??= [];
@@ -1540,15 +1575,14 @@ async function createSilgiCLI(config = {}, opts = {}) {
1540
1575
  await silgi.unimport.init();
1541
1576
  }
1542
1577
  await registerModuleExportScan(silgi);
1543
- await writeScanFiles(silgi);
1544
- sharedRuntimeConfig(silgi.options.runtimeConfig);
1578
+ await silgi.hooks.callHook("ready", silgi);
1545
1579
  return silgi;
1546
1580
  }
1547
1581
 
1548
1582
  async function generateApiFul(silgi) {
1549
1583
  const config = silgi.options.apiFul;
1550
1584
  if (!hasSilgiModule("openapi")) {
1551
- silgi.logger.info("Silgi OpenAPI module not found, if you want to use it, please install it @silgi/openapi");
1585
+ silgi.options.dev || silgi.logger.info("Silgi OpenAPI module not found, if you want to use it, please install it @silgi/openapi");
1552
1586
  return;
1553
1587
  }
1554
1588
  if (!config.services || hasSilgiModule("openapi")) {
@@ -1583,9 +1617,6 @@ async function generateApiFul(silgi) {
1583
1617
  });
1584
1618
  }
1585
1619
 
1586
- async function prepare(_silgi) {
1587
- }
1588
-
1589
1620
  function debugMode(name) {
1590
1621
  const silgi = useSilgiCLI$1();
1591
1622
  if (silgi.options.debug === true || typeof silgi.options.debug === "object" && silgi.options.debug[name]) {
@@ -1636,45 +1667,6 @@ async function prepareCommands(silgi = useSilgiCLI$1()) {
1636
1667
  silgi.options.commands = commands;
1637
1668
  }
1638
1669
 
1639
- async function prepareConfigs(silgi) {
1640
- const _data = {
1641
- runtimeConfig: {}
1642
- };
1643
- for (const module of silgi.scanModules) {
1644
- if (module.meta.cliToRuntimeOptionsKeys && module.meta.cliToRuntimeOptionsKeys?.length > 0) {
1645
- for (const key of module.meta.cliToRuntimeOptionsKeys) {
1646
- _data[module.meta.configKey] = {
1647
- ..._data[module.meta.configKey],
1648
- [key]: module.options[key]
1649
- };
1650
- }
1651
- } else {
1652
- _data[module.meta.configKey] = {};
1653
- }
1654
- }
1655
- await silgi.callHook("prepare:configs.ts", _data);
1656
- const importData = [
1657
- "import type { SilgiRuntimeOptions, SilgiRuntimeConfig, SilgiOptions } from 'silgi/types'",
1658
- "import { useRuntimeConfig } from 'silgi/runtime'",
1659
- "",
1660
- `export const runtimeConfig: SilgiRuntimeConfig = ${genObjectFromRawEntries(
1661
- Object.entries(_data.runtimeConfig).map(([key, value]) => [key, genEnsureSafeVar(value)]),
1662
- ""
1663
- )}`,
1664
- "",
1665
- "export const localConfig = useRuntimeConfig(undefined, runtimeConfig)",
1666
- ""
1667
- ];
1668
- delete _data.runtimeConfig;
1669
- importData.push(`export const cliConfigs: Partial<SilgiRuntimeOptions & SilgiOptions> = ${genObjectFromRawEntries(
1670
- Object.entries(_data).map(
1671
- ([key, value]) => [key, genEnsureSafeVar(value)]
1672
- )
1673
- )}`);
1674
- importData.unshift(...baseHeaderBannerComment);
1675
- return importData;
1676
- }
1677
-
1678
1670
  async function prepareCoreFile(silgi) {
1679
1671
  const { genImports, genTypeImports, addImportItem, addImportItemType } = addImports({
1680
1672
  imports: [
@@ -1834,17 +1826,12 @@ async function prepareCoreFile(silgi) {
1834
1826
 
1835
1827
  async function writeCoreFile(silgi) {
1836
1828
  const coreContent = await prepareCoreFile(silgi);
1837
- const configs = await prepareConfigs(silgi);
1838
1829
  const silgiDir = resolve(silgi.options.silgi.serverDir);
1839
1830
  const buildFiles = [];
1840
1831
  buildFiles.push({
1841
1832
  path: join(silgiDir, "core.ts"),
1842
1833
  contents: coreContent.join("\n")
1843
1834
  });
1844
- buildFiles.push({
1845
- path: join(silgiDir, "configs.ts"),
1846
- contents: configs.join("\n")
1847
- });
1848
1835
  buildFiles.push({
1849
1836
  path: join(silgiDir, "meta.ts"),
1850
1837
  contents: `export const meta = ${JSON.stringify(silgi.meta, null, 2)}`
@@ -2089,7 +2076,6 @@ async function writeTypesAndFiles(silgi) {
2089
2076
  }
2090
2077
 
2091
2078
  async function build(silgi) {
2092
- await prepare();
2093
2079
  await generateApiFul(silgi);
2094
2080
  await prepareCommands(silgi);
2095
2081
  await writeCoreFile(silgi);
package/dist/cli/dev.mjs CHANGED
@@ -21,15 +21,16 @@ async function prepareBuild(config) {
21
21
  }
22
22
 
23
23
  async function watchDev() {
24
+ const silgi = useSilgiCLI$1();
24
25
  let watcher;
25
26
  async function load() {
26
27
  await prepareBuild({
27
28
  commandType: "prepare",
28
- activeEnvironment: ".env"
29
+ activeEnvironment: silgi.options.activeEnvironment || ".env",
30
+ dev: true
29
31
  });
30
32
  }
31
33
  const reload = debounce(load);
32
- const silgi = useSilgiCLI$1();
33
34
  silgi.options.watchOptions.ignored ??= [];
34
35
  silgi.options.watchOptions.ignoreInitial = true;
35
36
  if (Array.isArray(silgi.options.watchOptions.ignored)) {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
3
 
4
- const version = "0.39.15";
4
+ const version = "0.40.0";
5
5
  const packageJson = {
6
6
  version: version};
7
7
 
@@ -20,10 +20,11 @@ const main = defineCommand({
20
20
  subCommands: {
21
21
  prepare: () => import('./prepare.mjs').then(function (n) { return n.p; }).then((m) => m.default),
22
22
  init: () => import('./init.mjs').then((m) => m.default),
23
- run: () => import('./prepare.mjs').then(function (n) { return n.r; }).then((m) => m.default),
23
+ commands: () => import('./prepare.mjs').then(function (n) { return n.b; }).then((m) => m.default),
24
24
  install: () => import('./install.mjs').then((m) => m.default),
25
25
  watch: () => import('./watch.mjs').then((m) => m.default),
26
- reset: () => import('./reset.mjs').then((m) => m.default)
26
+ reset: () => import('./reset.mjs').then((m) => m.default),
27
+ run: () => import('./run.mjs').then((m) => m.default)
27
28
  },
28
29
  run() {
29
30
  }
package/dist/cli/init.mjs CHANGED
@@ -26,9 +26,9 @@ import 'ufo';
26
26
  import 'oxc-parser';
27
27
  import 'tinyglobby';
28
28
  import 'ignore';
29
+ import 'scule';
29
30
  import 'klona';
30
31
  import 'unstorage';
31
- import 'scule';
32
32
  import './loader.mjs';
33
33
  import 'c12';
34
34
  import 'compatx';
@@ -30,9 +30,9 @@ import 'node:fs/promises';
30
30
  import 'oxc-parser';
31
31
  import 'tinyglobby';
32
32
  import 'ignore';
33
+ import 'scule';
33
34
  import 'klona';
34
35
  import 'unstorage';
35
- import 'scule';
36
36
  import './loader.mjs';
37
37
  import 'c12';
38
38
  import 'compatx';
@@ -51,7 +51,7 @@ const command$1 = defineCommand({
51
51
  async run({ args }) {
52
52
  if (args.prepare) {
53
53
  await runCommand(command, {
54
- rawArgs: ["--commandType", "run"]
54
+ rawArgs: ["--commandType", "commands"]
55
55
  });
56
56
  }
57
57
  const silgi = useSilgiCLI();
@@ -121,7 +121,7 @@ const command$1 = defineCommand({
121
121
  }
122
122
  });
123
123
 
124
- const run = {
124
+ const commands = {
125
125
  __proto__: null,
126
126
  default: command$1
127
127
  };
@@ -166,7 +166,7 @@ const command = defineCommand({
166
166
  activeEnvironment: args.env
167
167
  });
168
168
  await build(silgi);
169
- if (args.commandType !== "run") {
169
+ if (args.commandType !== "commands") {
170
170
  await runCommand(command$1, {
171
171
  rawArgs: ["--tag", "init", "--prepare", "false"]
172
172
  });
@@ -179,4 +179,4 @@ const prepare = {
179
179
  default: command
180
180
  };
181
181
 
182
- export { command as a, cancelOnCancel as c, prepare as p, run as r };
182
+ export { command as a, commands as b, cancelOnCancel as c, prepare as p };
@@ -0,0 +1,157 @@
1
+ import { defineCommand, runCommand } from 'citty';
2
+ import consola from 'consola';
3
+ import { useSilgiCLI } from 'silgi';
4
+ import { version } from 'silgi/meta';
5
+ import { x } from 'tinyexec';
6
+ import { w as watchDev } from './dev.mjs';
7
+ import { c as commonArgs } from './common.mjs';
8
+ import { a as command$1 } from './prepare.mjs';
9
+ import 'chokidar';
10
+ import 'pathe';
11
+ import 'perfect-debounce';
12
+ import '../_chunks/silgiApp.mjs';
13
+ import 'unctx';
14
+ import './build.mjs';
15
+ import 'hookable';
16
+ import 'silgi/kit';
17
+ import 'silgi/runtime';
18
+ import 'silgi/runtime/meta';
19
+ import 'unimport';
20
+ import '@clack/prompts';
21
+ import 'node:fs';
22
+ import 'dotenv';
23
+ import 'knitwork';
24
+ import 'mlly';
25
+ import 'dev-jiti';
26
+ import './compatibility.mjs';
27
+ import 'semver/functions/satisfies.js';
28
+ import 'node:url';
29
+ import 'defu';
30
+ import 'exsolve';
31
+ import 'ufo';
32
+ import 'node:fs/promises';
33
+ import 'oxc-parser';
34
+ import 'tinyglobby';
35
+ import 'ignore';
36
+ import 'scule';
37
+ import 'klona';
38
+ import 'unstorage';
39
+ import './loader.mjs';
40
+ import 'c12';
41
+ import 'compatx';
42
+ import 'klona/full';
43
+ import 'std-env';
44
+ import 'consola/utils';
45
+ import 'escape-string-regexp';
46
+ import 'pkg-types';
47
+ import 'apiful/openapi';
48
+ import 'pathe/utils';
49
+ import 'untyped';
50
+ import './types.mjs';
51
+ import 'node:child_process';
52
+
53
+ const command = defineCommand({
54
+ meta: {
55
+ name: "dev",
56
+ description: "Start the development server for the project",
57
+ version: version
58
+ },
59
+ args: {
60
+ ...commonArgs,
61
+ command: {
62
+ type: "string",
63
+ description: "your application start command",
64
+ required: false
65
+ }
66
+ },
67
+ async run({ args, rawArgs }) {
68
+ await runCommand(command$1, {
69
+ rawArgs: ["--commandType", "dev", "--dev", "true"]
70
+ });
71
+ const silgi = useSilgiCLI();
72
+ const startCommand = args.command || rawArgs[0];
73
+ let childPid = null;
74
+ let hasExited = false;
75
+ let exitTimeout = null;
76
+ const cleanupAndExit = (code = 0) => {
77
+ if (hasExited)
78
+ return;
79
+ hasExited = true;
80
+ if (exitTimeout)
81
+ clearTimeout(exitTimeout);
82
+ process.exit(code);
83
+ };
84
+ const handleSignal = async (signal, watcher) => {
85
+ consola.info(`Received ${signal}, terminating process...`);
86
+ if (watcher && typeof watcher.close === "function") {
87
+ try {
88
+ await watcher.close();
89
+ } catch {
90
+ }
91
+ }
92
+ if (childPid) {
93
+ try {
94
+ process.kill(childPid, signal);
95
+ } catch (err) {
96
+ consola.error(`Failed to kill process: ${err instanceof Error ? err.message : err}`);
97
+ }
98
+ exitTimeout = setTimeout(() => {
99
+ consola.warn("Process did not exit gracefully, forcing termination...");
100
+ try {
101
+ if (childPid)
102
+ process.kill(childPid, "SIGKILL");
103
+ } catch {
104
+ }
105
+ cleanupAndExit(1);
106
+ }, 3e3);
107
+ } else {
108
+ cleanupAndExit(0);
109
+ }
110
+ };
111
+ const setupSignalHandlers = (watcher) => {
112
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((signal) => {
113
+ process.on(signal, () => {
114
+ handleSignal(signal, watcher);
115
+ });
116
+ });
117
+ };
118
+ try {
119
+ const watcher = await watchDev();
120
+ setupSignalHandlers(watcher);
121
+ consola.info(`Starting command: nr ${startCommand}`);
122
+ const proc = x(
123
+ "nr",
124
+ [startCommand],
125
+ {
126
+ nodeOptions: {
127
+ stdio: "inherit",
128
+ shell: true,
129
+ cwd: process.cwd(),
130
+ killSignal: "SIGINT"
131
+ }
132
+ }
133
+ );
134
+ if (proc && typeof proc.pid === "number") {
135
+ childPid = proc.pid;
136
+ }
137
+ try {
138
+ await proc;
139
+ consola.success(`Process exited successfully.`);
140
+ cleanupAndExit(0);
141
+ } catch (procError) {
142
+ const exitCode = procError && typeof procError.exitCode === "number" ? procError.exitCode : 1;
143
+ consola.error(`Process exited with code: ${exitCode}`);
144
+ if (silgi.options.debug)
145
+ consola.withTag("silgi").error("Error while running the command", procError);
146
+ cleanupAndExit(exitCode);
147
+ }
148
+ } catch (error) {
149
+ consola.error(`Failed to start the development server: ${error instanceof Error ? error.message : error}`);
150
+ if (silgi.options.debug)
151
+ consola.withTag("silgi").error("Error while running the command", error);
152
+ cleanupAndExit(1);
153
+ }
154
+ }
155
+ });
156
+
157
+ export { command as default };
@@ -32,9 +32,9 @@ import 'node:fs/promises';
32
32
  import 'oxc-parser';
33
33
  import 'tinyglobby';
34
34
  import 'ignore';
35
+ import 'scule';
35
36
  import 'klona';
36
37
  import 'unstorage';
37
- import 'scule';
38
38
  import './loader.mjs';
39
39
  import 'c12';
40
40
  import 'compatx';
@@ -369,11 +369,11 @@ async function createSilgi(config) {
369
369
  silgiCtx.set(silgi);
370
370
  silgi.hook("close", () => silgiCtx.unset());
371
371
  }
372
- silgi.logger.info("Silgi installed");
373
372
  hooks.hookOnce("close", async () => {
374
373
  hooks.removeAllHooks();
375
374
  await silgi.storage.dispose();
376
375
  });
376
+ silgi.logger.info("Silgi Start");
377
377
  return silgi;
378
378
  }
379
379
 
@@ -922,7 +922,6 @@ interface SilgiCLIHooks extends SilgiHooks {
922
922
  * @returns Promise
923
923
  */
924
924
  'app:templatesGenerated': (app: SilgiCLI, templates: ResolvedSilgiTemplate[], options?: GenerateAppOptions) => HookResult;
925
- 'scanFiles:done': (app: SilgiCLI) => HookResult;
926
925
  'prepare:commands': (commands: Commands[]) => HookResult;
927
926
  'nextjs:prepare': (data: {
928
927
  config: NextConfig;
@@ -1207,7 +1206,7 @@ interface SilgiCLIOptions extends PresetOptions {
1207
1206
  ignoreOptions: Options;
1208
1207
  installPackages: Record<'dependencies' | 'devDependencies', Record<string, string>>;
1209
1208
  apiFul: ApifulConfig;
1210
- adapters: Record<string, Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>> | (() => Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>>) | (() => Promise<Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>>>)>;
1209
+ adapters: Record<string, Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>> | ((silgi: SilgiCLI) => Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>>) | ((silgi: SilgiCLI) => Promise<Adapter<Record<string, any>, TablesSchema, InferModelTypes<TablesSchema>>>)>;
1211
1210
  }
1212
1211
  /**
1213
1212
  * Silgi input config (silgi.config)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "silgi",
3
3
  "type": "module",
4
- "version": "0.39.15",
4
+ "version": "0.40.0",
5
5
  "private": false,
6
6
  "sideEffects": false,
7
7
  "exports": {
@@ -95,6 +95,7 @@
95
95
  }
96
96
  },
97
97
  "dependencies": {
98
+ "@antfu/ni": "^24.3.0",
98
99
  "@clack/prompts": "^0.10.1",
99
100
  "@fastify/deepmerge": "^3.1.0",
100
101
  "@standard-community/standard-json": "^0.2.0",
@@ -131,6 +132,7 @@
131
132
  "semver": "^7.7.1",
132
133
  "srvx": "^0.6.0",
133
134
  "std-env": "^3.9.0",
135
+ "tinyexec": "^1.0.1",
134
136
  "tinyglobby": "^0.2.13",
135
137
  "ufo": "^1.6.1",
136
138
  "unadapter": "^0.1.2",