@wwchen/stack 0.9.1 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -13
- package/blocks/AGENTS.md +4 -12
- package/blocks/CLAUDE.md +7 -15
- package/blocks/env.example +0 -11
- package/blocks/gitignore +1 -2
- package/dist/cli/builtin.d.ts +6 -0
- package/dist/cli/builtin.js +47 -0
- package/dist/cli/context.d.ts +6 -20
- package/dist/cli/context.js +2 -2
- package/dist/cli/host.d.ts +8 -0
- package/dist/cli/host.js +128 -0
- package/dist/cli/index.js +4 -71
- package/dist/cli/neon.d.ts +4 -4
- package/dist/cli/neon.js +19 -9
- package/dist/cli/run.js +1 -1
- package/dist/cli/sync-blocks.d.ts +9 -8
- package/dist/cli/sync-blocks.js +157 -47
- package/dist/configs/vitest.js +1 -6
- package/dist/connections/env.d.ts +8 -0
- package/dist/connections/env.js +15 -0
- package/dist/connections/index.d.ts +1 -1
- package/dist/connections/index.js +1 -1
- package/dist/connections/table.d.ts +5 -3
- package/dist/connections/table.js +3 -3
- package/dist/db/branches.d.ts +11 -0
- package/dist/db/branches.js +19 -0
- package/dist/db/doctor.d.ts +9 -0
- package/dist/db/doctor.js +120 -0
- package/dist/db/env.d.ts +14 -0
- package/dist/db/env.js +15 -0
- package/dist/db/health.d.ts +10 -0
- package/dist/db/health.js +26 -0
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +1 -0
- package/dist/db/target.js +2 -1
- package/dist/env/core-env.d.ts +23 -0
- package/dist/env/core-env.js +24 -0
- package/dist/env/define-env.d.ts +22 -10
- package/dist/env/define-env.js +72 -17
- package/dist/env/index.d.ts +2 -2
- package/dist/env/index.js +1 -1
- package/dist/http/client-ip.d.ts +6 -0
- package/dist/http/client-ip.js +21 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +2 -0
- package/dist/http/safe-next.d.ts +11 -0
- package/dist/http/safe-next.js +30 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/next/api.d.ts +9 -8
- package/dist/next/api.js +10 -8
- package/dist/next/health.d.ts +5 -7
- package/dist/next/health.js +16 -17
- package/dist/stack/contracts.d.ts +152 -0
- package/dist/stack/contracts.js +42 -0
- package/dist/vercel/index.d.ts +28 -0
- package/dist/vercel/index.js +90 -0
- package/package.json +22 -4
- package/dist/cli/doctor.d.ts +0 -40
- package/dist/cli/doctor.js +0 -166
- package/dist/cli/migrate-suite.d.ts +0 -2
- package/dist/cli/migrate-suite.js +0 -491
- package/dist/cli/user-create.d.ts +0 -6
- package/dist/cli/user-create.js +0 -77
- package/dist/cli/vercel-build.d.ts +0 -4
- package/dist/cli/vercel-build.js +0 -61
- package/dist/env/stack-env.d.ts +0 -37
- package/dist/env/stack-env.js +0 -54
package/dist/cli/doctor.js
DELETED
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
// `stack doctor` — a read-only audit of the linked Vercel project's hosting setup: the framework preset, and the environment variables the stack depends on. Prints its findings, errors first, and exits non-zero when any is an error. Changes nothing.
|
|
2
|
-
//
|
|
3
|
-
// It reads metadata only — each variable's name, type, targets, id, git branch, and the integration fields (`configurationId`, `comment`) — through the Vercel REST API (`vercel api`), without `decrypt`. A value is dropped the moment the response is parsed, and never printed: whether Preview's DATABASE_URL is production's database can only be told from its value, so that one is left to `stack vercel-build`, which refuses it at build time.
|
|
4
|
-
import { readFileSync } from "node:fs";
|
|
5
|
-
import { join } from "node:path";
|
|
6
|
-
import { CliError } from "./context.js";
|
|
7
|
-
/** What the Neon Vercel integration writes on every variable it creates. */
|
|
8
|
-
export const NEON_INTEGRATION_COMMENT = "The Neon Postgres integration sets this environment variable automatically";
|
|
9
|
-
/** Secrets a preview must hold its own value of, never production's (runbook §3). */
|
|
10
|
-
export const PREVIEW_OWN_SECRETS = [
|
|
11
|
-
"BETTER_AUTH_SECRET",
|
|
12
|
-
"TOKEN_ENCRYPTION_KEY",
|
|
13
|
-
"CRON_SECRET",
|
|
14
|
-
"RESEND_API_KEY",
|
|
15
|
-
"GOOGLE_CLIENT_SECRET",
|
|
16
|
-
];
|
|
17
|
-
const RANK = { error: 0, warning: 1, info: 2 };
|
|
18
|
-
const str = (value) => typeof value === "string" && value !== "" ? value : undefined;
|
|
19
|
-
/** The metadata of one API variable; its value (and anything else) is not copied. */
|
|
20
|
-
export function envVarMeta(raw) {
|
|
21
|
-
const r = (raw ?? {});
|
|
22
|
-
const target = Array.isArray(r.target) ? r.target : r.target === undefined ? [] : [r.target];
|
|
23
|
-
return {
|
|
24
|
-
id: String(r.id ?? ""),
|
|
25
|
-
key: String(r.key ?? ""),
|
|
26
|
-
type: String(r.type ?? ""),
|
|
27
|
-
target: target.filter((t) => typeof t === "string"),
|
|
28
|
-
gitBranch: str(r.gitBranch),
|
|
29
|
-
configurationId: str(r.configurationId),
|
|
30
|
-
comment: str(r.comment),
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
/** Variables named `key` that apply to every deployment of `target`: no single git branch. */
|
|
34
|
-
const covering = (h, key, target) => h.envs.filter((v) => v.key === key && v.target.includes(target) && !v.gitBranch);
|
|
35
|
-
const fromNeonIntegration = (v) => (v.configurationId !== undefined && v.gitBranch !== undefined) ||
|
|
36
|
-
(v.comment?.includes(NEON_INTEGRATION_COMMENT) === true && v.target.includes("preview"));
|
|
37
|
-
/** Every check, on metadata alone. Sorted: errors, then warnings, then notes. */
|
|
38
|
-
export function audit(h) {
|
|
39
|
-
const findings = [];
|
|
40
|
-
const add = (severity, message) => findings.push({ severity, message });
|
|
41
|
-
const preset = h.framework ?? "Other";
|
|
42
|
-
if (h.vercelJsonFramework !== undefined && h.vercelJsonFramework !== "nextjs") {
|
|
43
|
-
add("error", `vercel.json sets "framework": ${JSON.stringify(h.vercelJsonFramework)}, which overrides the project's preset; set it to "nextjs".`);
|
|
44
|
-
}
|
|
45
|
-
else if (h.framework !== "nextjs") {
|
|
46
|
-
if (h.vercelJsonFramework === "nextjs") {
|
|
47
|
-
add("info", `The project's framework preset is ${preset}, but vercel.json's "framework": "nextjs" overrides it.`);
|
|
48
|
-
}
|
|
49
|
-
else {
|
|
50
|
-
add("error", `The project's framework preset is ${preset}, not Next.js, and vercel.json sets no framework: ` +
|
|
51
|
-
'Vercel will not serve the app as Next.js. Add "framework": "nextjs" to vercel.json ' +
|
|
52
|
-
"(or set the preset in Project Settings, Build and Deployment).");
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
const integration = h.envs.filter(fromNeonIntegration);
|
|
56
|
-
if (integration.length > 0) {
|
|
57
|
-
const names = [
|
|
58
|
-
...new Set(integration.map((v) => (v.gitBranch ? `${v.key} (${v.gitBranch})` : v.key))),
|
|
59
|
-
];
|
|
60
|
-
add("error", `The Neon Vercel integration is creating per-preview database variables: ${names.join(", ")}. ` +
|
|
61
|
-
"It cuts each preview's branch from production, copying production's data into previews. " +
|
|
62
|
-
"Turn off its preview branching (Vercel, Integrations, Neon), remove these variables, and " +
|
|
63
|
-
"point Preview at the shared `preview` branch: `stack neon reset-preview --set-vercel`.");
|
|
64
|
-
}
|
|
65
|
-
for (const key of PREVIEW_OWN_SECRETS) {
|
|
66
|
-
const shared = h.envs.filter((v) => v.key === key && v.target.includes("production") && v.target.includes("preview"));
|
|
67
|
-
if (shared.length > 0) {
|
|
68
|
-
add("warning", `${key} is one variable for Production and Preview: give Preview its own value, so a ` +
|
|
69
|
-
"preview can never use production's.");
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
for (const target of ["production", "preview", "development"]) {
|
|
73
|
-
if (covering(h, "PRODUCTION_DATABASE_HOST", target).length === 0) {
|
|
74
|
-
add(target === "development" ? "warning" : "error", `PRODUCTION_DATABASE_HOST is not set for ${target}: set production's direct host (not a ` +
|
|
75
|
-
"secret) in every environment, so builds and local tooling can refuse production." +
|
|
76
|
-
(target === "preview" ? " `stack vercel-build` refuses a preview build without it." : ""));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
if (covering(h, "DATABASE_URL_UNPOOLED", "production").length === 0) {
|
|
80
|
-
add("warning", "DATABASE_URL_UNPOOLED is not set for Production, so migrations run through the pooler. " +
|
|
81
|
-
"Set it to production's direct (non -pooler) URL.");
|
|
82
|
-
}
|
|
83
|
-
if (covering(h, "DATABASE_URL", "preview").length === 0) {
|
|
84
|
-
add("error", "Preview has no DATABASE_URL, so every preview build fails. Run `stack neon reset-preview " +
|
|
85
|
-
"--set-vercel` to point Preview at the shared `preview` branch.");
|
|
86
|
-
}
|
|
87
|
-
else {
|
|
88
|
-
add("info", "Whether Preview's DATABASE_URL is production's database can only be told from its value, " +
|
|
89
|
-
"which doctor never reads; `stack vercel-build` refuses that at build time.");
|
|
90
|
-
}
|
|
91
|
-
if (h.truncated) {
|
|
92
|
-
add("info", "The project has more variables than one API page; only the first was checked.");
|
|
93
|
-
}
|
|
94
|
-
return findings.sort((a, b) => RANK[a.severity] - RANK[b.severity]);
|
|
95
|
-
}
|
|
96
|
-
/** Runs `vercel api <path>`; a failure names the endpoint and exit code, never the response. */
|
|
97
|
-
async function vercelApi(cli, path) {
|
|
98
|
-
const { stdout, code } = await cli.exec("vercel", ["api", path, "--raw"]);
|
|
99
|
-
if (code !== 0) {
|
|
100
|
-
throw new CliError(`vercel api ${path.split("?")[0]} failed (exit ${code}). Is the Vercel CLI signed in (\`vercel login\`)?`);
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
return JSON.parse(stdout);
|
|
104
|
-
}
|
|
105
|
-
catch {
|
|
106
|
-
throw new CliError(`vercel api ${path.split("?")[0]} did not answer with JSON.`);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
/** A JSON file's object, or undefined when there is no such file. */
|
|
110
|
-
function readJsonFile(path) {
|
|
111
|
-
let text;
|
|
112
|
-
try {
|
|
113
|
-
text = readFileSync(path, "utf8");
|
|
114
|
-
}
|
|
115
|
-
catch (error) {
|
|
116
|
-
if (error.code === "ENOENT")
|
|
117
|
-
return undefined;
|
|
118
|
-
throw error;
|
|
119
|
-
}
|
|
120
|
-
try {
|
|
121
|
-
return JSON.parse(text);
|
|
122
|
-
}
|
|
123
|
-
catch {
|
|
124
|
-
throw new CliError(`${path} is not valid JSON.`);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* The linked project (`.vercel/project.json`, written by `vercel link`), its preset and its variables' metadata from the Vercel API, and the app's `vercel.json`.
|
|
129
|
-
*/
|
|
130
|
-
export async function readHosting(cli) {
|
|
131
|
-
const link = readJsonFile(join(cli.cwd, ".vercel", "project.json"));
|
|
132
|
-
if (!link) {
|
|
133
|
-
throw new CliError("this directory is not linked to a Vercel project: run `vercel link`.");
|
|
134
|
-
}
|
|
135
|
-
const projectId = str(link.projectId);
|
|
136
|
-
if (!projectId)
|
|
137
|
-
throw new CliError(".vercel/project.json has no projectId: run `vercel link`.");
|
|
138
|
-
const orgId = str(link.orgId);
|
|
139
|
-
const query = orgId?.startsWith("team_") ? `?teamId=${encodeURIComponent(orgId)}` : "";
|
|
140
|
-
const id = encodeURIComponent(projectId);
|
|
141
|
-
const project = await vercelApi(cli, `/v9/projects/${id}${query}`);
|
|
142
|
-
const listed = await vercelApi(cli, `/v10/projects/${id}/env${query}`);
|
|
143
|
-
const rawEnvs = Array.isArray(listed.envs) ? listed.envs : [];
|
|
144
|
-
const next = listed.pagination?.next;
|
|
145
|
-
const vercelJson = readJsonFile(join(cli.cwd, "vercel.json")) ?? {};
|
|
146
|
-
return {
|
|
147
|
-
project: str(project.name) ?? projectId,
|
|
148
|
-
framework: str(project.framework) ?? null,
|
|
149
|
-
vercelJsonFramework: "framework" in vercelJson ? (vercelJson.framework ?? null) : undefined,
|
|
150
|
-
envs: rawEnvs.map(envVarMeta),
|
|
151
|
-
truncated: next !== undefined && next !== null,
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
export async function doctor(cli) {
|
|
155
|
-
const hosting = await readHosting(cli);
|
|
156
|
-
const findings = audit(hosting);
|
|
157
|
-
cli.log(`[doctor] ${hosting.project}: ${hosting.envs.length} environment variables checked`);
|
|
158
|
-
for (const { severity, message } of findings)
|
|
159
|
-
cli.log(`${severity.padEnd(7)} ${message}`);
|
|
160
|
-
const count = (s) => findings.filter((f) => f.severity === s).length;
|
|
161
|
-
const errors = count("error");
|
|
162
|
-
const warnings = count("warning");
|
|
163
|
-
cli.log(`[doctor] ${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}` +
|
|
164
|
-
(errors > 0 ? ": fix the errors before the next deploy." : "."));
|
|
165
|
-
return errors > 0 ? 1 : 0;
|
|
166
|
-
}
|
|
@@ -1,491 +0,0 @@
|
|
|
1
|
-
// `stack migrate-suite [--expect <version>]` — moves an app onto the suite's packages, as the installed stack knows them: adds the `@wwchen/stack-*` packages to package.json and to pnpm-workspace.yaml's release-age exemptions, and moves imports of the stack's old paths to them. Copier runs it after `pnpm install`; it changes nothing on an app already moved.
|
|
2
|
-
//
|
|
3
|
-
// Imports are found with the TypeScript compiler API, never by searching text: a comment or a string that names an old path stays as it is. Every change is worked out before any file is written.
|
|
4
|
-
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { dirname, join, relative, sep } from "node:path";
|
|
6
|
-
import { CliError, STACK_PACKAGE } from "./context.js";
|
|
7
|
-
const AUTH = "@wwchen/stack-auth";
|
|
8
|
-
const NOTIFY = "@wwchen/stack-notify";
|
|
9
|
-
const MAIL = "@wwchen/stack/mail";
|
|
10
|
-
/** Each old path and the specifier that replaces it. A Map, so no string matches an inherited property name. */
|
|
11
|
-
const MOVED = new Map([
|
|
12
|
-
["@wwchen/stack/auth", AUTH],
|
|
13
|
-
["@wwchen/stack/auth/better-auth", `${AUTH}/better-auth`],
|
|
14
|
-
["@wwchen/stack/auth/proxy", `${AUTH}/proxy`],
|
|
15
|
-
[MAIL, NOTIFY],
|
|
16
|
-
]);
|
|
17
|
-
/** Vitest's calls whose first argument is a module specifier: a mock left on an old path stops applying once the code imports the new one. */
|
|
18
|
-
const VI_MODULE_CALLS = new Set([
|
|
19
|
-
"mock",
|
|
20
|
-
"doMock",
|
|
21
|
-
"unmock",
|
|
22
|
-
"doUnmock",
|
|
23
|
-
"importActual",
|
|
24
|
-
"importMock",
|
|
25
|
-
]);
|
|
26
|
-
/** The one name `@wwchen/stack/mail` exports that lives in auth, not notify. */
|
|
27
|
-
const MAGIC = "waitForMagicLink";
|
|
28
|
-
const STACK_PACKAGE_NAME = "@wwchen/stack";
|
|
29
|
-
const WORKSPACE = "pnpm-workspace.yaml";
|
|
30
|
-
const RELEASE_AGE_EXCLUDE = "minimumReleaseAgeExclude";
|
|
31
|
-
export async function migrateSuite(cli, args) {
|
|
32
|
-
const expected = parseArgs(args);
|
|
33
|
-
if (expected !== undefined && expected !== "workspace:*" && expected !== STACK_PACKAGE.version) {
|
|
34
|
-
throw new CliError(`Upgrade @wwchen/stack to ${expected} first: ${STACK_PACKAGE.version} is installed.`);
|
|
35
|
-
}
|
|
36
|
-
const ts = await loadTypeScript();
|
|
37
|
-
const pkgPath = join(cli.cwd, "package.json");
|
|
38
|
-
if (!existsSync(pkgPath))
|
|
39
|
-
throw new CliError(`migrate-suite: no package.json in ${cli.cwd}`);
|
|
40
|
-
const pkgText = readFileSync(pkgPath, "utf8");
|
|
41
|
-
const packages = addPackages(pkgText);
|
|
42
|
-
const writes = new Map();
|
|
43
|
-
const notes = [];
|
|
44
|
-
for (const path of await sourceFiles(cli)) {
|
|
45
|
-
const text = readFileSync(join(cli.cwd, path), "utf8");
|
|
46
|
-
const moved = moveImports(ts, path, text);
|
|
47
|
-
notes.push(...moved.notes);
|
|
48
|
-
if (moved.text !== text)
|
|
49
|
-
writes.set(path, moved.text);
|
|
50
|
-
}
|
|
51
|
-
const moved = [...writes.keys()];
|
|
52
|
-
const workspacePath = join(cli.cwd, WORKSPACE);
|
|
53
|
-
const workspace = releaseAgeEdit(existsSync(workspacePath) ? readFileSync(workspacePath, "utf8") : undefined, suitePackages(packages.text));
|
|
54
|
-
if (packages.added.length > 0)
|
|
55
|
-
writeFileSync(pkgPath, packages.text);
|
|
56
|
-
if (workspace.text !== undefined)
|
|
57
|
-
writeFileSync(workspacePath, workspace.text);
|
|
58
|
-
for (const [path, text] of writes)
|
|
59
|
-
writeFileSync(join(cli.cwd, path), text);
|
|
60
|
-
const sorted = await sortImports(cli, [...writes.keys()]);
|
|
61
|
-
const lines = [];
|
|
62
|
-
if (packages.added.length > 0) {
|
|
63
|
-
lines.push(`package.json: added ${packages.added.map((name) => `${name} ${packages.spec}`).join(", ")}`);
|
|
64
|
-
}
|
|
65
|
-
if (workspace.added.length > 0) {
|
|
66
|
-
lines.push(`${WORKSPACE}: ${RELEASE_AGE_EXCLUDE} now lists ${workspace.added.join(", ")}`);
|
|
67
|
-
}
|
|
68
|
-
lines.push(...workspace.manual);
|
|
69
|
-
if (moved.length > 0) {
|
|
70
|
-
lines.push(`imports moved to the suite's packages in ${moved.length} ${moved.length === 1 ? "file" : "files"}:`, ...moved.sort().map((path) => ` ${path}`));
|
|
71
|
-
}
|
|
72
|
-
lines.push(...notes);
|
|
73
|
-
if (!sorted) {
|
|
74
|
-
lines.push("Biome could not sort the imports of the files above; run `pnpm lint:fix`.");
|
|
75
|
-
}
|
|
76
|
-
if (lines.length === 0) {
|
|
77
|
-
cli.log("migrate-suite: nothing to change");
|
|
78
|
-
return 0;
|
|
79
|
-
}
|
|
80
|
-
cli.log(lines.map((line) => (line.startsWith(" ") ? line : `migrate-suite: ${line}`)).join("\n"));
|
|
81
|
-
let code = 0;
|
|
82
|
-
// A new package, or a new exemption from the release-age hold, takes an install to settle the lockfile.
|
|
83
|
-
if (packages.added.length > 0 || workspace.text !== undefined) {
|
|
84
|
-
// In CI pnpm defaults to a frozen lockfile, which the packages just added would fail.
|
|
85
|
-
({ code } = await cli.exec("pnpm", ["--dir", cli.cwd, "install", "--no-frozen-lockfile"], {
|
|
86
|
-
inherit: true,
|
|
87
|
-
}));
|
|
88
|
-
if (code !== 0)
|
|
89
|
-
cli.error("migrate-suite: pnpm install failed; run it again in the app.");
|
|
90
|
-
}
|
|
91
|
-
return code;
|
|
92
|
-
}
|
|
93
|
-
function parseArgs(args) {
|
|
94
|
-
if (args.length === 0)
|
|
95
|
-
return undefined;
|
|
96
|
-
if (args.length === 2 && args[0] === "--expect" && args[1])
|
|
97
|
-
return args[1];
|
|
98
|
-
throw new CliError("usage: stack migrate-suite [--expect <version>]");
|
|
99
|
-
}
|
|
100
|
-
/** TypeScript is a peer, loaded only here, so the other commands run without it. */
|
|
101
|
-
async function loadTypeScript() {
|
|
102
|
-
try {
|
|
103
|
-
return (await import("typescript")).default;
|
|
104
|
-
}
|
|
105
|
-
catch {
|
|
106
|
-
throw new CliError("migrate-suite needs typescript, a peer of @wwchen/stack: install it.");
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* The app's package.json with every suite package the installed stack depends on, sorted in among `dependencies`; nothing else moves. Each is added at the stack's version, or at the app's own `workspace:` spec for the stack when it takes the stack from its workspace.
|
|
111
|
-
*/
|
|
112
|
-
function addPackages(text) {
|
|
113
|
-
const pkg = JSON.parse(text);
|
|
114
|
-
const sections = [
|
|
115
|
-
"dependencies",
|
|
116
|
-
"devDependencies",
|
|
117
|
-
"peerDependencies",
|
|
118
|
-
"optionalDependencies",
|
|
119
|
-
].map((s) => pkg[s] ?? {});
|
|
120
|
-
const has = (name) => sections.some((section) => Object.hasOwn(section, name));
|
|
121
|
-
const stackSpec = sections.map((section) => section["@wwchen/stack"]).find(Boolean);
|
|
122
|
-
const spec = stackSpec?.startsWith("workspace:") ? stackSpec : STACK_PACKAGE.version;
|
|
123
|
-
const added = Object.keys(STACK_PACKAGE.dependencies)
|
|
124
|
-
.filter((name) => name.startsWith("@wwchen/stack-") && !has(name))
|
|
125
|
-
.sort();
|
|
126
|
-
if (added.length === 0)
|
|
127
|
-
return { text, added, spec };
|
|
128
|
-
const entries = Object.entries(pkg.dependencies ?? {});
|
|
129
|
-
for (const name of added) {
|
|
130
|
-
const at = entries.findIndex(([existing]) => existing > name);
|
|
131
|
-
entries.splice(at === -1 ? entries.length : at, 0, [name, spec]);
|
|
132
|
-
}
|
|
133
|
-
pkg.dependencies = Object.fromEntries(entries);
|
|
134
|
-
return { text: `${JSON.stringify(pkg, null, 2)}\n`, added, spec };
|
|
135
|
-
}
|
|
136
|
-
/** `@wwchen/stack` and every `@wwchen/stack-*` package the app's package.json names, sorted. */
|
|
137
|
-
function suitePackages(pkgText) {
|
|
138
|
-
const pkg = JSON.parse(pkgText);
|
|
139
|
-
const names = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]
|
|
140
|
-
.flatMap((s) => Object.keys(pkg[s] ?? {}))
|
|
141
|
-
.filter((name) => name === STACK_PACKAGE_NAME || name.startsWith(`${STACK_PACKAGE_NAME}-`));
|
|
142
|
-
return [...new Set(names)].sort();
|
|
143
|
-
}
|
|
144
|
-
/** A single-line scalar and an optional comment after it; undefined for anything else (an anchor, an alias, a nested collection). */
|
|
145
|
-
function readScalar(raw) {
|
|
146
|
-
const text = raw.trim();
|
|
147
|
-
const double = /^"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$/.exec(text);
|
|
148
|
-
if (double)
|
|
149
|
-
return { value: double[1], quote: '"' };
|
|
150
|
-
const single = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(text);
|
|
151
|
-
if (single)
|
|
152
|
-
return { value: single[1].replace(/''/g, "'"), quote: "'" };
|
|
153
|
-
const plain = /^([^\s#&*!|>[\]{},'"%@`-][^#]*?|-[^\s#][^#]*?)(?:\s+#.*)?$/.exec(text);
|
|
154
|
-
return plain ? { value: plain[1], quote: "" } : undefined;
|
|
155
|
-
}
|
|
156
|
-
/** Whether an exemption names a package: exactly, or by a `*` pattern (`@scope/*`). */
|
|
157
|
-
const exempts = (entry, name) => entry === name ||
|
|
158
|
-
(entry.includes("*") &&
|
|
159
|
-
new RegExp(`^${entry.split("*").map(escapeRegExp).join(".*")}$`).test(name));
|
|
160
|
-
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
161
|
-
/**
|
|
162
|
-
* pnpm-workspace.yaml with every suite package in `minimumReleaseAgeExclude`, so an upgrade installs a release on the day it ships: missing names go in after the list's last `@wwchen/` entry (or its end), quoted and indented as its items are. Where only `minimumReleaseAge` is set, the key is added after it. Nothing where neither key is set (no name is exempt from the hold), the hold is off, or there is no file; the names to add when the key holds something else.
|
|
163
|
-
*/
|
|
164
|
-
function releaseAgeEdit(text, names) {
|
|
165
|
-
const none = { added: [], manual: [] };
|
|
166
|
-
if (text === undefined || names.length === 0)
|
|
167
|
-
return none;
|
|
168
|
-
const lines = text.split("\n");
|
|
169
|
-
const quoted = (name, quote) => `${quote || '"'}${name}${quote || '"'}`;
|
|
170
|
-
const keyAt = lines.findIndex((line) => line.startsWith(`${RELEASE_AGE_EXCLUDE}:`));
|
|
171
|
-
if (keyAt === -1) {
|
|
172
|
-
const ageAt = lines.findIndex((line) => /^minimumReleaseAge\s*:/.test(line));
|
|
173
|
-
const age = ageAt === -1 ? undefined : lines[ageAt].replace(/^[^:]*:|#.*$/g, "");
|
|
174
|
-
if (age === undefined || /^\s*0*\s*$/.test(age))
|
|
175
|
-
return none;
|
|
176
|
-
const block = [`${RELEASE_AGE_EXCLUDE}:`, ...names.map((name) => ` - ${quoted(name, '"')}`)];
|
|
177
|
-
lines.splice(ageAt + 1, 0, ...block);
|
|
178
|
-
return { text: lines.join("\n"), added: names, manual: [] };
|
|
179
|
-
}
|
|
180
|
-
const unreadable = {
|
|
181
|
-
added: [],
|
|
182
|
-
manual: [
|
|
183
|
-
`${WORKSPACE}'s ${RELEASE_AGE_EXCLUDE} is not a list migrate-suite can read; add these to it by hand, or a release of them is held for a day:`,
|
|
184
|
-
...names.map((name) => ` - ${quoted(name, '"')}`),
|
|
185
|
-
],
|
|
186
|
-
};
|
|
187
|
-
const keyLine = lines[keyAt];
|
|
188
|
-
const rest = keyLine.slice(RELEASE_AGE_EXCLUDE.length + 1);
|
|
189
|
-
const missingFrom = (entries) => names.filter((name) => !entries.some((entry) => exempts(entry.value, name)));
|
|
190
|
-
/** Where the new names go: after the last `@wwchen/` entry, else after the last entry. */
|
|
191
|
-
const insertAfter = (entries) => {
|
|
192
|
-
const at = entries.findLastIndex((entry) => entry.value.startsWith("@wwchen/"));
|
|
193
|
-
return at === -1 ? entries.length - 1 : at;
|
|
194
|
-
};
|
|
195
|
-
// A flow list on the key's line: `[a, "b"]`.
|
|
196
|
-
const flow = /^(\s*\[)(.*)\](\s*(?:#.*)?)$/.exec(rest);
|
|
197
|
-
if (flow) {
|
|
198
|
-
const inner = flow[2];
|
|
199
|
-
const pieces = inner.trim() === "" ? [] : inner.split(",");
|
|
200
|
-
const entries = pieces.map(readScalar);
|
|
201
|
-
if (entries.some((entry) => entry === undefined))
|
|
202
|
-
return unreadable;
|
|
203
|
-
const read = entries;
|
|
204
|
-
const missing = missingFrom(read);
|
|
205
|
-
if (missing.length === 0)
|
|
206
|
-
return none;
|
|
207
|
-
const quote = read.at(-1)?.quote ?? '"';
|
|
208
|
-
const list = missing.map((name) => quoted(name, quote)).join(", ");
|
|
209
|
-
let rewritten;
|
|
210
|
-
if (pieces.length === 0) {
|
|
211
|
-
rewritten = list;
|
|
212
|
-
}
|
|
213
|
-
else {
|
|
214
|
-
const after = insertAfter(read);
|
|
215
|
-
const end = pieces
|
|
216
|
-
.slice(0, after + 1)
|
|
217
|
-
.join(",")
|
|
218
|
-
.trimEnd().length;
|
|
219
|
-
rewritten = `${inner.slice(0, end)}, ${list}${inner.slice(end)}`;
|
|
220
|
-
}
|
|
221
|
-
lines[keyAt] = `${RELEASE_AGE_EXCLUDE}:${flow[1]}${rewritten}]${flow[3]}`;
|
|
222
|
-
return { text: lines.join("\n"), added: missing, manual: [] };
|
|
223
|
-
}
|
|
224
|
-
if (!/^\s*(#.*)?$/.test(rest))
|
|
225
|
-
return unreadable;
|
|
226
|
-
// A block list under the key: `- item` lines, with blank and comment lines among them.
|
|
227
|
-
const items = [];
|
|
228
|
-
for (let at = keyAt + 1; at < lines.length; at++) {
|
|
229
|
-
const line = lines[at];
|
|
230
|
-
if (/^\s*(#.*)?$/.test(line))
|
|
231
|
-
continue;
|
|
232
|
-
const item = /^(\s*)-\s+(.*)$/.exec(line);
|
|
233
|
-
if (!item) {
|
|
234
|
-
// An indented line that is not an item belongs to the value: something this cannot read.
|
|
235
|
-
if (/^\s/.test(line))
|
|
236
|
-
return unreadable;
|
|
237
|
-
break;
|
|
238
|
-
}
|
|
239
|
-
const scalar = readScalar(item[2]);
|
|
240
|
-
if (!scalar || (items[0] && items[0].indent !== item[1]))
|
|
241
|
-
return unreadable;
|
|
242
|
-
items.push({ at, indent: item[1], scalar });
|
|
243
|
-
}
|
|
244
|
-
const read = items.map((item) => item.scalar);
|
|
245
|
-
const missing = missingFrom(read);
|
|
246
|
-
if (missing.length === 0)
|
|
247
|
-
return none;
|
|
248
|
-
const last = items[insertAfter(read)];
|
|
249
|
-
const indent = last?.indent ?? " ";
|
|
250
|
-
const quote = items.at(-1)?.scalar.quote ?? '"';
|
|
251
|
-
lines.splice((last?.at ?? keyAt) + 1, 0, ...missing.map((name) => `${indent}- ${quoted(name, quote)}`));
|
|
252
|
-
return { text: lines.join("\n"), added: missing, manual: [] };
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Sorts the imports of the files just rewritten with the app's own Biome, its formatter and linter off: a moved specifier can sort differently (`@wwchen/stack/ui` before `@wwchen/stack-auth`), and the app's lint checks the order. Skipped when the app has no Biome; false when Biome failed.
|
|
256
|
-
*/
|
|
257
|
-
async function sortImports(cli, paths) {
|
|
258
|
-
if (paths.length === 0)
|
|
259
|
-
return true;
|
|
260
|
-
if (!existsSync(join(cli.cwd, "node_modules", "@biomejs", "biome", "package.json")))
|
|
261
|
-
return true;
|
|
262
|
-
const { code } = await cli.exec("pnpm", [
|
|
263
|
-
"--dir",
|
|
264
|
-
cli.cwd,
|
|
265
|
-
"exec",
|
|
266
|
-
"biome",
|
|
267
|
-
"check",
|
|
268
|
-
"--write",
|
|
269
|
-
"--formatter-enabled=false",
|
|
270
|
-
"--linter-enabled=false",
|
|
271
|
-
"--no-errors-on-unmatched",
|
|
272
|
-
"--files-ignore-unknown=true",
|
|
273
|
-
...paths.sort().map((path) => join(cli.cwd, path)),
|
|
274
|
-
]);
|
|
275
|
-
return code === 0;
|
|
276
|
-
}
|
|
277
|
-
const SOURCE = /\.(ts|tsx|mts)$/;
|
|
278
|
-
const SKIPPED_DIRS = new Set(["node_modules", ".next", "dist"]);
|
|
279
|
-
/** The app's TypeScript files, relative to its root: those git tracks, or, outside a repository, every one outside dependencies and build output. */
|
|
280
|
-
async function sourceFiles(cli) {
|
|
281
|
-
const isSource = (path) => SOURCE.test(path) &&
|
|
282
|
-
!path.split("/").includes("node_modules") &&
|
|
283
|
-
existsSync(join(cli.cwd, path));
|
|
284
|
-
if (!insideGit(cli.cwd))
|
|
285
|
-
return walk(cli.cwd).filter(isSource);
|
|
286
|
-
const { stdout, code } = await cli.exec("git", ["-C", cli.cwd, "ls-files", "-z"]);
|
|
287
|
-
if (code !== 0)
|
|
288
|
-
throw new CliError(`migrate-suite: git ls-files failed in ${cli.cwd}`);
|
|
289
|
-
return stdout.split("\0").filter(Boolean).filter(isSource);
|
|
290
|
-
}
|
|
291
|
-
function insideGit(dir) {
|
|
292
|
-
for (let at = dir;; at = dirname(at)) {
|
|
293
|
-
if (existsSync(join(at, ".git")))
|
|
294
|
-
return true;
|
|
295
|
-
if (dirname(at) === at)
|
|
296
|
-
return false;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
function walk(root, dir = root) {
|
|
300
|
-
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
301
|
-
const path = join(dir, entry.name);
|
|
302
|
-
if (entry.isDirectory())
|
|
303
|
-
return SKIPPED_DIRS.has(entry.name) ? [] : walk(root, path);
|
|
304
|
-
return entry.isFile() ? [relative(root, path).split(sep).join("/")] : [];
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
function parse(ts, path, text) {
|
|
308
|
-
const kind = path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
|
309
|
-
return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);
|
|
310
|
-
}
|
|
311
|
-
function applyEdits(text, edits) {
|
|
312
|
-
let out = text;
|
|
313
|
-
for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
|
|
314
|
-
out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
|
|
315
|
-
}
|
|
316
|
-
return out;
|
|
317
|
-
}
|
|
318
|
-
const newlines = (text) => text.split("\n").length - 1;
|
|
319
|
-
/** Moves every import and export specifier (static, dynamic, `import type`, `import x = require`) off the old paths. Comments and other strings are never changed; a string that is exactly an old path is pointed out. */
|
|
320
|
-
function moveImports(ts, path, text) {
|
|
321
|
-
const sf = parse(ts, path, text);
|
|
322
|
-
const edits = [];
|
|
323
|
-
const specifiers = new Set();
|
|
324
|
-
const pending = [];
|
|
325
|
-
let usesMagic;
|
|
326
|
-
const mentionsMagic = () => {
|
|
327
|
-
usesMagic ??= hasIdentifier(ts, sf, MAGIC);
|
|
328
|
-
return usesMagic;
|
|
329
|
-
};
|
|
330
|
-
const replace = (literal, to) => edits.push({ start: literal.getStart(sf) + 1, end: literal.end - 1, text: to });
|
|
331
|
-
/** A specifier that brings in the module whole (namespace, dynamic, `require`, type query). */
|
|
332
|
-
const whole = (literal) => {
|
|
333
|
-
const to = MOVED.get(literal.text);
|
|
334
|
-
if (!to)
|
|
335
|
-
return;
|
|
336
|
-
if (literal.text === MAIL && mentionsMagic()) {
|
|
337
|
-
pending.push({
|
|
338
|
-
pos: literal.getStart(sf),
|
|
339
|
-
note: (line) => `${path}:${line}: "${MAIL}" is imported whole and the file uses ${MAGIC}; left as is. Import ${MAGIC} from "${AUTH}" and the rest from "${NOTIFY}".`,
|
|
340
|
-
});
|
|
341
|
-
return;
|
|
342
|
-
}
|
|
343
|
-
replace(literal, to);
|
|
344
|
-
};
|
|
345
|
-
const visit = (node) => {
|
|
346
|
-
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
|
|
347
|
-
node.moduleSpecifier &&
|
|
348
|
-
ts.isStringLiteral(node.moduleSpecifier)) {
|
|
349
|
-
specifiers.add(node.moduleSpecifier);
|
|
350
|
-
const literal = node.moduleSpecifier;
|
|
351
|
-
if (literal.text !== MAIL) {
|
|
352
|
-
const to = MOVED.get(literal.text);
|
|
353
|
-
if (to)
|
|
354
|
-
replace(literal, to);
|
|
355
|
-
}
|
|
356
|
-
else {
|
|
357
|
-
const split = splitMail(ts, sf, node);
|
|
358
|
-
if (split === "whole")
|
|
359
|
-
whole(literal);
|
|
360
|
-
else
|
|
361
|
-
edits.push(split);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
else if (ts.isImportEqualsDeclaration(node) &&
|
|
365
|
-
ts.isExternalModuleReference(node.moduleReference) &&
|
|
366
|
-
ts.isStringLiteralLike(node.moduleReference.expression)) {
|
|
367
|
-
specifiers.add(node.moduleReference.expression);
|
|
368
|
-
whole(node.moduleReference.expression);
|
|
369
|
-
}
|
|
370
|
-
else if (ts.isCallExpression(node) &&
|
|
371
|
-
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
372
|
-
node.arguments[0] &&
|
|
373
|
-
ts.isStringLiteralLike(node.arguments[0])) {
|
|
374
|
-
specifiers.add(node.arguments[0]);
|
|
375
|
-
whole(node.arguments[0]);
|
|
376
|
-
}
|
|
377
|
-
else if (ts.isImportTypeNode(node) &&
|
|
378
|
-
ts.isLiteralTypeNode(node.argument) &&
|
|
379
|
-
ts.isStringLiteral(node.argument.literal)) {
|
|
380
|
-
specifiers.add(node.argument.literal);
|
|
381
|
-
whole(node.argument.literal);
|
|
382
|
-
}
|
|
383
|
-
else if (ts.isCallExpression(node) &&
|
|
384
|
-
ts.isPropertyAccessExpression(node.expression) &&
|
|
385
|
-
ts.isIdentifier(node.expression.expression) &&
|
|
386
|
-
node.expression.expression.text === "vi" &&
|
|
387
|
-
VI_MODULE_CALLS.has(node.expression.name.text) &&
|
|
388
|
-
node.arguments[0] &&
|
|
389
|
-
ts.isStringLiteralLike(node.arguments[0])) {
|
|
390
|
-
specifiers.add(node.arguments[0]);
|
|
391
|
-
whole(node.arguments[0]);
|
|
392
|
-
}
|
|
393
|
-
else if (ts.isStringLiteralLike(node) && !specifiers.has(node) && MOVED.has(node.text)) {
|
|
394
|
-
const { text: name } = node;
|
|
395
|
-
pending.push({
|
|
396
|
-
pos: node.getStart(sf),
|
|
397
|
-
note: (line) => `${path}:${line}: a string names "${name}" outside an import; if it names the module, change it to "${MOVED.get(name)}"`,
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
ts.forEachChild(node, visit);
|
|
401
|
-
};
|
|
402
|
-
visit(sf);
|
|
403
|
-
// A note's line is counted in the file as rewritten.
|
|
404
|
-
const lineAfterEdits = (pos) => sf.getLineAndCharacterOfPosition(pos).line +
|
|
405
|
-
1 +
|
|
406
|
-
edits
|
|
407
|
-
.filter((edit) => edit.end <= pos)
|
|
408
|
-
.reduce((sum, edit) => sum + newlines(edit.text) - newlines(text.slice(edit.start, edit.end)), 0);
|
|
409
|
-
const notes = pending
|
|
410
|
-
.sort((a, b) => a.pos - b.pos)
|
|
411
|
-
.map(({ pos, note }) => note(lineAfterEdits(pos)));
|
|
412
|
-
return { text: applyEdits(text, edits), notes };
|
|
413
|
-
}
|
|
414
|
-
function hasIdentifier(ts, sf, name) {
|
|
415
|
-
const visit = (node) => (ts.isIdentifier(node) && node.text === name) || (ts.forEachChild(node, visit) ?? false);
|
|
416
|
-
return visit(sf);
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* An import or export of `@wwchen/stack/mail` as one edit: `waitForMagicLink` from auth, the rest from notify, split in two declarations when it names both. `"whole"` for a namespace import or export, which names nothing.
|
|
420
|
-
*/
|
|
421
|
-
function splitMail(ts, sf, decl) {
|
|
422
|
-
const literal = decl.moduleSpecifier;
|
|
423
|
-
const start = decl.getStart(sf);
|
|
424
|
-
const original = sf.text.slice(start, decl.end);
|
|
425
|
-
const at = (node) => node.getStart(sf) - start;
|
|
426
|
-
const specifier = (to) => ({
|
|
427
|
-
start: at(literal) + 1,
|
|
428
|
-
end: literal.end - start - 1,
|
|
429
|
-
text: to,
|
|
430
|
-
});
|
|
431
|
-
const indent = sf.text.slice(sf.text.lastIndexOf("\n", start - 1) + 1, start);
|
|
432
|
-
const whole = (to) => ({
|
|
433
|
-
start,
|
|
434
|
-
end: decl.end,
|
|
435
|
-
text: applyEdits(original, [specifier(to)]),
|
|
436
|
-
});
|
|
437
|
-
let named;
|
|
438
|
-
let defaultName;
|
|
439
|
-
if (ts.isImportDeclaration(decl)) {
|
|
440
|
-
const clause = decl.importClause;
|
|
441
|
-
if (!clause)
|
|
442
|
-
return whole(NOTIFY);
|
|
443
|
-
if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
|
|
444
|
-
return "whole";
|
|
445
|
-
named = clause.namedBindings;
|
|
446
|
-
defaultName = clause.name;
|
|
447
|
-
}
|
|
448
|
-
else if (!decl.exportClause) {
|
|
449
|
-
// `export *` re-exports every name mail did: notify's, and waitForMagicLink from auth.
|
|
450
|
-
const magic = applyEdits(original, [
|
|
451
|
-
{
|
|
452
|
-
start: 0,
|
|
453
|
-
end: at(literal),
|
|
454
|
-
text: `export ${decl.isTypeOnly ? "type " : ""}{ ${MAGIC} } from `,
|
|
455
|
-
},
|
|
456
|
-
specifier(AUTH),
|
|
457
|
-
]);
|
|
458
|
-
return {
|
|
459
|
-
start,
|
|
460
|
-
end: decl.end,
|
|
461
|
-
text: `${magic}\n${indent}${applyEdits(original, [specifier(NOTIFY)])}`,
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
else if (ts.isNamespaceExport(decl.exportClause)) {
|
|
465
|
-
return "whole";
|
|
466
|
-
}
|
|
467
|
-
else {
|
|
468
|
-
named = decl.exportClause;
|
|
469
|
-
}
|
|
470
|
-
const elements = [...(named?.elements ?? [])];
|
|
471
|
-
const magic = elements.filter((e) => (e.propertyName ?? e.name).text === MAGIC);
|
|
472
|
-
const rest = elements.filter((e) => !magic.includes(e));
|
|
473
|
-
if (magic.length === 0)
|
|
474
|
-
return whole(NOTIFY);
|
|
475
|
-
if (!named || (rest.length === 0 && !defaultName))
|
|
476
|
-
return whole(AUTH);
|
|
477
|
-
// The names between the braces, first to last.
|
|
478
|
-
const names = {
|
|
479
|
-
start: at(elements[0]),
|
|
480
|
-
end: elements.at(-1).end - start,
|
|
481
|
-
};
|
|
482
|
-
const list = (picked) => picked.map((e) => e.getText(sf)).join(", ");
|
|
483
|
-
const authPart = applyEdits(original, [
|
|
484
|
-
// `import x, { waitForMagicLink }` keeps the default import with the rest.
|
|
485
|
-
...(defaultName ? [{ start: at(defaultName), end: at(named), text: "" }] : []),
|
|
486
|
-
{ ...names, text: list(magic) },
|
|
487
|
-
specifier(AUTH),
|
|
488
|
-
]);
|
|
489
|
-
const notifyPart = applyEdits(original, [{ ...names, text: list(rest) }, specifier(NOTIFY)]);
|
|
490
|
-
return { start, end: decl.end, text: `${authPart}\n${indent}${notifyPart}` };
|
|
491
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { type Cli } from "./context.ts";
|
|
2
|
-
export declare function userCreate(cli: Cli, args: string[]): Promise<number>;
|
|
3
|
-
/**
|
|
4
|
-
* `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
|
|
5
|
-
*/
|
|
6
|
-
export declare function userRole(cli: Cli, args: string[]): Promise<number>;
|