express-file-cluster 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/auth/index.d.cts +1 -1
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  4. package/dist/chunk-QKQZF573.js.map +1 -0
  5. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  6. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  7. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  8. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  9. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  10. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  11. package/dist/cli/db-runner.cjs +17 -17
  12. package/dist/cli/db-runner.js +2 -2
  13. package/dist/cli/index.cjs +363 -26
  14. package/dist/cli/index.cjs.map +1 -1
  15. package/dist/cli/index.js +343 -6
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/docs/api-reference/collection.md +155 -0
  18. package/dist/docs/cli/add.md +35 -6
  19. package/dist/docs/guides/authentication.md +50 -0
  20. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  21. package/dist/docs/guides/which-api.md +21 -12
  22. package/dist/docs/index.md +3 -1
  23. package/dist/docs/skills/SKILL.md +2 -2
  24. package/dist/docs/skills/api-surface.md +8 -0
  25. package/dist/docs/skills/what-not-to-invent.md +3 -2
  26. package/dist/index.cjs +11 -9
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +193 -3
  29. package/dist/index.d.ts +193 -3
  30. package/dist/index.js +4 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/registry/index.json +1 -1
  33. package/dist/tasks/index.d.cts +1 -1
  34. package/dist/tasks/index.d.ts +1 -1
  35. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.cts} +36 -7
  36. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.ts} +36 -7
  37. package/package.json +1 -1
  38. package/dist/chunk-2PBMLMO4.js.map +0 -1
  39. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  40. package/dist/chunk-6QNLN6AI.js.map +0 -1
  41. package/dist/chunk-RGTENTDN.cjs.map +0 -1
package/dist/cli/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  } from "../chunk-BBSZLGZW.js";
11
11
  import {
12
12
  tableNameFor
13
- } from "../chunk-2PBMLMO4.js";
13
+ } from "../chunk-QKQZF573.js";
14
14
  import "../chunk-HXV543HZ.js";
15
15
  import "../chunk-LJNSJFOL.js";
16
16
  import "../chunk-HBYSKULC.js";
@@ -879,6 +879,9 @@ var Registry = class {
879
879
  }
880
880
  dir;
881
881
  index;
882
+ has(name) {
883
+ return this.index.items.some((i) => i.name === name || i.aliases?.includes(name));
884
+ }
882
885
  meta(name) {
883
886
  const item = this.index.items.find((i) => i.name === name || i.aliases?.includes(name));
884
887
  if (!item) {
@@ -1264,6 +1267,231 @@ function lineDiff(a, b) {
1264
1267
  });
1265
1268
  return shown;
1266
1269
  }
