create-efforge 0.1.0 → 0.2.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 +44 -96
- package/dist/bin.js +7 -0
- package/dist/cli.js +21 -2
- package/dist/commands/add.js +233 -33
- package/dist/commands/create.js +189 -56
- package/dist/commands/list.js +80 -0
- package/dist/exec.js +16 -3
- package/dist/prompts/flow.js +16 -5
- package/dist/prompts/navigable.js +111 -15
- package/dist/rules.js +5 -2
- package/dist/slots.js +20 -0
- package/dist/write.js +3 -1
- package/package.json +1 -1
- package/templates/ai/effect-ai-byok/files/core/llm-crypto.test.ts +42 -37
- package/templates/ai/effect-ai-byok/files/routes/ai.tsx +5 -5
- package/templates/auth/better-auth/files/shared/components/user-menu.tsx +1 -1
- package/templates/auth/better-auth/files/shared/routes/sign-in.tsx +3 -3
- package/templates/auth/better-auth/files/shared/routes/sign-up.tsx +3 -3
- package/templates/auth/better-auth-orgs/files/components/org-switcher.tsx +1 -1
- package/templates/auth/better-auth-orgs/files/routes/accept-invite.$id.tsx +1 -1
- package/templates/auth/better-auth-orgs/files/routes/app/settings/members.tsx +11 -7
- package/templates/auth/better-auth-orgs/files/routes/onboarding.tsx +3 -3
- package/templates/base/addon.json +4 -0
- package/templates/base/files/AGENTS.md +12 -0
- package/templates/base/files/README.md +4 -0
- package/templates/base/files/root/lint/effect-tests.js +45 -0
- package/templates/base/files/root/vite.config.ts +25 -0
- package/templates/extras/realtime/files/realtime-demo.tsx +2 -2
package/README.md
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
<h1 align="center">efforge</h1>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
|
-
Start an <a href="https://effect.website">Effect</a>
|
|
8
|
+
Start a Cloudflare app where every server capability is an <a href="https://effect.website">Effect</a> service.<br>
|
|
9
|
+
Pick a database, auth, AI and extras now; add more later with one command.
|
|
9
10
|
</p>
|
|
10
11
|
|
|
11
12
|
<p align="center">
|
|
@@ -14,128 +15,75 @@
|
|
|
14
15
|
<a href="https://github.com/amagdy46/efforge/blob/main/LICENSE"><img src="https://img.shields.io/github/license/amagdy46/efforge" alt="MIT license"></a>
|
|
15
16
|
</p>
|
|
16
17
|
|
|
17
|
-
`npm create efforge` generates a TypeScript monorepo: a [TanStack Start](https://tanstack.com/start) app on Cloudflare Workers, where each capability is an Effect service and layer. You choose the database, ORM, auth, infrastructure tool, AI and extras when you create the project, and `efforge add` adds more later.
|
|
18
|
-
|
|
19
|
-
Status: v0.1, early. The default ORM (Drizzle) is pinned to a release candidate, and the optional Alchemy support uses a beta. Needs Node 24.11+ or 26+ (Vite+ does not support Node 25) and pnpm. MIT licensed.
|
|
20
|
-
|
|
21
|
-
```console
|
|
22
|
-
$ npm create efforge my-app -- --yes --database=d1 --orm=effect-sql --auth=better-auth --extras=storage
|
|
23
|
-
┌ create-efforge Effect apps on Cloudflare, already wired
|
|
24
|
-
◇ Your stack ─────────────────────────────────────────────────────────╮
|
|
25
|
-
│ name my-app │
|
|
26
|
-
│ runtime cloudflare │
|
|
27
|
-
│ database d1 │
|
|
28
|
-
│ orm effect-sql │
|
|
29
|
-
│ auth better-auth │
|
|
30
|
-
│ infra none │
|
|
31
|
-
│ ai none │
|
|
32
|
-
│ extras storage │
|
|
33
|
-
├──────────────────────────────────────────────────────────────────────╯
|
|
34
|
-
◇ ✓ Writing files
|
|
35
|
-
◇ ✓ Initializing git
|
|
36
|
-
◇ ✓ Installing dependencies (pnpm install)
|
|
37
|
-
◇ ✓ Generating the route tree (tsr generate)
|
|
38
|
-
◇ ✓ Formatting (vp fmt)
|
|
39
|
-
◇ ✓ Creating the initial commit
|
|
40
|
-
└ Done.
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
(Output abridged: blank lines and the re-run command are left out.)
|
|
44
|
-
|
|
45
|
-
## Why efforge
|
|
46
|
-
|
|
47
|
-
Other scaffolders cover parts of this stack. [create-effect-app](https://github.com/Effect-TS/examples) gives you a basic, CLI or monorepo Effect project. `npm create cloudflare` gives you a TanStack Start app on Workers.
|
|
48
|
-
|
|
49
|
-
efforge is narrower: it is for writing the whole server side in Effect, on Cloudflare.
|
|
50
|
-
|
|
51
|
-
- Each capability (database, auth, mail, storage, AI) is an Effect service with tagged errors in `packages/core`, implemented as a layer and composed in one file, `apps/web/src/server/layers.ts`.
|
|
52
|
-
- Application code gets Cloudflare bindings through Effect layers; only `apps/web/src/server/cloudflare.ts` reads the Worker environment. Code that uses bindings can be tested with `@effect/vitest`.
|
|
53
|
-
- `efforge add` wires a new add-on into the layers, exports, bindings and secrets with AST transforms, instead of asking you to paste code.
|
|
54
|
-
- The generated `AGENTS.md` gives coding agents the same layout and rules, and `pnpm check` runs format, lint (with Effect diagnostics) and types.
|
|
55
|
-
|
|
56
|
-
Use something else if you want Next.js, a runtime other than Cloudflare, or plain async code without Effect.
|
|
57
|
-
|
|
58
|
-
## Quick start
|
|
59
|
-
|
|
60
18
|
```sh
|
|
61
|
-
npm create efforge my-app
|
|
62
|
-
cd my-app
|
|
19
|
+
npm create efforge my-app
|
|
63
20
|
```
|
|
64
21
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
# Postgres (the default): start the bundled database, then migrate
|
|
69
|
-
docker compose up -d --wait
|
|
70
|
-
pnpm db:migrate
|
|
71
|
-
|
|
72
|
-
# D1: apply migrations to the local D1 database
|
|
73
|
-
pnpm db:migrate
|
|
74
|
-
|
|
75
|
-
pnpm dev # http://localhost:5173
|
|
76
|
-
```
|
|
22
|
+
<p align="center">
|
|
23
|
+
<img src="https://raw.githubusercontent.com/amagdy46/efforge/main/.github/assets/demo.gif" width="760" alt="Terminal recording: npm create efforge my-app picks Cloudflare D1, Effect SQL, Better Auth with organizations and Storage, installs and commits in a few seconds, then efforge add email adds a Mailer service and lists the new env vars">
|
|
24
|
+
</p>
|
|
77
25
|
|
|
78
|
-
|
|
26
|
+
`pnpm create efforge my-app` and `bun create efforge my-app` work too. The generated project uses pnpm, and needs Node 24.11+ or 26+.
|
|
79
27
|
|
|
80
|
-
##
|
|
28
|
+
## Why efforge
|
|
81
29
|
|
|
82
|
-
|
|
83
|
-
# accept the defaults: Postgres, Drizzle, Better Auth with organizations
|
|
84
|
-
npm create efforge my-app -- --yes
|
|
30
|
+
You get a TypeScript monorepo: a [TanStack Start](https://tanstack.com/start) app on Cloudflare Workers, with the server side written in Effect.
|
|
85
31
|
|
|
86
|
-
|
|
87
|
-
|
|
32
|
+
- **Every capability is a service.** Database, auth, mail, storage and AI are Effect services with tagged errors in `packages/core`, implemented as layers and composed in one file, `apps/web/src/server/layers.ts`. Swap a layer to test or to change a provider.
|
|
33
|
+
- **Cloudflare bindings stay at the edge of your code.** Only `apps/web/src/server/cloudflare.ts` reads the Worker environment. Everything else gets bindings through layers, so it runs under `@effect/vitest`.
|
|
34
|
+
- **`efforge add` edits code, not docs.** Adding email later wires the layer, the exports, the binding and the secrets with AST transforms, and refuses to overwrite a file you've changed.
|
|
35
|
+
- **Ready for coding agents.** The generated `AGENTS.md` describes the layout and its rules, and `pnpm check` runs format, lint (with Effect diagnostics) and types.
|
|
88
36
|
|
|
89
|
-
|
|
90
|
-
npx create-efforge add email
|
|
37
|
+
CI generates 15 stacks on every change, installs them and runs typecheck, lint, tests and a build on each. There is no telemetry.
|
|
91
38
|
|
|
92
|
-
|
|
93
|
-
npx create-efforge add ai/effect-ai-byok extras/storage --dry-run
|
|
94
|
-
```
|
|
39
|
+
Use something else if you want Next.js, a runtime other than Cloudflare, or plain async code without Effect: [create-effect-app](https://github.com/Effect-TS/examples) for an Effect project without the web stack, or `npm create cloudflare` for TanStack Start on Workers without Effect.
|
|
95
40
|
|
|
96
|
-
|
|
41
|
+
## Pick your stack
|
|
97
42
|
|
|
98
|
-
|
|
43
|
+
The prompts walk through these (and let you go back). Each one is also a flag, so `npm create efforge my-app -- --yes --database=d1 --orm=effect-sql` asks nothing.
|
|
99
44
|
|
|
100
45
|
| Slot | Options | Default |
|
|
101
46
|
|---|---|---|
|
|
102
|
-
| `runtime` | `cloudflare` | `cloudflare` |
|
|
103
47
|
| `database` | `postgres` (via Hyperdrive), `d1`, `none` | `postgres` |
|
|
104
48
|
| `orm` | `drizzle`, `effect-sql`, `none` | `drizzle` |
|
|
105
49
|
| `auth` | `better-auth-orgs`, `better-auth`, `none` | `better-auth-orgs` |
|
|
106
|
-
| `infra` | `none
|
|
50
|
+
| `infra` | `none` (`wrangler.jsonc`), `alchemy` | `none` |
|
|
107
51
|
| `ai` | `none`, `effect-ai-byok` | `none` |
|
|
108
|
-
| `extras`
|
|
52
|
+
| `extras` | `workflows`, `realtime`, `browser`, `storage`, `email` | none |
|
|
109
53
|
|
|
110
|
-
|
|
54
|
+
`orm` is set exactly when `database` is, and `auth` needs a database. When it finishes, efforge prints the next steps for your stack (start Postgres, run migrations, `pnpm dev`) and a command that recreates the same stack.
|
|
55
|
+
|
|
56
|
+
## Add more later
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npx create-efforge list # every add-on, ✓ for the ones you have
|
|
60
|
+
npx create-efforge add email # wire one in
|
|
61
|
+
npx create-efforge add ai/effect-ai-byok extras/storage --dry-run # see what would change
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`add` reads the stack from `efforge.jsonc`, checks the new choice is compatible, writes the add-on's files and edits the files that compose the app. It computes everything first and writes nothing if any step fails. Files you've edited since they were generated are left alone unless you pass `--overwrite`, and it shows you the diff. When it's done it lists the new env vars to fill in. Run it with a clean git tree and review the result with `git diff`.
|
|
111
65
|
|
|
112
66
|
## What you get
|
|
113
67
|
|
|
114
68
|
```
|
|
115
|
-
apps/web
|
|
116
|
-
packages/core
|
|
117
|
-
packages/db
|
|
118
|
-
infra/
|
|
119
|
-
apps/browser
|
|
120
|
-
efforge.jsonc
|
|
121
|
-
AGENTS.md
|
|
69
|
+
apps/web TanStack Start app: Worker entry, routes, shadcn/ui, Tailwind v4
|
|
70
|
+
packages/core service interfaces, tagged errors, schemas
|
|
71
|
+
packages/db schema, migrations, database layer (with a database)
|
|
72
|
+
infra/ alchemy.run.ts (infra=alchemy)
|
|
73
|
+
apps/browser Playwright container image (extras=browser)
|
|
74
|
+
efforge.jsonc your stack choices, read by efforge add
|
|
75
|
+
AGENTS.md layout and rules for coding agents
|
|
122
76
|
```
|
|
123
77
|
|
|
124
|
-
The workspace
|
|
125
|
-
|
|
126
|
-
## Status and limits
|
|
78
|
+
The workspace pins exact versions in a pnpm `catalog:`, runs `dev`, `build`, `typecheck` and `test` through Turborepo, and lints and formats with [Vite+](https://viteplus.dev) (Oxlint, Oxfmt).
|
|
127
79
|
|
|
128
|
-
|
|
80
|
+
## Status
|
|
129
81
|
|
|
130
|
-
|
|
131
|
-
- You can add add-ons but not remove them, and a single-choice slot only moves from `none` to a value. To switch from Postgres to D1, create a new project.
|
|
132
|
-
- `infra=alchemy` uses Alchemy 2.0 beta (`2.0.0-beta.83`). Drizzle is pinned to `1.0.0-rc.5-5935859` ([why](https://github.com/amagdy46/efforge/blob/main/docs/decisions/0002-drizzle-rc-pin.md)).
|
|
133
|
-
- With `infra=alchemy`, local secrets are read from `.env`, not `.dev.vars`, and `pnpm db:migrate` on D1 still expects a `wrangler.jsonc`. Both are known v0.1 gaps.
|
|
134
|
-
- CI generates, installs and runs the full gate (typecheck, check, test, build) for a matrix of 15 stacks, not every combination.
|
|
135
|
-
- With `--auth=none`, the `effect-ai-byok` demo server function is not gated, so anyone who can reach the app can spend the configured API key. Add auth or remove the demo before deploying.
|
|
82
|
+
v0.1: Cloudflare is the only runtime, add-ons can be added but not removed, and the CLI's options may still change. Drizzle is pinned to a release candidate and Alchemy support uses a beta. With `--auth=none`, the AI demo endpoint isn't gated; add auth or remove it before deploying. Details and known gaps: [docs/limits.md](https://github.com/amagdy46/efforge/blob/main/docs/limits.md).
|
|
136
83
|
|
|
137
|
-
##
|
|
84
|
+
## Docs
|
|
138
85
|
|
|
139
|
-
|
|
86
|
+
- [CLI reference](https://github.com/amagdy46/efforge/blob/main/docs/cli.md): every flag, CI and scripting, `add` in detail
|
|
87
|
+
- [Contributing](https://github.com/amagdy46/efforge/blob/main/CONTRIBUTING.md) and the [changelog](https://github.com/amagdy46/efforge/blob/main/CHANGELOG.md)
|
|
140
88
|
|
|
141
|
-
|
|
89
|
+
Prompts by [Clack](https://github.com/bombshell-dev/clack). MIT licensed.
|
package/dist/bin.js
CHANGED
|
@@ -3,4 +3,11 @@ import { NodeRuntime, NodeServices } from "@effect/platform-node";
|
|
|
3
3
|
import { Effect, Layer } from "effect";
|
|
4
4
|
import { main } from "./cli.js";
|
|
5
5
|
import { PromptIOLive } from "./prompts/navigable.js";
|
|
6
|
+
// `efforge list | head` closes the pipe early: that's the reader being done, not an error.
|
|
7
|
+
for (const stream of [process.stdout, process.stderr])
|
|
8
|
+
stream.on("error", (e) => {
|
|
9
|
+
if (e.code === "EPIPE")
|
|
10
|
+
process.exit(0);
|
|
11
|
+
throw e;
|
|
12
|
+
});
|
|
6
13
|
main.pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, PromptIOLive)), NodeRuntime.runMain);
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
import { Command } from "effect/cli";
|
|
2
2
|
import { addCommand } from "./commands/add.js";
|
|
3
3
|
import { createCommand, createConfig, createHandler } from "./commands/create.js";
|
|
4
|
+
import { listCommand } from "./commands/list.js";
|
|
4
5
|
import { efforgeVersion } from "./versions.js";
|
|
5
|
-
/** Root behaves as `create`; `efforge create` is an explicit alias, `
|
|
6
|
-
export const root = Command.make("create-efforge", createConfig, createHandler).pipe(Command.withDescription("Scaffold an Effect + TanStack Start app on Cloudflare with database, auth and services already wired together"), Command.withSubcommands([createCommand, addCommand])
|
|
6
|
+
/** Root behaves as `create`; `efforge create` is an explicit alias, `add` and `list` are separate. */
|
|
7
|
+
export const root = Command.make("create-efforge", createConfig, createHandler).pipe(Command.withDescription("Scaffold an Effect + TanStack Start app on Cloudflare with database, auth and services already wired together"), Command.withSubcommands([createCommand, addCommand, listCommand]), Command.withExamples([
|
|
8
|
+
{
|
|
9
|
+
command: "npm create efforge my-app",
|
|
10
|
+
description: "Answer a few questions, then create ./my-app",
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
command: "npm create efforge my-app -- --yes --database=d1 --orm=effect-sql",
|
|
14
|
+
description: "No questions: flags, defaults for the rest",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
command: "npm create efforge . -- --yes",
|
|
18
|
+
description: "Create in the current (empty) directory",
|
|
19
|
+
},
|
|
20
|
+
{ command: "npx create-efforge list", description: "See every add-on" },
|
|
21
|
+
{
|
|
22
|
+
command: "npx create-efforge add email storage",
|
|
23
|
+
description: "Add add-ons to an existing project",
|
|
24
|
+
},
|
|
25
|
+
]));
|
|
7
26
|
export const main = Command.run(root, { version: efforgeVersion });
|
|
8
27
|
/** Same command, but with explicit arguments (used by tests). */
|
|
9
28
|
export const runWith = Command.runWith(root, { version: efforgeVersion });
|
package/dist/commands/add.js
CHANGED
|
@@ -5,7 +5,7 @@ import pc from "picocolors";
|
|
|
5
5
|
import { parseDocument } from "yaml";
|
|
6
6
|
import { addonIdsFor, loadAddons } from "../addon.js";
|
|
7
7
|
import { unifiedDiff } from "../diff.js";
|
|
8
|
-
import { exec } from "../exec.js";
|
|
8
|
+
import { exec, has } from "../exec.js";
|
|
9
9
|
import { GenerateError, generate, isComputed, matches } from "../generate.js";
|
|
10
10
|
import { EfforgeManifest, hash, renderManifest } from "../manifest.js";
|
|
11
11
|
import { applyProjectName } from "../projectName.js";
|
|
@@ -15,10 +15,17 @@ import { slots } from "../slots.js";
|
|
|
15
15
|
import { toCommand } from "../stack.js";
|
|
16
16
|
import { WRANGLER_FILE } from "../transforms/addWranglerBinding.js";
|
|
17
17
|
import { runTransform, transformTargets, } from "../transforms/index.js";
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
18
|
+
import { PromptIO } from "../prompts/navigable.js";
|
|
19
|
+
import { efforgeVersion, versions } from "../versions.js";
|
|
20
|
+
import { PnpmMissing, TemplatesDir } from "./create.js";
|
|
20
21
|
export class NotAnEfforgeProject extends Schema.TaggedError()("NotAnEfforgeProject", { dir: Schema.String, reason: Schema.String }) {
|
|
21
22
|
}
|
|
23
|
+
/** An id that names no add-on (typo, removal via `none`, or ambiguous). */
|
|
24
|
+
export class UnknownAddon extends Schema.TaggedError()("UnknownAddon", {
|
|
25
|
+
id: Schema.String,
|
|
26
|
+
message: Schema.String,
|
|
27
|
+
}) {
|
|
28
|
+
}
|
|
22
29
|
/** A target file that exists, differs from what efforge generated, and `--overwrite` wasn't given. */
|
|
23
30
|
export class OverlayConflict extends Schema.TaggedError()("OverlayConflict", {
|
|
24
31
|
file: Schema.String,
|
|
@@ -27,22 +34,74 @@ export class OverlayConflict extends Schema.TaggedError()("OverlayConflict", {
|
|
|
27
34
|
}
|
|
28
35
|
const incompatible = (slot, value, allowed, reason) => new IncompatibleStack({ slot, value, allowed, reason });
|
|
29
36
|
const allIds = slots.flatMap((s) => s.options.filter((o) => o.id !== "none").map((o) => `${s.id}/${o.id}`));
|
|
37
|
+
/** Edit distance, for "did you mean". */
|
|
38
|
+
const distance = (a, b) => {
|
|
39
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
40
|
+
for (let i = 1; i <= a.length; i++) {
|
|
41
|
+
let prev = row[0];
|
|
42
|
+
row[0] = i;
|
|
43
|
+
for (let j = 1; j <= b.length; j++) {
|
|
44
|
+
const tmp = row[j];
|
|
45
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
46
|
+
prev = tmp;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return row[b.length];
|
|
50
|
+
};
|
|
51
|
+
const suggest = (id) => {
|
|
52
|
+
// a slot name or a fragment ("ai", "auth", "better") before edit distance, which favours short ids
|
|
53
|
+
const partial = allIds.filter((full) => full.split("/").some((part) => part.startsWith(id)));
|
|
54
|
+
if (partial.length > 0)
|
|
55
|
+
return partial.join(", ");
|
|
56
|
+
const best = allIds
|
|
57
|
+
.flatMap((full) => [full, full.split("/")[1]])
|
|
58
|
+
.map((c) => [c, distance(id, c)])
|
|
59
|
+
.toSorted((a, b) => a[1] - b[1])[0];
|
|
60
|
+
return best !== undefined && best[1] <= 3 ? best[0] : undefined;
|
|
61
|
+
};
|
|
62
|
+
/** Same JSONC data and comments, ignoring formatting, key order and array order (earlier `add`s reorder bindings). */
|
|
63
|
+
const sameJsonc = (a, b) => {
|
|
64
|
+
if (b === undefined)
|
|
65
|
+
return false;
|
|
66
|
+
const canon = (v) => Array.isArray(v)
|
|
67
|
+
? v.map(canon).toSorted((x, y) => byName(JSON.stringify(x), JSON.stringify(y)))
|
|
68
|
+
: v !== null && typeof v === "object"
|
|
69
|
+
? Object.fromEntries(Object.entries(v)
|
|
70
|
+
.toSorted(([x], [y]) => byName(x, y))
|
|
71
|
+
.map(([k, x]) => [k, canon(x)]))
|
|
72
|
+
: v;
|
|
73
|
+
const read = (t) => {
|
|
74
|
+
const errors = [];
|
|
75
|
+
const v = parse(t, errors, { allowTrailingComma: true });
|
|
76
|
+
return errors.length > 0 ? undefined : JSON.stringify(canon(v));
|
|
77
|
+
};
|
|
78
|
+
// comments are user content too, and the parser drops them
|
|
79
|
+
const comments = (t) => (t.match(/\/\/.*$|\/\*[\s\S]*?\*\//gm) ?? [])
|
|
80
|
+
.map((c) => c.trim())
|
|
81
|
+
.toSorted()
|
|
82
|
+
.join("\n");
|
|
83
|
+
const x = read(a);
|
|
84
|
+
return x !== undefined && x === read(b) && comments(a) === comments(b);
|
|
85
|
+
};
|
|
30
86
|
const isNewPackageJson = (target) => target.endsWith("/package.json");
|
|
31
87
|
const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
32
88
|
/** `email`, `extras/email`, `ai/effect-ai-byok`, `ai=effect-ai-byok` -> slot + option. */
|
|
33
|
-
const parseId = (
|
|
89
|
+
const parseId = (raw) => {
|
|
90
|
+
const id = raw.trim().toLowerCase();
|
|
34
91
|
const [slotPart, option = ""] = id.includes("=")
|
|
35
92
|
? id.split("=", 2)
|
|
36
93
|
: id.includes("/")
|
|
37
94
|
? id.split("/", 2)
|
|
38
95
|
: [undefined, id];
|
|
39
|
-
const unknown = (
|
|
96
|
+
const unknown = (message) => Effect.fail(new UnknownAddon({ id: raw, message }));
|
|
40
97
|
if (option === "none")
|
|
41
|
-
return unknown(
|
|
98
|
+
return unknown(`Removing an add-on isn't supported in v0.1 ("${raw}").`);
|
|
42
99
|
const candidates = slots.filter((s) => (slotPart === undefined || s.id === slotPart) && s.options.some((o) => o.id === option));
|
|
43
100
|
const [first] = candidates;
|
|
44
|
-
if (first === undefined)
|
|
45
|
-
|
|
101
|
+
if (first === undefined) {
|
|
102
|
+
const guess = suggest(id);
|
|
103
|
+
return unknown(`"${raw}" is not an add-on.${guess === undefined ? "" : ` Did you mean ${guess}?`} Run efforge list to see them all.`);
|
|
104
|
+
}
|
|
46
105
|
if (candidates.length > 1)
|
|
47
106
|
return unknown(`"${id}" is ambiguous; write it as ${candidates.map((s) => `${s.id}/${id}`).join(" or ")}.`);
|
|
48
107
|
return Effect.succeed({ slot: first, option });
|
|
@@ -71,12 +130,24 @@ const applyIds = (stack, ids) => Effect.gen(function* () {
|
|
|
71
130
|
else
|
|
72
131
|
return yield* incompatible(slot.id, option, [current], `${slot.id} is already "${current}"; swapping an existing choice isn't supported in v0.1. Create a new project to use a different ${slot.id}.`);
|
|
73
132
|
}
|
|
74
|
-
|
|
133
|
+
const valid = yield* validate(next).pipe(Effect.mapError((e) => {
|
|
134
|
+
// the stack rules hold across slots: say which ids to add together
|
|
135
|
+
const typed = ids.map((x) => x.trim().toLowerCase());
|
|
136
|
+
const hasOrm = typed.some((x) => x.startsWith("orm/") || x === "drizzle" || x === "effect-sql");
|
|
137
|
+
if (next.database === "none" && (e.slot === "orm" || e.slot === "auth"))
|
|
138
|
+
return incompatible(e.slot, e.value, [...e.allowed], `${e.slot === "auth" ? "auth" : "an ORM"} needs a database, and this project has none. Add one in the same command: efforge add database/d1 ${[...(hasOrm ? [] : ["orm/effect-sql"]), ...typed].join(" ")}`);
|
|
139
|
+
if (e.slot === "orm" && next.orm === "none")
|
|
140
|
+
return incompatible("database", next.database, [...e.allowed], `a database needs an ORM. Add one with it: efforge add ${typed.join(" ")} orm/drizzle (or orm/effect-sql)`);
|
|
141
|
+
return e;
|
|
142
|
+
}));
|
|
143
|
+
return { stack: valid, skipped };
|
|
75
144
|
});
|
|
76
|
-
const readManifest = (dir) => Effect.gen(function* () {
|
|
145
|
+
export const readManifest = (dir) => Effect.gen(function* () {
|
|
77
146
|
const fs = yield* FileSystem.FileSystem;
|
|
78
147
|
const path = yield* Path.Path;
|
|
79
148
|
const fail = (reason) => new NotAnEfforgeProject({ dir, reason });
|
|
149
|
+
if (!(yield* fs.exists(dir).pipe(Effect.orElseSucceed(() => false))))
|
|
150
|
+
return yield* fail("the directory does not exist");
|
|
80
151
|
const text = yield* fs
|
|
81
152
|
.readFileString(path.join(dir, "efforge.jsonc"))
|
|
82
153
|
.pipe(Effect.mapError(() => fail("efforge.jsonc not found")));
|
|
@@ -192,7 +263,7 @@ export const addAddons = (dir, ids, opts) => Effect.gen(function* () {
|
|
|
192
263
|
const existing = (yield* read(WRANGLER_FILE));
|
|
193
264
|
const generated = (yield* generate(manifest.stack, addons)).get(WRANGLER_FILE);
|
|
194
265
|
if (opts.overwrite ||
|
|
195
|
-
existing
|
|
266
|
+
sameJsonc(existing, generated) ||
|
|
196
267
|
manifest.files[WRANGLER_FILE] === hash(existing))
|
|
197
268
|
removed.add(WRANGLER_FILE);
|
|
198
269
|
else
|
|
@@ -296,6 +367,7 @@ export const addAddons = (dir, ids, opts) => Effect.gen(function* () {
|
|
|
296
367
|
packages.set(target, `${JSON.stringify({ ...pkg, [key]: ordered }, null, indent)}${text.endsWith("\n") ? "\n" : ""}`);
|
|
297
368
|
}
|
|
298
369
|
// scripts of the new add-ons (they replace same-named ones, like generate does)
|
|
370
|
+
const replacedScripts = [];
|
|
299
371
|
for (const { manifest: m } of fresh)
|
|
300
372
|
for (const [pkgDir, scripts] of Object.entries(m.scripts ?? {})) {
|
|
301
373
|
const target = pkgDir === "." ? "package.json" : `${pkgDir}/package.json`;
|
|
@@ -307,7 +379,11 @@ export const addAddons = (dir, ids, opts) => Effect.gen(function* () {
|
|
|
307
379
|
message: `${m.id} adds scripts to ${target}, which does not exist`,
|
|
308
380
|
});
|
|
309
381
|
const pkg = JSON.parse(text);
|
|
310
|
-
const
|
|
382
|
+
const existingScripts = pkg.scripts ?? {};
|
|
383
|
+
for (const [name, cmd] of Object.entries(scripts))
|
|
384
|
+
if (existingScripts[name] !== undefined && existingScripts[name] !== cmd)
|
|
385
|
+
replacedScripts.push(`${target}: ${name}`);
|
|
386
|
+
const merged = { ...existingScripts, ...scripts };
|
|
311
387
|
const indent = /^([ \t]+)"/m.exec(text)?.[1] ?? " ";
|
|
312
388
|
const next = `${JSON.stringify({ ...pkg, scripts: merged }, null, indent)}${text.endsWith("\n") ? "\n" : ""}`;
|
|
313
389
|
if (next !== text)
|
|
@@ -337,10 +413,13 @@ export const addAddons = (dir, ids, opts) => Effect.gen(function* () {
|
|
|
337
413
|
const envText = (yield* read(".env.example")) ?? "";
|
|
338
414
|
const have = new Set(envText.split("\n").map((l) => l.split("=")[0]?.trim()));
|
|
339
415
|
const groups = [];
|
|
416
|
+
const envVars = [];
|
|
340
417
|
for (const { manifest: m } of scope) {
|
|
341
418
|
const vars = m.envVars.filter((v) => switchedOn(m.id, v.when) && !have.has(v.name));
|
|
342
|
-
for (const v of vars)
|
|
419
|
+
for (const v of vars) {
|
|
343
420
|
have.add(v.name);
|
|
421
|
+
envVars.push({ name: v.name, description: v.description });
|
|
422
|
+
}
|
|
344
423
|
if (vars.length > 0)
|
|
345
424
|
groups.push(`# ${m.title}\n${vars.map((v) => `${v.name}=${v.example}`).join("\n")}`);
|
|
346
425
|
}
|
|
@@ -363,9 +442,15 @@ export const addAddons = (dir, ids, opts) => Effect.gen(function* () {
|
|
|
363
442
|
}
|
|
364
443
|
const result = {
|
|
365
444
|
written: [...written].toSorted(),
|
|
445
|
+
created: [...written].filter((f) => disk.has(f) && disk.get(f) === undefined).toSorted(),
|
|
366
446
|
transformed: [...transformed].toSorted(),
|
|
367
447
|
skipped: skipped.toSorted(),
|
|
368
448
|
removed: [...removed].toSorted(),
|
|
449
|
+
added: fresh.map(({ manifest: m }) => m.docs === undefined
|
|
450
|
+
? { id: m.id, title: m.title }
|
|
451
|
+
: { id: m.id, title: m.title, docs: m.docs }),
|
|
452
|
+
envVars,
|
|
453
|
+
replacedScripts,
|
|
369
454
|
};
|
|
370
455
|
if (opts.dryRun)
|
|
371
456
|
return result;
|
|
@@ -389,8 +474,12 @@ const describe = (e) => {
|
|
|
389
474
|
switch (e._tag) {
|
|
390
475
|
case "NotAnEfforgeProject":
|
|
391
476
|
return `${String(e.dir)} is not an efforge project (${String(e.reason)}). Run this from the project root or pass --cwd.`;
|
|
477
|
+
case "PnpmMissing":
|
|
478
|
+
return "efforge projects use pnpm, and it isn't on your PATH. Install it (corepack enable pnpm, or https://pnpm.io/installation) and re-run, or pass --no-install.";
|
|
479
|
+
case "UnknownAddon":
|
|
480
|
+
return String(e.message);
|
|
392
481
|
case "IncompatibleStack":
|
|
393
|
-
return `Can't add
|
|
482
|
+
return `Can't add ${String(e.slot)}/${String(e.value)}: ${typeof e.reason === "string" ? e.reason : "not compatible with the current stack."}`;
|
|
394
483
|
case "OverlayConflict":
|
|
395
484
|
return `You've edited ${String(e.file)} since it was generated. Nothing was written. Re-run with --overwrite to replace it.\n\n${String(e.diff)}`;
|
|
396
485
|
case "TransformAnchorMissing":
|
|
@@ -409,32 +498,143 @@ export const addConfig = {
|
|
|
409
498
|
cwd: Flag.String("cwd").pipe(Flag.withDescription("Project directory (default: current directory)"), Flag.withDefault(".")),
|
|
410
499
|
install: Flag.Boolean("install").pipe(Flag.withDescription("Run pnpm install afterwards (--no-install to skip)"), Flag.withDefault(true)),
|
|
411
500
|
};
|
|
501
|
+
/** `a.b.c` -> numbers, for the "project is newer than this CLI" check. */
|
|
502
|
+
const newer = (a, b) => {
|
|
503
|
+
const pa = a.split(/[.-]/).map(Number);
|
|
504
|
+
const pb = b.split(/[.-]/).map(Number);
|
|
505
|
+
for (let i = 0; i < 3; i++) {
|
|
506
|
+
const x = pa[i] ?? 0;
|
|
507
|
+
const y = pb[i] ?? 0;
|
|
508
|
+
if (x !== y)
|
|
509
|
+
return x > y;
|
|
510
|
+
}
|
|
511
|
+
return false;
|
|
512
|
+
};
|
|
513
|
+
/** Word-wraps `text` to `width` columns. */
|
|
514
|
+
const wrap = (text, width) => {
|
|
515
|
+
const lines = [];
|
|
516
|
+
let line = "";
|
|
517
|
+
for (const word of text.split(/\s+/)) {
|
|
518
|
+
if (line !== "" && line.length + 1 + word.length > width) {
|
|
519
|
+
lines.push(line);
|
|
520
|
+
line = word;
|
|
521
|
+
}
|
|
522
|
+
else
|
|
523
|
+
line = line === "" ? word : `${line} ${word}`;
|
|
524
|
+
}
|
|
525
|
+
if (line !== "")
|
|
526
|
+
lines.push(line);
|
|
527
|
+
return lines;
|
|
528
|
+
};
|
|
529
|
+
const list = (files, mark) => files.map((f) => `${mark} ${f}`);
|
|
412
530
|
export const addHandler = (input) => Effect.gen(function* () {
|
|
413
531
|
const path = yield* Path.Path;
|
|
414
|
-
const
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
532
|
+
const live = yield* PromptIO;
|
|
533
|
+
const dir = path.resolve(input.cwd);
|
|
534
|
+
// --json keeps stdout to the one JSON document: steps still run, silently
|
|
535
|
+
const io = input.json
|
|
536
|
+
? {
|
|
537
|
+
...live,
|
|
538
|
+
step: (_label, eff) => eff,
|
|
539
|
+
task: (_label, eff) => eff(() => { }),
|
|
540
|
+
}
|
|
541
|
+
: live;
|
|
542
|
+
if (!input.json)
|
|
543
|
+
yield* io.intro(`${pc.bgCyan(pc.black(" efforge add "))}${pc.dim(` ${input.ids.join(" ")}`)}`);
|
|
544
|
+
const manifest = yield* readManifest(dir);
|
|
545
|
+
if (!input.json && newer(manifest.efforgeVersion, efforgeVersion))
|
|
546
|
+
yield* io.warn(`This project was made with efforge ${manifest.efforgeVersion}, newer than this CLI (${efforgeVersion}). Use npx create-efforge@latest add.`);
|
|
547
|
+
const opts = { overwrite: input.overwrite, install: false };
|
|
548
|
+
// checked before anything is written: install and the route tree both need pnpm
|
|
549
|
+
if (input.install && !input.dryRun && !(yield* has("pnpm", dir)))
|
|
550
|
+
return yield* new PnpmMissing();
|
|
551
|
+
// plan first (in memory): the dirty-tree warning only matters when something will change
|
|
552
|
+
const plan = yield* addAddons(dir, input.ids, { ...opts, dryRun: true });
|
|
553
|
+
const changes = plan.written.length + plan.transformed.length + plan.removed.length > 0;
|
|
554
|
+
if (changes && !input.dryRun && !input.json) {
|
|
555
|
+
const dirty = yield* exec("git", ["status", "--porcelain"], dir).pipe(Effect.map((out) => out.trim() !== ""), Effect.catchTag("CommandFailed", () => Effect.succeed(false)));
|
|
556
|
+
if (dirty)
|
|
557
|
+
yield* io.warn("You have uncommitted changes, so git diff will mix them with efforge's edits. Commit or stash first to review them on their own.");
|
|
558
|
+
}
|
|
559
|
+
const result = input.dryRun || !changes ? plan : yield* addAddons(dir, input.ids, { ...opts, dryRun: false });
|
|
560
|
+
// only when dependencies changed: package.json files or the catalog
|
|
561
|
+
const depsChanged = result.written.some((f) => f.endsWith("package.json") || f === "pnpm-workspace.yaml");
|
|
562
|
+
const finish = Effect.gen(function* () {
|
|
563
|
+
if (!input.install || input.dryRun || !changes)
|
|
564
|
+
return;
|
|
565
|
+
if (depsChanged)
|
|
566
|
+
yield* io.task("Installing dependencies (pnpm install)", (log) => exec("pnpm", ["install"], dir, log));
|
|
567
|
+
// add-ons may add or replace routes
|
|
568
|
+
yield* io.step("Generating the route tree", generateRouteTree(dir));
|
|
418
569
|
});
|
|
419
|
-
if (input.json)
|
|
570
|
+
if (input.json) {
|
|
571
|
+
yield* finish;
|
|
420
572
|
return yield* Console.log(JSON.stringify({ dryRun: input.dryRun, ...result }, null, 2));
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
573
|
+
}
|
|
574
|
+
const changed = result.written.length + result.transformed.length + result.removed.length > 0;
|
|
575
|
+
if (!changed) {
|
|
576
|
+
yield* io.info(`Already there: ${result.skipped.join(", ")}`);
|
|
577
|
+
return yield* io.outro("Nothing to do.");
|
|
578
|
+
}
|
|
579
|
+
yield* io.note([
|
|
580
|
+
...list(result.created, pc.green("+")),
|
|
581
|
+
...list([
|
|
582
|
+
...result.written.filter((f) => !result.created.includes(f)),
|
|
583
|
+
...result.transformed,
|
|
584
|
+
].toSorted(), pc.yellow("~")),
|
|
585
|
+
...list(result.removed, pc.red("-")),
|
|
586
|
+
].join("\n"), `${input.dryRun ? "Would change" : "Changed"}: ${result.added.map((a) => a.title).join(", ") || "stack"}`);
|
|
587
|
+
if (result.removed.length > 0)
|
|
588
|
+
yield* io.warn(`${input.dryRun ? "Would remove" : "Removed"} ${result.removed.join(", ")}: the new add-ons replace it.`);
|
|
589
|
+
if (result.replacedScripts.length > 0)
|
|
590
|
+
yield* io.warn(`${input.dryRun ? "Would replace" : "Replaced"} existing package scripts:\n${result.replacedScripts.map((x) => ` ${x}`).join("\n")}`);
|
|
591
|
+
if (input.dryRun)
|
|
592
|
+
return yield* io.outro(pc.dim("dry run: nothing written"));
|
|
593
|
+
yield* finish;
|
|
594
|
+
// a new database needs its tables before the app (or sign-up) can use it
|
|
595
|
+
const database = result.added.find((a) => a.id.startsWith("database/"))?.id.split("/")[1];
|
|
596
|
+
const alchemy = manifest.stack.infra === "alchemy" || result.added.some((a) => a.id === "infra/alchemy");
|
|
597
|
+
const commands = [
|
|
598
|
+
...(input.install || !depsChanged ? [] : ["pnpm install"]),
|
|
599
|
+
...(database === "postgres" ? ["docker compose up -d --wait", "pnpm db:migrate"] : []),
|
|
600
|
+
...(database === "d1" && !alchemy ? ["pnpm db:migrate"] : []),
|
|
601
|
+
];
|
|
602
|
+
const width = Math.max(0, ...result.envVars.map((x) => x.name.length));
|
|
603
|
+
const room = Math.max(30, (process.stdout.columns || 80) - 14);
|
|
604
|
+
const steps = [
|
|
605
|
+
...commands.map((c) => ` ${pc.cyan(c)}`),
|
|
606
|
+
...(result.envVars.length > 0
|
|
607
|
+
? [
|
|
608
|
+
`${commands.length > 0 ? "\n" : ""}${pc.bold("New env vars")} ${pc.dim("(in .env.example; local values in .dev.vars)")}`,
|
|
609
|
+
// full descriptions, wrapped under the name: the hint at the end is often the useful part
|
|
610
|
+
...result.envVars.map((v) => ` ${v.name.padEnd(width)}\n${wrap(v.description, room)
|
|
611
|
+
.map((l) => ` ${pc.dim(l)}`)
|
|
612
|
+
.join("\n")}`),
|
|
613
|
+
]
|
|
431
614
|
: []),
|
|
432
|
-
...
|
|
433
|
-
|
|
615
|
+
...result.added
|
|
616
|
+
.filter((a) => a.docs !== undefined)
|
|
617
|
+
.map((a) => `${a.title}: ${pc.dim(a.docs)}`),
|
|
618
|
+
];
|
|
619
|
+
if (steps.length > 0)
|
|
620
|
+
yield* io.note(steps.join("\n"), "Next steps");
|
|
621
|
+
yield* io.outro(`${pc.green("Done.")} ${pc.dim("Review the changes with")} git diff`);
|
|
434
622
|
}).pipe(Effect.catch((e) => Effect.gen(function* () {
|
|
435
|
-
yield* Console.error(pc.red(describe(e)));
|
|
436
623
|
yield* Effect.sync(() => {
|
|
437
624
|
process.exitCode = 1;
|
|
438
625
|
});
|
|
626
|
+
if (input.json)
|
|
627
|
+
return yield* Console.log(JSON.stringify({ error: { code: e._tag, message: describe(e) } }, null, 2));
|
|
628
|
+
yield* Console.error(pc.red(describe(e)));
|
|
439
629
|
})));
|
|
440
|
-
export const addCommand = Command.make("add", addConfig, addHandler).pipe(Command.withDescription("Add an add-on to an existing efforge project")
|
|
630
|
+
export const addCommand = Command.make("add", addConfig, addHandler).pipe(Command.withDescription("Add an add-on to an existing efforge project"), Command.withExamples([
|
|
631
|
+
{ command: "npx create-efforge add email", description: "Add the email add-on" },
|
|
632
|
+
{
|
|
633
|
+
command: "npx create-efforge add ai/effect-ai-byok extras/storage --dry-run",
|
|
634
|
+
description: "Show what would change; write nothing",
|
|
635
|
+
},
|
|
636
|
+
{
|
|
637
|
+
command: "npx create-efforge add database/d1 orm/effect-sql auth/better-auth",
|
|
638
|
+
description: "Add a database, an ORM and auth together",
|
|
639
|
+
},
|
|
640
|
+
]));
|