express-file-cluster 0.7.1 → 0.8.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/README.md +3 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/chunk-75O3WQKR.cjs +1386 -0
- package/dist/chunk-75O3WQKR.cjs.map +1 -0
- package/dist/{chunk-6OGOVV57.js → chunk-B2I7SYQ3.js} +100 -1261
- package/dist/chunk-B2I7SYQ3.js.map +1 -0
- package/dist/chunk-BBSZLGZW.js +113 -0
- package/dist/chunk-BBSZLGZW.js.map +1 -0
- package/dist/{chunk-AZYXQU3Z.cjs → chunk-FQFKHPLR.cjs} +217 -1378
- package/dist/chunk-FQFKHPLR.cjs.map +1 -0
- package/dist/chunk-OSES7ZQ5.js +1386 -0
- package/dist/chunk-OSES7ZQ5.js.map +1 -0
- package/dist/chunk-QL6EWT4B.cjs +113 -0
- package/dist/chunk-QL6EWT4B.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +611 -26
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +610 -25
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +1210 -12
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +1221 -23
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/db.md +1 -0
- package/dist/docs/cli/add.md +136 -0
- package/dist/docs/cli/db.md +25 -2
- package/dist/docs/cli/index.md +10 -1
- package/dist/docs/core-concepts/middleware.md +1 -1
- package/dist/docs/getting-started/index.md +25 -18
- package/dist/docs/getting-started/project-structure.md +6 -7
- package/dist/docs/guides/authentication.md +3 -1
- package/dist/docs/guides/coming-from-prisma.md +75 -0
- package/dist/docs/guides/database.md +3 -2
- package/dist/docs/guides/generated-portals.md +36 -19
- package/dist/docs/guides/mailer.md +7 -10
- package/dist/docs/guides/migrations.md +114 -3
- package/dist/docs/guides/oauth.md +94 -0
- package/dist/docs/guides/rbac.md +5 -40
- package/dist/docs/index.md +5 -3
- package/dist/docs/skills/SKILL.md +3 -3
- package/dist/docs/skills/what-not-to-invent.md +22 -6
- package/dist/index.cjs +10 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +8 -6
- package/dist/index.js.map +1 -1
- package/dist/registry/index.json +506 -0
- package/dist/registry/js-mongo/_base.json +1 -0
- package/dist/registry/js-mongo/account-security.json +1 -0
- package/dist/registry/js-mongo/account-settings.json +1 -0
- package/dist/registry/js-mongo/admin-admins.json +1 -0
- package/dist/registry/js-mongo/admin-analytics.json +1 -0
- package/dist/registry/js-mongo/admin-billing.json +1 -0
- package/dist/registry/js-mongo/admin-content.json +1 -0
- package/dist/registry/js-mongo/admin-logs.json +1 -0
- package/dist/registry/js-mongo/admin-support.json +1 -0
- package/dist/registry/js-mongo/admin-system.json +1 -0
- package/dist/registry/js-mongo/admin-users.json +1 -0
- package/dist/registry/js-mongo/admin.json +1 -0
- package/dist/registry/js-mongo/auth.json +1 -0
- package/dist/registry/js-mongo/auth@apple.json +1 -0
- package/dist/registry/js-mongo/auth@google.json +1 -0
- package/dist/registry/js-mongo/billing.json +1 -0
- package/dist/registry/js-mongo/email-client.json +1 -0
- package/dist/registry/js-mongo/email-verification.json +1 -0
- package/dist/registry/js-mongo/files.json +1 -0
- package/dist/registry/js-mongo/forgot-password.json +1 -0
- package/dist/registry/js-mongo/notifications.json +1 -0
- package/dist/registry/js-mongo/support.json +1 -0
- package/dist/registry/js-mongo/user-profile.json +1 -0
- package/dist/registry/js-pg-model/_base.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -0
- package/dist/registry/js-pg-model/account-settings.json +1 -0
- package/dist/registry/js-pg-model/admin-admins.json +1 -0
- package/dist/registry/js-pg-model/admin-analytics.json +1 -0
- package/dist/registry/js-pg-model/admin-billing.json +1 -0
- package/dist/registry/js-pg-model/admin-content.json +1 -0
- package/dist/registry/js-pg-model/admin-logs.json +1 -0
- package/dist/registry/js-pg-model/admin-support.json +1 -0
- package/dist/registry/js-pg-model/admin-system.json +1 -0
- package/dist/registry/js-pg-model/admin-users.json +1 -0
- package/dist/registry/js-pg-model/admin.json +1 -0
- package/dist/registry/js-pg-model/auth.json +1 -0
- package/dist/registry/js-pg-model/auth@apple.json +1 -0
- package/dist/registry/js-pg-model/auth@google.json +1 -0
- package/dist/registry/js-pg-model/billing.json +1 -0
- package/dist/registry/js-pg-model/email-client.json +1 -0
- package/dist/registry/js-pg-model/email-verification.json +1 -0
- package/dist/registry/js-pg-model/files.json +1 -0
- package/dist/registry/js-pg-model/forgot-password.json +1 -0
- package/dist/registry/js-pg-model/notifications.json +1 -0
- package/dist/registry/js-pg-model/support.json +1 -0
- package/dist/registry/js-pg-model/user-profile.json +1 -0
- package/dist/registry/js-pg-table/_base.json +1 -0
- package/dist/registry/js-pg-table/account-security.json +1 -0
- package/dist/registry/js-pg-table/account-settings.json +1 -0
- package/dist/registry/js-pg-table/admin-admins.json +1 -0
- package/dist/registry/js-pg-table/admin-analytics.json +1 -0
- package/dist/registry/js-pg-table/admin-billing.json +1 -0
- package/dist/registry/js-pg-table/admin-content.json +1 -0
- package/dist/registry/js-pg-table/admin-logs.json +1 -0
- package/dist/registry/js-pg-table/admin-support.json +1 -0
- package/dist/registry/js-pg-table/admin-system.json +1 -0
- package/dist/registry/js-pg-table/admin-users.json +1 -0
- package/dist/registry/js-pg-table/admin.json +1 -0
- package/dist/registry/js-pg-table/auth.json +1 -0
- package/dist/registry/js-pg-table/auth@apple.json +1 -0
- package/dist/registry/js-pg-table/auth@google.json +1 -0
- package/dist/registry/js-pg-table/billing.json +1 -0
- package/dist/registry/js-pg-table/email-client.json +1 -0
- package/dist/registry/js-pg-table/email-verification.json +1 -0
- package/dist/registry/js-pg-table/files.json +1 -0
- package/dist/registry/js-pg-table/forgot-password.json +1 -0
- package/dist/registry/js-pg-table/notifications.json +1 -0
- package/dist/registry/js-pg-table/support.json +1 -0
- package/dist/registry/js-pg-table/user-profile.json +1 -0
- package/dist/registry/ts-mongo/_base.json +1 -0
- package/dist/registry/ts-mongo/account-security.json +1 -0
- package/dist/registry/ts-mongo/account-settings.json +1 -0
- package/dist/registry/ts-mongo/admin-admins.json +1 -0
- package/dist/registry/ts-mongo/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo/admin-billing.json +1 -0
- package/dist/registry/ts-mongo/admin-content.json +1 -0
- package/dist/registry/ts-mongo/admin-logs.json +1 -0
- package/dist/registry/ts-mongo/admin-support.json +1 -0
- package/dist/registry/ts-mongo/admin-system.json +1 -0
- package/dist/registry/ts-mongo/admin-users.json +1 -0
- package/dist/registry/ts-mongo/admin.json +1 -0
- package/dist/registry/ts-mongo/auth.json +1 -0
- package/dist/registry/ts-mongo/auth@apple.json +1 -0
- package/dist/registry/ts-mongo/auth@google.json +1 -0
- package/dist/registry/ts-mongo/billing.json +1 -0
- package/dist/registry/ts-mongo/email-client.json +1 -0
- package/dist/registry/ts-mongo/email-verification.json +1 -0
- package/dist/registry/ts-mongo/files.json +1 -0
- package/dist/registry/ts-mongo/forgot-password.json +1 -0
- package/dist/registry/ts-mongo/notifications.json +1 -0
- package/dist/registry/ts-mongo/support.json +1 -0
- package/dist/registry/ts-mongo/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/_base.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -0
- package/dist/registry/ts-pg-model/account-settings.json +1 -0
- package/dist/registry/ts-pg-model/admin-admins.json +1 -0
- package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-model/admin-billing.json +1 -0
- package/dist/registry/ts-pg-model/admin-content.json +1 -0
- package/dist/registry/ts-pg-model/admin-logs.json +1 -0
- package/dist/registry/ts-pg-model/admin-support.json +1 -0
- package/dist/registry/ts-pg-model/admin-system.json +1 -0
- package/dist/registry/ts-pg-model/admin-users.json +1 -0
- package/dist/registry/ts-pg-model/admin.json +1 -0
- package/dist/registry/ts-pg-model/auth.json +1 -0
- package/dist/registry/ts-pg-model/auth@apple.json +1 -0
- package/dist/registry/ts-pg-model/auth@google.json +1 -0
- package/dist/registry/ts-pg-model/billing.json +1 -0
- package/dist/registry/ts-pg-model/email-client.json +1 -0
- package/dist/registry/ts-pg-model/email-verification.json +1 -0
- package/dist/registry/ts-pg-model/files.json +1 -0
- package/dist/registry/ts-pg-model/forgot-password.json +1 -0
- package/dist/registry/ts-pg-model/notifications.json +1 -0
- package/dist/registry/ts-pg-model/support.json +1 -0
- package/dist/registry/ts-pg-model/user-profile.json +1 -0
- package/dist/registry/ts-pg-table/_base.json +1 -0
- package/dist/registry/ts-pg-table/account-security.json +1 -0
- package/dist/registry/ts-pg-table/account-settings.json +1 -0
- package/dist/registry/ts-pg-table/admin-admins.json +1 -0
- package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
- package/dist/registry/ts-pg-table/admin-billing.json +1 -0
- package/dist/registry/ts-pg-table/admin-content.json +1 -0
- package/dist/registry/ts-pg-table/admin-logs.json +1 -0
- package/dist/registry/ts-pg-table/admin-support.json +1 -0
- package/dist/registry/ts-pg-table/admin-system.json +1 -0
- package/dist/registry/ts-pg-table/admin-users.json +1 -0
- package/dist/registry/ts-pg-table/admin.json +1 -0
- package/dist/registry/ts-pg-table/auth.json +1 -0
- package/dist/registry/ts-pg-table/auth@apple.json +1 -0
- package/dist/registry/ts-pg-table/auth@google.json +1 -0
- package/dist/registry/ts-pg-table/billing.json +1 -0
- package/dist/registry/ts-pg-table/email-client.json +1 -0
- package/dist/registry/ts-pg-table/email-verification.json +1 -0
- package/dist/registry/ts-pg-table/files.json +1 -0
- package/dist/registry/ts-pg-table/forgot-password.json +1 -0
- package/dist/registry/ts-pg-table/notifications.json +1 -0
- package/dist/registry/ts-pg-table/support.json +1 -0
- package/dist/registry/ts-pg-table/user-profile.json +1 -0
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-B6lVw4bj.d.cts → types-B1tJoI4g.d.cts} +6 -0
- package/dist/{types-B6lVw4bj.d.ts → types-B1tJoI4g.d.ts} +6 -0
- package/package.json +11 -2
- package/dist/chunk-6OGOVV57.js.map +0 -1
- package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -5,16 +5,23 @@ import {
|
|
|
5
5
|
import {
|
|
6
6
|
parseRedisUrl
|
|
7
7
|
} from "../chunk-UBQYQPBU.js";
|
|
8
|
+
import {
|
|
9
|
+
writeModels
|
|
10
|
+
} from "../chunk-BBSZLGZW.js";
|
|
11
|
+
import {
|
|
12
|
+
tableNameFor
|
|
13
|
+
} from "../chunk-OSES7ZQ5.js";
|
|
14
|
+
import "../chunk-BUBXO7WU.js";
|
|
8
15
|
import "../chunk-LJNSJFOL.js";
|
|
9
16
|
import "../chunk-HBYSKULC.js";
|
|
10
17
|
import "../chunk-277BSYVH.js";
|
|
11
18
|
|
|
12
19
|
// src/cli/index.ts
|
|
13
|
-
import
|
|
14
|
-
import
|
|
20
|
+
import fs10 from "fs";
|
|
21
|
+
import path10 from "path";
|
|
15
22
|
import { spawn as spawn5 } from "child_process";
|
|
16
|
-
import { fileURLToPath as
|
|
17
|
-
import { Command as
|
|
23
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
24
|
+
import { Command as Command10 } from "commander";
|
|
18
25
|
|
|
19
26
|
// src/cli/commands/start.ts
|
|
20
27
|
import { Command } from "commander";
|
|
@@ -562,14 +569,14 @@ async function run(opts, fn) {
|
|
|
562
569
|
});
|
|
563
570
|
}
|
|
564
571
|
}
|
|
565
|
-
function ids(
|
|
572
|
+
function ids(list2, all) {
|
|
566
573
|
if (all) return [];
|
|
567
|
-
if (
|
|
574
|
+
if (list2.length === 0) {
|
|
568
575
|
console.error(pc5.red("Pass job ids, or --all"));
|
|
569
576
|
process.exitCode = 1;
|
|
570
577
|
return null;
|
|
571
578
|
}
|
|
572
|
-
return
|
|
579
|
+
return list2;
|
|
573
580
|
}
|
|
574
581
|
function taskAdminCommands() {
|
|
575
582
|
const failed = withConnectionOptions(
|
|
@@ -608,8 +615,8 @@ function taskAdminCommands() {
|
|
|
608
615
|
);
|
|
609
616
|
const retry = withConnectionOptions(
|
|
610
617
|
new Command5("retry").description("Re-queue failed jobs").argument("[ids...]", "job ids")
|
|
611
|
-
).option("--all", "retry every failed job").action((
|
|
612
|
-
const selected = ids(
|
|
618
|
+
).option("--all", "retry every failed job").action((list2, opts) => {
|
|
619
|
+
const selected = ids(list2, opts.all);
|
|
613
620
|
if (!selected) return;
|
|
614
621
|
return run(opts, async (admin) => {
|
|
615
622
|
console.log(pc5.green(`Retried ${await admin.retry(selected)} job(s)`));
|
|
@@ -617,8 +624,8 @@ function taskAdminCommands() {
|
|
|
617
624
|
});
|
|
618
625
|
const purge = withConnectionOptions(
|
|
619
626
|
new Command5("purge").description("Delete failed jobs").argument("[ids...]", "job ids")
|
|
620
|
-
).option("--all", "delete every failed job").action((
|
|
621
|
-
const selected = ids(
|
|
627
|
+
).option("--all", "delete every failed job").action((list2, opts) => {
|
|
628
|
+
const selected = ids(list2, opts.all);
|
|
622
629
|
if (!selected) return;
|
|
623
630
|
return run(opts, async (admin) => {
|
|
624
631
|
console.log(pc5.green(`Removed ${await admin.purge(selected)} job(s)`));
|
|
@@ -777,9 +784,22 @@ function run2(command, opts) {
|
|
|
777
784
|
var common = (cmd) => cmd.option("--database-url <url>", "override DATABASE_URL").option("--dist", "load compiled files from dist/src even when tsx is installed");
|
|
778
785
|
function dbCommand() {
|
|
779
786
|
const cmd = new Command7("db").description("Database migrations, seeds and studio");
|
|
780
|
-
common(cmd.command("migrate").description("Run pending migrations in src/migrations")).
|
|
787
|
+
common(cmd.command("migrate").description("Run pending migrations in src/migrations")).option(
|
|
788
|
+
"--baseline",
|
|
789
|
+
"record pending migrations as applied without running them (the schema already matches)"
|
|
790
|
+
).action(
|
|
781
791
|
(opts) => run2("migrate", opts)
|
|
782
792
|
);
|
|
793
|
+
common(
|
|
794
|
+
cmd.command("generate").description(
|
|
795
|
+
"Write a migration that brings the schema from src/migrations in line with the models"
|
|
796
|
+
).argument("[name]", "migration name, e.g. add_posts (omit to only print the plan)")
|
|
797
|
+
).option("--allow-drop", "also drop columns the models no longer declare (data is lost)").option("--tighten", "add NOT NULL for required fields and validate enum checks").option(
|
|
798
|
+
"--verify",
|
|
799
|
+
"replay all migrations into a scratch schema and fail if they miss anything"
|
|
800
|
+
).action(
|
|
801
|
+
(name, opts) => run2("generate", { ...opts, ...name !== void 0 && { name } })
|
|
802
|
+
);
|
|
783
803
|
common(cmd.command("rollback").description("Revert the last batch of migrations")).option("--steps <n>", "number of batches to revert", "1").action((opts) => {
|
|
784
804
|
const steps = Number(opts.steps);
|
|
785
805
|
if (!Number.isInteger(steps) || steps < 1) {
|
|
@@ -790,9 +810,17 @@ function dbCommand() {
|
|
|
790
810
|
});
|
|
791
811
|
common(
|
|
792
812
|
cmd.command("sync").description("Bring tables/collections and indexes in line with the models in src/model(s)")
|
|
793
|
-
).option("--dry-run", "print the changes (SQL on PostgreSQL) without applying them").
|
|
813
|
+
).option("--dry-run", "print the changes (SQL on PostgreSQL) without applying them").option(
|
|
814
|
+
"--exit-code",
|
|
815
|
+
"with --dry-run: exit with code 2 when there are changes (CI drift check)"
|
|
816
|
+
).action(
|
|
794
817
|
(opts) => run2("sync", opts)
|
|
795
818
|
);
|
|
819
|
+
common(
|
|
820
|
+
cmd.command("pull").description("Write defineTable models for the tables in the database (PostgreSQL)")
|
|
821
|
+
).option("--out <dir>", "where to write the models", "src/model").option("--force", "overwrite model files that already exist").action(
|
|
822
|
+
(opts) => run2("pull", opts)
|
|
823
|
+
);
|
|
796
824
|
common(cmd.command("status").description("List applied and pending migrations")).action(
|
|
797
825
|
(opts) => run2("status", opts)
|
|
798
826
|
);
|
|
@@ -807,21 +835,1189 @@ function dbCommand() {
|
|
|
807
835
|
return cmd;
|
|
808
836
|
}
|
|
809
837
|
|
|
838
|
+
// src/cli/commands/registry.ts
|
|
839
|
+
import { Command as Command8 } from "commander";
|
|
840
|
+
import { spawnSync } from "child_process";
|
|
841
|
+
import fs8 from "fs";
|
|
842
|
+
import path8 from "path";
|
|
843
|
+
import readline from "readline/promises";
|
|
844
|
+
import { Writable } from "stream";
|
|
845
|
+
import pc8 from "picocolors";
|
|
846
|
+
|
|
847
|
+
// src/cli/registry.ts
|
|
848
|
+
import crypto from "crypto";
|
|
849
|
+
import fs7 from "fs";
|
|
850
|
+
import path7 from "path";
|
|
851
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
852
|
+
var EFC_JSON = "efc.json";
|
|
853
|
+
function sha256(content) {
|
|
854
|
+
return crypto.createHash("sha256").update(content).digest("hex");
|
|
855
|
+
}
|
|
856
|
+
function registryDir() {
|
|
857
|
+
const override = process.env["EFC_REGISTRY_DIR"];
|
|
858
|
+
if (override) return path7.resolve(override);
|
|
859
|
+
for (let dir = path7.dirname(fileURLToPath2(import.meta.url)); ; dir = path7.dirname(dir)) {
|
|
860
|
+
const pkg = path7.join(dir, "package.json");
|
|
861
|
+
if (fs7.existsSync(pkg)) {
|
|
862
|
+
const { name } = JSON.parse(fs7.readFileSync(pkg, "utf8"));
|
|
863
|
+
if (name === "express-file-cluster") return path7.join(dir, "dist", "registry");
|
|
864
|
+
}
|
|
865
|
+
if (path7.dirname(dir) === dir) break;
|
|
866
|
+
}
|
|
867
|
+
throw new Error("Could not locate the express-file-cluster package (for its registry)");
|
|
868
|
+
}
|
|
869
|
+
var Registry = class {
|
|
870
|
+
constructor(dir = registryDir()) {
|
|
871
|
+
this.dir = dir;
|
|
872
|
+
const file = path7.join(dir, "index.json");
|
|
873
|
+
if (!fs7.existsSync(file)) {
|
|
874
|
+
throw new Error(
|
|
875
|
+
`The feature registry is missing (${file}) \u2014 reinstall express-file-cluster, or build it with \`npm run build\``
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
this.index = JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
879
|
+
}
|
|
880
|
+
dir;
|
|
881
|
+
index;
|
|
882
|
+
meta(name) {
|
|
883
|
+
const item = this.index.items.find((i) => i.name === name || i.aliases?.includes(name));
|
|
884
|
+
if (!item) {
|
|
885
|
+
const names = this.index.items.map((i) => i.name).join(", ");
|
|
886
|
+
throw new Error(`Unknown item "${name}". Available: ${names}`);
|
|
887
|
+
}
|
|
888
|
+
return item;
|
|
889
|
+
}
|
|
890
|
+
item(variant, name) {
|
|
891
|
+
const { name: file } = this.meta(name);
|
|
892
|
+
return JSON.parse(
|
|
893
|
+
fs7.readFileSync(path7.join(this.dir, variant, `${file}.json`), "utf8")
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
base(variant) {
|
|
897
|
+
return JSON.parse(fs7.readFileSync(path7.join(this.dir, variant, "_base.json"), "utf8")).files;
|
|
898
|
+
}
|
|
899
|
+
/** `names` plus their registry dependencies, dependencies first. */
|
|
900
|
+
withDependencies(names) {
|
|
901
|
+
const out = [];
|
|
902
|
+
const visit = (alias) => {
|
|
903
|
+
const name = this.meta(alias).name;
|
|
904
|
+
if (out.includes(name)) return;
|
|
905
|
+
for (const dep of this.meta(name).registryDependencies) visit(dep);
|
|
906
|
+
out.push(name);
|
|
907
|
+
};
|
|
908
|
+
for (const name of names) visit(name);
|
|
909
|
+
return out;
|
|
910
|
+
}
|
|
911
|
+
};
|
|
912
|
+
function variantOf(cfg) {
|
|
913
|
+
const lang = cfg.language === "typescript" ? "ts" : "js";
|
|
914
|
+
if (cfg.database === "mongodb") return `${lang}-mongo`;
|
|
915
|
+
return `${lang}-pg-${cfg.modelApi === "defineTable" ? "table" : "model"}`;
|
|
916
|
+
}
|
|
917
|
+
function readJson(file) {
|
|
918
|
+
return JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
919
|
+
}
|
|
920
|
+
function readEfcJson(cwd) {
|
|
921
|
+
const file = path7.join(cwd, EFC_JSON);
|
|
922
|
+
return fs7.existsSync(file) ? readJson(file) : void 0;
|
|
923
|
+
}
|
|
924
|
+
function writeEfcJson(cwd, cfg) {
|
|
925
|
+
const files = Object.fromEntries(
|
|
926
|
+
Object.entries(cfg.files).sort(([a], [b]) => a.localeCompare(b))
|
|
927
|
+
);
|
|
928
|
+
fs7.writeFileSync(
|
|
929
|
+
path7.join(cwd, EFC_JSON),
|
|
930
|
+
JSON.stringify({ ...cfg, items: [...cfg.items].sort(), files }, null, 2) + "\n"
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
function detectProject(cwd, version2) {
|
|
934
|
+
const pkgFile = path7.join(cwd, "package.json");
|
|
935
|
+
if (!fs7.existsSync(pkgFile)) throw new Error(`No package.json in ${cwd}`);
|
|
936
|
+
const pkg = readJson(pkgFile);
|
|
937
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
938
|
+
const language = fs7.existsSync(path7.join(cwd, "src", "index.ts")) || fs7.existsSync(path7.join(cwd, "tsconfig.json")) ? "typescript" : "javascript";
|
|
939
|
+
let database;
|
|
940
|
+
if (deps["mongoose"]) database = "mongodb";
|
|
941
|
+
else if (deps["pg"]) database = "postgresql";
|
|
942
|
+
else {
|
|
943
|
+
throw new Error(
|
|
944
|
+
"Could not tell the database from package.json \u2014 install mongoose (MongoDB) or pg + drizzle-orm (PostgreSQL)"
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
let modelApi = database === "postgresql" ? "defineTable" : "defineModel";
|
|
948
|
+
const modelDir = path7.join(cwd, "src", "model");
|
|
949
|
+
if (database === "postgresql" && fs7.existsSync(modelDir)) {
|
|
950
|
+
const sources = fs7.readdirSync(modelDir).filter((f) => /\.[jt]s$/.test(f)).map((f) => fs7.readFileSync(path7.join(modelDir, f), "utf8")).join("\n");
|
|
951
|
+
if (/\bdefineModel\(/.test(sources) && !/\bdefineTable\(/.test(sources))
|
|
952
|
+
modelApi = "defineModel";
|
|
953
|
+
}
|
|
954
|
+
const tasks = deps["bullmq"] ? "bullmq" : deps["pg-boss"] ? "pg-boss" : null;
|
|
955
|
+
return { registry: version2, language, database, modelApi, tasks, items: [], files: {} };
|
|
956
|
+
}
|
|
957
|
+
function planAdd(cwd, registry, names, opts = {}, cfg = readEfcJson(cwd) ?? detectProject(cwd, registry.index.version)) {
|
|
958
|
+
const variant = variantOf(cfg);
|
|
959
|
+
const named = names.map((n) => registry.meta(n).name);
|
|
960
|
+
const items = registry.withDependencies(named).filter((n) => named.includes(n) || !cfg.items.includes(n));
|
|
961
|
+
const plan = {
|
|
962
|
+
cfg,
|
|
963
|
+
variant,
|
|
964
|
+
items,
|
|
965
|
+
files: [],
|
|
966
|
+
dependencies: {},
|
|
967
|
+
devDependencies: {},
|
|
968
|
+
env: [],
|
|
969
|
+
prompts: [],
|
|
970
|
+
docs: [],
|
|
971
|
+
problems: []
|
|
972
|
+
};
|
|
973
|
+
const pkg = fs7.existsSync(path7.join(cwd, "package.json")) ? readJson(
|
|
974
|
+
path7.join(cwd, "package.json")
|
|
975
|
+
) : {};
|
|
976
|
+
const envKeys = /* @__PURE__ */ new Set([
|
|
977
|
+
...readEnvKeys(path7.join(cwd, ".env")),
|
|
978
|
+
...readEnvKeys(path7.join(cwd, ".env.example"))
|
|
979
|
+
]);
|
|
980
|
+
const planned = /* @__PURE__ */ new Map();
|
|
981
|
+
const addFile = (file, item) => {
|
|
982
|
+
const prior = planned.get(file.path);
|
|
983
|
+
if (prior !== void 0) {
|
|
984
|
+
if (prior !== file.content)
|
|
985
|
+
plan.problems.push(`${item} and another item both write ${file.path}`);
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
planned.set(file.path, file.content);
|
|
989
|
+
const abs = path7.join(cwd, file.path);
|
|
990
|
+
let action;
|
|
991
|
+
if (!fs7.existsSync(abs)) action = "create";
|
|
992
|
+
else {
|
|
993
|
+
const local = fs7.readFileSync(abs, "utf8");
|
|
994
|
+
if (local === file.content) action = "skip-identical";
|
|
995
|
+
else if (cfg.files[file.path] === sha256(local)) action = "update";
|
|
996
|
+
else if (opts.overwrite) action = "overwrite";
|
|
997
|
+
else action = "conflict";
|
|
998
|
+
}
|
|
999
|
+
plan.files.push({ path: file.path, content: file.content, action, item });
|
|
1000
|
+
};
|
|
1001
|
+
const needsTasks = items.filter((n) => registry.meta(n).requiresTasks);
|
|
1002
|
+
if (needsTasks.length) {
|
|
1003
|
+
if (!cfg.tasks) {
|
|
1004
|
+
plan.problems.push(
|
|
1005
|
+
`${needsTasks.join(", ")} send email through the SendEmail task, which needs a task backend \u2014 set \`tasks\` in efc.config (bullmq or pg-boss) and record it in efc.json`
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
const ext = cfg.language === "typescript" ? "ts" : "js";
|
|
1009
|
+
const sendEmail = `src/tasks/SendEmail.${ext}`;
|
|
1010
|
+
if (!items.includes("mailer") && !fs7.existsSync(path7.join(cwd, sendEmail))) {
|
|
1011
|
+
const stub = registry.base(variant).find((f) => f.path === sendEmail);
|
|
1012
|
+
if (stub) addFile(stub, "base");
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
for (const name of items) {
|
|
1016
|
+
const meta = registry.meta(name);
|
|
1017
|
+
const item = registry.item(variant, name);
|
|
1018
|
+
for (const file of item.files) addFile(file, name);
|
|
1019
|
+
for (const [dep, range] of Object.entries(item.dependencies)) {
|
|
1020
|
+
if (!pkg.dependencies?.[dep]) plan.dependencies[dep] = range;
|
|
1021
|
+
}
|
|
1022
|
+
for (const [dep, range] of Object.entries(item.devDependencies)) {
|
|
1023
|
+
if (!pkg.devDependencies?.[dep] && !pkg.dependencies?.[dep])
|
|
1024
|
+
plan.devDependencies[dep] = range;
|
|
1025
|
+
}
|
|
1026
|
+
for (const v of item.env) {
|
|
1027
|
+
if (!envKeys.has(v.key) && !plan.env.some((e) => e.key === v.key)) plan.env.push(v);
|
|
1028
|
+
}
|
|
1029
|
+
if (meta.docs) plan.docs.push({ item: name, text: meta.docs });
|
|
1030
|
+
}
|
|
1031
|
+
const adding = new Set(plan.env.map((v) => v.key));
|
|
1032
|
+
for (const name of items) {
|
|
1033
|
+
const prompts = registry.meta(name).prompts ?? [];
|
|
1034
|
+
const sets = (p) => isEnvName(p.name) ? adding.has(p.name) : (p.options ?? []).some((o) => Object.keys(o.env ?? {}).some((k) => adding.has(k))) || prompts.some(
|
|
1035
|
+
(q) => isEnvName(q.name) && adding.has(q.name) && q.when?.[p.name] !== void 0
|
|
1036
|
+
);
|
|
1037
|
+
for (const p of prompts) {
|
|
1038
|
+
const dup = plan.prompts.some(
|
|
1039
|
+
(q) => q.name === p.name && JSON.stringify(q.when) === JSON.stringify(p.when)
|
|
1040
|
+
);
|
|
1041
|
+
if (!dup && sets(p)) plan.prompts.push(p);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
return plan;
|
|
1045
|
+
}
|
|
1046
|
+
function readEnvKeys(file) {
|
|
1047
|
+
if (!fs7.existsSync(file)) return [];
|
|
1048
|
+
return fs7.readFileSync(file, "utf8").split("\n").map((l) => /^([A-Za-z0-9_]+)=/.exec(l)?.[1]).filter((k) => !!k);
|
|
1049
|
+
}
|
|
1050
|
+
function appendEnv(file, lines) {
|
|
1051
|
+
if (lines.length === 0) return;
|
|
1052
|
+
const existing = fs7.existsSync(file) ? fs7.readFileSync(file, "utf8") : "";
|
|
1053
|
+
const sep = existing === "" || existing.endsWith("\n") ? "" : "\n";
|
|
1054
|
+
fs7.writeFileSync(file, existing + sep + lines.join("\n") + "\n");
|
|
1055
|
+
}
|
|
1056
|
+
var isEnvName = (name) => /^[A-Z][A-Z0-9_]*$/.test(name);
|
|
1057
|
+
function promptApplies(p, answers) {
|
|
1058
|
+
return Object.entries(p.when ?? {}).every(([k, v]) => answers[k] === v);
|
|
1059
|
+
}
|
|
1060
|
+
function promptDefault(p, answers) {
|
|
1061
|
+
return p.default?.replace(/\{\{(\w+)\}\}/g, (_, k) => answers[k] ?? "");
|
|
1062
|
+
}
|
|
1063
|
+
function normalizeAnswer(p, raw, cwd) {
|
|
1064
|
+
let value = p.stripSpaces ? raw.replace(/\s/g, "") : raw.trim();
|
|
1065
|
+
if (!value) return p.required ? { error: "Required" } : { value };
|
|
1066
|
+
if (p.type === "file") {
|
|
1067
|
+
const file = path7.resolve(cwd, value.replace(/^~(?=$|\/)/, process.env["HOME"] ?? "~"));
|
|
1068
|
+
if (!fs7.existsSync(file)) return { error: `No such file: ${file}` };
|
|
1069
|
+
value = fs7.readFileSync(file, "utf8").trim();
|
|
1070
|
+
}
|
|
1071
|
+
if (p.pattern && !new RegExp(p.pattern).test(value)) {
|
|
1072
|
+
return { error: p.patternMessage ?? `Must match ${p.pattern}` };
|
|
1073
|
+
}
|
|
1074
|
+
if (p.type === "file") value = value.replace(/\r?\n/g, "\\n");
|
|
1075
|
+
return { value };
|
|
1076
|
+
}
|
|
1077
|
+
function envFromAnswers(prompts, answers) {
|
|
1078
|
+
const env = {};
|
|
1079
|
+
for (const p of prompts) {
|
|
1080
|
+
if (!(p.name in answers) || !promptApplies(p, answers)) continue;
|
|
1081
|
+
if (isEnvName(p.name)) env[p.name] = answers[p.name];
|
|
1082
|
+
const chosen = p.options?.find((o) => o.value === answers[p.name]);
|
|
1083
|
+
Object.assign(env, chosen?.env ?? {});
|
|
1084
|
+
}
|
|
1085
|
+
return env;
|
|
1086
|
+
}
|
|
1087
|
+
function envLine(key, value) {
|
|
1088
|
+
if (!/[\s#"'`]/.test(value)) return `${key}=${value}`;
|
|
1089
|
+
return value.includes("'") ? `${key}="${value.replace(/"/g, '\\"')}"` : `${key}='${value}'`;
|
|
1090
|
+
}
|
|
1091
|
+
function applyAdd(cwd, plan, registry, env = {}) {
|
|
1092
|
+
const result = {
|
|
1093
|
+
written: [],
|
|
1094
|
+
skipped: [],
|
|
1095
|
+
conflicts: [],
|
|
1096
|
+
manual: [],
|
|
1097
|
+
installNeeded: false
|
|
1098
|
+
};
|
|
1099
|
+
const cfg = { ...plan.cfg, files: { ...plan.cfg.files }, items: [...plan.cfg.items] };
|
|
1100
|
+
const newModels = [];
|
|
1101
|
+
for (const f of plan.files) {
|
|
1102
|
+
if (f.action === "conflict") {
|
|
1103
|
+
result.conflicts.push(f.path);
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
if (f.action === "skip-identical") {
|
|
1107
|
+
result.skipped.push(f.path);
|
|
1108
|
+
} else {
|
|
1109
|
+
const abs = path7.join(cwd, f.path);
|
|
1110
|
+
const existed = fs7.existsSync(abs);
|
|
1111
|
+
fs7.mkdirSync(path7.dirname(abs), { recursive: true });
|
|
1112
|
+
fs7.writeFileSync(abs, f.content);
|
|
1113
|
+
result.written.push(f.path);
|
|
1114
|
+
const model = /^src\/model\/([A-Za-z0-9_]+)\.[jt]s$/.exec(f.path)?.[1];
|
|
1115
|
+
if (model && model !== "index" && !existed) newModels.push(model);
|
|
1116
|
+
}
|
|
1117
|
+
cfg.files[f.path] = sha256(f.content);
|
|
1118
|
+
}
|
|
1119
|
+
const pkgFile = path7.join(cwd, "package.json");
|
|
1120
|
+
if (fs7.existsSync(pkgFile) && (Object.keys(plan.dependencies).length || Object.keys(plan.devDependencies).length)) {
|
|
1121
|
+
const pkg = readJson(pkgFile);
|
|
1122
|
+
const sorted = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
|
|
1123
|
+
pkg["dependencies"] = sorted({
|
|
1124
|
+
...pkg["dependencies"],
|
|
1125
|
+
...plan.dependencies
|
|
1126
|
+
});
|
|
1127
|
+
if (Object.keys(plan.devDependencies).length) {
|
|
1128
|
+
pkg["devDependencies"] = sorted({
|
|
1129
|
+
...pkg["devDependencies"],
|
|
1130
|
+
...plan.devDependencies
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
1133
|
+
fs7.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + "\n");
|
|
1134
|
+
result.installNeeded = true;
|
|
1135
|
+
}
|
|
1136
|
+
const envFile = path7.join(cwd, ".env");
|
|
1137
|
+
const exampleFile = path7.join(cwd, ".env.example");
|
|
1138
|
+
appendEnv(
|
|
1139
|
+
envFile,
|
|
1140
|
+
plan.env.filter((v) => !readEnvKeys(envFile).includes(v.key)).map((v) => envLine(v.key, env[v.key] ?? v.value))
|
|
1141
|
+
);
|
|
1142
|
+
if (fs7.existsSync(exampleFile)) {
|
|
1143
|
+
appendEnv(
|
|
1144
|
+
exampleFile,
|
|
1145
|
+
plan.env.filter((v) => !readEnvKeys(exampleFile).includes(v.key)).map((v) => `${v.key}=${v.example}`)
|
|
1146
|
+
);
|
|
1147
|
+
}
|
|
1148
|
+
if (cfg.modelApi === "defineTable" && cfg.database === "postgresql" && newModels.length) {
|
|
1149
|
+
result.manual.push(...registerModels(cwd, cfg.language, newModels));
|
|
1150
|
+
}
|
|
1151
|
+
for (const name of plan.items) if (!cfg.items.includes(name)) cfg.items.push(name);
|
|
1152
|
+
cfg.registry = registry.index.version;
|
|
1153
|
+
writeEfcJson(cwd, cfg);
|
|
1154
|
+
return result;
|
|
1155
|
+
}
|
|
1156
|
+
function registerModels(cwd, language, models) {
|
|
1157
|
+
const ts = language === "typescript";
|
|
1158
|
+
const file = path7.join(cwd, "src", "model", `index.${ts ? "ts" : "js"}`);
|
|
1159
|
+
const rel = path7.relative(cwd, file);
|
|
1160
|
+
if (!fs7.existsSync(file)) {
|
|
1161
|
+
const names = [...models].sort();
|
|
1162
|
+
fs7.writeFileSync(file, modelIndex(names, ts));
|
|
1163
|
+
return [];
|
|
1164
|
+
}
|
|
1165
|
+
let text = fs7.readFileSync(file, "utf8");
|
|
1166
|
+
const manual = [];
|
|
1167
|
+
for (const name of [...models].sort()) {
|
|
1168
|
+
const exportLine = `export { ${name} } from './${name}.js';`;
|
|
1169
|
+
if (!new RegExp(`export \\{ ${name} \\}`).test(text)) {
|
|
1170
|
+
text = insertAfterLast(text, /^export \{ [A-Za-z0-9_]+ \} from .*$/gm, exportLine) ?? exportLine + "\n" + text;
|
|
1171
|
+
}
|
|
1172
|
+
if (!ts) continue;
|
|
1173
|
+
const importLine = `import type { ${name} } from './${name}.js';`;
|
|
1174
|
+
if (!text.includes(importLine)) {
|
|
1175
|
+
const next = insertAfterLast(text, /^import type \{ [A-Za-z0-9_]+ \} from .*$/gm, importLine);
|
|
1176
|
+
if (next) text = next;
|
|
1177
|
+
else manual.push(`${rel}: add \`${importLine}\``);
|
|
1178
|
+
}
|
|
1179
|
+
if (!new RegExp(`^\\s+${name}: typeof ${name};`, "m").test(text)) {
|
|
1180
|
+
const m = /interface Tables \{\n/.exec(text);
|
|
1181
|
+
if (m) {
|
|
1182
|
+
const at = m.index + m[0].length;
|
|
1183
|
+
text = text.slice(0, at) + ` ${name}: typeof ${name};
|
|
1184
|
+
` + text.slice(at);
|
|
1185
|
+
} else manual.push(`${rel}: add \`${name}: typeof ${name};\` to \`interface Tables\``);
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
fs7.writeFileSync(file, text);
|
|
1189
|
+
return manual;
|
|
1190
|
+
}
|
|
1191
|
+
function insertAfterLast(text, re, line) {
|
|
1192
|
+
let last;
|
|
1193
|
+
for (const m of text.matchAll(re)) last = m;
|
|
1194
|
+
if (!last) return void 0;
|
|
1195
|
+
const at = last.index + last[0].length;
|
|
1196
|
+
return text.slice(0, at) + "\n" + line + text.slice(at);
|
|
1197
|
+
}
|
|
1198
|
+
function modelIndex(names, ts) {
|
|
1199
|
+
const exports = names.map((n) => `export { ${n} } from './${n}.js';`).join("\n");
|
|
1200
|
+
const tables = ts ? `
|
|
1201
|
+
${names.map((n) => `import type { ${n} } from './${n}.js';`).join("\n")}
|
|
1202
|
+
|
|
1203
|
+
// Types \`include\` results: relations name models by string, this maps the names to models.
|
|
1204
|
+
declare module 'express-file-cluster' {
|
|
1205
|
+
interface Tables {
|
|
1206
|
+
${names.map((n) => ` ${n}: typeof ${n};`).join("\n")}
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
` : "";
|
|
1210
|
+
return `// Every model, in one import: \`import { User } from '../model/index.js'\` also registers the
|
|
1211
|
+
// models its relations reach, which \`include\` needs.
|
|
1212
|
+
${exports}
|
|
1213
|
+
${tables}`;
|
|
1214
|
+
}
|
|
1215
|
+
function itemStatus(cwd, registry, cfg, name) {
|
|
1216
|
+
return registry.item(variantOf(cfg), name).files.map((f) => {
|
|
1217
|
+
const abs = path7.join(cwd, f.path);
|
|
1218
|
+
if (!fs7.existsSync(abs))
|
|
1219
|
+
return { path: f.path, status: "missing", registry: f.content };
|
|
1220
|
+
const local = fs7.readFileSync(abs, "utf8");
|
|
1221
|
+
if (local === f.content)
|
|
1222
|
+
return { path: f.path, status: "unchanged", registry: f.content, local };
|
|
1223
|
+
const written = cfg.files[f.path];
|
|
1224
|
+
const modified = written !== sha256(local);
|
|
1225
|
+
const outdated = written !== void 0 && written !== sha256(f.content);
|
|
1226
|
+
const status = outdated ? modified ? "outdated+modified" : "outdated" : "modified";
|
|
1227
|
+
return { path: f.path, status, registry: f.content, local };
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
function lineDiff(a, b) {
|
|
1231
|
+
const x = a.split("\n");
|
|
1232
|
+
const y = b.split("\n");
|
|
1233
|
+
const n = x.length;
|
|
1234
|
+
const m = y.length;
|
|
1235
|
+
const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
|
1236
|
+
for (let i2 = n - 1; i2 >= 0; i2--) {
|
|
1237
|
+
for (let j2 = m - 1; j2 >= 0; j2--) {
|
|
1238
|
+
lcs[i2][j2] = x[i2] === y[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
const out = [];
|
|
1242
|
+
let i = 0;
|
|
1243
|
+
let j = 0;
|
|
1244
|
+
while (i < n || j < m) {
|
|
1245
|
+
if (i < n && j < m && x[i] === y[j]) {
|
|
1246
|
+
out.push(` ${x[i]}`);
|
|
1247
|
+
i++;
|
|
1248
|
+
j++;
|
|
1249
|
+
} else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j])) {
|
|
1250
|
+
out.push(`+ ${y[j]}`);
|
|
1251
|
+
j++;
|
|
1252
|
+
} else {
|
|
1253
|
+
out.push(`- ${x[i]}`);
|
|
1254
|
+
i++;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const keep = out.map(
|
|
1258
|
+
(l, k) => out.slice(Math.max(0, k - 2), k + 3).some((c) => !c.startsWith(" "))
|
|
1259
|
+
);
|
|
1260
|
+
const shown = [];
|
|
1261
|
+
out.forEach((l, k) => {
|
|
1262
|
+
if (keep[k]) shown.push(l);
|
|
1263
|
+
else if (keep[k - 1]) shown.push(" \u2026");
|
|
1264
|
+
});
|
|
1265
|
+
return shown;
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/cli/commands/registry.ts
|
|
1269
|
+
function registryCommands() {
|
|
1270
|
+
return [initCommand(), addCommand(), listCommand(), viewCommand(), diffCommand()];
|
|
1271
|
+
}
|
|
1272
|
+
function fail(err) {
|
|
1273
|
+
console.error(pc8.red(`[EFC] ${err instanceof Error ? err.message : String(err)}`));
|
|
1274
|
+
process.exit(1);
|
|
1275
|
+
}
|
|
1276
|
+
function load() {
|
|
1277
|
+
const cwd = process.cwd();
|
|
1278
|
+
const registry = new Registry();
|
|
1279
|
+
const existing = readEfcJson(cwd);
|
|
1280
|
+
return {
|
|
1281
|
+
cwd,
|
|
1282
|
+
registry,
|
|
1283
|
+
cfg: existing ?? detectProject(cwd, registry.index.version),
|
|
1284
|
+
detected: !existing
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
function describe(cfg) {
|
|
1288
|
+
const tasks = cfg.tasks ?? "no task backend";
|
|
1289
|
+
return `${cfg.language}, ${cfg.database}${cfg.database === "postgresql" ? ` (${cfg.modelApi})` : ""}, ${tasks}`;
|
|
1290
|
+
}
|
|
1291
|
+
function initCommand() {
|
|
1292
|
+
return new Command8("init").description(`Write ${EFC_JSON} for an existing app (detects language, database and tasks)`).option("--force", `replace an existing ${EFC_JSON}`).action((opts) => {
|
|
1293
|
+
try {
|
|
1294
|
+
const cwd = process.cwd();
|
|
1295
|
+
if (readEfcJson(cwd) && !opts.force) {
|
|
1296
|
+
console.log(pc8.yellow(`${EFC_JSON} already exists (--force to redetect).`));
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
const registry = new Registry();
|
|
1300
|
+
const cfg = detectProject(cwd, registry.index.version);
|
|
1301
|
+
writeEfcJson(cwd, cfg);
|
|
1302
|
+
console.log(pc8.green(` created ${EFC_JSON}`) + pc8.dim(` (${describe(cfg)})`));
|
|
1303
|
+
console.log(
|
|
1304
|
+
pc8.dim(
|
|
1305
|
+
" Check the values, then add features with `efc add <item>` \u2014 `efc list` shows them."
|
|
1306
|
+
)
|
|
1307
|
+
);
|
|
1308
|
+
} catch (err) {
|
|
1309
|
+
fail(err);
|
|
1310
|
+
}
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
var ACTION_LABEL = {
|
|
1314
|
+
create: pc8.green("create "),
|
|
1315
|
+
update: pc8.cyan("update "),
|
|
1316
|
+
overwrite: pc8.yellow("overwrite"),
|
|
1317
|
+
"skip-identical": pc8.dim("identical"),
|
|
1318
|
+
conflict: pc8.red("conflict ")
|
|
1319
|
+
};
|
|
1320
|
+
function printPlan(plan) {
|
|
1321
|
+
console.log(pc8.bold(`
|
|
1322
|
+
Adding ${plan.items.join(", ")}`) + pc8.dim(` (${plan.variant})
|
|
1323
|
+
`));
|
|
1324
|
+
for (const f of plan.files) console.log(` ${ACTION_LABEL[f.action]} ${f.path}`);
|
|
1325
|
+
const deps = Object.entries(plan.dependencies);
|
|
1326
|
+
const devDeps = Object.entries(plan.devDependencies);
|
|
1327
|
+
if (deps.length || devDeps.length) {
|
|
1328
|
+
console.log(pc8.bold("\n Packages"));
|
|
1329
|
+
for (const [n, r] of deps) console.log(` ${pc8.green("+")} ${n}@${r}`);
|
|
1330
|
+
for (const [n, r] of devDeps) console.log(` ${pc8.green("+")} ${n}@${r} ${pc8.dim("(dev)")}`);
|
|
1331
|
+
}
|
|
1332
|
+
if (plan.env.length) {
|
|
1333
|
+
console.log(pc8.bold("\n Environment") + pc8.dim(" (.env / .env.example)"));
|
|
1334
|
+
for (const v of plan.env) console.log(` ${pc8.green("+")} ${v.key}`);
|
|
1335
|
+
}
|
|
1336
|
+
const conflicts = plan.files.filter((f) => f.action === "conflict");
|
|
1337
|
+
if (conflicts.length) {
|
|
1338
|
+
console.log(
|
|
1339
|
+
pc8.yellow(
|
|
1340
|
+
`
|
|
1341
|
+
${conflicts.length} file(s) differ from the registry and were changed in this app \u2014 they'll be left alone (--overwrite replaces them; \`efc diff\` shows the changes).`
|
|
1342
|
+
)
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
console.log();
|
|
1346
|
+
}
|
|
1347
|
+
function openTerminal() {
|
|
1348
|
+
let muted = false;
|
|
1349
|
+
const output = new Writable({
|
|
1350
|
+
write(chunk, encoding, cb) {
|
|
1351
|
+
if (!muted) process.stdout.write(chunk, encoding);
|
|
1352
|
+
cb();
|
|
1353
|
+
}
|
|
1354
|
+
});
|
|
1355
|
+
const rl = readline.createInterface({ input: process.stdin, output, terminal: true });
|
|
1356
|
+
const lines = [];
|
|
1357
|
+
const waiting = [];
|
|
1358
|
+
let closed = false;
|
|
1359
|
+
rl.on("line", (line) => {
|
|
1360
|
+
const next = waiting.shift();
|
|
1361
|
+
if (next) next(line);
|
|
1362
|
+
else lines.push(line);
|
|
1363
|
+
});
|
|
1364
|
+
rl.on("close", () => {
|
|
1365
|
+
closed = true;
|
|
1366
|
+
for (const next of waiting.splice(0)) next(void 0);
|
|
1367
|
+
});
|
|
1368
|
+
return {
|
|
1369
|
+
async ask(question, hidden = false) {
|
|
1370
|
+
if (hidden) {
|
|
1371
|
+
process.stdout.write(question);
|
|
1372
|
+
rl.setPrompt("");
|
|
1373
|
+
muted = true;
|
|
1374
|
+
} else {
|
|
1375
|
+
rl.setPrompt(question);
|
|
1376
|
+
rl.prompt();
|
|
1377
|
+
}
|
|
1378
|
+
try {
|
|
1379
|
+
const line = lines.length > 0 ? lines.shift() : closed ? void 0 : await new Promise((resolve) => waiting.push(resolve));
|
|
1380
|
+
if (line === void 0) throw new Error("Aborted \u2014 no more input");
|
|
1381
|
+
return line;
|
|
1382
|
+
} finally {
|
|
1383
|
+
if (hidden) {
|
|
1384
|
+
muted = false;
|
|
1385
|
+
process.stdout.write("\n");
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
},
|
|
1389
|
+
close: () => rl.close()
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
async function confirm(term, question) {
|
|
1393
|
+
return /^y(es)?$/i.test((await term.ask(question)).trim());
|
|
1394
|
+
}
|
|
1395
|
+
async function askPrompts(term, prompts, cwd) {
|
|
1396
|
+
const answers = {};
|
|
1397
|
+
{
|
|
1398
|
+
for (const p of prompts) {
|
|
1399
|
+
if (!promptApplies(p, answers)) continue;
|
|
1400
|
+
if (p.note) console.log(pc8.dim(`
|
|
1401
|
+
${p.note}`));
|
|
1402
|
+
if (p.type === "select") {
|
|
1403
|
+
const options = p.options ?? [];
|
|
1404
|
+
console.log(` ${p.message}`);
|
|
1405
|
+
options.forEach(
|
|
1406
|
+
(o, i) => console.log(
|
|
1407
|
+
` ${pc8.cyan(String(i + 1))}) ${o.label}${o.hint ? pc8.dim(` ${o.hint}`) : ""}`
|
|
1408
|
+
)
|
|
1409
|
+
);
|
|
1410
|
+
for (; ; ) {
|
|
1411
|
+
const raw = (await term.ask(` Choose 1-${options.length} ${pc8.dim("(1)")}: `)).trim();
|
|
1412
|
+
const chosen = options[raw === "" ? 0 : Number(raw) - 1];
|
|
1413
|
+
if (chosen) {
|
|
1414
|
+
answers[p.name] = chosen.value;
|
|
1415
|
+
break;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
const def = promptDefault(p, answers);
|
|
1421
|
+
const hint = def ? pc8.dim(` (${def})`) : p.placeholder ? pc8.dim(` e.g. ${p.placeholder}`) : "";
|
|
1422
|
+
for (; ; ) {
|
|
1423
|
+
const raw = p.type === "password" ? await term.ask(` ${p.message} `, true) : await term.ask(` ${p.message}${hint} `);
|
|
1424
|
+
const r = normalizeAnswer(p, raw.trim() === "" ? def ?? "" : raw, cwd);
|
|
1425
|
+
if ("error" in r) {
|
|
1426
|
+
console.log(pc8.red(` ${r.error}`));
|
|
1427
|
+
continue;
|
|
1428
|
+
}
|
|
1429
|
+
answers[p.name] = r.value;
|
|
1430
|
+
break;
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
return answers;
|
|
1435
|
+
}
|
|
1436
|
+
function packageManager(cwd) {
|
|
1437
|
+
if (fs8.existsSync(path8.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
|
|
1438
|
+
if (fs8.existsSync(path8.join(cwd, "yarn.lock"))) return "yarn";
|
|
1439
|
+
if (fs8.existsSync(path8.join(cwd, "bun.lockb")) || fs8.existsSync(path8.join(cwd, "bun.lock")))
|
|
1440
|
+
return "bun";
|
|
1441
|
+
return "npm";
|
|
1442
|
+
}
|
|
1443
|
+
function addCommand() {
|
|
1444
|
+
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(
|
|
1448
|
+
async (names, opts) => {
|
|
1449
|
+
try {
|
|
1450
|
+
const { cwd, registry, cfg, detected } = load();
|
|
1451
|
+
const plan = planAdd(cwd, registry, names, { overwrite: !!opts.overwrite }, cfg);
|
|
1452
|
+
if (plan.problems.length) fail(plan.problems.join("\n"));
|
|
1453
|
+
if (plan.items.length === 0) {
|
|
1454
|
+
console.log(pc8.dim(`Already installed: ${names.join(", ")}`));
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (detected) {
|
|
1458
|
+
console.log(
|
|
1459
|
+
pc8.dim(`
|
|
1460
|
+
No ${EFC_JSON} yet \u2014 detected ${describe(cfg)}; it'll be created.`)
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
printPlan(plan);
|
|
1464
|
+
if (opts.dryRun) return;
|
|
1465
|
+
const tty = !!process.stdin.isTTY;
|
|
1466
|
+
if (!opts.yes && !tty) fail("Not a terminal \u2014 pass --yes to add without confirming.");
|
|
1467
|
+
const ask = opts.prompt && tty && plan.prompts.length > 0;
|
|
1468
|
+
let env = {};
|
|
1469
|
+
if (!opts.yes || ask) {
|
|
1470
|
+
const term = openTerminal();
|
|
1471
|
+
try {
|
|
1472
|
+
if (!opts.yes && !await confirm(term, " Proceed? (y/N) ")) {
|
|
1473
|
+
console.log(pc8.dim(" Nothing changed."));
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
if (ask) {
|
|
1477
|
+
console.log(pc8.bold("\n Configuration") + pc8.dim(" (saved to .env)\n"));
|
|
1478
|
+
env = envFromAnswers(plan.prompts, await askPrompts(term, plan.prompts, cwd));
|
|
1479
|
+
console.log();
|
|
1480
|
+
}
|
|
1481
|
+
} finally {
|
|
1482
|
+
term.close();
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
const result = applyAdd(cwd, plan, registry, env);
|
|
1486
|
+
console.log(
|
|
1487
|
+
pc8.green(` \u2713 ${result.written.length} file(s) written`) + (result.conflicts.length ? pc8.yellow(`, ${result.conflicts.length} left alone`) : "")
|
|
1488
|
+
);
|
|
1489
|
+
for (const m of result.manual) console.log(pc8.yellow(` ! ${m}`));
|
|
1490
|
+
if (result.installNeeded) {
|
|
1491
|
+
const pm = packageManager(cwd);
|
|
1492
|
+
if (opts.install) {
|
|
1493
|
+
console.log(pc8.dim(` $ ${pm} install`));
|
|
1494
|
+
const r = spawnSync(pm, ["install"], {
|
|
1495
|
+
cwd,
|
|
1496
|
+
stdio: "inherit",
|
|
1497
|
+
shell: process.platform === "win32"
|
|
1498
|
+
});
|
|
1499
|
+
if (r.status !== 0)
|
|
1500
|
+
console.log(pc8.yellow(` ${pm} install failed \u2014 run it yourself.`));
|
|
1501
|
+
} else {
|
|
1502
|
+
console.log(pc8.yellow(` Run \`${pm} install\` for the new packages.`));
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
const unset = plan.env.filter((v) => !(v.key in env)).map((v) => v.key);
|
|
1506
|
+
if (unset.length) {
|
|
1507
|
+
console.log(
|
|
1508
|
+
pc8.yellow(
|
|
1509
|
+
` Added ${unset.join(", ")} to .env with placeholder values \u2014 fill them in.`
|
|
1510
|
+
)
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
for (const d of plan.docs) console.log(` ${pc8.bold(d.item)}: ${d.text}`);
|
|
1514
|
+
if (plan.files.some((f) => f.path.startsWith("src/model/"))) {
|
|
1515
|
+
console.log(
|
|
1516
|
+
pc8.dim(
|
|
1517
|
+
" New tables/collections are created on first use (autoSync); with autoSync: false, run `efc db sync`."
|
|
1518
|
+
)
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
console.log();
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
fail(err);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
);
|
|
1527
|
+
}
|
|
1528
|
+
function listCommand() {
|
|
1529
|
+
return new Command8("list").description("List the features `efc add` can install").action(() => {
|
|
1530
|
+
try {
|
|
1531
|
+
const cwd = process.cwd();
|
|
1532
|
+
const registry = new Registry();
|
|
1533
|
+
const installed = new Set(readEfcJson(cwd)?.items ?? []);
|
|
1534
|
+
const groups = [...new Set(registry.index.items.map((i) => i.group))];
|
|
1535
|
+
for (const group of groups) {
|
|
1536
|
+
console.log(pc8.bold(`
|
|
1537
|
+
${group}`));
|
|
1538
|
+
for (const item of registry.index.items.filter((i) => i.group === group)) {
|
|
1539
|
+
const mark = installed.has(item.name) ? pc8.green("\u2713") : " ";
|
|
1540
|
+
const deps = item.registryDependencies.length ? pc8.dim(` (needs ${item.registryDependencies.join(", ")})`) : "";
|
|
1541
|
+
console.log(` ${mark} ${pc8.cyan(item.name.padEnd(20))} ${item.description}${deps}`);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
console.log(pc8.dim("\n efc add <item...> \xB7 efc view <item>\n"));
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
fail(err);
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
function viewCommand() {
|
|
1551
|
+
return new Command8("view").description("Print an item's files for this app's language and database").argument("<item>").option("--json", "print the registry item as JSON").action((name, opts) => {
|
|
1552
|
+
try {
|
|
1553
|
+
const { registry, cfg } = load();
|
|
1554
|
+
const variant = variantOf(cfg);
|
|
1555
|
+
const meta = registry.meta(name);
|
|
1556
|
+
const item = registry.item(variant, name);
|
|
1557
|
+
if (opts.json) {
|
|
1558
|
+
console.log(JSON.stringify({ ...meta, ...item, variant }, null, 2));
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
console.log(pc8.bold(`
|
|
1562
|
+
${meta.title}`) + pc8.dim(` \u2014 ${meta.description} (${variant})`));
|
|
1563
|
+
if (meta.registryDependencies.length)
|
|
1564
|
+
console.log(pc8.dim(` needs: ${meta.registryDependencies.join(", ")}`));
|
|
1565
|
+
for (const f of item.files) {
|
|
1566
|
+
console.log(pc8.cyan(`
|
|
1567
|
+
\u2500\u2500 ${f.path} ${"\u2500".repeat(Math.max(0, 60 - f.path.length))}`));
|
|
1568
|
+
console.log(f.content);
|
|
1569
|
+
}
|
|
1570
|
+
} catch (err) {
|
|
1571
|
+
fail(err);
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
function diffCommand() {
|
|
1576
|
+
return new Command8("diff").description(
|
|
1577
|
+
"Compare installed features with the registry (local changes and available updates)"
|
|
1578
|
+
).argument("[item]").action((name) => {
|
|
1579
|
+
try {
|
|
1580
|
+
const cwd = process.cwd();
|
|
1581
|
+
const registry = new Registry();
|
|
1582
|
+
const cfg = readEfcJson(cwd);
|
|
1583
|
+
if (!cfg)
|
|
1584
|
+
fail(`No ${EFC_JSON} \u2014 nothing was added with efc yet (\`efc init\` creates one).`);
|
|
1585
|
+
const names = name ? [name] : cfg.items;
|
|
1586
|
+
let clean = true;
|
|
1587
|
+
for (const n of names) {
|
|
1588
|
+
for (const f of itemStatus(cwd, registry, cfg, n)) {
|
|
1589
|
+
if (f.status === "unchanged") continue;
|
|
1590
|
+
clean = false;
|
|
1591
|
+
const label = f.status === "missing" ? pc8.red("missing") : f.status === "modified" ? pc8.yellow("changed in app") : f.status === "outdated" ? pc8.cyan("update available") : pc8.magenta("update available + changed in app");
|
|
1592
|
+
console.log(`
|
|
1593
|
+
${pc8.bold(n)} ${f.path} ${label}`);
|
|
1594
|
+
if (f.local !== void 0) {
|
|
1595
|
+
for (const line of lineDiff(f.local, f.registry)) {
|
|
1596
|
+
console.log(
|
|
1597
|
+
line.startsWith("+") ? pc8.green(line) : line.startsWith("-") ? pc8.red(line) : pc8.dim(line)
|
|
1598
|
+
);
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
if (clean) console.log(pc8.green("Every installed feature matches the registry."));
|
|
1604
|
+
else {
|
|
1605
|
+
console.log(
|
|
1606
|
+
pc8.dim(
|
|
1607
|
+
"\n (- this app, + registry) \xB7 `efc add <item> --overwrite` takes the registry version"
|
|
1608
|
+
)
|
|
1609
|
+
);
|
|
1610
|
+
}
|
|
1611
|
+
} catch (err) {
|
|
1612
|
+
fail(err);
|
|
1613
|
+
}
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// src/cli/commands/import-prisma.ts
|
|
1618
|
+
import { Command as Command9 } from "commander";
|
|
1619
|
+
import fs9 from "fs";
|
|
1620
|
+
import path9 from "path";
|
|
1621
|
+
import pc9 from "picocolors";
|
|
1622
|
+
|
|
1623
|
+
// src/db/prisma-import.ts
|
|
1624
|
+
function splitTop(s, sep) {
|
|
1625
|
+
const out = [];
|
|
1626
|
+
let depth = 0;
|
|
1627
|
+
let str = null;
|
|
1628
|
+
let cur = "";
|
|
1629
|
+
for (const ch of s) {
|
|
1630
|
+
if (str) {
|
|
1631
|
+
cur += ch;
|
|
1632
|
+
if (ch === str) str = null;
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
if (ch === '"' || ch === "'") str = ch;
|
|
1636
|
+
else if ("([{".includes(ch)) depth++;
|
|
1637
|
+
else if (")]}".includes(ch)) depth--;
|
|
1638
|
+
if (ch === sep && depth === 0) {
|
|
1639
|
+
out.push(cur.trim());
|
|
1640
|
+
cur = "";
|
|
1641
|
+
} else cur += ch;
|
|
1642
|
+
}
|
|
1643
|
+
if (cur.trim()) out.push(cur.trim());
|
|
1644
|
+
return out;
|
|
1645
|
+
}
|
|
1646
|
+
function parseAttrs(s) {
|
|
1647
|
+
const out = [];
|
|
1648
|
+
let i = 0;
|
|
1649
|
+
while (i < s.length) {
|
|
1650
|
+
const m = /^@@?[\w.]+/.exec(s.slice(i));
|
|
1651
|
+
if (!m) {
|
|
1652
|
+
i++;
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
i += m[0].length;
|
|
1656
|
+
const attr = { name: m[0] };
|
|
1657
|
+
if (s[i] === "(") {
|
|
1658
|
+
let depth = 0;
|
|
1659
|
+
let j = i;
|
|
1660
|
+
let str = null;
|
|
1661
|
+
for (; j < s.length; j++) {
|
|
1662
|
+
const ch = s[j];
|
|
1663
|
+
if (str) {
|
|
1664
|
+
if (ch === str) str = null;
|
|
1665
|
+
continue;
|
|
1666
|
+
}
|
|
1667
|
+
if (ch === '"') str = ch;
|
|
1668
|
+
else if (ch === "(") depth++;
|
|
1669
|
+
else if (ch === ")" && --depth === 0) break;
|
|
1670
|
+
}
|
|
1671
|
+
attr.args = s.slice(i + 1, j);
|
|
1672
|
+
i = j + 1;
|
|
1673
|
+
}
|
|
1674
|
+
out.push(attr);
|
|
1675
|
+
}
|
|
1676
|
+
return out;
|
|
1677
|
+
}
|
|
1678
|
+
function arg(a, name) {
|
|
1679
|
+
if (!a?.args) return void 0;
|
|
1680
|
+
const parts = splitTop(a.args, ",");
|
|
1681
|
+
if (name) {
|
|
1682
|
+
const p = parts.find((x) => x.startsWith(`${name}:`));
|
|
1683
|
+
return p?.slice(name.length + 1).trim();
|
|
1684
|
+
}
|
|
1685
|
+
return parts.find((x) => !/^\w+\s*:/.test(x));
|
|
1686
|
+
}
|
|
1687
|
+
var unquote = (s) => s?.replace(/^"(.*)"$/, "$1");
|
|
1688
|
+
var list = (s) => s ? splitTop(s.replace(/^\[|\]$/g, ""), ",").map((x) => x.trim()).filter(Boolean) : [];
|
|
1689
|
+
function parsePrisma(source) {
|
|
1690
|
+
const text = source.replace(/\/\/.*$/gm, "");
|
|
1691
|
+
const models = [];
|
|
1692
|
+
const enums = /* @__PURE__ */ new Map();
|
|
1693
|
+
let provider;
|
|
1694
|
+
for (const block of text.matchAll(
|
|
1695
|
+
/(model|enum|datasource|generator|type|view)\s+(\w+)\s*\{([^}]*)\}/g
|
|
1696
|
+
)) {
|
|
1697
|
+
const [, kind, name, body] = block;
|
|
1698
|
+
const lines = body.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
1699
|
+
if (kind === "datasource") {
|
|
1700
|
+
provider = unquote(/provider\s*=\s*("[^"]*")/.exec(body)?.[1]);
|
|
1701
|
+
} else if (kind === "enum") {
|
|
1702
|
+
const values = [];
|
|
1703
|
+
const names = [];
|
|
1704
|
+
let map;
|
|
1705
|
+
for (const l of lines) {
|
|
1706
|
+
if (l.startsWith("@@map")) map = unquote(arg(parseAttrs(l)[0]));
|
|
1707
|
+
else {
|
|
1708
|
+
const [value, ...rest] = l.split(/\s+/);
|
|
1709
|
+
const mapped = unquote(arg(parseAttrs(rest.join(" ")).find((a) => a.name === "@map")));
|
|
1710
|
+
names.push(value);
|
|
1711
|
+
values.push(mapped ?? value);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
enums.set(name, { values, names, ...map && { map } });
|
|
1715
|
+
} else if (kind === "model") {
|
|
1716
|
+
const fields = [];
|
|
1717
|
+
const blockAttrs = [];
|
|
1718
|
+
for (const l of lines) {
|
|
1719
|
+
if (l.startsWith("@@")) {
|
|
1720
|
+
blockAttrs.push(...parseAttrs(l));
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
const m = /^(\w+)\s+([\w.]+(?:\([^)]*\))?)(\[\])?(\?)?\s*(.*)$/.exec(l);
|
|
1724
|
+
if (!m) continue;
|
|
1725
|
+
fields.push({
|
|
1726
|
+
name: m[1],
|
|
1727
|
+
type: m[2],
|
|
1728
|
+
list: Boolean(m[3]),
|
|
1729
|
+
optional: Boolean(m[4]),
|
|
1730
|
+
attrs: parseAttrs(m[5])
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
models.push({ name, fields, blockAttrs });
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
return { models, enums, ...provider && { provider } };
|
|
1737
|
+
}
|
|
1738
|
+
var ID_FIELD_TYPE = {
|
|
1739
|
+
uuid: "uuid",
|
|
1740
|
+
serial: "integer",
|
|
1741
|
+
bigserial: "bigint"
|
|
1742
|
+
};
|
|
1743
|
+
var ACTIONS = { Cascade: "cascade", SetNull: "setNull" };
|
|
1744
|
+
function importPrisma(source) {
|
|
1745
|
+
const { models, enums, provider } = parsePrisma(source);
|
|
1746
|
+
const warnings = [];
|
|
1747
|
+
if (provider && provider !== "postgresql" && provider !== "postgres") {
|
|
1748
|
+
throw new Error(
|
|
1749
|
+
`[EFC] import-prisma maps PostgreSQL schemas to defineTable \u2014 this one's provider is "${provider}"`
|
|
1750
|
+
);
|
|
1751
|
+
}
|
|
1752
|
+
const byName = new Map(models.map((m) => [m.name, m]));
|
|
1753
|
+
const attr = (f, n) => f.attrs.find((a) => a.name === n);
|
|
1754
|
+
const blocks = (m, n) => m.blockAttrs.filter((a) => a.name === n);
|
|
1755
|
+
const dbName = (f) => unquote(arg(attr(f, "@map"))) ?? f.name;
|
|
1756
|
+
const idKind = /* @__PURE__ */ new Map();
|
|
1757
|
+
for (const m of models) {
|
|
1758
|
+
const id = m.fields.find((f) => attr(f, "@id"));
|
|
1759
|
+
const def = arg(attr(id ?? { attrs: [] }, "@default")) ?? "";
|
|
1760
|
+
idKind.set(
|
|
1761
|
+
m.name,
|
|
1762
|
+
id?.type === "Int" && /autoincrement/.test(def) ? "serial" : id?.type === "BigInt" && /autoincrement/.test(def) ? "bigserial" : "uuid"
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
const rels = [];
|
|
1766
|
+
for (const m of models) {
|
|
1767
|
+
for (const f of m.fields) {
|
|
1768
|
+
if (!byName.has(f.type)) continue;
|
|
1769
|
+
const r = attr(f, "@relation");
|
|
1770
|
+
const relName = unquote(arg(r)) ?? unquote(arg(r, "name"));
|
|
1771
|
+
rels.push({
|
|
1772
|
+
model: m.name,
|
|
1773
|
+
field: f.name,
|
|
1774
|
+
target: f.type,
|
|
1775
|
+
...relName && { name: relName },
|
|
1776
|
+
fkScalars: list(arg(r, "fields")),
|
|
1777
|
+
list: f.list,
|
|
1778
|
+
optional: f.optional,
|
|
1779
|
+
...arg(r, "onDelete") && { onDelete: arg(r, "onDelete") }
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
const sameRelation = (a, b) => a !== b && a.target === b.model && b.target === a.model && (a.name ?? "") === (b.name ?? "");
|
|
1784
|
+
const partner = (r) => rels.find((o) => sameRelation(r, o) && (r.model !== r.target || o.field !== r.field));
|
|
1785
|
+
const out = [];
|
|
1786
|
+
for (const m of models) {
|
|
1787
|
+
const notes = [];
|
|
1788
|
+
const options = {};
|
|
1789
|
+
const fields = [];
|
|
1790
|
+
const relations = {};
|
|
1791
|
+
const table = unquote(arg(blocks(m, "@@map")[0])) ?? m.name;
|
|
1792
|
+
if (table !== tableNameFor(m.name)) options["collection"] = table;
|
|
1793
|
+
const kind = idKind.get(m.name);
|
|
1794
|
+
if (kind !== "uuid") options["id"] = kind;
|
|
1795
|
+
if (blocks(m, "@@id").length) {
|
|
1796
|
+
warnings.push(`${m.name}: composite @@id isn't supported \u2014 skipped`);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
const fkScalar = /* @__PURE__ */ new Map();
|
|
1800
|
+
for (const r of rels.filter((x) => x.model === m.name && x.fkScalars.length)) {
|
|
1801
|
+
if (r.fkScalars.length > 1) {
|
|
1802
|
+
notes.push(`${r.field}: composite foreign keys aren't supported \u2014 kept as plain columns`);
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1805
|
+
fkScalar.set(r.fkScalars[0], r);
|
|
1806
|
+
}
|
|
1807
|
+
const renamed = /* @__PURE__ */ new Map();
|
|
1808
|
+
const created = m.fields.find(
|
|
1809
|
+
(f) => f.name === "createdAt" && f.type === "DateTime" && !attr(f, "@map")
|
|
1810
|
+
);
|
|
1811
|
+
const updated = m.fields.find(
|
|
1812
|
+
(f) => f.name === "updatedAt" && f.type === "DateTime" && !attr(f, "@map")
|
|
1813
|
+
);
|
|
1814
|
+
if (!created && !updated) options["timestamps"] = false;
|
|
1815
|
+
else if (!created) options["timestamps"] = { createdAt: false };
|
|
1816
|
+
else if (!updated) options["timestamps"] = { updatedAt: false };
|
|
1817
|
+
for (const f of m.fields) {
|
|
1818
|
+
if (f === created || f === updated) continue;
|
|
1819
|
+
if (attr(f, "@id")) {
|
|
1820
|
+
if (f.name !== "id") notes.push(`${f.name}: EFC's primary key is always "id"`);
|
|
1821
|
+
const def2 = arg(attr(f, "@default")) ?? "";
|
|
1822
|
+
if (f.type === "String" && !/uuid/.test(def2))
|
|
1823
|
+
notes.push(
|
|
1824
|
+
`id: ${def2 || "String"} ids become uuid \u2014 existing non-UUID ids won't convert`
|
|
1825
|
+
);
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
if (byName.has(f.type)) {
|
|
1829
|
+
const r = rels.find((x) => x.model === m.name && x.field === f.name);
|
|
1830
|
+
if (r.fkScalars.length === 1) {
|
|
1831
|
+
const scalar = m.fields.find((x) => x.name === r.fkScalars[0]);
|
|
1832
|
+
const def2 = {
|
|
1833
|
+
type: ID_FIELD_TYPE[idKind.get(r.target)],
|
|
1834
|
+
ref: r.target
|
|
1835
|
+
};
|
|
1836
|
+
if (!f.optional) def2["required"] = true;
|
|
1837
|
+
if (scalar && attr(scalar, "@unique")) def2["unique"] = true;
|
|
1838
|
+
if (r.onDelete && ACTIONS[r.onDelete]) def2["onDelete"] = ACTIONS[r.onDelete];
|
|
1839
|
+
else if (r.onDelete && r.onDelete !== "Restrict" && r.onDelete !== "NoAction")
|
|
1840
|
+
notes.push(`${f.name}: onDelete ${r.onDelete} isn't supported \u2014 restrict`);
|
|
1841
|
+
if (def2["onDelete"] === "setNull") delete def2["required"];
|
|
1842
|
+
def2["column"] = scalar ? dbName(scalar) : `${f.name}Id`;
|
|
1843
|
+
if (scalar) renamed.set(scalar.name, f.name);
|
|
1844
|
+
fields.push([f.name, def2]);
|
|
1845
|
+
continue;
|
|
1846
|
+
}
|
|
1847
|
+
const other = partner(r);
|
|
1848
|
+
if (r.list && other?.list) {
|
|
1849
|
+
if (m.name < r.target || m.name === r.target && f.name < other.field) {
|
|
1850
|
+
fields.push([
|
|
1851
|
+
f.name,
|
|
1852
|
+
{ type: "array", of: ID_FIELD_TYPE[idKind.get(r.target)], ref: r.target }
|
|
1853
|
+
]);
|
|
1854
|
+
notes.push(
|
|
1855
|
+
`${f.name}: links move to the join table "${table}_${f.name}" \u2014 copy them from Prisma's "_${[m.name, r.target].sort().join("To")}" table`
|
|
1856
|
+
);
|
|
1857
|
+
} else {
|
|
1858
|
+
relations[f.name] = { hasMany: r.target, foreignKey: other.field };
|
|
1859
|
+
}
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
if (other && other.fkScalars.length === 1) {
|
|
1863
|
+
const otherScalar = byName.get(other.model).fields.find((x) => x.name === other.fkScalars[0]);
|
|
1864
|
+
const unique = otherScalar && attr(otherScalar, "@unique");
|
|
1865
|
+
relations[f.name] = r.list || !unique ? { hasMany: r.target, foreignKey: other.field } : { hasOne: r.target, foreignKey: other.field };
|
|
1866
|
+
} else {
|
|
1867
|
+
notes.push(`${f.name}: relation to ${r.target} not carried over`);
|
|
1868
|
+
}
|
|
1869
|
+
continue;
|
|
1870
|
+
}
|
|
1871
|
+
if (fkScalar.has(f.name)) continue;
|
|
1872
|
+
const def = scalarDef(f, enums, notes);
|
|
1873
|
+
if (!def) continue;
|
|
1874
|
+
if (!f.optional && !f.list) def["required"] = true;
|
|
1875
|
+
if (attr(f, "@unique")) def["unique"] = true;
|
|
1876
|
+
const d = arg(attr(f, "@default"));
|
|
1877
|
+
if (d !== void 0) {
|
|
1878
|
+
if (d === "now()") def["default"] = "$now";
|
|
1879
|
+
else if (/^(uuid|cuid|nanoid)\(/.test(d)) def["default"] = "$uuid";
|
|
1880
|
+
else if (d === "autoincrement()") {
|
|
1881
|
+
def["sequence"] = true;
|
|
1882
|
+
def["type"] = "number";
|
|
1883
|
+
} else if (d === "true" || d === "false") def["default"] = d === "true";
|
|
1884
|
+
else if (/^-?\d+(\.\d+)?$/.test(d)) def["default"] = Number(d);
|
|
1885
|
+
else if (/^".*"$/.test(d)) def["default"] = unquote(d);
|
|
1886
|
+
else if (enums.has(f.type)) {
|
|
1887
|
+
const e = enums.get(f.type);
|
|
1888
|
+
def["default"] = e.values[e.names.indexOf(d)] ?? d;
|
|
1889
|
+
} else notes.push(`${f.name}: @default(${d}) not carried over`);
|
|
1890
|
+
}
|
|
1891
|
+
if (attr(f, "@updatedAt")) notes.push(`${f.name}: @updatedAt \u2014 use the updatedAt timestamp`);
|
|
1892
|
+
if (dbName(f) !== f.name) def["column"] = dbName(f);
|
|
1893
|
+
fields.push([f.name, def]);
|
|
1894
|
+
}
|
|
1895
|
+
const indexes = [];
|
|
1896
|
+
for (const a of [...blocks(m, "@@index"), ...blocks(m, "@@unique")]) {
|
|
1897
|
+
const spec = Object.fromEntries(
|
|
1898
|
+
list(arg(a, "fields") ?? arg(a)).map((x) => {
|
|
1899
|
+
const n = /^(\w+)/.exec(x)[1];
|
|
1900
|
+
return [renamed.get(n) ?? n, /sort:\s*Desc/.test(x) ? -1 : 1];
|
|
1901
|
+
})
|
|
1902
|
+
);
|
|
1903
|
+
const name = unquote(arg(a, "map")) ?? unquote(arg(a, "name"));
|
|
1904
|
+
indexes.push({
|
|
1905
|
+
fields: spec,
|
|
1906
|
+
...a.name === "@@unique" && { unique: true },
|
|
1907
|
+
...name && { name }
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
if (indexes.length) options["indexes"] = indexes;
|
|
1911
|
+
if (Object.keys(relations).length) options["relations"] = relations;
|
|
1912
|
+
out.push({ name: m.name, fields, options, notes });
|
|
1913
|
+
}
|
|
1914
|
+
return { models: out, warnings };
|
|
1915
|
+
}
|
|
1916
|
+
function scalarDef(f, enums, notes) {
|
|
1917
|
+
const db = f.attrs.find((a) => a.name.startsWith("@db."));
|
|
1918
|
+
const dbType = db?.name.slice(4);
|
|
1919
|
+
let def;
|
|
1920
|
+
const e = enums.get(f.type);
|
|
1921
|
+
if (e) def = { type: "string", enum: e.values, nativeEnum: true };
|
|
1922
|
+
else {
|
|
1923
|
+
switch (f.type) {
|
|
1924
|
+
case "String":
|
|
1925
|
+
if (dbType === "Uuid") def = { type: "uuid" };
|
|
1926
|
+
else if (dbType === "VarChar" && db?.args)
|
|
1927
|
+
def = { type: "string", maxLength: Number(db.args) };
|
|
1928
|
+
else def = { type: "string" };
|
|
1929
|
+
break;
|
|
1930
|
+
case "Int":
|
|
1931
|
+
def = { type: "integer" };
|
|
1932
|
+
break;
|
|
1933
|
+
case "BigInt":
|
|
1934
|
+
def = { type: "bigint" };
|
|
1935
|
+
break;
|
|
1936
|
+
case "Float":
|
|
1937
|
+
def = { type: "number" };
|
|
1938
|
+
break;
|
|
1939
|
+
case "Decimal": {
|
|
1940
|
+
const [p, s] = (db?.args ?? "").split(",").map((x) => Number(x.trim()));
|
|
1941
|
+
def = p ? { type: "decimal", precision: p, scale: s ?? 0 } : { type: "decimal" };
|
|
1942
|
+
break;
|
|
1943
|
+
}
|
|
1944
|
+
case "Boolean":
|
|
1945
|
+
def = { type: "boolean" };
|
|
1946
|
+
break;
|
|
1947
|
+
case "DateTime":
|
|
1948
|
+
def = { type: "date" };
|
|
1949
|
+
break;
|
|
1950
|
+
case "Json":
|
|
1951
|
+
def = { type: "json" };
|
|
1952
|
+
break;
|
|
1953
|
+
default:
|
|
1954
|
+
notes.push(`${f.name}: ${f.type} has no EFC type \u2014 skipped`);
|
|
1955
|
+
return void 0;
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
if (f.list) {
|
|
1959
|
+
if (def["type"] === "json" || e) {
|
|
1960
|
+
notes.push(`${f.name}: lists of ${f.type} are stored as json`);
|
|
1961
|
+
return { type: "json" };
|
|
1962
|
+
}
|
|
1963
|
+
return { type: "array", of: def["type"] };
|
|
1964
|
+
}
|
|
1965
|
+
return def;
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
// src/cli/commands/import-prisma.ts
|
|
1969
|
+
function importPrismaCommand() {
|
|
1970
|
+
return new Command9("import-prisma").description("Write defineTable models from a Prisma schema (PostgreSQL)").argument("[schema]", "path to schema.prisma", "prisma/schema.prisma").option("--out <dir>", "where to write the models", "src/model").option("--force", "overwrite model files that already exist").action((schema, opts) => {
|
|
1971
|
+
const file = path9.resolve(schema);
|
|
1972
|
+
if (!fs9.existsSync(file)) {
|
|
1973
|
+
console.error(pc9.red(` ${schema} not found`));
|
|
1974
|
+
process.exit(1);
|
|
1975
|
+
}
|
|
1976
|
+
const { models, warnings } = importPrisma(fs9.readFileSync(file, "utf8"));
|
|
1977
|
+
const typescript = fs9.existsSync(path9.join(process.cwd(), "tsconfig.json"));
|
|
1978
|
+
const dir = path9.resolve(opts.out);
|
|
1979
|
+
const { written, skipped } = writeModels(dir, models, {
|
|
1980
|
+
typescript,
|
|
1981
|
+
...opts.force && { force: true }
|
|
1982
|
+
});
|
|
1983
|
+
console.log(pc9.bold(`
|
|
1984
|
+
Imported ${models.length} model(s) from ${schema}
|
|
1985
|
+
`));
|
|
1986
|
+
for (const f of written) console.log(` ${pc9.green("+")} ${path9.relative(process.cwd(), f)}`);
|
|
1987
|
+
for (const f of skipped)
|
|
1988
|
+
console.log(
|
|
1989
|
+
` ${pc9.yellow("\u2022")} ${path9.relative(process.cwd(), f)} ${pc9.dim("exists \u2014 kept (--force overwrites)")}`
|
|
1990
|
+
);
|
|
1991
|
+
for (const w of warnings) console.log(pc9.yellow(` ! ${w}`));
|
|
1992
|
+
const notes = models.reduce((n, m) => n + m.notes.length, 0);
|
|
1993
|
+
if (notes)
|
|
1994
|
+
console.log(
|
|
1995
|
+
pc9.dim(`
|
|
1996
|
+
${notes} note(s) about what couldn't be carried over are in the files`)
|
|
1997
|
+
);
|
|
1998
|
+
console.log(
|
|
1999
|
+
pc9.dim(
|
|
2000
|
+
"\n Next: efc db generate --verify against your database, or efc db generate init on a new one\n"
|
|
2001
|
+
)
|
|
2002
|
+
);
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
|
|
810
2006
|
// src/cli/index.ts
|
|
811
2007
|
var { version } = JSON.parse(
|
|
812
|
-
|
|
2008
|
+
fs10.readFileSync(new URL("../../package.json", import.meta.url), "utf8")
|
|
813
2009
|
);
|
|
814
2010
|
function localCli() {
|
|
815
2011
|
if (process.env["EFC_CLI_DELEGATED"]) return void 0;
|
|
816
|
-
const self =
|
|
817
|
-
for (let dir = process.cwd(); ; dir =
|
|
818
|
-
const pkgDir =
|
|
819
|
-
if (
|
|
820
|
-
const real =
|
|
821
|
-
const cli =
|
|
822
|
-
return real !== self &&
|
|
2012
|
+
const self = fs10.realpathSync(fileURLToPath3(new URL("../..", import.meta.url)));
|
|
2013
|
+
for (let dir = process.cwd(); ; dir = path10.dirname(dir)) {
|
|
2014
|
+
const pkgDir = path10.join(dir, "node_modules", "express-file-cluster");
|
|
2015
|
+
if (fs10.existsSync(path10.join(pkgDir, "package.json"))) {
|
|
2016
|
+
const real = fs10.realpathSync(pkgDir);
|
|
2017
|
+
const cli = path10.join(real, "dist", "cli", "index.js");
|
|
2018
|
+
return real !== self && fs10.existsSync(cli) ? cli : void 0;
|
|
823
2019
|
}
|
|
824
|
-
if (
|
|
2020
|
+
if (path10.dirname(dir) === dir) return void 0;
|
|
825
2021
|
}
|
|
826
2022
|
}
|
|
827
2023
|
var delegate = localCli();
|
|
@@ -836,12 +2032,14 @@ if (delegate) {
|
|
|
836
2032
|
run3();
|
|
837
2033
|
}
|
|
838
2034
|
function run3() {
|
|
839
|
-
const program = new
|
|
2035
|
+
const program = new Command10("efc").description("Express File Cluster CLI").version(version);
|
|
840
2036
|
program.addCommand(startCommand());
|
|
841
2037
|
program.addCommand(buildCommand());
|
|
842
2038
|
program.addCommand(runCommand());
|
|
843
2039
|
program.addCommand(generateCommand());
|
|
844
2040
|
program.addCommand(dbCommand());
|
|
2041
|
+
program.addCommand(importPrismaCommand());
|
|
2042
|
+
for (const cmd of registryCommands()) program.addCommand(cmd);
|
|
845
2043
|
for (const cmd of diagnosticsCommands()) {
|
|
846
2044
|
program.addCommand(cmd);
|
|
847
2045
|
}
|