1270
+ var RESERVED_ENTITIES = /* @__PURE__ */ new Set(["user", "admin"]);
1271
+ function toPascal(s) {
1272
+ const parts = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[-_]+/g, " ").trim().split(/\s+/);
1273
+ return parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
1274
+ }
1275
+ function toCamel(s) {
1276
+ const p = toPascal(s);
1277
+ return p.charAt(0).toLowerCase() + p.slice(1);
1278
+ }
1279
+ function toSlug(s) {
1280
+ return s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[-_\s]+/g, "-").toLowerCase();
1281
+ }
1282
+ function validateEntityName(name) {
1283
+ const raw = name.trim();
1284
+ if (!raw) return { error: "Entity name cannot be empty" };
1285
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(raw))
1286
+ return { error: `Entity name must be alphanumeric and start with a letter: "${raw}"` };
1287
+ const pascal = toPascal(raw);
1288
+ const camel = toCamel(raw);
1289
+ const slug = toSlug(raw);
1290
+ if (RESERVED_ENTITIES.has(slug) || RESERVED_ENTITIES.has(pascal.toLowerCase()))
1291
+ return { error: `"${pascal}" is a built-in entity \u2014 use \`efc add auth\` for User/Admin` };
1292
+ return { pascal, camel, slug };
1293
+ }
1294
+ function entityUsesTables(cfg) {
1295
+ return cfg.database === "postgresql" && cfg.modelApi === "defineTable";
1296
+ }
1297
+ function entityOrm(cfg) {
1298
+ const t = entityUsesTables(cfg);
1299
+ return {
1300
+ findOne: (model, filter) => t ? `${model}.findFirst({ where: ${filter} })` : `${model}.findOne(${filter})`,
1301
+ create: (model, data) => t ? `${model}.create({ data: ${data} })` : `${model}.create(${data})`
1302
+ };
1303
+ }
1304
+ function entityModelContent(pascal, slug, cfg) {
1305
+ const api = entityUsesTables(cfg) ? "defineTable" : "defineModel";
1306
+ return `import { ${api} } from 'express-file-cluster';
1307
+
1308
+ export const ${pascal} = ${api}('${pascal}', {
1309
+ name: { type: 'string', required: true },
1310
+ email: { type: 'string', required: true, unique: true },
1311
+ password: { type: 'string', required: true },
1312
+ role: { type: 'string', required: true, default: '${slug}' },
1313
+ avatar: { type: 'string' },
1314
+ isVerified: { type: 'boolean', default: false },
1315
+ isActive: { type: 'boolean', default: true },
1316
+ verifyToken: { type: 'string' },
1317
+ resetToken: { type: 'string' },
1318
+ resetTokenExpiry: { type: 'date' },
1319
+ refreshToken: { type: 'string' },
1320
+ refreshTokenExpiry: { type: 'date' },
1321
+ });
1322
+ `;
1323
+ }
1324
+ function entityRegisterContent(pascal, camel, cfg) {
1325
+ const ts = cfg.language === "typescript";
1326
+ const db = entityOrm(cfg);
1327
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1328
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1329
+ return `${typeImport}import bcrypt from 'bcrypt';
1330
+ import { ${pascal} } from '../../../model/${pascal}.js';
1331
+
1332
+ export const POST = async ${typedArgs} => {
1333
+ const { name, email, password } = req.body;
1334
+ if (!name || !email || !password) {
1335
+ return res.status(400).json({ error: 'name, email and password are required' });
1336
+ }
1337
+ const existing = await ${db.findOne(pascal, "{ email }")};
1338
+ if (existing) return res.status(409).json({ error: 'Email already in use' });
1339
+ const hashed = await bcrypt.hash(password, 10);
1340
+ const record = await ${db.create(pascal, "{ name, email, password: hashed }")};
1341
+ const { password: _, ...safe } = record;
1342
+ res.status(201).json({ message: '${pascal} account created', ${camel}: safe });
1343
+ };
1344
+ `;
1345
+ }
1346
+ function entityLoginContent(pascal, slug, cfg) {
1347
+ const ts = cfg.language === "typescript";
1348
+ const db = entityOrm(cfg);
1349
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1350
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1351
+ return `${typeImport}import bcrypt from 'bcrypt';
1352
+ import { issueToken } from 'express-file-cluster/auth';
1353
+ import { ${pascal} } from '../../../model/${pascal}.js';
1354
+
1355
+ export const POST = async ${typedArgs} => {
1356
+ const { email, password } = req.body;
1357
+ if (!email || !password) return res.status(400).json({ error: 'email and password are required' });
1358
+
1359
+ const record = await ${db.findOne(pascal, "{ email }")};
1360
+ if (!record) return res.status(401).json({ error: 'Invalid credentials' });
1361
+ const match = await bcrypt.compare(password, record.password);
1362
+ if (!match) return res.status(401).json({ error: 'Invalid credentials' });
1363
+ if (!record.isActive) return res.status(403).json({ error: 'Account suspended' });
1364
+ await issueToken(res, { id: record.id, role: record.role, email: record.email });
1365
+ res.json({ message: 'Logged in as ${slug}' });
1366
+ };
1367
+ `;
1368
+ }
1369
+ function entityLogoutContent(cfg) {
1370
+ const ts = cfg.language === "typescript";
1371
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1372
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1373
+ return `${typeImport}import { requireAuth, revokeSession } from 'express-file-cluster/auth';
1374
+
1375
+ export const middlewares = [requireAuth];
1376
+
1377
+ export const POST = async ${typedArgs} => {
1378
+ try {
1379
+ await revokeSession(req, res);
1380
+ } catch {
1381
+ res.clearCookie('efc_token');
1382
+ }
1383
+ res.json({ message: 'Logged out successfully' });
1384
+ };
1385
+ `;
1386
+ }
1387
+ function entityMeContent(slug, cfg) {
1388
+ const ts = cfg.language === "typescript";
1389
+ const typedArgs = ts ? "(req: Request, res: Response)" : "(req, res)";
1390
+ const typeImport = ts ? "import type { Request, Response } from 'express';\n" : "";
1391
+ return `${typeImport}import { requireAuth } from 'express-file-cluster/auth';
1392
+
1393
+ export const middlewares = [requireAuth('${slug}')];
1394
+
1395
+ export const GET = async ${typedArgs} => {
1396
+ res.json((req${ts ? " as any" : ""}).user);
1397
+ };
1398
+ `;
1399
+ }
1400
+ function generateEntityAuth(cwd, entityName, cfg, options) {
1401
+ const validated = validateEntityName(entityName);
1402
+ if ("error" in validated) throw new Error(`[EFC] ${validated.error}`);
1403
+ const { pascal, camel, slug } = validated;
1404
+ const ext = cfg.language === "typescript" ? "ts" : "js";
1405
+ const result = { written: [], manual: [], conflicts: [] };
1406
+ const files = [
1407
+ { rel: `src/model/${pascal}.${ext}`, content: entityModelContent(pascal, slug, cfg) },
1408
+ {
1409
+ rel: `src/api/auth/${slug}/register.${ext}`,
1410
+ content: entityRegisterContent(pascal, camel, cfg)
1411
+ },
1412
+ {
1413
+ rel: `src/api/auth/${slug}/login.${ext}`,
1414
+ content: entityLoginContent(pascal, slug, cfg)
1415
+ },
1416
+ {
1417
+ rel: `src/api/auth/${slug}/logout.${ext}`,
1418
+ content: entityLogoutContent(cfg)
1419
+ },
1420
+ {
1421
+ rel: `src/api/auth/${slug}/me.${ext}`,
1422
+ content: entityMeContent(slug, cfg)
1423
+ }
1424
+ ];
1425
+ for (const f of files) {
1426
+ const abs = path7.join(cwd, f.rel);
1427
+ const exists = fs7.existsSync(abs);
1428
+ if (exists && !options?.overwrite) {
1429
+ result.conflicts.push(f.rel);
1430
+ result.manual.push(`${f.rel} already exists \u2014 skipped (pass --overwrite to replace)`);
1431
+ continue;
1432
+ }
1433
+ result.written.push(f.rel);
1434
+ if (!options?.dryRun) {
1435
+ fs7.mkdirSync(path7.dirname(abs), { recursive: true });
1436
+ fs7.writeFileSync(abs, f.content);
1437
+ cfg.files[f.rel] = sha256(f.content);
1438
+ }
1439
+ }
1440
+ if (entityUsesTables(cfg) && !options?.dryRun) {
1441
+ result.manual.push(...registerModels(cwd, cfg.language, [pascal]));
1442
+ }
1443
+ const pkgFile = path7.join(cwd, "package.json");
1444
+ if (fs7.existsSync(pkgFile)) {
1445
+ try {
1446
+ const pkg = JSON.parse(fs7.readFileSync(pkgFile, "utf8"));
1447
+ let pkgChanged = false;
1448
+ const deps = pkg["dependencies"] ?? {};
1449
+ const devDeps = pkg["devDependencies"] ?? {};
1450
+ if (!deps["bcrypt"]) {
1451
+ deps["bcrypt"] = "^5.1.0";
1452
+ pkg["dependencies"] = Object.fromEntries(
1453
+ Object.entries(deps).sort(([a], [b]) => a.localeCompare(b))
1454
+ );
1455
+ pkgChanged = true;
1456
+ }
1457
+ if (cfg.language === "typescript" && !devDeps["@types/bcrypt"]) {
1458
+ devDeps["@types/bcrypt"] = "^5.0.0";
1459
+ pkg["devDependencies"] = Object.fromEntries(
1460
+ Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1461
+ );
1462
+ pkgChanged = true;
1463
+ }
1464
+ if (pkgChanged) {
1465
+ result.installNeeded = true;
1466
+ if (!options?.dryRun) {
1467
+ fs7.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
1468
+ }
1469
+ }
1470
+ } catch {
1471
+ }
1472
+ }
1473
+ const envFile = path7.join(cwd, ".env");
1474
+ if (fs7.existsSync(envFile)) {
1475
+ const envKeys = readEnvKeys(envFile);
1476
+ if (!envKeys.includes("JWT_SECRET")) {
1477
+ const secret = crypto.randomBytes(64).toString("hex");
1478
+ if (!options?.dryRun) {
1479
+ appendEnv(envFile, [`JWT_SECRET=${secret}`]);
1480
+ const exampleFile = path7.join(cwd, ".env.example");
1481
+ if (fs7.existsSync(exampleFile) && !readEnvKeys(exampleFile).includes("JWT_SECRET")) {
1482
+ appendEnv(exampleFile, ["JWT_SECRET=<generate with: openssl rand -hex 64>"]);
1483
+ }
1484
+ }
1485
+ result.manual.push("Added JWT_SECRET to .env");
1486
+ }
1487
+ }
1488
+ const itemName = `auth:${slug}`;
1489
+ if (!cfg.items.includes(itemName)) cfg.items.push(itemName);
1490
+ if (!options?.dryRun) {
1491
+ writeEfcJson(cwd, cfg);
1492
+ }
1493
+ return result;
1494
+ }
1267
1495
 
