@wkovacs64/add-icon 0.1.0-dev.645a9b96

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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Justin R. Hall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # @wkovacs64/add-icon
2
+
3
+ A command-line tool to download icons from the [Iconify Framework](https://iconify.design/) and
4
+ apply custom transformations.
5
+
6
+ ## Installation
7
+
8
+ Add it to your project:
9
+
10
+ ```bash
11
+ npm install @wkovacs64/add-icon
12
+ ```
13
+
14
+ Or use it directly with npx without installing:
15
+
16
+ ```bash
17
+ npx @wkovacs64/add-icon heroicons:arrow-up-circle
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ### Basic Usage
23
+
24
+ Download an icon:
25
+
26
+ ```bash
27
+ npx @wkovacs64/add-icon heroicons:arrow-up-circle
28
+ ```
29
+
30
+ Specify an output directory:
31
+
32
+ ```bash
33
+ npx @wkovacs64/add-icon heroicons:arrow-up-circle --output-dir ./my-icons
34
+ ```
35
+
36
+ ### Transformations
37
+
38
+ The tool fetches SVG icons directly from the Iconify API with width and height attributes removed automatically. You can add custom transformations for more advanced modifications.
39
+
40
+ ### Custom Transformations
41
+
42
+ You can write custom transforms in either JavaScript or TypeScript!
43
+
44
+ #### JavaScript Transform
45
+
46
+ Create a custom transform file (e.g., `my-transform.js`):
47
+
48
+ ```js
49
+ /**
50
+ * Custom transform to add a title element to SVG
51
+ * @param {Object} args - Transform arguments
52
+ * @param {string} args.svg - SVG content
53
+ * @param {string} args.iconName - Icon name (e.g., 'heroicons:arrow-up-circle')
54
+ * @param {string} args.prefix - Icon set prefix (e.g., 'heroicons')
55
+ * @param {string} args.name - Icon name without prefix (e.g., 'arrow-up-circle')
56
+ * @returns {string} - Transformed SVG
57
+ */
58
+ export default function addTitle(args) {
59
+ const titleElement = `<title>${args.iconName}</title>`;
60
+ return args.svg.replace(/<svg([^>]*)>/, `<svg$1>${titleElement}`);
61
+ }
62
+ ```
63
+
64
+ #### TypeScript Transform
65
+
66
+ Create a custom transform file (e.g., `my-transform.ts`):
67
+
68
+ ```ts
69
+ import type { TransformArgs } from '@wkovacs64/add-icon';
70
+
71
+ /**
72
+ * Custom transform to add a title element to SVG
73
+ * @param args - Transform arguments containing SVG content and icon information
74
+ * @returns The transformed SVG
75
+ */
76
+ export default function addTitle(args: TransformArgs): string {
77
+ const titleElement = `<title>${args.iconSet}:${args.iconName}</title>`;
78
+ return args.svg.replace(/<svg([^>]*)>/, `<svg$1>${titleElement}`);
79
+ }
80
+ ```
81
+
82
+ Then use it with the CLI:
83
+
84
+ ```bash
85
+ # JavaScript transform
86
+ npx @wkovacs64/add-icon heroicons:arrow-up-circle --transform ./my-transform.js
87
+
88
+ # TypeScript transform
89
+ npx @wkovacs64/add-icon heroicons:arrow-up-circle --transform ./my-transform.ts
90
+ ```
91
+
92
+ ## Configuration File
93
+
94
+ You can create a configuration file in your project root, using either JavaScript (`add-icon.config.js`) or TypeScript (`add-icon.config.ts`).
95
+
96
+ ### JavaScript Configuration
97
+
98
+ ```js
99
+ // Define custom transform
100
+ function addCustomAttribute(args) {
101
+ return args.svg.replace(/<svg/, `<svg data-icon="${args.iconName}"`);
102
+ }
103
+
104
+ export default {
105
+ outputDir: './assets/icons',
106
+ transforms: [addCustomAttribute],
107
+ };
108
+ ```
109
+
110
+ ### TypeScript Configuration
111
+
112
+ ```ts
113
+ import type { IconifyConfig, TransformArgs } from '@wkovacs64/add-icon';
114
+
115
+ // Define custom transform
116
+ function addCustomAttribute(args: TransformArgs): string {
117
+ return args.svg.replace(/<svg/, `<svg data-icon="${args.iconName}"`);
118
+ }
119
+
120
+ const config: IconifyConfig = {
121
+ outputDir: './assets/icons',
122
+ transforms: [addCustomAttribute],
123
+ };
124
+
125
+ export default config;
126
+ ```
127
+
128
+ ## Using as a Library
129
+
130
+ You can also use iconify-cli as a library in your own projects:
131
+
132
+ ### JavaScript
133
+
134
+ ```js
135
+ import { downloadIcon } from '@wkovacs64/add-icon';
136
+
137
+ // Create custom transform
138
+ function addCustomAttribute(args) {
139
+ return args.svg.replace(/<svg/, `<svg data-custom="${args.iconSet}"`);
140
+ }
141
+
142
+ // Download an icon with transforms
143
+ async function downloadCustomIcon() {
144
+ const iconPath = await downloadIcon('heroicons:heart', {
145
+ outputDir: './icons',
146
+ transforms: [addCustomAttribute],
147
+ });
148
+
149
+ console.log(`Icon saved to: ${iconPath}`);
150
+ }
151
+
152
+ downloadCustomIcon();
153
+ ```
154
+
155
+ ### TypeScript
156
+
157
+ ```ts
158
+ import { downloadIcon, type TransformArgs } from '@wkovacs64/add-icon';
159
+
160
+ // Create custom transform
161
+ const addCustomAttribute = (args: TransformArgs): string => {
162
+ return args.svg.replace(/<svg/, `<svg data-custom="${args.iconSet}"`);
163
+ };
164
+
165
+ // Download an icon with transforms
166
+ async function downloadCustomIcon(): Promise<void> {
167
+ try {
168
+ const iconPath = await downloadIcon('heroicons:heart', {
169
+ outputDir: './icons',
170
+ transforms: [addCustomAttribute],
171
+ });
172
+
173
+ console.log(`Icon saved to: ${iconPath}`);
174
+ } catch (error) {
175
+ console.error(
176
+ 'Error downloading icon:',
177
+ error instanceof Error ? error.message : String(error),
178
+ );
179
+ }
180
+ }
181
+
182
+ downloadCustomIcon();
183
+ ```
184
+
185
+ ## License
186
+
187
+ MIT
@@ -0,0 +1,11 @@
1
+ import type { IconifyConfig } from './types.js';
2
+ /**
3
+ * Default configuration
4
+ */
5
+ export declare const defaultConfig: IconifyConfig;
6
+ /**
7
+ * Loads configuration from file if it exists
8
+ * @param configPath - Path to config file
9
+ * @returns Configuration object
10
+ */
11
+ export declare function loadConfig(configPath?: string): Promise<IconifyConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,84 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * Default configuration
5
+ */
6
+ export const defaultConfig = {
7
+ outputDir: '.', // Current directory
8
+ };
9
+ /**
10
+ * Loads configuration from file if it exists
11
+ * @param configPath - Path to config file
12
+ * @returns Configuration object
13
+ */
14
+ export async function loadConfig(configPath) {
15
+ // If a specific config path is provided, use it
16
+ if (configPath) {
17
+ return await loadConfigFile(configPath);
18
+ }
19
+ // Try to find a config file in the current directory, checking both JS and TS
20
+ const jsConfigPath = path.resolve(process.cwd(), 'add-icon.config.js');
21
+ const tsConfigPath = path.resolve(process.cwd(), 'add-icon.config.ts');
22
+ // Check for TypeScript config first
23
+ if (fs.existsSync(tsConfigPath)) {
24
+ return await loadTSConfigFile(tsConfigPath);
25
+ }
26
+ // Then check for JavaScript config
27
+ if (fs.existsSync(jsConfigPath)) {
28
+ return await loadConfigFile(jsConfigPath);
29
+ }
30
+ // Fall back to default config
31
+ return defaultConfig;
32
+ }
33
+ /**
34
+ * Loads a JavaScript config file
35
+ * @param configPath - Path to JS config file
36
+ * @returns Configuration object
37
+ */
38
+ async function loadConfigFile(configPath) {
39
+ try {
40
+ // For ESM, we need to use dynamic import with file:// protocol
41
+ const fileUrl = `file://${configPath}`;
42
+ const config = await import(fileUrl);
43
+ return { ...defaultConfig, ...config.default };
44
+ }
45
+ catch (error) {
46
+ const errorMessage = error instanceof Error ? error.message : String(error);
47
+ console.error(`Error loading config file: ${errorMessage}`);
48
+ return defaultConfig;
49
+ }
50
+ }
51
+ /**
52
+ * Loads a TypeScript config file by transpiling it first
53
+ * @param configPath - Path to TS config file
54
+ * @returns Configuration object
55
+ */
56
+ async function loadTSConfigFile(configPath) {
57
+ try {
58
+ // Create a temporary JS file for the TypeScript config
59
+ const jsPath = configPath.replace(/\.ts$/, '.js');
60
+ try {
61
+ // Use TypeScript to compile the config file
62
+ const { execSync } = await import('node:child_process');
63
+ execSync(`npx tsc "${configPath}" --outDir "${path.dirname(configPath)}" --target es2020 --module NodeNext --moduleResolution NodeNext --esModuleInterop`, { stdio: 'ignore' });
64
+ // Load the compiled JS config
65
+ const result = await loadConfigFile(jsPath);
66
+ // Clean up the temporary JS file
67
+ if (process.env.NODE_ENV !== 'development') {
68
+ fs.unlinkSync(jsPath);
69
+ }
70
+ return result;
71
+ }
72
+ catch (err) {
73
+ const errorMessage = err instanceof Error ? err.message : String(err);
74
+ console.error(`Error transpiling TypeScript config: ${errorMessage}`);
75
+ console.error('Make sure TypeScript is installed or use a JavaScript (.js) config file.');
76
+ return defaultConfig;
77
+ }
78
+ }
79
+ catch (error) {
80
+ const errorMessage = error instanceof Error ? error.message : String(error);
81
+ console.error(`Error loading TypeScript config file: ${errorMessage}`);
82
+ return defaultConfig;
83
+ }
84
+ }
@@ -0,0 +1,17 @@
1
+ import type { IconifyConfig } from './types.js';
2
+ /**
3
+ * Parses an icon reference into iconSet and iconName
4
+ * @param iconReference - Reference in format 'iconSet:iconName'
5
+ * @returns Object with iconSet and iconName
6
+ */
7
+ export declare function parseIconReference(iconReference: string): {
8
+ iconSet: string;
9
+ iconName: string;
10
+ };
11
+ /**
12
+ * Downloads an icon and applies transforms
13
+ * @param iconReference - Icon reference (e.g., 'heroicons:arrow-up-circle')
14
+ * @param config - Configuration options
15
+ * @returns Path to saved icon file
16
+ */
17
+ export declare function downloadIcon(iconReference: string, config: IconifyConfig): Promise<string>;
@@ -0,0 +1,78 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * Parses an icon reference into iconSet and iconName
5
+ * @param iconReference - Reference in format 'iconSet:iconName'
6
+ * @returns Object with iconSet and iconName
7
+ */
8
+ export function parseIconReference(iconReference) {
9
+ const parts = iconReference.split(':');
10
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
11
+ throw new Error(`Invalid icon reference: ${iconReference}. Expected format: iconSet:iconName`);
12
+ }
13
+ return {
14
+ iconSet: parts[0],
15
+ iconName: parts[1],
16
+ };
17
+ }
18
+ /**
19
+ * Fetches icon SVG directly from Iconify API
20
+ * @param iconSet - Icon set name
21
+ * @param iconName - Icon name
22
+ * @returns Promise with SVG string
23
+ */
24
+ async function fetchIconSvg(iconSet, iconName) {
25
+ // Using width=unset parameter to remove width/height attributes automatically
26
+ const apiUrl = `https://api.iconify.design/${iconSet}/${iconName}.svg?width=unset`;
27
+ try {
28
+ const response = await fetch(apiUrl);
29
+ if (!response.ok) {
30
+ throw new Error(`HTTP error! Status: ${response.status}`);
31
+ }
32
+ return await response.text();
33
+ }
34
+ catch (error) {
35
+ const errorMessage = error instanceof Error ? error.message : String(error);
36
+ throw new Error(`Failed to fetch icon SVG: ${errorMessage}`);
37
+ }
38
+ }
39
+ /**
40
+ * Downloads an icon and applies transforms
41
+ * @param iconReference - Icon reference (e.g., 'heroicons:arrow-up-circle')
42
+ * @param config - Configuration options
43
+ * @returns Path to saved icon file
44
+ */
45
+ export async function downloadIcon(iconReference, config) {
46
+ try {
47
+ const { iconSet, iconName } = parseIconReference(iconReference);
48
+ // Ensure the output directory exists
49
+ if (!fs.existsSync(config.outputDir)) {
50
+ fs.mkdirSync(config.outputDir, { recursive: true });
51
+ }
52
+ // Fetch SVG directly with width=unset parameter to remove width/height attributes
53
+ let svg = await fetchIconSvg(iconSet, iconName);
54
+ // Apply custom transforms if specified
55
+ if (config.transforms && config.transforms.length > 0) {
56
+ for (const transform of config.transforms) {
57
+ // Create transform arguments object
58
+ const transformArgs = {
59
+ svg,
60
+ iconSet,
61
+ iconName,
62
+ };
63
+ // Apply transform
64
+ svg = await Promise.resolve(transform(transformArgs));
65
+ }
66
+ }
67
+ // Create file name
68
+ const fileName = `${iconSet}-${iconName}.svg`;
69
+ const filePath = path.join(config.outputDir, fileName);
70
+ // Write the SVG file
71
+ fs.writeFileSync(filePath, svg, 'utf8');
72
+ return filePath;
73
+ }
74
+ catch (error) {
75
+ const errorMessage = error instanceof Error ? error.message : String(error);
76
+ throw new Error(`Failed to download icon: ${errorMessage}`);
77
+ }
78
+ }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import type { IconTransform, TransformArgs } from './types.js';
3
+ export type { IconTransform, TransformArgs };
4
+ export { downloadIcon, parseIconReference } from './iconify.js';
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import url from 'node:url';
5
+ import os from 'node:os';
6
+ import { execSync } from 'node:child_process';
7
+ import { Command } from 'commander';
8
+ import { downloadIcon } from './iconify.js';
9
+ import { loadConfig } from './config.js';
10
+ // Re-export other useful functions
11
+ export { downloadIcon, parseIconReference } from './iconify.js';
12
+ // Create CLI program
13
+ const program = new Command();
14
+ program
15
+ .name('add-icon')
16
+ .description('Download and transform icons from Iconify')
17
+ .version('1.0.0')
18
+ .argument('<icon>', 'Icon reference (e.g., heroicons:arrow-up-circle)')
19
+ .option('-o, --output-dir <dir>', 'Directory to save icon')
20
+ .option('-c, --config <path>', 'Path to config file')
21
+ .option('-t, --transform <path>', 'Path to custom transform module (.js or .ts)')
22
+ .action(async (icon, options) => {
23
+ try {
24
+ // Load config (first from config file, then override with CLI options)
25
+ const config = await loadConfig(options.config);
26
+ // Override output directory if specified in CLI
27
+ if (options.outputDir) {
28
+ config.outputDir = options.outputDir;
29
+ }
30
+ // Load custom transform if specified
31
+ if (options.transform) {
32
+ try {
33
+ const transformPath = path.resolve(process.cwd(), options.transform);
34
+ let customTransform;
35
+ // Handle TypeScript files
36
+ if (transformPath.endsWith('.ts')) {
37
+ // Create a temporary JS file for the transform
38
+ const jsPath = transformPath.replace(/\.ts$/, '.js');
39
+ try {
40
+ // Use tsc to compile the TypeScript file
41
+ execSync(`npx tsc "${transformPath}" --outDir "${path.dirname(transformPath)}" --target es2020 --module NodeNext --moduleResolution NodeNext --esModuleInterop`);
42
+ // Import the compiled JS file
43
+ customTransform = await import(`file://${jsPath}`);
44
+ // Clean up temporary JS file if not in dev mode
45
+ if (process.env.NODE_ENV !== 'development') {
46
+ fs.unlinkSync(jsPath);
47
+ }
48
+ }
49
+ catch (err) {
50
+ const errorMessage = err instanceof Error ? err.message : String(err);
51
+ console.error(`Error transpiling TypeScript transform: ${errorMessage}`);
52
+ console.error('Make sure TypeScript is installed or use a JavaScript (.js) transform file.');
53
+ process.exit(1);
54
+ }
55
+ }
56
+ else {
57
+ // For JavaScript files, use dynamic import
58
+ customTransform = await import(`file://${transformPath}`);
59
+ }
60
+ if (customTransform && typeof customTransform.default === 'function') {
61
+ config.transforms = [customTransform.default];
62
+ }
63
+ else {
64
+ console.error('Custom transform must export a default function');
65
+ process.exit(1);
66
+ }
67
+ }
68
+ catch (error) {
69
+ const errorMessage = error instanceof Error ? error.message : String(error);
70
+ console.error(`Failed to load custom transform: ${errorMessage}`);
71
+ process.exit(1);
72
+ }
73
+ }
74
+ // Download the icon
75
+ console.log(`Downloading icon: ${icon}...`);
76
+ const savedPath = await downloadIcon(icon, config);
77
+ console.log(`✓ Icon saved to: ${savedPath}`);
78
+ }
79
+ catch (error) {
80
+ const errorMessage = error instanceof Error ? error.message : String(error);
81
+ console.error(`Error: ${errorMessage}`);
82
+ process.exit(1);
83
+ }
84
+ });
85
+ const __filename = url.fileURLToPath(import.meta.url);
86
+ const __dirname = path.dirname(__filename);
87
+ // This logic only runs when executed directly as CLI, not when imported as a library
88
+ if (os.platform() === 'win32'
89
+ ? process.argv[1] === __filename
90
+ : process.argv[1] === __filename || process.argv[1] === __dirname) {
91
+ // Parse command line arguments
92
+ program.parse();
93
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Arguments passed to transform functions
3
+ */
4
+ export interface TransformArgs {
5
+ /** The SVG content as a string */
6
+ svg: string;
7
+ /** The icon set (e.g., 'heroicons') */
8
+ iconSet: string;
9
+ /** The icon name (e.g., 'arrow-up-circle') */
10
+ iconName: string;
11
+ }
12
+ /**
13
+ * SVG transformation function type
14
+ */
15
+ export type IconTransform = (args: TransformArgs) => Promise<string> | string;
16
+ /**
17
+ * Configuration options for the Iconify CLI
18
+ */
19
+ export interface IconifyConfig {
20
+ /** Directory to output icons */
21
+ outputDir: string;
22
+ /** Array of transform functions to apply to icons */
23
+ transforms?: IconTransform[];
24
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@wkovacs64/add-icon",
3
+ "version": "0.1.0-dev.645a9b96",
4
+ "description": "CLI tool to download and transform icons from Iconify",
5
+ "keywords": [
6
+ "iconify",
7
+ "icons",
8
+ "svg",
9
+ "cli",
10
+ "download"
11
+ ],
12
+ "author": "Justin R. Hall <justin.r.hall@gmail.com>",
13
+ "license": "MIT",
14
+ "type": "module",
15
+ "main": "dist/index.js",
16
+ "exports": {
17
+ ".": "./dist/index.js",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "bin": {
21
+ "add-icon": "dist/index.js"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsc",
28
+ "clean": "del-cli dist",
29
+ "prebuild": "npm run --silent clean",
30
+ "prepublishOnly": "run-p --silent lint typecheck build",
31
+ "start": "node dist/index.js",
32
+ "dev": "tsx src/index.ts",
33
+ "typecheck": "attw --pack --profile esm-only",
34
+ "lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
35
+ "format": "prettier --cache --write .",
36
+ "format:check": "prettier --cache --check .",
37
+ "changeset": "changeset",
38
+ "changeset:version": "changeset version && npm install --package-lock-only",
39
+ "changeset:publish": "changeset publish"
40
+ },
41
+ "prettier": "@wkovacs64/prettier-config",
42
+ "engines": {
43
+ "node": ">=20.19.0"
44
+ },
45
+ "dependencies": {
46
+ "commander": "^13.1.0",
47
+ "tsx": "^4.19.3",
48
+ "typescript": "^5.8.3"
49
+ },
50
+ "devDependencies": {
51
+ "@arethetypeswrong/cli": "0.17.4",
52
+ "@changesets/changelog-github": "0.5.1",
53
+ "@changesets/cli": "2.29.0",
54
+ "@types/node": "22.14.1",
55
+ "@wkovacs64/eslint-config": "7.5.2",
56
+ "@wkovacs64/prettier-config": "4.1.1",
57
+ "del-cli": "6.0.0",
58
+ "eslint": "9.24.0",
59
+ "npm-run-all2": "7.0.2",
60
+ "prettier": "3.5.3"
61
+ }
62
+ }