Skip to content

Commit 0f0b9f5

Browse files
fix(create-objectstack): refuse a project name npm would refuse, before writing anything (#26796)
Fixes #26642 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么:** `create-objectstack` 在写任何文件之前,先用 npm 自己的包名规则检查项目名(参数,或无参数时的当前目录名);不合法就退出 1,打印 npm 的拒绝理由、规则和一个建议名(`My App!` 与 `MyApp` 都建议 `my-app`)。名字永不被悄悄改写。 - **为什么改:** 以前 `"My App!"` 原样写进 `package.json` 和 manifest,`validate`、`build` 都通过,直到 `npm publish` 才被拒,离原因很远。 - **风险与回滚:** 新增一个运行时依赖 `validate-npm-package-name`(npm 自己用的判定模块,零依赖,锁文件里本来就有 7.0.2);以前能"成功"的非法名(包括 `./my-app` 这种路径写法)现在会被拒。回滚即 revert 本 PR。 - **先看:** ① `packages/create-objectstack/src/index.ts` 中 `checkProjectName` 的接线(必须在第一次写盘之前);② `src/package-name.ts`(判定与建议名);③ `package.json` 与 `pnpm-lock.yaml` 的新依赖。 - **两分钟验证:** 在空目录跑 `node packages/create-objectstack/bin/create-objectstack.js "My App!" --skip-install --skip-skills; echo $?`,预期看到规则与 `Suggested name: create-objectstack my-app`,退出码 1,目录里没有任何新文件。 - **需要你做的:** 无,席位落地。 ## What changes - **New `src/package-name.ts`.** `checkProjectName(name)` returns npm's own verdict for a NEW package (`validate-npm-package-name`'s `validForNewPackages`), with npm's reasons verbatim. `suggestPackageName(name)` derives a slug (`My App!` and `MyApp` give `my-app`, `@Acme/My App` gives `@acme/my-app`, combining marks are dropped) and returns nothing when the slug is empty or would itself be refused (`HTTP` slugs to the core module name `http`), so a refusal never recommends a name it would refuse next. `describeInvalidProjectName` renders the refusal: the headline, npm's reasons, the rule in one sentence, and the re-run line. - **`src/index.ts`.** The check runs on the resolved `projectName` (so the no-argument, current-directory branch is covered too) right after it is resolved and before the first write. A refused name exits 1. In the current-directory case the remedy says the name came from the directory: rename it, or scaffold into a new directory with an explicit name. - **Why a dependency rather than a local rule set.** The defect is "npm refuses this name", so the predicate is npm's own module rather than a restated copy that can drift from it. It is small, has no dependencies, and was already in the lockfile at 7.0.2 (through `shadcn`), so no new package enters the install graph. `@types/validate-npm-package-name` is a dev dependency for the typecheck. The lockfile diff is only the two importer entries: `pnpm add` also re-picked an unrelated `jsdom` peer in two snapshot keys, and that churn was reverted by hand (`pnpm install --frozen-lockfile` exits 0 on the result). - **No prompt path exists.** `create-objectstack` has no interactive prompt, so the refusal is the only path. Nothing is rewritten: the written value is always what the user typed. - One `patch` changeset, `.changeset/26642-npm-name-check.md`. ## Tests New `src/package-name.test.ts` (32 tests): - predicate: accepts `my-app`, `@scope/my-app`, `my.app`, `a_b`, `app2`, `x`; refuses `My App!`, `MyApp`, `HTTP`, `http`, `.hidden`, `_private`, a leading space, `node_modules`, `apps/my-app` and a 215-character name, each naming npm's reason; - slug: the expected slug per input, none for `HTTP` and `!!!`, and every slug it does return passes `validForNewPackages`; - the real CLI under `tsx`: `My App!` and `MyApp` exit 1, print the rule and `Suggested name: create-objectstack my-app`, and leave the temp directory empty; a current directory named `My App` exits 1 and stays empty; control legs: `my-app` and `@scope/my-app` exit 0 and write the name verbatim to `package.json` and `objectstack.manifest.json`. Ablation (the refusal pins can fail): `node scripts/ablation-replace.mjs` replaced `if (!nameVerdict.valid) {` with `if (false && !nameVerdict.valid) {` in `index.ts` (anchor 1 to 0, blob `625a2dc9` to `9824e843`), and the three CLI refusal legs went red while the control legs stayed green. The tool then restored the file (blob equal to HEAD, `git diff HEAD` empty). <details><summary>Ablation run (excerpt)</summary> ```text ablation-replace: ok mutation landed: anchor 1 -> 0, blob 625a2dc -> 9824e843117f × "My App!": exit 1, the rule, the slug, and no directory 740ms × "MyApp": exit 1, the rule, the slug, and no directory 721ms × the current directory's name is checked too, and the directory stays empty 681ms AssertionError: expected +0 to be 1 // Object.is equality Test Files 1 failed (1) Tests 3 failed | 29 passed (32) ablation-replace: ok restored: blob == HEAD (625a2dc) and `git diff HEAD` is empty ``` </details> <details><summary>Package build, typecheck, full test suite at 0108d0c</summary> ```text pnpm --workspace-concurrency=2 --filter 'create-objectstack^...' build -> VERDICT command-exit 0 pnpm --filter create-objectstack build && pnpm --filter create-objectstack typecheck && pnpm --filter create-objectstack exec vitest run --maxWorkers=2 ESM ⚡️ Build success in 34ms DTS ⚡️ Build success in 856ms > tsc --noEmit Test Files 19 passed (19) Tests 301 passed (301) os-verify-lock: VERDICT command-exit 0 ``` The built `dist/index.js` keeps `validate-npm-package-name` external (`import validateNpmPackageName from "validate-npm-package-name"`), and `node bin/create-objectstack.js "My App!"` exits 1 with the refusal, while `my-app` exits 0 with `"name": "my-app"`. </details> ## Acceptance notes - **Path-shaped names are now refused.** `create-objectstack ./my-app` or `apps/my-app` used to write that string (an illegal package name) into `package.json`; it is now refused with the slug (`my-app`, `apps-my-app`). The `[name]` argument is documented as a name, not a path. - **The sibling scaffolder keeps its own rule set.** `os init` (`packages/cli/src/commands/init.ts`, `validateProjectName`) already refuses before writing, with a hand-written subset of npm's rules: it refuses scoped names and does not refuse core module names such as `http`, and it suggests no slug. The two scaffolders therefore answer differently for `@scope/my-app` and `http`. Recorded only; no wrong answer from `os init` was measured here. - `test:repo` (the vitest `repo` project) was not run locally; it belongs to CI's `Test Core`. ## Verification Gate families derived from the diff (`node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`, no paths, at `0108d0c2`): 71 commands. 68 exit 0. 3 are NOT MEASURED (exit 3, PREREQUISITE NOT MET), and CI's `Lint & Repo Gates` runs them on a full build: - `pnpm check:dual-build-cjs-loads` and `pnpm check:lean-entry-closure` need every package's `dist`, and only `create-objectstack` and its closure were built; - `node scripts/check-plugin-teardown-shape.mjs --self-test` needs an unshallowed clone (checker health only). `--ran` reconciliation with recorded exit codes: `71 derived famil(ies) accounted for — 68 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3)`. `pnpm exec eslint` on the three changed source files exits 0. The control-byte scan of the new files is clean, and `check:nul-bytes` is OK. <details><summary>Selected gate verdict lines</summary> ```text ✓ check:published-files — 73 publishable package(s) of 85 workspace member(s) declare a `files` whitelist ... ✓ check:undeclared-dep-imports: 129 workspace packages ... 3 ledger row(s), all evidence intact. ✓ 65 published-manifest declaration(s) covered by pnpm-workspace.yaml overrides all resolve to their override targets. ✓ check-adr-0087-registration: this PR adds no declared-breaking changeset (1 non-breaking changeset(s) seen). ✓ No empty-frontmatter changeset introduced by this diff (1 declaring changeset(s) added). ✓ This diff introduces no `major` bump. ✓ .changeset/config.json "fixed" group is in sync with 109 public workspace packages and 1 declared private member(s). check-nul-bytes: OK (scanned 21457 text file(s) ...; no raw ASCII control bytes). ``` </details> Durable attribution: written by an os-dev agent in session `session_01QSeKYmQXM3rHJcPnrEPk4B`, dispatched by the PM loop (seat `domain:server#3`). --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYmQXM3rHJcPnrEPk4B)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8b27638 commit 0f0b9f5

6 files changed

Lines changed: 342 additions & 1 deletion

File tree

‎.changeset/26642-npm-name-check.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'create-objectstack': patch
3+
---
4+
5+
fix(create-objectstack): a project name npm would refuse is refused before anything is written, with the rule and a suggested name
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`create-objectstack "My App!"` (or `MyApp`, or no argument inside a directory called `My App`) used to write that name verbatim into `package.json` and `objectstack.manifest.json`. `validate` and `build` passed, and the first refusal came from npm at `npm publish`.
11+
12+
The resolved project name (the argument, or the current directory's name when there is none) is now checked against npm's rules for a new package name, using `validate-npm-package-name` (the module npm itself uses), before the first file is written. A refused name exits 1 and prints npm's reasons, the rule, and a suggested name (`My App!` and `MyApp` both suggest `my-app`). The name is never rewritten for you: re-run with the suggested name or one of your own. Names npm accepts, such as `my-app` and `@scope/my-app`, scaffold as before.
13+
14+
`create-objectstack` gains one runtime dependency, `validate-npm-package-name`.

‎packages/create-objectstack/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,13 @@
3333
"license": "Apache-2.0",
3434
"dependencies": {
3535
"chalk": "^6.0.1",
36-
"commander": "^15.0.0"
36+
"commander": "^15.0.0",
37+
"validate-npm-package-name": "^7.0.2"
3738
},
3839
"devDependencies": {
3940
"@objectstack/spec": "workspace:*",
4041
"@types/node": "^26.6.3",
42+
"@types/validate-npm-package-name": "^4.0.2",
4143
"tsup": "^8.5.1",
4244
"typescript": "^6.0.3",
4345
"vitest": "^4.1.11",

‎packages/create-objectstack/src/index.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@
1717
* `template-registry.ts` still names them, so `-t todo` refuses with an
1818
* explanation instead of a bare "unknown template".
1919
*
20+
* Before anything is written, the resolved project name (the `[name]`
21+
* argument, or the current directory's basename) is checked against npm's
22+
* package-name rules, and a name npm would refuse is refused here — with the
23+
* rule and a suggested slug, never a silent rewrite (package-name.ts).
24+
*
2025
* After the files land in `targetDir`, four files are rewritten with the
2126
* user-supplied project name:
2227
* - package.json .name
@@ -90,6 +95,7 @@ import {
9095
skillsSyncedFromPackage,
9196
} from './skills-install.js';
9297
import { renderVersionBanner } from './banner.js';
98+
import { checkProjectName, describeInvalidProjectName } from './package-name.js';
9399

94100
const __filename = fileURLToPath(import.meta.url);
95101
const __dirname = path.dirname(__filename);
@@ -500,6 +506,22 @@ const program = new Command()
500506

501507
const cwd = process.cwd();
502508
const projectName = name || path.basename(cwd);
509+
510+
// Refused BEFORE anything touches the disk: the name is written verbatim
511+
// into package.json and objectstack.manifest.json, and npm is the first to
512+
// refuse a name like `My App!` — at publish, far from here. Never
513+
// normalised silently: the user re-runs with the slug, or a name of their
514+
// own (package-name.ts carries the why).
515+
const nameVerdict = checkProjectName(projectName);
516+
if (!nameVerdict.valid) {
517+
const [headline, ...detail] = describeInvalidProjectName(projectName, nameVerdict, {
518+
fromDirectory: !name,
519+
});
520+
printError(headline);
521+
for (const line of detail) console.log(chalk.dim(` ${line}`));
522+
process.exit(1);
523+
}
524+
503525
const namespace = sanitizeNamespace(projectName);
504526
const targetDir = name ? path.resolve(cwd, name) : cwd;
505527
const isCurrentDir = targetDir === cwd;
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license.
2+
//
3+
// The project name is refused BEFORE anything is written when npm would refuse
4+
// it as a package name — with the rule stated and a suggested slug, and never
5+
// a silent rewrite. Two layers:
6+
//
7+
// - the predicate and the slug (package-name.ts), imported directly;
8+
// - the wiring, through the real CLI under `tsx` (index.ts calls
9+
// `program.parse()` on import, so it cannot be imported — the same
10+
// no-build subprocess pattern scaffold-description.test.ts uses). This is
11+
// the layer that proves the refusal happens before the first write: the
12+
// verdict is the exit code, the message, and an untouched directory.
13+
//
14+
// The legal-name legs are the control: a check that refused everything would
15+
// pass every refusal leg, and only `my-app` / `@scope/my-app` scaffolding as
16+
// before tells the two apart.
17+
18+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
19+
import { execFileSync } from 'node:child_process';
20+
import fs from 'node:fs';
21+
import os from 'node:os';
22+
import path from 'node:path';
23+
import { fileURLToPath } from 'node:url';
24+
import validateNpmPackageName from 'validate-npm-package-name';
25+
import {
26+
NPM_NAME_RULE,
27+
checkProjectName,
28+
describeInvalidProjectName,
29+
suggestPackageName,
30+
} from './package-name.js';
31+
32+
const HERE = path.dirname(fileURLToPath(import.meta.url));
33+
const PKG_ROOT = path.resolve(HERE, '..');
34+
const REPO_ROOT = path.resolve(PKG_ROOT, '..', '..');
35+
const TSX = path.join(REPO_ROOT, 'node_modules', '.bin', 'tsx');
36+
const INDEX_TS = path.join(PKG_ROOT, 'src', 'index.ts');
37+
38+
describe('checkProjectName — npm\'s rule for a NEW package', () => {
39+
it.each(['my-app', '@scope/my-app', 'my.app', 'a_b', 'app2', 'x'])('accepts %s', (name) => {
40+
expect(checkProjectName(name)).toEqual({ valid: true });
41+
});
42+
43+
it.each([
44+
['My App!', /URL-friendly/],
45+
['MyApp', /capital letters/],
46+
['HTTP', /core module name/],
47+
['http', /core module name/],
48+
['.hidden', /start with a period/],
49+
['_private', /start with an underscore/],
50+
[' my-app', /leading or trailing spaces/],
51+
['node_modules', /not a valid package name/],
52+
['apps/my-app', /URL-friendly/],
53+
['a'.repeat(215), /214 characters/],
54+
])('refuses %j, naming npm\'s reason', (name, reason) => {
55+
const verdict = checkProjectName(name);
56+
expect(verdict.valid).toBe(false);
57+
if (verdict.valid) return;
58+
expect(verdict.reasons.join('; ')).toMatch(reason);
59+
});
60+
});
61+
62+
describe('suggestPackageName — the slug a refusal offers', () => {
63+
it.each([
64+
['My App!', 'my-app'],
65+
['MyApp', 'my-app'],
66+
['my app', 'my-app'],
67+
['@Acme/My App', '@acme/my-app'],
68+
['./my-app', 'my-app'],
69+
[' Support Desk ', 'support-desk'],
70+
['Ünïcode App', 'unicode-app'],
71+
])('%j -> %j', (name, slug) => {
72+
expect(suggestPackageName(name)).toBe(slug);
73+
});
74+
75+
it('suggests nothing rather than a name npm would refuse next', () => {
76+
// `HTTP` slugs to `http`, a core module name.
77+
expect(suggestPackageName('HTTP')).toBeUndefined();
78+
expect(suggestPackageName('!!!')).toBeUndefined();
79+
});
80+
81+
it('every suggestion it does make is a valid new package name', () => {
82+
for (const name of ['My App!', 'MyApp', '@Acme/My App', 'A'.repeat(300), '@X/' + 'B'.repeat(300), 'Ünïcode App']) {
83+
const slug = suggestPackageName(name);
84+
expect(slug, name).toBeDefined();
85+
expect(validateNpmPackageName(slug!).validForNewPackages, `${name} -> ${slug}`).toBe(true);
86+
}
87+
});
88+
});
89+
90+
describe('describeInvalidProjectName', () => {
91+
it('names the rule and the slug for a typed name', () => {
92+
const verdict = checkProjectName('My App!');
93+
if (verdict.valid) throw new Error('precondition: My App! is invalid');
94+
const lines = describeInvalidProjectName('My App!', verdict, { fromDirectory: false });
95+
expect(lines[0]).toContain('"My App!" is not a valid npm package name');
96+
expect(lines).toContain(NPM_NAME_RULE);
97+
expect(lines.join('\n')).toContain('create-objectstack my-app');
98+
});
99+
100+
it('for the current-directory name, says the name came from the directory', () => {
101+
const verdict = checkProjectName('My App');
102+
if (verdict.valid) throw new Error('precondition: My App is invalid');
103+
const lines = describeInvalidProjectName('My App', verdict, { fromDirectory: true });
104+
expect(lines[0]).toContain('current directory');
105+
expect(lines.join('\n')).toContain('Rename this directory to "my-app"');
106+
});
107+
});
108+
109+
// ─── The real CLI ──────────────────────────────────────────────────
110+
111+
let tmp: string;
112+
beforeEach(() => {
113+
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'create-objectstack-npm-name-'));
114+
});
115+
afterEach(() => fs.rmSync(tmp, { recursive: true, force: true }));
116+
117+
/** Run the CLI in `cwd`; never throws — the exit status is part of the verdict. */
118+
function run(cwd: string, args: string[]): { status: number; stdout: string } {
119+
try {
120+
const stdout = execFileSync(TSX, [INDEX_TS, ...args, '--skip-install', '--skip-skills'], {
121+
cwd,
122+
encoding: 'utf8',
123+
stdio: 'pipe',
124+
env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: '0' },
125+
});
126+
return { status: 0, stdout };
127+
} catch (error) {
128+
const e = error as { status?: number; stdout?: string };
129+
return { status: e.status ?? -1, stdout: e.stdout ?? '' };
130+
}
131+
}
132+
133+
describe('the CLI refuses an illegal project name before writing anything', () => {
134+
it.each(['My App!', 'MyApp'])('%j: exit 1, the rule, the slug, and no directory', (name) => {
135+
const { status, stdout } = run(tmp, [name]);
136+
expect(status).toBe(1);
137+
expect(stdout).toContain(`"${name}" is not a valid npm package name`);
138+
expect(stdout).toContain(NPM_NAME_RULE);
139+
expect(stdout).toContain('Suggested name: create-objectstack my-app');
140+
expect(stdout).not.toContain('Template files written');
141+
expect(fs.readdirSync(tmp)).toEqual([]);
142+
}, 30_000);
143+
144+
it('the current directory\'s name is checked too, and the directory stays empty', () => {
145+
const here = path.join(tmp, 'My App');
146+
fs.mkdirSync(here);
147+
const { status, stdout } = run(here, []);
148+
expect(status).toBe(1);
149+
expect(stdout).toContain('The current directory\'s name "My App" is the project name');
150+
expect(stdout).toContain('Rename this directory to "my-app"');
151+
expect(fs.readdirSync(here)).toEqual([]);
152+
}, 30_000);
153+
154+
it.each([
155+
['my-app', 'my-app'],
156+
['@scope/my-app', path.join('@scope', 'my-app')],
157+
])('control: %j scaffolds as before, written verbatim', (name, dir) => {
158+
const { status, stdout } = run(tmp, [name]);
159+
expect(status, stdout).toBe(0);
160+
const projectDir = path.join(tmp, dir);
161+
const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf8'));
162+
const manifest = JSON.parse(
163+
fs.readFileSync(path.join(projectDir, 'objectstack.manifest.json'), 'utf8'),
164+
);
165+
expect(pkg.name).toBe(name);
166+
expect(manifest.name).toBe(name);
167+
}, 30_000);
168+
});
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license.
2+
//
3+
// The project name is checked against npm's package-name rules BEFORE the
4+
// scaffolder writes anything. Kept out of index.ts because that module calls
5+
// `program.parse()` on import — anything a test needs must be importable
6+
// without running the CLI (same reason as pkg-utils.ts).
7+
//
8+
// WHY A REFUSAL, AND NEVER A REWRITE
9+
// ----------------------------------
10+
// The resolved project name — the `[name]` argument, or the current
11+
// directory's basename when there is none — is written verbatim into
12+
// `package.json` `name` and `objectstack.manifest.json` `name`. A display-style
13+
// name (`My App!`, `MyApp`) used to land there unchecked: `validate` and
14+
// `build` pass on such a project, and the first refusal came from npm itself,
15+
// at `npm publish`, far from its cause.
16+
//
17+
// The name is the user's choice, so the scaffolder does not normalise it
18+
// behind their back: it refuses, states the rule, and names the slug it would
19+
// suggest instead. The user re-runs with the name they accept, and that is the
20+
// value written.
21+
//
22+
// WHY npm's OWN PREDICATE
23+
// -----------------------
24+
// The verdict is `validate-npm-package-name`'s `validForNewPackages` — the
25+
// module npm itself consults — rather than a restated rule set. "Valid for NEW
26+
// packages" is the bar a freshly scaffolded project has to meet: names npm
27+
// still accepts only for packages that already exist (capital letters, a core
28+
// module name such as `http`) are refused here too.
29+
30+
import validateNpmPackageName from 'validate-npm-package-name';
31+
32+
/** npm's ceiling on a package name, the scope included. */
33+
const NPM_NAME_MAX_LENGTH = 214;
34+
35+
/** The rule, stated once, in the refusal every invalid name gets. */
36+
export const NPM_NAME_RULE =
37+
'An npm package name is lowercase, at most 214 characters, made of URL-safe ' +
38+
'characters (letters, digits, "-", ".", "_"), does not start with ".", "_" or "-", ' +
39+
'and may carry a scope (@scope/name).';
40+
41+
export type ProjectNameVerdict =
42+
| { valid: true }
43+
| {
44+
valid: false;
45+
/** npm's own reasons, verbatim from `validate-npm-package-name`. */
46+
reasons: string[];
47+
/** A legal name derived from the input, or undefined when none derives cleanly. */
48+
suggestion: string | undefined;
49+
};
50+
51+
/** Whether `name` may be written to a new project's `package.json` as-is. */
52+
export function checkProjectName(name: string): ProjectNameVerdict {
53+
const result = validateNpmPackageName(name);
54+
if (result.validForNewPackages) return { valid: true };
55+
return {
56+
valid: false,
57+
reasons: [...(result.errors ?? []), ...(result.warnings ?? [])],
58+
suggestion: suggestPackageName(name),
59+
};
60+
}
61+
62+
/** One name segment → lowercase, hyphen-separated, npm-safe characters only. */
63+
function slugSegment(segment: string): string {
64+
return segment
65+
.normalize('NFKD')
66+
.replace(/[\u0300-\u036f]/g, '') // Ünïcode -> Unicode: drop combining marks
67+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2') // MyApp -> My-App
68+
.toLowerCase()
69+
.replace(/[^a-z0-9._]+/g, '-')
70+
.replace(/-{2,}/g, '-')
71+
.replace(/^[-._]+|[-._]+$/g, '');
72+
}
73+
74+
/**
75+
* The slug a refusal suggests for `name`: `My App!` → `my-app`, `MyApp` →
76+
* `my-app`, `@Acme/My App` → `@acme/my-app`.
77+
*
78+
* Only a SUGGESTION — it is printed, never written. Returns undefined when the
79+
* slug is empty or is itself refused by npm (`HTTP` slugs to the core module
80+
* name `http`), so the refusal never recommends a name it would refuse next.
81+
*/
82+
export function suggestPackageName(name: string): string | undefined {
83+
const scoped = /^@([^/]*)\/(.*)$/.exec(name.trim());
84+
const scope = scoped ? slugSegment(scoped[1]) : '';
85+
const prefix = scope ? `@${scope}/` : '';
86+
const budget = NPM_NAME_MAX_LENGTH - prefix.length;
87+
const base = slugSegment(scoped ? scoped[2] : name)
88+
.slice(0, budget)
89+
.replace(/[-._]+$/, '');
90+
if (!base) return undefined;
91+
const slug = `${prefix}${base}`;
92+
return validateNpmPackageName(slug).validForNewPackages ? slug : undefined;
93+
}
94+
95+
/**
96+
* The lines of the refusal, without colour, the first one being the headline.
97+
*
98+
* `fromDirectory` is the no-argument path: the name was not typed, it is the
99+
* current directory's basename, so the remedy is to rename the directory or
100+
* to scaffold into a new one under a name passed explicitly.
101+
*/
102+
export function describeInvalidProjectName(
103+
name: string,
104+
verdict: Extract<ProjectNameVerdict, { valid: false }>,
105+
{ fromDirectory }: { fromDirectory: boolean },
106+
): string[] {
107+
const subject = fromDirectory
108+
? `The current directory's name "${name}" is the project name, and it`
109+
: `The project name "${name}"`;
110+
const lines = [
111+
`${subject} is not a valid npm package name, so it cannot be written to package.json. Nothing was written.`,
112+
`npm refuses it: ${verdict.reasons.join('; ')}.`,
113+
NPM_NAME_RULE,
114+
];
115+
const example = verdict.suggestion ?? 'my-app';
116+
const rerun = `create-objectstack ${example}`;
117+
if (fromDirectory) {
118+
lines.push(
119+
verdict.suggestion
120+
? `Rename this directory to "${verdict.suggestion}" and re-run, or scaffold into a new directory: ${rerun}`
121+
: `Rename this directory to a valid name and re-run, or scaffold into a new directory, e.g.: ${rerun}`,
122+
);
123+
} else {
124+
lines.push(
125+
verdict.suggestion ? `Suggested name: ${rerun}` : `Choose a valid name, e.g.: ${rerun}`,
126+
);
127+
}
128+
return lines;
129+
}

‎pnpm-lock.yaml‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)