1268
1496
  // src/cli/commands/registry.ts
1269
1497
  function registryCommands() {
@@ -1442,16 +1670,102 @@ function packageManager(cwd) {
1442
1670
  }
1443
1671
  function addCommand() {
1444
1672
  return new Command8("add").description("Add features to the app from the registry (copies their source into src/)").argument(
1445
- "<items...>",
1446
- "registry items, e.g. auth forgot-password admin-users \u2014 `efc list` shows them"
1447
- ).option("-y, --yes", "skip the confirmation").option("--overwrite", "replace files that were changed in this app").option("--dry-run", "show what would change without writing anything").option("--no-install", "don't run the package manager afterwards").option("--no-prompt", "don't ask for credentials \u2014 write placeholders to .env instead").action(
1673
+ "[items...]",
1674
+ "registry items (auth forgot-password admin-users) or custom auth entities (auth:merchant, auth --entity merchant)"
1675
+ ).option("-y, --yes", "skip the confirmation").option("--overwrite", "replace files that were changed in this app").option("--dry-run", "show what would change without writing anything").option("--no-install", "don't run the package manager afterwards").option("--no-prompt", "don't ask for credentials \u2014 write placeholders to .env instead").option("--entity <name>", "scaffold a custom auth entity (model + auth routes)").action(
1448
1676
  async (names, opts) => {
1449
1677
  try {
1678
+ const rawNames = names ?? [];
1679
+ const entityNames = [];
1680
+ const registryNames = [];
1681
+ let i = 0;
1682
+ if (rawNames[0] === "auth" && rawNames[1] === "new" && rawNames.length >= 3) {
1683
+ for (let j = 2; j < rawNames.length; j++) {
1684
+ entityNames.push(rawNames[j]);
1685
+ }
1686
+ i = rawNames.length;
1687
+ }
1688
+ for (; i < rawNames.length; i++) {
1689
+ const n = rawNames[i];
1690
+ const colonMatch = /^auth:([A-Za-z][A-Za-z0-9_-]*)$/.exec(n);
1691
+ if (colonMatch) {
1692
+ entityNames.push(colonMatch[1]);
1693
+ } else if (opts.entity && n === "auth") {
1694
+ continue;
1695
+ } else {
1696
+ registryNames.push(n);
1697
+ }
1698
+ }
1699
+ if (opts.entity && !entityNames.includes(opts.entity)) {
1700
+ entityNames.push(opts.entity);
1701
+ }
1702
+ if (entityNames.length === 0 && registryNames.length === 0) {
1703
+ fail(
1704
+ "Specify at least one item or entity to add \u2014 e.g. `efc add auth` or `efc add auth:merchant`. Run `efc list` to see available features."
1705
+ );
1706
+ }
1707
+ let anyInstallNeeded = false;
1708
+ if (entityNames.length > 0) {
1709
+ const { cwd: cwd2, cfg: cfg2, detected: detected2 } = load();
1710
+ if (detected2) {
1711
+ console.log(
1712
+ pc8.dim(`
1713
+ No ${EFC_JSON} yet \u2014 detected ${describe(cfg2)}; it'll be created.`)
1714
+ );
1715
+ }
1716
+ for (const eName of entityNames) {
1717
+ const validated = validateEntityName(eName);
1718
+ if ("error" in validated) fail(validated.error);
1719
+ const { pascal, slug } = validated;
1720
+ console.log(pc8.bold(`
1721
+ Adding auth entity: ${pascal}
1722
+ `));
1723
+ const result2 = generateEntityAuth(cwd2, eName, cfg2, {
1724
+ dryRun: opts.dryRun,
1725
+ overwrite: opts.overwrite
1726
+ });
1727
+ if (result2.written.length) {
1728
+ for (const f of result2.written) console.log(` ${pc8.green("create ")} ${f}`);
1729
+ const actionVerb = opts.dryRun ? "would be written (dry run)" : "written";
1730
+ console.log(pc8.green(`
1731
+ \u2713 ${result2.written.length} file(s) ${actionVerb}`));
1732
+ }
1733
+ for (const m of result2.manual) console.log(pc8.yellow(` ! ${m}`));
1734
+ console.log(
1735
+ pc8.dim(
1736
+ `
1737
+ Routes: POST /auth/${slug}/register, /login, /logout; GET /me`
1738
+ )
1739
+ );
1740
+ console.log(
1741
+ pc8.dim(` Protect routes with: requireAuth('${slug}')`)
1742
+ );
1743
+ if (result2.installNeeded) anyInstallNeeded = true;
1744
+ }
1745
+ console.log();
1746
+ if (anyInstallNeeded && !opts.dryRun) {
1747
+ const pm = packageManager(cwd2);
1748
+ if (opts.install) {
1749
+ console.log(pc8.dim(` $ ${pm} install`));
1750
+ const r = spawnSync(pm, ["install"], {
1751
+ cwd: cwd2,
1752
+ stdio: "inherit",
1753
+ shell: process.platform === "win32"
1754
+ });
1755
+ if (r.status !== 0)
1756
+ console.log(pc8.yellow(` ${pm} install failed \u2014 run it yourself.`));
1757
+ } else {
1758
+ console.log(pc8.yellow(` Run \`${pm} install\` for the new packages.`));
1759
+ }
1760
+ }
1761
+ if (registryNames.length === 0) return;
1762
+ }
1450
1763
  const { cwd, registry, cfg, detected } = load();
1451
- const plan = planAdd(cwd, registry, names, { overwrite: !!opts.overwrite }, cfg);
1764
+ const itemsToAdd = registryNames;
1765
+ const plan = planAdd(cwd, registry, itemsToAdd, { overwrite: !!opts.overwrite }, cfg);
1452
1766
  if (plan.problems.length) fail(plan.problems.join("\n"));
1453
1767
  if (plan.items.length === 0) {
1454
- console.log(pc8.dim(`Already installed: ${names.join(", ")}`));
1768
+ console.log(pc8.dim(`Already installed: ${itemsToAdd.join(", ")}`));
1455
1769
  return;
1456
1770
  }
1457
1771
  if (detected) {
@@ -1541,6 +1855,13 @@ function listCommand() {
1541
1855
  console.log(` ${mark} ${pc8.cyan(item.name.padEnd(20))} ${item.description}${deps}`);
1542
1856
  }
1543
1857
  }
1858
+ const entities = (readEfcJson(cwd)?.items ?? []).filter((i) => i.startsWith("auth:")).map((i) => i.slice(5));
1859
+ if (entities.length > 0) {
1860
+ console.log(pc8.bold("\n custom auth entities"));
1861
+ for (const e of entities) {
1862
+ console.log(` ${pc8.green("\u2713")} ${pc8.cyan(e.padEnd(20))} model + auth routes for ${e}`);
1863
+ }
1864
+ }
1544
1865
  console.log(pc8.dim("\n efc add <item...> \xB7 efc view <item>\n"));
1545
1866
  } catch (err) {
1546
1867
  fail(err);
@@ -1585,6 +1906,22 @@ function diffCommand() {
1585
1906
  const names = name ? [name] : cfg.items;
1586
1907
  let clean = true;
1587
1908
  for (const n of names) {
1909
+ if (!registry.has(n)) {
1910
+ if (n.startsWith("auth:")) {
1911
+ if (name) {
1912
+ console.log(
1913
+ pc8.dim(
1914
+ `
1915
+ ${n} is a custom auth entity (files are owned by your project, no upstream registry item to diff).`
1916
+ )
1917
+ );
1918
+ }
1919
+ } else {
1920
+ console.log(pc8.dim(`
1921
+ ${n} is not a registry item.`));
1922
+ }
1923
+ continue;
1924
+ }
1588
1925
  for (const f of itemStatus(cwd, registry, cfg, n)) {
1589
1926
  if (f.status === "unchanged") continue;
1590
1927
  clean = false;