Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): experimental icon sets — write the current package name after a package rename (#10897)

Joey90f8b7e74a03
diff --git a/.changeset/icon-sets-package-rename.md b/.changeset/icon-sets-package-rename.md
new file mode 100644
index 0000000000..6a3cbb350d
--- /dev/null
+++ b/.changeset/icon-sets-package-rename.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[experimental] Icon sets: after you rename an icon-set package in package.json, the next `experimental icon` command that writes the data file (`new-set` on the existing set, with or without `--from`, `add`, `map`, or `new-definition --icon`, even one that changes nothing else) writes the new package name to the data file's `module`, and keeps any subpath (`@acme/old-icons/outline` becomes `@acme/new-icons/outline`). Before, the old name stayed, and `integration check` failed until you edited the file by hand. The receipt of each of these commands names the new and the old `module` (`Updated module to "@acme/new-icons/outline" (was "@acme/old-icons/outline"), from the package name in package.json.`), and `map` words each `map` entry from what it replaced, so an entry that did not change says so. Only the experimental icon commands and the icon-sets guide change.
+@josephfarina
diff --git a/packages/cli/api/icon/_authoring.mjs b/packages/cli/api/icon/_authoring.mjs
index a6e78b360c..8676297daa 100644
--- a/packages/cli/api/icon/_authoring.mjs
+++ b/packages/cli/api/icon/_authoring.mjs
@@ -691,6 +691,7 @@ async function redeclareIconSet(
);
result.data.icons = set.data.icons.length;
result.data.updated = true;
+ if (where.moduleUpdate) result.data.moduleUpdate = where.moduleUpdate;
// A look the icons' own library draws comes from that library, so its
// command runs as printed; any other look comes from a module the
// author names.
@@ -1388,6 +1389,7 @@ async function refreshIconSet(
);
result.data.icons = icons.length;
result.data.refreshed = true;
+ if (where.moduleUpdate) result.data.moduleUpdate = where.moduleUpdate;
// Every entry an exact name gives, kept or new, so a refresh lists
// them for review again.
const byName = Object.fromEntries(
@@ -1542,7 +1544,7 @@ export async function addIconDefinition(name, options) {
throw error;
}
}
- return receipt(
+ const result = receipt(
'icon-definition',
doc.name,
{
@@ -1559,5 +1561,10 @@ export async function addIconDefinition(name, options) {
files,
dryRun,
);
+ // Only a new definition with an icon writes the data file.
+ if (icon != null && where.moduleUpdate) {
+ result.data.moduleUpdate = where.moduleUpdate;
+ }
+ return result;
});
}
diff --git a/packages/cli/api/icon/add/add.mjs b/packages/cli/api/icon/add/add.mjs
index 7d1821a682..a5f520b571 100644
--- a/packages/cli/api/icon/add/add.mjs
+++ b/packages/cli/api/icon/add/add.mjs
@@ -395,6 +395,8 @@ export async function iconAdd(exportName, options) {
map,
icons,
};
+ const dataChanged =
+ JSON.stringify(next) !== JSON.stringify(set.data) || where.moduleRenamed;
/** @type {string[]} */
const files = [];
// Every write happens inside this try, so any failure undoes the ones
@@ -422,7 +424,7 @@ export async function iconAdd(exportName, options) {
.join('/'),
);
}
- if (JSON.stringify(next) !== JSON.stringify(set.data)) {
+ if (dataChanged) {
writeIconSetData(set, next, {
extraDefinitions: created ? [created.name] : [],
});
@@ -442,10 +444,12 @@ export async function iconAdd(exportName, options) {
}
throw error;
}
- const changed =
+ // A renamed package's new name alone is not an added icon.
+ const added =
JSON.stringify(next) !== JSON.stringify(set.data) ||
created != null ||
generatedChanged;
+ const changed = dataChanged || added;
// A ./ file publishes only when package.json `files` lists it; the
// author adds it (architecture:cli-surface INV16).
const note =
@@ -466,6 +470,8 @@ export async function iconAdd(exportName, options) {
...(created ? {newDefinition: created.name} : {}),
files,
changed,
+ added,
+ ...(where.moduleUpdate ? {moduleUpdate: where.moduleUpdate} : {}),
...(note ? {note} : {}),
},
};
@@ -774,7 +780,8 @@ async function addVariantForAll({cwd, from, selector, variant}) {
const files = [];
const written = writeGeneratedIcons(packageDir, generated, next, toWrite);
files.push(...written.files);
- const dataChanged = JSON.stringify(next) !== JSON.stringify(set.data);
+ const dataChanged =
+ JSON.stringify(next) !== JSON.stringify(set.data) || where.moduleRenamed;
if (dataChanged) {
try {
writeIconSetData(set, next);
@@ -798,6 +805,7 @@ async function addVariantForAll({cwd, from, selector, variant}) {
missing,
files,
changed: dataChanged || written.changed,
+ ...(where.moduleUpdate ? {moduleUpdate: where.moduleUpdate} : {}),
},
};
}
diff --git a/packages/cli/api/icon/icon.type.mjs b/packages/cli/api/icon/icon.type.mjs
index 59b29325c1..919ffe236e 100644
--- a/packages/cli/api/icon/icon.type.mjs
+++ b/packages/cli/api/icon/icon.type.mjs
@@ -156,6 +156,7 @@
* @property {string} data.file - The data file, relative to the package.
* @property {Array<{definition: string, icon: string, previous: string | null, changed: boolean}>} data.entries - Each pair, in order, and what it replaced.
* @property {boolean} data.changed - Whether the file was written.
+ * @property {{previous: string, module: string}} [data.moduleUpdate] - The data file's `module` before and after this command, when the package was renamed and the command wrote its new name.
* @property {string[]} [data.files] - The generated module and its types, when its theme map was rewritten.
*/
@@ -172,6 +173,7 @@
* @property {string | null} data.icon - The id of the icon now mapped (the icon may be named by any name `map` accepts); null after `remove`.
* @property {string | null} data.previous - The icon id it replaced.
* @property {boolean} data.changed - Whether the file was written.
+ * @property {{previous: string, module: string}} [data.moduleUpdate] - The data file's `module` before and after this command, when the package was renamed and the command wrote its new name.
* @property {string[]} [data.files] - The generated module and its types, when its theme map was rewritten.
*/
@@ -207,6 +209,7 @@
* @property {string[]} data.missing - Ids of icons `from` has no export for; they keep no such variant.
* @property {string[]} data.files - Files written, relative to the package.
* @property {boolean} data.changed
+ * @property {{previous: string, module: string}} [data.moduleUpdate] - The data file's `module` before and after this command, when the package was renamed and the command wrote its new name.
*/
/**
@@ -223,6 +226,8 @@
* @property {string} [data.newDefinition] - The set's own definition the command wrote.
* @property {string[]} data.files - Files written, relative to the package.
* @property {boolean} data.changed - Whether anything was written.
+ * @property {boolean} data.added - Whether the icon, its variant, its `map` entry, or a new definition was added. False when the set already had them, even when `changed` is true because the command wrote a renamed package's new name.
+ * @property {{previous: string, module: string}} [data.moduleUpdate] - The data file's `module` before and after this command, when the package was renamed and the command wrote its new name.
* @property {string} [data.note] - What the package still needs, as text to copy: the entry line that exports the icon from the set's module, and the package.json `files` that publishes a `./` source.
*/
@@ -332,6 +337,7 @@
* @property {Array<{definition: string, icon: string}>} [mapped] - With `from`: the `map` entries an icon with the definition's exact name gives (on a refresh, every such entry, kept or new); check each.
* @property {Array<{definition: string, icon: string, word: string}>} [suggestions] - With `from`: for each unmapped Astryx definition, up to three icons it might map to, best first: the definition's name in another spelling or as another name of an icon, ids that start with it, an id or another name that is one of its words, then two-word ids that are a one-word word sized, shaped, or numbered (`grid-2x2`); never a negated form, the opposite direction, or an icon already mapped. `word` is the name or word that matched. Never written.
* @property {string[]} [notes] - What the author does next, including each change the package needs that the CLI never makes itself (its entry, peers, scripts), as text to copy.
+ * @property {{previous: string, module: string}} [moduleUpdate] - On a refresh, an update, or a new definition with `icon`: the data file's `module` before and after this command, when the package was renamed and the command writes its new name.
*/
/**
diff --git a/packages/cli/api/icon/map/map.mjs b/packages/cli/api/icon/map/map.mjs
index bc02a75376..d81748d731 100644
--- a/packages/cli/api/icon/map/map.mjs
+++ b/packages/cli/api/icon/map/map.mjs
@@ -77,7 +77,8 @@ export async function iconMap(definition, icon, options = {}) {
ERROR_CODES.ERR_MISSING_ARGUMENT,
);
}
- const {packageDir, set} = await findLocalIconSet(cwd, selector);
+ const {packageDir, set, moduleRenamed, moduleUpdate} =
+ await findLocalIconSet(cwd, selector);
// The docs' kebab id (`eye-slash`) names the same definition, and a
// library's other name for an icon (`trash-2`) names the same icon.
definition = definitionNameOf(definition, mappableDefinitions(set));
@@ -112,7 +113,8 @@ export async function iconMap(definition, icon, options = {}) {
}
map[definition] = /** @type {string} */ (icon);
}
- const changed = remove ? previous != null : previous !== icon;
+ const changed =
+ (remove ? previous != null : previous !== icon) || moduleRenamed;
/** @type {string[]} */
const files = [];
if (changed) {
@@ -139,6 +141,7 @@ export async function iconMap(definition, icon, options = {}) {
icon: remove ? null : /** @type {string} */ (icon),
previous,
changed,
+ ...(moduleUpdate ? {moduleUpdate} : {}),
...(files.length > 0 ? {files} : {}),
},
};
@@ -161,7 +164,10 @@ async function mapMany({cwd, selector, pairs}) {
ERROR_CODES.ERR_MISSING_ARGUMENT,
);
}
- const {packageDir, set} = await findLocalIconSet(cwd, selector);
+ const {packageDir, set, moduleRenamed, moduleUpdate} = await findLocalIconSet(
+ cwd,
+ selector,
+ );
const known = mappableDefinitions(set);
const ids = set.data.icons.map(each => each.id);
const map = {...(set.data.map ?? {})};
@@ -204,7 +210,7 @@ async function mapMany({cwd, selector, pairs}) {
changed: previous !== id,
});
}
- const changed = entries.some(each => each.changed);
+ const changed = entries.some(each => each.changed) || moduleRenamed;
/** @type {string[]} */
const files = [];
if (changed) {
@@ -228,6 +234,7 @@ async function mapMany({cwd, selector, pairs}) {
file: path.relative(packageDir, set.dataPath).split(path.sep).join('/'),
entries,
changed,
+ ...(moduleUpdate ? {moduleUpdate} : {}),
...(files.length > 0 ? {files} : {}),
},
};
diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjs
index 9a8b973009..99f3134d6b 100644
--- a/packages/cli/api/integration/add-helpers.mjs
+++ b/packages/cli/api/integration/add-helpers.mjs
@@ -486,7 +486,7 @@ export async function loadCurrentManifest(manifestFile, manifestExists) {
* @param {string} manifestPath
* @param {string[]} files
* @param {boolean} dryRun
- * @returns {{type: 'integration.add', data: Omit<import('./integration-authoring.type.mjs').IntegrationAddData, 'kind'> & {kind: K, icons?: number, refreshed?: boolean, updated?: boolean, renamed?: Array<{from: string, to: string}>, moved?: Array<{id: string, from: string, to: string}>, licenseNoticeMissing?: {library: string, path: string}, mapped?: Array<{definition: string, icon: string}>, suggestions?: Array<{definition: string, icon: string, word: string}>, notes?: string[]}}}
+ * @returns {{type: 'integration.add', data: Omit<import('./integration-authoring.type.mjs').IntegrationAddData, 'kind'> & {kind: K, icons?: number, refreshed?: boolean, updated?: boolean, renamed?: Array<{from: string, to: string}>, moved?: Array<{id: string, from: string, to: string}>, licenseNoticeMissing?: {library: string, path: string}, mapped?: Array<{definition: string, icon: string}>, suggestions?: Array<{definition: string, icon: string, word: string}>, notes?: string[], moduleUpdate?: {previous: string, module: string}}}}
*/
export function receipt(kind, name, root, manifestPath, files, dryRun) {
return {
diff --git a/packages/cli/assets/docs/tree/icon-sets.doc.mjs b/packages/cli/assets/docs/tree/icon-sets.doc.mjs
index b91ace0ad4..7556fddb01 100644
--- a/packages/cli/assets/docs/tree/icon-sets.doc.mjs
+++ b/packages/cli/assets/docs/tree/icon-sets.doc.mjs
@@ -61,7 +61,7 @@ export const docs = {
},
{
type: 'prose',
- text: "`outline.doc.mjs` is the descriptor: name, display name and description (`--display-name`, `--description`), and `license`, the SPDX license of the artwork (it starts as your package's own). `outline.icons.json` starts with no icons and an empty `map`; its `module` is your package name. `outline.generated.js` is the set's generated module, with its declaration file `outline.generated.d.ts`: the CLI writes both, and every icon and the theme map are exports of it. Every field is in {@link schema:icon-set-doc} and {@link schema:icon-set-data}.",
+ text: "`outline.doc.mjs` is the descriptor: name, display name and description (`--display-name`, `--description`), and `license`, the SPDX license of the artwork (it starts as your package's own). `outline.icons.json` starts with no icons and an empty `map`; its `module` is your package name. After you rename the package, the next command that writes the data file (`new-set` on the existing set, with or without `--from`, `add`, `map`, or `new-definition --icon`) writes the new name and keeps any subpath (`@acme/old-icons/outline` becomes `@acme/new-icons/outline`), and its receipt says so. `outline.generated.js` is the set's generated module, with its declaration file `outline.generated.d.ts`: the CLI writes both, and every icon and the theme map are exports of it. Every field is in {@link schema:icon-set-doc} and {@link schema:icon-set-data}.",
},
{
type: 'prose',
diff --git a/packages/cli/clients/cli/commands/experimental/icon.mjs b/packages/cli/clients/cli/commands/experimental/icon.mjs
index ee1d813e76..1f3dc032a5 100644
--- a/packages/cli/clients/cli/commands/experimental/icon.mjs
+++ b/packages/cli/clients/cli/commands/experimental/icon.mjs
@@ -59,6 +59,20 @@ const defaultVariantText = value =>
/** @param {unknown} value */
const variantsText = value => (Array.isArray(value) ? value.join('/') : '');
+/**
+ * The receipt line for a data file whose `module` the command rewrote after
+ * a package rename.
+ * @param {{moduleUpdate?: {previous: string, module: string}, dryRun?: boolean}} data
+ */
+const moduleUpdateLines = data =>
+ data.moduleUpdate
+ ? [
+ text(
+ `${data.dryRun ? '[plan] Would update' : '[ok] Updated'} module to "${data.moduleUpdate.module}" (was "${data.moduleUpdate.previous}"), from the package name in package.json.`,
+ ),
+ ]
+ : [];
+
/**
* Register `icon` and its subcommands under the `experimental` group.
* @param {import('commander').Command} group the `experimental` command
@@ -376,20 +390,24 @@ export function registerExperimentalIcon(group, program) {
(
/** @type {{definition: string, icon: string, previous: string | null}} */ each,
) =>
- `${each.definition} = "${each.icon}"${each.previous && each.previous !== each.icon ? ` (was "${each.previous}")` : ''}`,
+ `${each.definition} = "${each.icon}"${each.previous === each.icon ? ' (unchanged)' : each.previous ? ` (was "${each.previous}")` : ' (was not mapped)'}`,
),
),
+ ...moduleUpdateLines(data),
)
: emit(
+ // The entry line reads `previous` and `icon`: a write can
+ // come from a package rename alone.
text(
data.icon == null
- ? data.changed
+ ? data.previous != null
? `[ok] Removed map.${data.definition} (was "${data.previous}") from ${data.file}.`
: `[ok] ${data.file} has no map.${data.definition}.`
- : data.changed
+ : data.previous !== data.icon
? `[ok] map.${data.definition} = "${data.icon}" in ${data.file}${data.previous ? ` (was "${data.previous}")` : ''}.`
: `[ok] map.${data.definition} is already "${data.icon}".`,
),
+ ...moduleUpdateLines(data),
),
),
});
@@ -430,6 +448,7 @@ export function registerExperimentalIcon(group, program) {
text(
`[ok] ${data.variant}: ${data.added} icons gained it${data.already > 0 ? `, ${data.already} already had it` : ''}, read from ${data.from}.`,
),
+ ...moduleUpdateLines(data),
...(data.files.length > 0 ? [list(data.files)] : []),
...(data.missing.length > 0
? [
@@ -488,10 +507,11 @@ export function registerExperimentalIcon(group, program) {
const {data} = result;
emit(
text(
- data.changed
+ data.added
? `[ok] Added ${data.icon.export} as "${data.icon.id}"${data.variant ? ` (variant ${data.variant})` : ''}${data.definition ? `, map.${data.definition} = "${data.icon.id}"` : ''}.`
: `[ok] ${data.icon.export} is already "${data.icon.id}"${data.definition ? ` and map.${data.definition} names it` : ''}.`,
),
+ ...moduleUpdateLines(data),
...(data.files.length > 0 ? [list(data.files)] : []),
...(data.note ? [text(`[next] ${data.note}`)] : []),
);
@@ -543,6 +563,7 @@ export function registerExperimentalIcon(group, program) {
: `The experimental.iconSets root ${root.path} in ${manifest} is unchanged.`
: `${dryRun ? 'Would update' : 'Updated'} ${manifest}.`,
),
+ ...moduleUpdateLines(data),
...(files.length > 0 ? [list(files)] : []),
// What to do next comes before the long lists, so it never scrolls
// away.
diff --git a/packages/cli/clients/cli/commands/icon-package-rename.test.mjs b/packages/cli/clients/cli/commands/icon-package-rename.test.mjs
new file mode 100644
index 0000000000..6721031182
--- /dev/null
+++ b/packages/cli/clients/cli/commands/icon-package-rename.test.mjs
@@ -0,0 +1,377 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Icon sets after the package is renamed in package.json: the next
+ * command that writes the data file gives its `module` the new name, so
+ * `integration check` passes without a hand edit, and its receipt says so.
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+import {ICON_NAMES} from '../../../authoring/doctypes/icon-set/icon-names.mjs';
+
+/** @type {string} */
+let tmp;
+/** @type {string} */
+let pkg;
+
+const LIBRARY = '@acme/glyph-library';
+
+beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-icon-rename-'));
+ pkg = path.join(tmp, 'icons');
+ const lib = path.join(pkg, 'node_modules', ...LIBRARY.split('/'));
+ fs.mkdirSync(lib, {recursive: true});
+ fs.writeFileSync(
+ path.join(lib, 'package.json'),
+ JSON.stringify({
+ name: LIBRARY,
+ version: '2.0.0',
+ license: 'MIT',
+ type: 'module',
+ exports: {'.': './index.js'},
+ }),
+ );
+ fs.writeFileSync(path.join(lib, 'LICENSE'), 'MIT License\n');
+ fs.writeFileSync(
+ path.join(lib, 'index.js'),
+ [
+ 'export function Bin(props) { return null; }',
+ 'export function Cross(props) { return null; }',
+ '',
+ ].join('\n'),
+ );
+ writePackage('@acme/old-icons');
+ fs.writeFileSync(
+ path.join(pkg, 'index.js'),
+ "export * from './icon-sets/outline/outline.generated.js';\n",
+ );
+});
+afterEach(() => {
+ fs.rmSync(tmp, {recursive: true, force: true});
+});
+
+/**
+ * @param {string} name
+ * @param {Record<string, string>} [exports]
+ */
+function writePackage(name, exports = {'.': './index.js'}) {
+ fs.writeFileSync(
+ path.join(pkg, 'package.json'),
+ JSON.stringify(
+ {
+ name,
+ version: '1.0.0',
+ license: 'MIT',
+ type: 'module',
+ exports,
+ dependencies: {[LIBRARY]: '^2.0.0'},
+ },
+ null,
+ 2,
+ ),
+ );
+}
+
+/** @param {string[]} args */
+async function json(args) {
+ const res = await runCli([...args, '--json'], pkg);
+ return {code: res.code, body: JSON.parse(res.stdout)};
+}
+
+const dataFile = () =>
+ path.join(pkg, 'icon-sets', 'outline', 'outline.icons.json');
+const dataOf = () => JSON.parse(fs.readFileSync(dataFile(), 'utf-8'));
+
+/** The pairs that map every built-in definition to `cross`. */
+const ALL_PAIRS = ICON_NAMES.map(name => `${name}=cross`).join(',');
+
+/** Wrap the library and map every built-in definition. */
+async function wrapAndMap() {
+ const wrapped = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'outline',
+ '--from',
+ LIBRARY,
+ ]);
+ expect(wrapped.code, JSON.stringify(wrapped.body)).toBe(0);
+ const mapped = await json([
+ 'experimental',
+ 'icon',
+ 'map',
+ '--pairs',
+ ALL_PAIRS,
+ ]);
+ expect(mapped.code, JSON.stringify(mapped.body)).toBe(0);
+ expect(dataOf().module).toBe('@acme/old-icons');
+}
+
+/**
+ * Every issue the strict check reports and every failure, without the
+ * skipped TypeScript work.
+ */
+async function strictFailures() {
+ const res = await runCli(['integration', 'check', '--strict', '--json'], pkg);
+ const {checks, failures} = JSON.parse(res.stdout).data;
+ return [
+ ...checks.flatMap(
+ (/** @type {any} */ each) => each.response?.data?.issues ?? [],
+ ),
+ ...failures,
+ ]
+ .filter(
+ (/** @type {{code: string}} */ each) => each.code !== 'doc_types_skipped',
+ )
+ .map(
+ (/** @type {{code: string, message: string}} */ each) =>
+ `${each.code}: ${each.message}`,
+ );
+}
+
+describe('a renamed icon-set package', () => {
+ it('map, run again with the same entries, writes the new package name', async () => {
+ await wrapAndMap();
+ expect(await strictFailures()).toEqual([]);
+ writePackage('@acme/new-icons');
+ const mapped = await json([
+ 'experimental',
+ 'icon',
+ 'map',
+ '--pairs',
+ ALL_PAIRS,
+ ]);
+ expect(mapped.code, JSON.stringify(mapped.body)).toBe(0);
+ expect(dataOf().module).toBe('@acme/new-icons');
+ expect(await strictFailures()).toEqual([]);
+ });
+
+ it('a refresh and an add each write the new package name', async () => {
+ await wrapAndMap();
+ for (const [name, run] of /** @type {Array<[string, string[]]>} */ ([
+ ['@acme/refreshed', ['new-set', 'outline', '--from', LIBRARY]],
+ [
+ '@acme/added',
+ ['add', 'Bin', '--from', LIBRARY, '--definition', 'delete'],
+ ],
+ ])) {
+ writePackage(name);
+ const done = await json(['experimental', 'icon', ...run]);
+ expect(done.code, JSON.stringify(done.body)).toBe(0);
+ expect(dataOf().module, run.join(' ')).toBe(name);
+ expect(await strictFailures(), run.join(' ')).toEqual([]);
+ }
+ });
+});
+
+describe('receipts after a package rename', () => {
+ const MODULE_LINE =
+ '[ok] Updated module to "@acme/new-icons" (was "@acme/old-icons"), from the package name in package.json.';
+ const MODULE_UPDATE = {
+ previous: '@acme/old-icons',
+ module: '@acme/new-icons',
+ };
+
+ /** @param {string[]} args */
+ async function textOf(args) {
+ const res = await runCli(['experimental', 'icon', ...args], pkg);
+ expect(res.code, res.stdout + res.stderr).toBe(0);
+ return res.stdout;
+ }
+
+ it('a repeated add says the icon is already there and reports the module rewrite', async () => {
+ await wrapAndMap();
+ await textOf(['add', 'Bin', '--from', LIBRARY, '--definition', 'delete']);
+ writePackage('@acme/new-icons');
+ const done = await json([
+ 'experimental',
+ 'icon',
+ 'add',
+ 'Bin',
+ '--from',
+ LIBRARY,
+ '--definition',
+ 'delete',
+ ]);
+ expect(done.code, JSON.stringify(done.body)).toBe(0);
+ expect(done.body.data).toMatchObject({
+ added: false,
+ changed: true,
+ moduleUpdate: {previous: '@acme/old-icons', module: '@acme/new-icons'},
+ });
+ writePackage('@acme/old-icons');
+ await textOf(['map', 'close', 'cross']);
+ writePackage('@acme/new-icons');
+ const out = await textOf([
+ 'add',
+ 'Bin',
+ '--from',
+ LIBRARY,
+ '--definition',
+ 'delete',
+ ]);
+ expect(out).toContain(
+ '[ok] BinIcon is already "bin" and map.delete names it.',
+ );
+ expect(out).toContain(MODULE_LINE);
+ expect(out).not.toContain('Added');
+ });
+
+ it('a single map that changes no entry says so and reports the module rewrite', async () => {
+ await wrapAndMap();
+ writePackage('@acme/new-icons');
+ const out = await textOf(['map', 'close', 'cross']);
+ expect(out).toContain('[ok] map.close is already "cross".');
+ expect(out).toContain(MODULE_LINE);
+ expect(out).not.toContain('(was "cross")');
+ expect(dataOf().module).toBe('@acme/new-icons');
+ });
+
+ it('map --remove on an unmapped definition says it has no entry and reports the module rewrite', async () => {
+ await wrapAndMap();
+ await textOf(['map', 'close', '--remove']);
+ writePackage('@acme/new-icons');
+ const res = await json([
+ 'experimental',
+ 'icon',
+ 'map',
+ 'close',
+ '--remove',
+ ]);
+ expect(res.body.data).toMatchObject({
+ previous: null,
+ changed: true,
+ moduleUpdate: {previous: '@acme/old-icons', module: '@acme/new-icons'},
+ });
+ writePackage('@acme/old-icons');
+ await textOf(['map', 'search', '--remove']);
+ writePackage('@acme/new-icons');
+ const out = await textOf(['map', 'search', '--remove']);
+ expect(out).toContain('has no map.search.');
+ expect(out).toContain(MODULE_LINE);
+ expect(out).not.toContain('Removed');
+ expect(out).not.toContain('"null"');
+ });
+
+ it('--pairs words each entry from its previous icon and reports the module rewrite', async () => {
+ await wrapAndMap();
+ await textOf(['map', 'search', '--remove']);
+ writePackage('@acme/new-icons');
+ const out = await textOf([
+ 'map',
+ '--pairs',
+ 'close=cross,menu=bin,search=bin',
+ ]);
+ expect(out).toContain('2 of 3 map entries changed');
+ expect(out).toContain('close = "cross" (unchanged)');
+ expect(out).toContain('menu = "bin" (was "cross")');
+ expect(out).toContain('search = "bin" (was not mapped)');
+ expect(out).toContain(MODULE_LINE);
+ expect(dataOf().module).toBe('@acme/new-icons');
+ });
+
+ it('a refresh with new-set --from reports the module rewrite', async () => {
+ await wrapAndMap();
+ writePackage('@acme/new-icons');
+ const res = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'outline',
+ '--from',
+ LIBRARY,
+ ]);
+ expect(res.code, JSON.stringify(res.body)).toBe(0);
+ expect(res.body.data.moduleUpdate).toEqual(MODULE_UPDATE);
+ writePackage('@acme/old-icons');
+ await textOf(['new-set', 'outline', '--from', LIBRARY]);
+ writePackage('@acme/new-icons');
+ const out = await textOf(['new-set', 'outline', '--from', LIBRARY]);
+ expect(out).toContain(MODULE_LINE);
+ expect(dataOf().module).toBe('@acme/new-icons');
+ });
+
+ it('new-set without --from reports the rewrite of a subpath module', async () => {
+ await wrapAndMap();
+ const subpath = {
+ '.': './index.js',
+ './outline': './icon-sets/outline/outline.generated.js',
+ };
+ writePackage('@acme/old-icons', subpath);
+ fs.writeFileSync(
+ dataFile(),
+ JSON.stringify({...dataOf(), module: '@acme/old-icons/outline'}),
+ );
+ writePackage('@acme/new-icons', subpath);
+ const res = await json([
+ 'experimental',
+ 'icon',
+ 'new-set',
+ 'outline',
+ '--display-name',
+ 'Outline',
+ ]);
+ expect(res.code, JSON.stringify(res.body)).toBe(0);
+ expect(res.body.data.moduleUpdate).toEqual({
+ previous: '@acme/old-icons/outline',
+ module: '@acme/new-icons/outline',
+ });
+ writePackage('@acme/old-icons', subpath);
+ await textOf(['new-set', 'outline', '--display-name', 'Outline']);
+ writePackage('@acme/new-icons', subpath);
+ const out = await textOf([
+ 'new-set',
+ 'outline',
+ '--display-name',
+ 'Outline',
+ ]);
+ expect(out).toContain(
+ '[ok] Updated module to "@acme/new-icons/outline" (was "@acme/old-icons/outline"), from the package name in package.json.',
+ );
+ expect(dataOf().module).toBe('@acme/new-icons/outline');
+ });
+
+ const DESCRIBED = ['--description', 'Throws an item away.', '--words', 'bin'];
+
+ it('new-definition --icon reports the module rewrite, and new-definition without --icon does not', async () => {
+ await wrapAndMap();
+ writePackage('@acme/new-icons');
+ const plain = await json([
+ 'experimental',
+ 'icon',
+ 'new-definition',
+ 'trash-can',
+ ...DESCRIBED,
+ ]);
+ expect(plain.code, JSON.stringify(plain.body)).toBe(0);
+ expect(plain.body.data.moduleUpdate).toBeUndefined();
+ expect(dataOf().module).toBe('@acme/old-icons');
+ const res = await json([
+ 'experimental',
+ 'icon',
+ 'new-definition',
+ 'waste-bin',
+ ...DESCRIBED,
+ '--icon',
+ 'bin',
+ ]);
+ expect(res.code, JSON.stringify(res.body)).toBe(0);
+ expect(res.body.data.moduleUpdate).toEqual(MODULE_UPDATE);
+ writePackage('@acme/old-icons');
+ await textOf(['new-definition', 'garbage', ...DESCRIBED, '--icon', 'bin']);
+ writePackage('@acme/new-icons');
+ const out = await textOf([
+ 'new-definition',
+ 'rubbish',
+ ...DESCRIBED,
+ '--icon',
+ 'bin',
+ ]);
+ expect(out).toContain(MODULE_LINE);
+ expect(dataOf().module).toBe('@acme/new-icons');
+ });
+});
diff --git a/packages/cli/foundation/discovery/icon-set-writer.mjs b/packages/cli/foundation/discovery/icon-set-writer.mjs
index 8904cd33db..546c6514af 100644
--- a/packages/cli/foundation/discovery/icon-set-writer.mjs
+++ b/packages/cli/foundation/discovery/icon-set-writer.mjs
@@ -156,7 +156,11 @@ function packageDirOf(cwd) {
* `selector` names, else the only set.
* @param {string} cwd
* @param {string} [selector] a set name
- * @returns {Promise<{packageDir: string, pkg: Record<string, any>, root: string, set: DiscoveredIconSet, sets: DiscoveredIconSet[]}>}
+ * The set's `module` names the package as package.json names it now;
+ * `moduleRenamed` says the data file still names an old name, so a command
+ * writes the data file even when nothing else changes; `moduleUpdate` gives
+ * the old and the new name for the receipt, else null.
+ * @returns {Promise<{packageDir: string, pkg: Record<string, any>, root: string, set: DiscoveredIconSet, sets: DiscoveredIconSet[], moduleRenamed: boolean, moduleUpdate: {previous: string, module: string} | null}>}
*/
export async function findLocalIconSet(cwd, selector) {
const packageDir = packageDirOf(cwd);
@@ -200,12 +204,20 @@ export async function findLocalIconSet(cwd, selector) {
? found.sets.filter(set => set.name === selector)
: found.sets;
if (named.length === 1) {
+ const set = {...named[0], packageDir};
+ const module = moduleInPackage(set.data.module, pkg.name);
+ const moduleUpdate =
+ module !== set.data.module ? {previous: set.data.module, module} : null;
+ const moduleRenamed = moduleUpdate != null;
+ if (moduleRenamed) set.data = {...set.data, module};
return {
packageDir,
pkg,
root,
- set: {...named[0], packageDir},
+ set,
sets: found.sets,
+ moduleRenamed,
+ moduleUpdate,
};
}
const broken = selector
@@ -239,6 +251,22 @@ export async function findLocalIconSet(cwd, selector) {
);
}
+/**
+ * The data file's `module` in the package as it is named now. The data file
+ * belongs to the CLI, so after a package rename the next write gives the new
+ * name (`@acme/old/solid` → `@acme/new/solid`). A ./ path, or a package
+ * with no name, is left as it is.
+ * @param {string} module
+ * @param {unknown} name the package.json `name`
+ */
+function moduleInPackage(module, name) {
+ if (typeof name !== 'string' || name === '' || module.startsWith('.')) {
+ return module;
+ }
+ const owner = iconModulePackage(module);
+ return owner === name ? module : `${name}${module.slice(owner.length)}`;
+}
+
/** The data file's fields, in the order the file is written. */
const DATA_KEYS = [
'schemaVersion',