@taterlaxmi/react-icon-library 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +107 -0
- package/dist/chunk-N5DDYT6F.js +174 -0
- package/dist/chunk-N5DDYT6F.js.map +1 -0
- package/dist/cli.cjs +217 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +25 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +208 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# React Icon Library
|
|
2
|
+
|
|
3
|
+
Generate reusable, typed React icon components from SVG and raster image files. The CLI converts SVGs to JSX and wraps raster images in SVG components with the image data embedded.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js 20 or newer
|
|
8
|
+
- npm
|
|
9
|
+
- A React application to render the generated components
|
|
10
|
+
|
|
11
|
+
## Generate icons in this repository
|
|
12
|
+
|
|
13
|
+
Put source images in `brand-assets/`. For example:
|
|
14
|
+
|
|
15
|
+
```text
|
|
16
|
+
react-icon-library/
|
|
17
|
+
├── brand-assets/
|
|
18
|
+
│ └── kiwi.png
|
|
19
|
+
└── src/
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Install dependencies, then run the default command:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install
|
|
26
|
+
npm run dev
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The `dev` script uses `brand-assets/` as its input and writes components to `src/icons/`. For the example above it generates `src/icons/Kiwi.tsx` and `src/icons/index.ts`. The component name is based on the filename: `kiwi.png` becomes `Kiwi` and `kiw.png` becomes `Kiw`.
|
|
30
|
+
|
|
31
|
+
**Rerunning `npm run dev` overwrites generated files** in `src/icons/`. Avoid editing generated components by hand; change the source image and regenerate instead.
|
|
32
|
+
|
|
33
|
+
## Use the generator in another repository
|
|
34
|
+
|
|
35
|
+
The generator package runs against image files in the React app where you invoke it. In the other React application's root, place the image in a folder such as `brand-assets/kiwi.png`, then install this GitHub package as a development dependency:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install --save-dev github:taterlaxmi/react-icon-library
|
|
39
|
+
npx react-icon-library ./brand-assets --output ./src/icons
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The CLI does not overwrite existing files by default. To regenerate an existing icon set, add `--overwrite`:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
npx react-icon-library ./brand-assets --output ./src/icons --overwrite
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Commit the generated `src/icons/` files in the React app. Import its generated icon like this:
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
import { Kiwi } from './icons';
|
|
52
|
+
|
|
53
|
+
export function Brand() {
|
|
54
|
+
return <Kiwi title="Kiwi" width={32} height={32} />;
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The installed package provides the generator CLI and `generateIcons()` API; it does **not** currently export this repository's sample `Kiwi` component from the package root. To use Kiwi in another app, put `kiwi.png` in that app's `brand-assets/` folder and generate the component there as shown above.
|
|
59
|
+
|
|
60
|
+
## CLI options
|
|
61
|
+
|
|
62
|
+
General form:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
npx react-icon-library [input-dir] --output <directory> [options]
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| Argument or option | Default | Description |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `[input-dir]` | `icons` | Folder containing the images |
|
|
71
|
+
| `-o, --output <directory>` | `src/icons` | Folder for generated `.tsx` files and the barrel export |
|
|
72
|
+
| `--no-recursive` | Recursive scan enabled | Only read images directly inside the input folder |
|
|
73
|
+
| `--overwrite` | Off | Replace existing generated component and index files |
|
|
74
|
+
|
|
75
|
+
From this repository, `npm run generate -- ./brand-assets --output ./src/icons` runs the CLI with custom paths. Paths are resolved from the current working directory.
|
|
76
|
+
|
|
77
|
+
## Supported images
|
|
78
|
+
|
|
79
|
+
- SVG (`.svg`): optimized and converted to inline JSX.
|
|
80
|
+
- PNG, JPEG (`.jpg`, `.jpeg`), GIF, WebP, and AVIF: embedded in the generated SVG component as a data URI.
|
|
81
|
+
|
|
82
|
+
Prefer SVG for logos and icons when possible; raster files remain raster images and the embedded data increases the generated source size. Unsupported extensions are skipped. Symbolic links are ignored. Do not feed untrusted SVG files to the generator.
|
|
83
|
+
|
|
84
|
+
## Accessibility and component props
|
|
85
|
+
|
|
86
|
+
Generated icons accept SVG props such as `className`, `style`, `width`, and `height`. Supply `title` to provide an accessible label; omit it for a decorative icon.
|
|
87
|
+
|
|
88
|
+
## Programmatic API
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { generateIcons } from 'react-icon-library';
|
|
92
|
+
|
|
93
|
+
const result = await generateIcons({
|
|
94
|
+
inputDir: './brand-assets',
|
|
95
|
+
outputDir: './src/icons',
|
|
96
|
+
recursive: true,
|
|
97
|
+
overwrite: true,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
console.log(result.icons);
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`inputDir` and `outputDir` are required. `recursive` defaults to `true`; `overwrite` defaults to `false`. The function returns generated icon names and file paths, and reports missing directories, invalid assets, name collisions, and existing output with errors.
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { access, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "fs/promises";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { randomUUID } from "crypto";
|
|
5
|
+
import { imageSize } from "image-size";
|
|
6
|
+
import { transform } from "@svgr/core";
|
|
7
|
+
var RASTER_MIME_TYPES = {
|
|
8
|
+
".png": "image/png",
|
|
9
|
+
".jpg": "image/jpeg",
|
|
10
|
+
".jpeg": "image/jpeg",
|
|
11
|
+
".gif": "image/gif",
|
|
12
|
+
".webp": "image/webp",
|
|
13
|
+
".avif": "image/avif"
|
|
14
|
+
};
|
|
15
|
+
var VECTOR_EXTENSIONS = /* @__PURE__ */ new Set([".svg"]);
|
|
16
|
+
function componentName(filePath) {
|
|
17
|
+
const baseName = path.basename(filePath, path.extname(filePath));
|
|
18
|
+
const words = baseName.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").match(/[A-Za-z0-9]+/g);
|
|
19
|
+
const name = (words ?? []).map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
|
20
|
+
const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;
|
|
21
|
+
return safeName || "Icon";
|
|
22
|
+
}
|
|
23
|
+
function isWithin(parent, child) {
|
|
24
|
+
const relative = path.relative(parent, child);
|
|
25
|
+
return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
|
|
26
|
+
}
|
|
27
|
+
function errorMessage(error) {
|
|
28
|
+
return error instanceof Error ? error.message : String(error);
|
|
29
|
+
}
|
|
30
|
+
async function findAssets(inputDir, outputDir, recursive) {
|
|
31
|
+
const assets = [];
|
|
32
|
+
async function visit(directory) {
|
|
33
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
34
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
35
|
+
for (const entry of entries) {
|
|
36
|
+
const fullPath = path.join(directory, entry.name);
|
|
37
|
+
if (entry.isSymbolicLink()) continue;
|
|
38
|
+
if (entry.isDirectory()) {
|
|
39
|
+
if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (!entry.isFile()) continue;
|
|
43
|
+
const extension = path.extname(entry.name).toLowerCase();
|
|
44
|
+
if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {
|
|
45
|
+
assets.push({ path: fullPath, name: componentName(fullPath), extension });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
await visit(inputDir);
|
|
50
|
+
return assets;
|
|
51
|
+
}
|
|
52
|
+
async function rasterComponent(asset, component) {
|
|
53
|
+
const bytes = await readFile(asset.path);
|
|
54
|
+
let dimensions;
|
|
55
|
+
try {
|
|
56
|
+
dimensions = imageSize(bytes);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new Error(`Cannot read image dimensions for "${asset.path}": ${errorMessage(error)}`);
|
|
59
|
+
}
|
|
60
|
+
if (!dimensions.width || !dimensions.height) throw new Error(`Image "${asset.path}" does not have valid dimensions.`);
|
|
61
|
+
const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString("base64")}`;
|
|
62
|
+
return `import type { SVGProps } from 'react';
|
|
63
|
+
|
|
64
|
+
export interface ${component}Props extends SVGProps<SVGSVGElement> {
|
|
65
|
+
/** Accessible label. Omit for a decorative icon. */
|
|
66
|
+
title?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const imageSource = ${JSON.stringify(dataUri)};
|
|
70
|
+
|
|
71
|
+
export default function ${component}({ title, width, height, ...props }: ${component}Props) {
|
|
72
|
+
return (
|
|
73
|
+
<svg
|
|
74
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
75
|
+
viewBox="0 0 ${dimensions.width} ${dimensions.height}"
|
|
76
|
+
width={width ?? '1em'}
|
|
77
|
+
height={height ?? '1em'}
|
|
78
|
+
role={title ? 'img' : undefined}
|
|
79
|
+
aria-hidden={title ? undefined : true}
|
|
80
|
+
{...props}
|
|
81
|
+
>
|
|
82
|
+
{title ? <title>{title}</title> : null}
|
|
83
|
+
<image href={imageSource} x="0" y="0" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" />
|
|
84
|
+
</svg>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
async function svgComponent(asset, component) {
|
|
90
|
+
const source = await readFile(asset.path, "utf8");
|
|
91
|
+
try {
|
|
92
|
+
return await transform(source, {
|
|
93
|
+
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"],
|
|
94
|
+
typescript: true,
|
|
95
|
+
jsxRuntime: "automatic",
|
|
96
|
+
icon: true,
|
|
97
|
+
titleProp: true,
|
|
98
|
+
exportType: "default",
|
|
99
|
+
prettier: false
|
|
100
|
+
}, { componentName: component });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw new Error(`Cannot convert SVG "${asset.path}": ${errorMessage(error)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function generateIcons(options) {
|
|
106
|
+
const inputDir = path.resolve(options.inputDir);
|
|
107
|
+
const outputDir = path.resolve(options.outputDir);
|
|
108
|
+
const recursive = options.recursive ?? true;
|
|
109
|
+
const overwrite = options.overwrite ?? false;
|
|
110
|
+
let inputStat;
|
|
111
|
+
try {
|
|
112
|
+
inputStat = await stat(inputDir);
|
|
113
|
+
} catch {
|
|
114
|
+
throw new Error(`Input directory does not exist: "${inputDir}"`);
|
|
115
|
+
}
|
|
116
|
+
if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: "${inputDir}"`);
|
|
117
|
+
const assets = await findAssets(inputDir, outputDir, recursive);
|
|
118
|
+
if (assets.length === 0) throw new Error(`No supported image assets found in "${inputDir}".`);
|
|
119
|
+
const names = /* @__PURE__ */ new Map();
|
|
120
|
+
for (const asset of assets) {
|
|
121
|
+
const normalizedName = asset.name.toLocaleLowerCase("en-US");
|
|
122
|
+
const previous = names.get(normalizedName);
|
|
123
|
+
if (previous) {
|
|
124
|
+
throw new Error(`Name collision: "${previous}" and "${asset.path}" both generate the component "${asset.name}". Rename one of the source files.`);
|
|
125
|
+
}
|
|
126
|
+
names.set(normalizedName, asset.path);
|
|
127
|
+
}
|
|
128
|
+
const converted = await Promise.all(assets.map(async (asset) => ({
|
|
129
|
+
asset,
|
|
130
|
+
contents: VECTOR_EXTENSIONS.has(asset.extension) ? await svgComponent(asset, asset.name) : await rasterComponent(asset, asset.name)
|
|
131
|
+
})));
|
|
132
|
+
const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join("\n")}
|
|
133
|
+
`;
|
|
134
|
+
const outputs = [
|
|
135
|
+
...converted.map(({ asset, contents }) => ({ filePath: path.join(outputDir, `${asset.name}.tsx`), contents })),
|
|
136
|
+
{ filePath: path.join(outputDir, "index.ts"), contents: indexContents }
|
|
137
|
+
];
|
|
138
|
+
if (!overwrite) {
|
|
139
|
+
const conflicts = [];
|
|
140
|
+
for (const output of outputs) {
|
|
141
|
+
try {
|
|
142
|
+
await access(output.filePath);
|
|
143
|
+
conflicts.push(output.filePath);
|
|
144
|
+
} catch {
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(", ")}. Use --overwrite to replace them.`);
|
|
148
|
+
}
|
|
149
|
+
await mkdir(outputDir, { recursive: true });
|
|
150
|
+
for (const output of outputs) {
|
|
151
|
+
const temporaryPath = `${output.filePath}.${randomUUID()}.tmp`;
|
|
152
|
+
try {
|
|
153
|
+
await writeFile(temporaryPath, output.contents, "utf8");
|
|
154
|
+
if (overwrite) await rm(output.filePath, { force: true });
|
|
155
|
+
await rename(temporaryPath, output.filePath);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
await rm(temporaryPath, { force: true });
|
|
158
|
+
throw new Error(`Failed to write "${output.filePath}": ${errorMessage(error)}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
icons: converted.map(({ asset }) => ({
|
|
163
|
+
name: asset.name,
|
|
164
|
+
source: path.relative(inputDir, asset.path),
|
|
165
|
+
componentFile: path.join(outputDir, `${asset.name}.tsx`)
|
|
166
|
+
})),
|
|
167
|
+
outputDir
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export {
|
|
172
|
+
generateIcons
|
|
173
|
+
};
|
|
174
|
+
//# sourceMappingURL=chunk-N5DDYT6F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { access, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\r\nimport path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { imageSize } from 'image-size';\r\nimport { transform } from '@svgr/core';\r\n\r\nconst RASTER_MIME_TYPES: Readonly<Record<string, string>> = {\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n};\r\nconst VECTOR_EXTENSIONS = new Set(['.svg']);\r\n\r\nexport interface GenerateIconsOptions {\r\n /** Directory containing source image assets. */\r\n inputDir: string;\r\n /** Directory where generated React components and their barrel are written. */\r\n outputDir: string;\r\n /** Include nested folders. Enabled by default. */\r\n recursive?: boolean;\r\n /** Replace generated files that already exist. Disabled by default. */\r\n overwrite?: boolean;\r\n}\r\n\r\nexport interface GeneratedIcon {\r\n name: string;\r\n source: string;\r\n componentFile: string;\r\n}\r\n\r\nexport interface GenerateIconsResult {\r\n icons: GeneratedIcon[];\r\n outputDir: string;\r\n}\r\n\r\ninterface SourceAsset {\r\n path: string;\r\n name: string;\r\n extension: string;\r\n}\r\n\r\nfunction componentName(filePath: string): string {\r\n const baseName = path.basename(filePath, path.extname(filePath));\r\n const words = baseName\r\n .normalize('NFKD')\r\n .replace(/[\\u0300-\\u036f]/g, '')\r\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\r\n .match(/[A-Za-z0-9]+/g);\r\n const name = (words ?? []).map((word) => word[0]!.toUpperCase() + word.slice(1)).join('');\r\n const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;\r\n return safeName || 'Icon';\r\n}\r\n\r\nfunction isWithin(parent: string, child: string): boolean {\r\n const relative = path.relative(parent, child);\r\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction errorMessage(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\nasync function findAssets(inputDir: string, outputDir: string, recursive: boolean): Promise<SourceAsset[]> {\r\n const assets: SourceAsset[] = [];\r\n\r\n async function visit(directory: string): Promise<void> {\r\n const entries = await readdir(directory, { withFileTypes: true });\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n for (const entry of entries) {\r\n const fullPath = path.join(directory, entry.name);\r\n if (entry.isSymbolicLink()) continue;\r\n if (entry.isDirectory()) {\r\n if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);\r\n continue;\r\n }\r\n if (!entry.isFile()) continue;\r\n const extension = path.extname(entry.name).toLowerCase();\r\n if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {\r\n assets.push({ path: fullPath, name: componentName(fullPath), extension });\r\n }\r\n }\r\n }\r\n\r\n await visit(inputDir);\r\n return assets;\r\n}\r\n\r\nasync function rasterComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const bytes = await readFile(asset.path);\r\n let dimensions: ReturnType<typeof imageSize>;\r\n try {\r\n dimensions = imageSize(bytes);\r\n } catch (error) {\r\n throw new Error(`Cannot read image dimensions for \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n if (!dimensions.width || !dimensions.height) throw new Error(`Image \"${asset.path}\" does not have valid dimensions.`);\r\n\r\n const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString('base64')}`;\r\n return `import type { SVGProps } from 'react';\r\n\r\nexport interface ${component}Props extends SVGProps<SVGSVGElement> {\r\n /** Accessible label. Omit for a decorative icon. */\r\n title?: string;\r\n}\r\n\r\nconst imageSource = ${JSON.stringify(dataUri)};\r\n\r\nexport default function ${component}({ title, width, height, ...props }: ${component}Props) {\r\n return (\r\n <svg\r\n xmlns=\"http://www.w3.org/2000/svg\"\r\n viewBox=\"0 0 ${dimensions.width} ${dimensions.height}\"\r\n width={width ?? '1em'}\r\n height={height ?? '1em'}\r\n role={title ? 'img' : undefined}\r\n aria-hidden={title ? undefined : true}\r\n {...props}\r\n >\r\n {title ? <title>{title}</title> : null}\r\n <image href={imageSource} x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" />\r\n </svg>\r\n );\r\n}\r\n`;\r\n}\r\n\r\nasync function svgComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const source = await readFile(asset.path, 'utf8');\r\n try {\r\n return await transform(source, {\r\n plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx'],\r\n typescript: true,\r\n jsxRuntime: 'automatic',\r\n icon: true,\r\n titleProp: true,\r\n exportType: 'default',\r\n prettier: false,\r\n }, { componentName: component });\r\n } catch (error) {\r\n throw new Error(`Cannot convert SVG \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n}\r\n\r\n/** Generate typed React components and a named-export barrel from image files. */\r\nexport async function generateIcons(options: GenerateIconsOptions): Promise<GenerateIconsResult> {\r\n const inputDir = path.resolve(options.inputDir);\r\n const outputDir = path.resolve(options.outputDir);\r\n const recursive = options.recursive ?? true;\r\n const overwrite = options.overwrite ?? false;\r\n\r\n let inputStat;\r\n try {\r\n inputStat = await stat(inputDir);\r\n } catch {\r\n throw new Error(`Input directory does not exist: \"${inputDir}\"`);\r\n }\r\n if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: \"${inputDir}\"`);\r\n\r\n const assets = await findAssets(inputDir, outputDir, recursive);\r\n if (assets.length === 0) throw new Error(`No supported image assets found in \"${inputDir}\".`);\r\n\r\n const names = new Map<string, string>();\r\n for (const asset of assets) {\r\n const normalizedName = asset.name.toLocaleLowerCase('en-US');\r\n const previous = names.get(normalizedName);\r\n if (previous) {\r\n throw new Error(`Name collision: \"${previous}\" and \"${asset.path}\" both generate the component \"${asset.name}\". Rename one of the source files.`);\r\n }\r\n names.set(normalizedName, asset.path);\r\n }\r\n\r\n // Convert all inputs before writing so malformed assets do not leave partial output.\r\n const converted = await Promise.all(assets.map(async (asset) => ({\r\n asset,\r\n contents: VECTOR_EXTENSIONS.has(asset.extension)\r\n ? await svgComponent(asset, asset.name)\r\n : await rasterComponent(asset, asset.name),\r\n })));\r\n\r\n const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join('\\n')}\\n`;\r\n const outputs = [\r\n ...converted.map(({ asset, contents }) => ({ filePath: path.join(outputDir, `${asset.name}.tsx`), contents })),\r\n { filePath: path.join(outputDir, 'index.ts'), contents: indexContents },\r\n ];\r\n\r\n if (!overwrite) {\r\n const conflicts: string[] = [];\r\n for (const output of outputs) {\r\n try {\r\n await access(output.filePath);\r\n conflicts.push(output.filePath);\r\n } catch {\r\n // A missing destination is expected for a fresh generation.\r\n }\r\n }\r\n if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(', ')}. Use --overwrite to replace them.`);\r\n }\r\n\r\n await mkdir(outputDir, { recursive: true });\r\n for (const output of outputs) {\r\n const temporaryPath = `${output.filePath}.${randomUUID()}.tmp`;\r\n try {\r\n await writeFile(temporaryPath, output.contents, 'utf8');\r\n if (overwrite) await rm(output.filePath, { force: true });\r\n await rename(temporaryPath, output.filePath);\r\n } catch (error) {\r\n await rm(temporaryPath, { force: true });\r\n throw new Error(`Failed to write \"${output.filePath}\": ${errorMessage(error)}`);\r\n }\r\n }\r\n\r\n return {\r\n icons: converted.map(({ asset }) => ({\r\n name: asset.name,\r\n source: path.relative(inputDir, asset.path),\r\n componentFile: path.join(outputDir, `${asset.name}.tsx`),\r\n })),\r\n outputDir,\r\n };\r\n}"],"mappings":";AAAA,SAAS,QAAQ,OAAO,UAAU,SAAS,QAAQ,IAAI,MAAM,iBAAiB;AAC9E,OAAO,UAAU;AACjB,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAE1B,IAAM,oBAAsD;AAAA,EAC1D,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AACX;AACA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,MAAM,CAAC;AA8B1C,SAAS,cAAc,UAA0B;AAC/C,QAAM,WAAW,KAAK,SAAS,UAAU,KAAK,QAAQ,QAAQ,CAAC;AAC/D,QAAM,QAAQ,SACX,UAAU,MAAM,EAChB,QAAQ,oBAAoB,EAAE,EAC9B,QAAQ,sBAAsB,OAAO,EACrC,MAAM,eAAe;AACxB,QAAM,QAAQ,SAAS,CAAC,GAAG,IAAI,CAAC,SAAS,KAAK,CAAC,EAAG,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE;AACxF,QAAM,WAAW,cAAc,KAAK,IAAI,IAAI,OAAO,OAAO,IAAI;AAC9D,SAAO,YAAY;AACrB;AAEA,SAAS,SAAS,QAAgB,OAAwB;AACxD,QAAM,WAAW,KAAK,SAAS,QAAQ,KAAK;AAC5C,SAAO,aAAa,MAAO,CAAC,SAAS,WAA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AAK,IAAI,CAAC,oCAAoC;AAAA,EACrJ;AAEA,QAAM,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,aAAW,UAAU,SAAS;AAC5B,UAAM,gBAAgB,GAAG,OAAO,QAAQ,IAAI,WAAW,CAAC;AACxD,QAAI;AACF,YAAM,UAAU,eAAe,OAAO,UAAU,MAAM;AACtD,UAAI,UAAW,OAAM,GAAG,OAAO,UAAU,EAAE,OAAO,KAAK,CAAC;AACxD,YAAM,OAAO,eAAe,OAAO,QAAQ;AAAA,IAC7C,SAAS,OAAO;AACd,YAAM,GAAG,eAAe,EAAE,OAAO,KAAK,CAAC;AACvC,YAAM,IAAI,MAAM,oBAAoB,OAAO,QAAQ,MAAM,aAAa,KAAK,CAAC,EAAE;AAAA,IAChF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,UAAU,IAAI,CAAC,EAAE,MAAM,OAAO;AAAA,MACnC,MAAM,MAAM;AAAA,MACZ,QAAQ,KAAK,SAAS,UAAU,MAAM,IAAI;AAAA,MAC1C,eAAe,KAAK,KAAK,WAAW,GAAG,MAAM,IAAI,MAAM;AAAA,IACzD,EAAE;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// src/cli.ts
|
|
27
|
+
var import_commander = require("commander");
|
|
28
|
+
|
|
29
|
+
// src/index.ts
|
|
30
|
+
var import_promises = require("fs/promises");
|
|
31
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
32
|
+
var import_node_crypto = require("crypto");
|
|
33
|
+
var import_image_size = require("image-size");
|
|
34
|
+
var import_core = require("@svgr/core");
|
|
35
|
+
var RASTER_MIME_TYPES = {
|
|
36
|
+
".png": "image/png",
|
|
37
|
+
".jpg": "image/jpeg",
|
|
38
|
+
".jpeg": "image/jpeg",
|
|
39
|
+
".gif": "image/gif",
|
|
40
|
+
".webp": "image/webp",
|
|
41
|
+
".avif": "image/avif"
|
|
42
|
+
};
|
|
43
|
+
var VECTOR_EXTENSIONS = /* @__PURE__ */ new Set([".svg"]);
|
|
44
|
+
function componentName(filePath) {
|
|
45
|
+
const baseName = import_node_path.default.basename(filePath, import_node_path.default.extname(filePath));
|
|
46
|
+
const words = baseName.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").match(/[A-Za-z0-9]+/g);
|
|
47
|
+
const name = (words ?? []).map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
|
48
|
+
const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;
|
|
49
|
+
return safeName || "Icon";
|
|
50
|
+
}
|
|
51
|
+
function isWithin(parent, child) {
|
|
52
|
+
const relative = import_node_path.default.relative(parent, child);
|
|
53
|
+
return relative === "" || !relative.startsWith(`..${import_node_path.default.sep}`) && relative !== ".." && !import_node_path.default.isAbsolute(relative);
|
|
54
|
+
}
|
|
55
|
+
function errorMessage(error) {
|
|
56
|
+
return error instanceof Error ? error.message : String(error);
|
|
57
|
+
}
|
|
58
|
+
async function findAssets(inputDir, outputDir, recursive) {
|
|
59
|
+
const assets = [];
|
|
60
|
+
async function visit(directory) {
|
|
61
|
+
const entries = await (0, import_promises.readdir)(directory, { withFileTypes: true });
|
|
62
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
const fullPath = import_node_path.default.join(directory, entry.name);
|
|
65
|
+
if (entry.isSymbolicLink()) continue;
|
|
66
|
+
if (entry.isDirectory()) {
|
|
67
|
+
if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (!entry.isFile()) continue;
|
|
71
|
+
const extension = import_node_path.default.extname(entry.name).toLowerCase();
|
|
72
|
+
if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {
|
|
73
|
+
assets.push({ path: fullPath, name: componentName(fullPath), extension });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
await visit(inputDir);
|
|
78
|
+
return assets;
|
|
79
|
+
}
|
|
80
|
+
async function rasterComponent(asset, component) {
|
|
81
|
+
const bytes = await (0, import_promises.readFile)(asset.path);
|
|
82
|
+
let dimensions;
|
|
83
|
+
try {
|
|
84
|
+
dimensions = (0, import_image_size.imageSize)(bytes);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
throw new Error(`Cannot read image dimensions for "${asset.path}": ${errorMessage(error)}`);
|
|
87
|
+
}
|
|
88
|
+
if (!dimensions.width || !dimensions.height) throw new Error(`Image "${asset.path}" does not have valid dimensions.`);
|
|
89
|
+
const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString("base64")}`;
|
|
90
|
+
return `import type { SVGProps } from 'react';
|
|
91
|
+
|
|
92
|
+
export interface ${component}Props extends SVGProps<SVGSVGElement> {
|
|
93
|
+
/** Accessible label. Omit for a decorative icon. */
|
|
94
|
+
title?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const imageSource = ${JSON.stringify(dataUri)};
|
|
98
|
+
|
|
99
|
+
export default function ${component}({ title, width, height, ...props }: ${component}Props) {
|
|
100
|
+
return (
|
|
101
|
+
<svg
|
|
102
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
103
|
+
viewBox="0 0 ${dimensions.width} ${dimensions.height}"
|
|
104
|
+
width={width ?? '1em'}
|
|
105
|
+
height={height ?? '1em'}
|
|
106
|
+
role={title ? 'img' : undefined}
|
|
107
|
+
aria-hidden={title ? undefined : true}
|
|
108
|
+
{...props}
|
|
109
|
+
>
|
|
110
|
+
{title ? <title>{title}</title> : null}
|
|
111
|
+
<image href={imageSource} x="0" y="0" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" />
|
|
112
|
+
</svg>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
`;
|
|
116
|
+
}
|
|
117
|
+
async function svgComponent(asset, component) {
|
|
118
|
+
const source = await (0, import_promises.readFile)(asset.path, "utf8");
|
|
119
|
+
try {
|
|
120
|
+
return await (0, import_core.transform)(source, {
|
|
121
|
+
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"],
|
|
122
|
+
typescript: true,
|
|
123
|
+
jsxRuntime: "automatic",
|
|
124
|
+
icon: true,
|
|
125
|
+
titleProp: true,
|
|
126
|
+
exportType: "default",
|
|
127
|
+
prettier: false
|
|
128
|
+
}, { componentName: component });
|
|
129
|
+
} catch (error) {
|
|
130
|
+
throw new Error(`Cannot convert SVG "${asset.path}": ${errorMessage(error)}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function generateIcons(options) {
|
|
134
|
+
const inputDir = import_node_path.default.resolve(options.inputDir);
|
|
135
|
+
const outputDir = import_node_path.default.resolve(options.outputDir);
|
|
136
|
+
const recursive = options.recursive ?? true;
|
|
137
|
+
const overwrite = options.overwrite ?? false;
|
|
138
|
+
let inputStat;
|
|
139
|
+
try {
|
|
140
|
+
inputStat = await (0, import_promises.stat)(inputDir);
|
|
141
|
+
} catch {
|
|
142
|
+
throw new Error(`Input directory does not exist: "${inputDir}"`);
|
|
143
|
+
}
|
|
144
|
+
if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: "${inputDir}"`);
|
|
145
|
+
const assets = await findAssets(inputDir, outputDir, recursive);
|
|
146
|
+
if (assets.length === 0) throw new Error(`No supported image assets found in "${inputDir}".`);
|
|
147
|
+
const names = /* @__PURE__ */ new Map();
|
|
148
|
+
for (const asset of assets) {
|
|
149
|
+
const normalizedName = asset.name.toLocaleLowerCase("en-US");
|
|
150
|
+
const previous = names.get(normalizedName);
|
|
151
|
+
if (previous) {
|
|
152
|
+
throw new Error(`Name collision: "${previous}" and "${asset.path}" both generate the component "${asset.name}". Rename one of the source files.`);
|
|
153
|
+
}
|
|
154
|
+
names.set(normalizedName, asset.path);
|
|
155
|
+
}
|
|
156
|
+
const converted = await Promise.all(assets.map(async (asset) => ({
|
|
157
|
+
asset,
|
|
158
|
+
contents: VECTOR_EXTENSIONS.has(asset.extension) ? await svgComponent(asset, asset.name) : await rasterComponent(asset, asset.name)
|
|
159
|
+
})));
|
|
160
|
+
const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join("\n")}
|
|
161
|
+
`;
|
|
162
|
+
const outputs = [
|
|
163
|
+
...converted.map(({ asset, contents }) => ({ filePath: import_node_path.default.join(outputDir, `${asset.name}.tsx`), contents })),
|
|
164
|
+
{ filePath: import_node_path.default.join(outputDir, "index.ts"), contents: indexContents }
|
|
165
|
+
];
|
|
166
|
+
if (!overwrite) {
|
|
167
|
+
const conflicts = [];
|
|
168
|
+
for (const output of outputs) {
|
|
169
|
+
try {
|
|
170
|
+
await (0, import_promises.access)(output.filePath);
|
|
171
|
+
conflicts.push(output.filePath);
|
|
172
|
+
} catch {
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(", ")}. Use --overwrite to replace them.`);
|
|
176
|
+
}
|
|
177
|
+
await (0, import_promises.mkdir)(outputDir, { recursive: true });
|
|
178
|
+
for (const output of outputs) {
|
|
179
|
+
const temporaryPath = `${output.filePath}.${(0, import_node_crypto.randomUUID)()}.tmp`;
|
|
180
|
+
try {
|
|
181
|
+
await (0, import_promises.writeFile)(temporaryPath, output.contents, "utf8");
|
|
182
|
+
if (overwrite) await (0, import_promises.rm)(output.filePath, { force: true });
|
|
183
|
+
await (0, import_promises.rename)(temporaryPath, output.filePath);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
await (0, import_promises.rm)(temporaryPath, { force: true });
|
|
186
|
+
throw new Error(`Failed to write "${output.filePath}": ${errorMessage(error)}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
icons: converted.map(({ asset }) => ({
|
|
191
|
+
name: asset.name,
|
|
192
|
+
source: import_node_path.default.relative(inputDir, asset.path),
|
|
193
|
+
componentFile: import_node_path.default.join(outputDir, `${asset.name}.tsx`)
|
|
194
|
+
})),
|
|
195
|
+
outputDir
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/cli.ts
|
|
200
|
+
var program = new import_commander.Command();
|
|
201
|
+
program.name("react-icon-library").description("Generate reusable React icon components from SVG and raster image files.").argument("[input-dir]", "directory containing image assets", "icons").option("-o, --output <directory>", "output directory for generated components", "src/icons").option("--no-recursive", "only read images directly inside the input directory").option("--overwrite", "replace existing generated component files").action(async (inputDir, options) => {
|
|
202
|
+
try {
|
|
203
|
+
const result = await generateIcons({
|
|
204
|
+
inputDir,
|
|
205
|
+
outputDir: options.output,
|
|
206
|
+
recursive: options.recursive,
|
|
207
|
+
...options.overwrite === void 0 ? {} : { overwrite: options.overwrite }
|
|
208
|
+
});
|
|
209
|
+
console.log(`Generated ${result.icons.length} React icon(s) in ${result.outputDir}`);
|
|
210
|
+
for (const icon of result.icons) console.log(` ${icon.name} \u2190 ${icon.source}`);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
213
|
+
process.exitCode = 1;
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
program.parseAsync();
|
|
217
|
+
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { Command } from 'commander';\r\nimport { generateIcons } from './index.js';\r\n\r\nconst program = new Command();\r\nprogram\r\n .name('react-icon-library')\r\n .description('Generate reusable React icon components from SVG and raster image files.')\r\n .argument('[input-dir]', 'directory containing image assets', 'icons')\r\n .option('-o, --output <directory>', 'output directory for generated components', 'src/icons')\r\n .option('--no-recursive', 'only read images directly inside the input directory')\r\n .option('--overwrite', 'replace existing generated component files')\r\n .action(async (inputDir: string, options: { output: string; recursive: boolean; overwrite?: boolean }) => {\r\n try {\r\n const result = await generateIcons({\r\n inputDir,\r\n outputDir: options.output,\r\n recursive: options.recursive,\r\n ...(options.overwrite === undefined ? {} : { overwrite: options.overwrite }),\r\n });\r\n console.log(`Generated ${result.icons.length} React icon(s) in ${result.outputDir}`);\r\n for (const icon of result.icons) console.log(` ${icon.name} ← ${icon.source}`);\r\n } catch (error) {\r\n console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\r\n process.exitCode = 1;\r\n }\r\n });\r\n\r\nprogram.parseAsync();","import { access, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\r\nimport path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { imageSize } from 'image-size';\r\nimport { transform } from '@svgr/core';\r\n\r\nconst RASTER_MIME_TYPES: Readonly<Record<string, string>> = {\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n};\r\nconst VECTOR_EXTENSIONS = new Set(['.svg']);\r\n\r\nexport interface GenerateIconsOptions {\r\n /** Directory containing source image assets. */\r\n inputDir: string;\r\n /** Directory where generated React components and their barrel are written. */\r\n outputDir: string;\r\n /** Include nested folders. Enabled by default. */\r\n recursive?: boolean;\r\n /** Replace generated files that already exist. Disabled by default. */\r\n overwrite?: boolean;\r\n}\r\n\r\nexport interface GeneratedIcon {\r\n name: string;\r\n source: string;\r\n componentFile: string;\r\n}\r\n\r\nexport interface GenerateIconsResult {\r\n icons: GeneratedIcon[];\r\n outputDir: string;\r\n}\r\n\r\ninterface SourceAsset {\r\n path: string;\r\n name: string;\r\n extension: string;\r\n}\r\n\r\nfunction componentName(filePath: string): string {\r\n const baseName = path.basename(filePath, path.extname(filePath));\r\n const words = baseName\r\n .normalize('NFKD')\r\n .replace(/[\\u0300-\\u036f]/g, '')\r\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\r\n .match(/[A-Za-z0-9]+/g);\r\n const name = (words ?? []).map((word) => word[0]!.toUpperCase() + word.slice(1)).join('');\r\n const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;\r\n return safeName || 'Icon';\r\n}\r\n\r\nfunction isWithin(parent: string, child: string): boolean {\r\n const relative = path.relative(parent, child);\r\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction errorMessage(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\nasync function findAssets(inputDir: string, outputDir: string, recursive: boolean): Promise<SourceAsset[]> {\r\n const assets: SourceAsset[] = [];\r\n\r\n async function visit(directory: string): Promise<void> {\r\n const entries = await readdir(directory, { withFileTypes: true });\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n for (const entry of entries) {\r\n const fullPath = path.join(directory, entry.name);\r\n if (entry.isSymbolicLink()) continue;\r\n if (entry.isDirectory()) {\r\n if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);\r\n continue;\r\n }\r\n if (!entry.isFile()) continue;\r\n const extension = path.extname(entry.name).toLowerCase();\r\n if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {\r\n assets.push({ path: fullPath, name: componentName(fullPath), extension });\r\n }\r\n }\r\n }\r\n\r\n await visit(inputDir);\r\n return assets;\r\n}\r\n\r\nasync function rasterComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const bytes = await readFile(asset.path);\r\n let dimensions: ReturnType<typeof imageSize>;\r\n try {\r\n dimensions = imageSize(bytes);\r\n } catch (error) {\r\n throw new Error(`Cannot read image dimensions for \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n if (!dimensions.width || !dimensions.height) throw new Error(`Image \"${asset.path}\" does not have valid dimensions.`);\r\n\r\n const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString('base64')}`;\r\n return `import type { SVGProps } from 'react';\r\n\r\nexport interface ${component}Props extends SVGProps<SVGSVGElement> {\r\n /** Accessible label. Omit for a decorative icon. */\r\n title?: string;\r\n}\r\n\r\nconst imageSource = ${JSON.stringify(dataUri)};\r\n\r\nexport default function ${component}({ title, width, height, ...props }: ${component}Props) {\r\n return (\r\n <svg\r\n xmlns=\"http://www.w3.org/2000/svg\"\r\n viewBox=\"0 0 ${dimensions.width} ${dimensions.height}\"\r\n width={width ?? '1em'}\r\n height={height ?? '1em'}\r\n role={title ? 'img' : undefined}\r\n aria-hidden={title ? undefined : true}\r\n {...props}\r\n >\r\n {title ? <title>{title}</title> : null}\r\n <image href={imageSource} x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" />\r\n </svg>\r\n );\r\n}\r\n`;\r\n}\r\n\r\nasync function svgComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const source = await readFile(asset.path, 'utf8');\r\n try {\r\n return await transform(source, {\r\n plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx'],\r\n typescript: true,\r\n jsxRuntime: 'automatic',\r\n icon: true,\r\n titleProp: true,\r\n exportType: 'default',\r\n prettier: false,\r\n }, { componentName: component });\r\n } catch (error) {\r\n throw new Error(`Cannot convert SVG \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n}\r\n\r\n/** Generate typed React components and a named-export barrel from image files. */\r\nexport async function generateIcons(options: GenerateIconsOptions): Promise<GenerateIconsResult> {\r\n const inputDir = path.resolve(options.inputDir);\r\n const outputDir = path.resolve(options.outputDir);\r\n const recursive = options.recursive ?? true;\r\n const overwrite = options.overwrite ?? false;\r\n\r\n let inputStat;\r\n try {\r\n inputStat = await stat(inputDir);\r\n } catch {\r\n throw new Error(`Input directory does not exist: \"${inputDir}\"`);\r\n }\r\n if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: \"${inputDir}\"`);\r\n\r\n const assets = await findAssets(inputDir, outputDir, recursive);\r\n if (assets.length === 0) throw new Error(`No supported image assets found in \"${inputDir}\".`);\r\n\r\n const names = new Map<string, string>();\r\n for (const asset of assets) {\r\n const normalizedName = asset.name.toLocaleLowerCase('en-US');\r\n const previous = names.get(normalizedName);\r\n if (previous) {\r\n throw new Error(`Name collision: \"${previous}\" and \"${asset.path}\" both generate the component \"${asset.name}\". Rename one of the source files.`);\r\n }\r\n names.set(normalizedName, asset.path);\r\n }\r\n\r\n // Convert all inputs before writing so malformed assets do not leave partial output.\r\n const converted = await Promise.all(assets.map(async (asset) => ({\r\n asset,\r\n contents: VECTOR_EXTENSIONS.has(asset.extension)\r\n ? await svgComponent(asset, asset.name)\r\n : await rasterComponent(asset, asset.name),\r\n })));\r\n\r\n const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join('\\n')}\\n`;\r\n const outputs = [\r\n ...converted.map(({ asset, contents }) => ({ filePath: path.join(outputDir, `${asset.name}.tsx`), contents })),\r\n { filePath: path.join(outputDir, 'index.ts'), contents: indexContents },\r\n ];\r\n\r\n if (!overwrite) {\r\n const conflicts: string[] = [];\r\n for (const output of outputs) {\r\n try {\r\n await access(output.filePath);\r\n conflicts.push(output.filePath);\r\n } catch {\r\n // A missing destination is expected for a fresh generation.\r\n }\r\n }\r\n if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(', ')}. Use --overwrite to replace them.`);\r\n }\r\n\r\n await mkdir(outputDir, { recursive: true });\r\n for (const output of outputs) {\r\n const temporaryPath = `${output.filePath}.${randomUUID()}.tmp`;\r\n try {\r\n await writeFile(temporaryPath, output.contents, 'utf8');\r\n if (overwrite) await rm(output.filePath, { force: true });\r\n await rename(temporaryPath, output.filePath);\r\n } catch (error) {\r\n await rm(temporaryPath, { force: true });\r\n throw new Error(`Failed to write \"${output.filePath}\": ${errorMessage(error)}`);\r\n }\r\n }\r\n\r\n return {\r\n icons: converted.map(({ asset }) => ({\r\n name: asset.name,\r\n source: path.relative(inputDir, asset.path),\r\n componentFile: path.join(outputDir, `${asset.name}.tsx`),\r\n })),\r\n outputDir,\r\n };\r\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,uBAAwB;;;ACDxB,sBAA8E;AAC9E,uBAAiB;AACjB,yBAA2B;AAC3B,wBAA0B;AAC1B,kBAA0B;AAE1B,IAAM,oBAAsD;AAAA,EAC1D,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,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import {
|
|
3
|
+
generateIcons
|
|
4
|
+
} from "./chunk-N5DDYT6F.js";
|
|
5
|
+
|
|
6
|
+
// src/cli.ts
|
|
7
|
+
import { Command } from "commander";
|
|
8
|
+
var program = new Command();
|
|
9
|
+
program.name("react-icon-library").description("Generate reusable React icon components from SVG and raster image files.").argument("[input-dir]", "directory containing image assets", "icons").option("-o, --output <directory>", "output directory for generated components", "src/icons").option("--no-recursive", "only read images directly inside the input directory").option("--overwrite", "replace existing generated component files").action(async (inputDir, options) => {
|
|
10
|
+
try {
|
|
11
|
+
const result = await generateIcons({
|
|
12
|
+
inputDir,
|
|
13
|
+
outputDir: options.output,
|
|
14
|
+
recursive: options.recursive,
|
|
15
|
+
...options.overwrite === void 0 ? {} : { overwrite: options.overwrite }
|
|
16
|
+
});
|
|
17
|
+
console.log(`Generated ${result.icons.length} React icon(s) in ${result.outputDir}`);
|
|
18
|
+
for (const icon of result.icons) console.log(` ${icon.name} \u2190 ${icon.source}`);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
program.parseAsync();
|
|
25
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { Command } from 'commander';\r\nimport { generateIcons } from './index.js';\r\n\r\nconst program = new Command();\r\nprogram\r\n .name('react-icon-library')\r\n .description('Generate reusable React icon components from SVG and raster image files.')\r\n .argument('[input-dir]', 'directory containing image assets', 'icons')\r\n .option('-o, --output <directory>', 'output directory for generated components', 'src/icons')\r\n .option('--no-recursive', 'only read images directly inside the input directory')\r\n .option('--overwrite', 'replace existing generated component files')\r\n .action(async (inputDir: string, options: { output: string; recursive: boolean; overwrite?: boolean }) => {\r\n try {\r\n const result = await generateIcons({\r\n inputDir,\r\n outputDir: options.output,\r\n recursive: options.recursive,\r\n ...(options.overwrite === undefined ? {} : { overwrite: options.overwrite }),\r\n });\r\n console.log(`Generated ${result.icons.length} React icon(s) in ${result.outputDir}`);\r\n for (const icon of result.icons) console.log(` ${icon.name} ← ${icon.source}`);\r\n } catch (error) {\r\n console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\r\n process.exitCode = 1;\r\n }\r\n });\r\n\r\nprogram.parseAsync();"],"mappings":";;;;;;AACA,SAAS,eAAe;AAGxB,IAAM,UAAU,IAAI,QAAQ;AAC5B,QACG,KAAK,oBAAoB,EACzB,YAAY,0EAA0E,EACtF,SAAS,eAAe,qCAAqC,OAAO,EACpE,OAAO,4BAA4B,6CAA6C,WAAW,EAC3F,OAAO,kBAAkB,sDAAsD,EAC/E,OAAO,eAAe,4CAA4C,EAClE,OAAO,OAAO,UAAkB,YAAyE;AACxG,MAAI;AACF,UAAM,SAAS,MAAM,cAAc;AAAA,MACjC;AAAA,MACA,WAAW,QAAQ;AAAA,MACnB,WAAW,QAAQ;AAAA,MACnB,GAAI,QAAQ,cAAc,SAAY,CAAC,IAAI,EAAE,WAAW,QAAQ,UAAU;AAAA,IAC5E,CAAC;AACD,YAAQ,IAAI,aAAa,OAAO,MAAM,MAAM,qBAAqB,OAAO,SAAS,EAAE;AACnF,eAAW,QAAQ,OAAO,MAAO,SAAQ,IAAI,KAAK,KAAK,IAAI,aAAQ,KAAK,MAAM,EAAE;AAAA,EAClF,SAAS,OAAO;AACd,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,YAAQ,WAAW;AAAA,EACrB;AACF,CAAC;AAEH,QAAQ,WAAW;","names":[]}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
generateIcons: () => generateIcons
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(index_exports);
|
|
36
|
+
var import_promises = require("fs/promises");
|
|
37
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
38
|
+
var import_node_crypto = require("crypto");
|
|
39
|
+
var import_image_size = require("image-size");
|
|
40
|
+
var import_core = require("@svgr/core");
|
|
41
|
+
var RASTER_MIME_TYPES = {
|
|
42
|
+
".png": "image/png",
|
|
43
|
+
".jpg": "image/jpeg",
|
|
44
|
+
".jpeg": "image/jpeg",
|
|
45
|
+
".gif": "image/gif",
|
|
46
|
+
".webp": "image/webp",
|
|
47
|
+
".avif": "image/avif"
|
|
48
|
+
};
|
|
49
|
+
var VECTOR_EXTENSIONS = /* @__PURE__ */ new Set([".svg"]);
|
|
50
|
+
function componentName(filePath) {
|
|
51
|
+
const baseName = import_node_path.default.basename(filePath, import_node_path.default.extname(filePath));
|
|
52
|
+
const words = baseName.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").match(/[A-Za-z0-9]+/g);
|
|
53
|
+
const name = (words ?? []).map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
|
54
|
+
const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;
|
|
55
|
+
return safeName || "Icon";
|
|
56
|
+
}
|
|
57
|
+
function isWithin(parent, child) {
|
|
58
|
+
const relative = import_node_path.default.relative(parent, child);
|
|
59
|
+
return relative === "" || !relative.startsWith(`..${import_node_path.default.sep}`) && relative !== ".." && !import_node_path.default.isAbsolute(relative);
|
|
60
|
+
}
|
|
61
|
+
function errorMessage(error) {
|
|
62
|
+
return error instanceof Error ? error.message : String(error);
|
|
63
|
+
}
|
|
64
|
+
async function findAssets(inputDir, outputDir, recursive) {
|
|
65
|
+
const assets = [];
|
|
66
|
+
async function visit(directory) {
|
|
67
|
+
const entries = await (0, import_promises.readdir)(directory, { withFileTypes: true });
|
|
68
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
69
|
+
for (const entry of entries) {
|
|
70
|
+
const fullPath = import_node_path.default.join(directory, entry.name);
|
|
71
|
+
if (entry.isSymbolicLink()) continue;
|
|
72
|
+
if (entry.isDirectory()) {
|
|
73
|
+
if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!entry.isFile()) continue;
|
|
77
|
+
const extension = import_node_path.default.extname(entry.name).toLowerCase();
|
|
78
|
+
if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {
|
|
79
|
+
assets.push({ path: fullPath, name: componentName(fullPath), extension });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
await visit(inputDir);
|
|
84
|
+
return assets;
|
|
85
|
+
}
|
|
86
|
+
async function rasterComponent(asset, component) {
|
|
87
|
+
const bytes = await (0, import_promises.readFile)(asset.path);
|
|
88
|
+
let dimensions;
|
|
89
|
+
try {
|
|
90
|
+
dimensions = (0, import_image_size.imageSize)(bytes);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
throw new Error(`Cannot read image dimensions for "${asset.path}": ${errorMessage(error)}`);
|
|
93
|
+
}
|
|
94
|
+
if (!dimensions.width || !dimensions.height) throw new Error(`Image "${asset.path}" does not have valid dimensions.`);
|
|
95
|
+
const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString("base64")}`;
|
|
96
|
+
return `import type { SVGProps } from 'react';
|
|
97
|
+
|
|
98
|
+
export interface ${component}Props extends SVGProps<SVGSVGElement> {
|
|
99
|
+
/** Accessible label. Omit for a decorative icon. */
|
|
100
|
+
title?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const imageSource = ${JSON.stringify(dataUri)};
|
|
104
|
+
|
|
105
|
+
export default function ${component}({ title, width, height, ...props }: ${component}Props) {
|
|
106
|
+
return (
|
|
107
|
+
<svg
|
|
108
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
109
|
+
viewBox="0 0 ${dimensions.width} ${dimensions.height}"
|
|
110
|
+
width={width ?? '1em'}
|
|
111
|
+
height={height ?? '1em'}
|
|
112
|
+
role={title ? 'img' : undefined}
|
|
113
|
+
aria-hidden={title ? undefined : true}
|
|
114
|
+
{...props}
|
|
115
|
+
>
|
|
116
|
+
{title ? <title>{title}</title> : null}
|
|
117
|
+
<image href={imageSource} x="0" y="0" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" />
|
|
118
|
+
</svg>
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
`;
|
|
122
|
+
}
|
|
123
|
+
async function svgComponent(asset, component) {
|
|
124
|
+
const source = await (0, import_promises.readFile)(asset.path, "utf8");
|
|
125
|
+
try {
|
|
126
|
+
return await (0, import_core.transform)(source, {
|
|
127
|
+
plugins: ["@svgr/plugin-svgo", "@svgr/plugin-jsx"],
|
|
128
|
+
typescript: true,
|
|
129
|
+
jsxRuntime: "automatic",
|
|
130
|
+
icon: true,
|
|
131
|
+
titleProp: true,
|
|
132
|
+
exportType: "default",
|
|
133
|
+
prettier: false
|
|
134
|
+
}, { componentName: component });
|
|
135
|
+
} catch (error) {
|
|
136
|
+
throw new Error(`Cannot convert SVG "${asset.path}": ${errorMessage(error)}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function generateIcons(options) {
|
|
140
|
+
const inputDir = import_node_path.default.resolve(options.inputDir);
|
|
141
|
+
const outputDir = import_node_path.default.resolve(options.outputDir);
|
|
142
|
+
const recursive = options.recursive ?? true;
|
|
143
|
+
const overwrite = options.overwrite ?? false;
|
|
144
|
+
let inputStat;
|
|
145
|
+
try {
|
|
146
|
+
inputStat = await (0, import_promises.stat)(inputDir);
|
|
147
|
+
} catch {
|
|
148
|
+
throw new Error(`Input directory does not exist: "${inputDir}"`);
|
|
149
|
+
}
|
|
150
|
+
if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: "${inputDir}"`);
|
|
151
|
+
const assets = await findAssets(inputDir, outputDir, recursive);
|
|
152
|
+
if (assets.length === 0) throw new Error(`No supported image assets found in "${inputDir}".`);
|
|
153
|
+
const names = /* @__PURE__ */ new Map();
|
|
154
|
+
for (const asset of assets) {
|
|
155
|
+
const normalizedName = asset.name.toLocaleLowerCase("en-US");
|
|
156
|
+
const previous = names.get(normalizedName);
|
|
157
|
+
if (previous) {
|
|
158
|
+
throw new Error(`Name collision: "${previous}" and "${asset.path}" both generate the component "${asset.name}". Rename one of the source files.`);
|
|
159
|
+
}
|
|
160
|
+
names.set(normalizedName, asset.path);
|
|
161
|
+
}
|
|
162
|
+
const converted = await Promise.all(assets.map(async (asset) => ({
|
|
163
|
+
asset,
|
|
164
|
+
contents: VECTOR_EXTENSIONS.has(asset.extension) ? await svgComponent(asset, asset.name) : await rasterComponent(asset, asset.name)
|
|
165
|
+
})));
|
|
166
|
+
const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join("\n")}
|
|
167
|
+
`;
|
|
168
|
+
const outputs = [
|
|
169
|
+
...converted.map(({ asset, contents }) => ({ filePath: import_node_path.default.join(outputDir, `${asset.name}.tsx`), contents })),
|
|
170
|
+
{ filePath: import_node_path.default.join(outputDir, "index.ts"), contents: indexContents }
|
|
171
|
+
];
|
|
172
|
+
if (!overwrite) {
|
|
173
|
+
const conflicts = [];
|
|
174
|
+
for (const output of outputs) {
|
|
175
|
+
try {
|
|
176
|
+
await (0, import_promises.access)(output.filePath);
|
|
177
|
+
conflicts.push(output.filePath);
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(", ")}. Use --overwrite to replace them.`);
|
|
182
|
+
}
|
|
183
|
+
await (0, import_promises.mkdir)(outputDir, { recursive: true });
|
|
184
|
+
for (const output of outputs) {
|
|
185
|
+
const temporaryPath = `${output.filePath}.${(0, import_node_crypto.randomUUID)()}.tmp`;
|
|
186
|
+
try {
|
|
187
|
+
await (0, import_promises.writeFile)(temporaryPath, output.contents, "utf8");
|
|
188
|
+
if (overwrite) await (0, import_promises.rm)(output.filePath, { force: true });
|
|
189
|
+
await (0, import_promises.rename)(temporaryPath, output.filePath);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
await (0, import_promises.rm)(temporaryPath, { force: true });
|
|
192
|
+
throw new Error(`Failed to write "${output.filePath}": ${errorMessage(error)}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
icons: converted.map(({ asset }) => ({
|
|
197
|
+
name: asset.name,
|
|
198
|
+
source: import_node_path.default.relative(inputDir, asset.path),
|
|
199
|
+
componentFile: import_node_path.default.join(outputDir, `${asset.name}.tsx`)
|
|
200
|
+
})),
|
|
201
|
+
outputDir
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
205
|
+
0 && (module.exports = {
|
|
206
|
+
generateIcons
|
|
207
|
+
});
|
|
208
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { access, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\r\nimport path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { imageSize } from 'image-size';\r\nimport { transform } from '@svgr/core';\r\n\r\nconst RASTER_MIME_TYPES: Readonly<Record<string, string>> = {\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n};\r\nconst VECTOR_EXTENSIONS = new Set(['.svg']);\r\n\r\nexport interface GenerateIconsOptions {\r\n /** Directory containing source image assets. */\r\n inputDir: string;\r\n /** Directory where generated React components and their barrel are written. */\r\n outputDir: string;\r\n /** Include nested folders. Enabled by default. */\r\n recursive?: boolean;\r\n /** Replace generated files that already exist. Disabled by default. */\r\n overwrite?: boolean;\r\n}\r\n\r\nexport interface GeneratedIcon {\r\n name: string;\r\n source: string;\r\n componentFile: string;\r\n}\r\n\r\nexport interface GenerateIconsResult {\r\n icons: GeneratedIcon[];\r\n outputDir: string;\r\n}\r\n\r\ninterface SourceAsset {\r\n path: string;\r\n name: string;\r\n extension: string;\r\n}\r\n\r\nfunction componentName(filePath: string): string {\r\n const baseName = path.basename(filePath, path.extname(filePath));\r\n const words = baseName\r\n .normalize('NFKD')\r\n .replace(/[\\u0300-\\u036f]/g, '')\r\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\r\n .match(/[A-Za-z0-9]+/g);\r\n const name = (words ?? []).map((word) => word[0]!.toUpperCase() + word.slice(1)).join('');\r\n const safeName = /^[A-Za-z_$]/.test(name) ? name : `Icon${name}`;\r\n return safeName || 'Icon';\r\n}\r\n\r\nfunction isWithin(parent: string, child: string): boolean {\r\n const relative = path.relative(parent, child);\r\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction errorMessage(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\nasync function findAssets(inputDir: string, outputDir: string, recursive: boolean): Promise<SourceAsset[]> {\r\n const assets: SourceAsset[] = [];\r\n\r\n async function visit(directory: string): Promise<void> {\r\n const entries = await readdir(directory, { withFileTypes: true });\r\n entries.sort((a, b) => a.name.localeCompare(b.name));\r\n for (const entry of entries) {\r\n const fullPath = path.join(directory, entry.name);\r\n if (entry.isSymbolicLink()) continue;\r\n if (entry.isDirectory()) {\r\n if (recursive && !(directory === inputDir && isWithin(fullPath, outputDir))) await visit(fullPath);\r\n continue;\r\n }\r\n if (!entry.isFile()) continue;\r\n const extension = path.extname(entry.name).toLowerCase();\r\n if (VECTOR_EXTENSIONS.has(extension) || extension in RASTER_MIME_TYPES) {\r\n assets.push({ path: fullPath, name: componentName(fullPath), extension });\r\n }\r\n }\r\n }\r\n\r\n await visit(inputDir);\r\n return assets;\r\n}\r\n\r\nasync function rasterComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const bytes = await readFile(asset.path);\r\n let dimensions: ReturnType<typeof imageSize>;\r\n try {\r\n dimensions = imageSize(bytes);\r\n } catch (error) {\r\n throw new Error(`Cannot read image dimensions for \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n if (!dimensions.width || !dimensions.height) throw new Error(`Image \"${asset.path}\" does not have valid dimensions.`);\r\n\r\n const dataUri = `data:${RASTER_MIME_TYPES[asset.extension]};base64,${bytes.toString('base64')}`;\r\n return `import type { SVGProps } from 'react';\r\n\r\nexport interface ${component}Props extends SVGProps<SVGSVGElement> {\r\n /** Accessible label. Omit for a decorative icon. */\r\n title?: string;\r\n}\r\n\r\nconst imageSource = ${JSON.stringify(dataUri)};\r\n\r\nexport default function ${component}({ title, width, height, ...props }: ${component}Props) {\r\n return (\r\n <svg\r\n xmlns=\"http://www.w3.org/2000/svg\"\r\n viewBox=\"0 0 ${dimensions.width} ${dimensions.height}\"\r\n width={width ?? '1em'}\r\n height={height ?? '1em'}\r\n role={title ? 'img' : undefined}\r\n aria-hidden={title ? undefined : true}\r\n {...props}\r\n >\r\n {title ? <title>{title}</title> : null}\r\n <image href={imageSource} x=\"0\" y=\"0\" width=\"100%\" height=\"100%\" preserveAspectRatio=\"xMidYMid meet\" />\r\n </svg>\r\n );\r\n}\r\n`;\r\n}\r\n\r\nasync function svgComponent(asset: SourceAsset, component: string): Promise<string> {\r\n const source = await readFile(asset.path, 'utf8');\r\n try {\r\n return await transform(source, {\r\n plugins: ['@svgr/plugin-svgo', '@svgr/plugin-jsx'],\r\n typescript: true,\r\n jsxRuntime: 'automatic',\r\n icon: true,\r\n titleProp: true,\r\n exportType: 'default',\r\n prettier: false,\r\n }, { componentName: component });\r\n } catch (error) {\r\n throw new Error(`Cannot convert SVG \"${asset.path}\": ${errorMessage(error)}`);\r\n }\r\n}\r\n\r\n/** Generate typed React components and a named-export barrel from image files. */\r\nexport async function generateIcons(options: GenerateIconsOptions): Promise<GenerateIconsResult> {\r\n const inputDir = path.resolve(options.inputDir);\r\n const outputDir = path.resolve(options.outputDir);\r\n const recursive = options.recursive ?? true;\r\n const overwrite = options.overwrite ?? false;\r\n\r\n let inputStat;\r\n try {\r\n inputStat = await stat(inputDir);\r\n } catch {\r\n throw new Error(`Input directory does not exist: \"${inputDir}\"`);\r\n }\r\n if (!inputStat.isDirectory()) throw new Error(`Input path is not a directory: \"${inputDir}\"`);\r\n\r\n const assets = await findAssets(inputDir, outputDir, recursive);\r\n if (assets.length === 0) throw new Error(`No supported image assets found in \"${inputDir}\".`);\r\n\r\n const names = new Map<string, string>();\r\n for (const asset of assets) {\r\n const normalizedName = asset.name.toLocaleLowerCase('en-US');\r\n const previous = names.get(normalizedName);\r\n if (previous) {\r\n throw new Error(`Name collision: \"${previous}\" and \"${asset.path}\" both generate the component \"${asset.name}\". Rename one of the source files.`);\r\n }\r\n names.set(normalizedName, asset.path);\r\n }\r\n\r\n // Convert all inputs before writing so malformed assets do not leave partial output.\r\n const converted = await Promise.all(assets.map(async (asset) => ({\r\n asset,\r\n contents: VECTOR_EXTENSIONS.has(asset.extension)\r\n ? await svgComponent(asset, asset.name)\r\n : await rasterComponent(asset, asset.name),\r\n })));\r\n\r\n const indexContents = `${converted.map(({ asset }) => `export { default as ${asset.name} } from './${asset.name}.js';`).join('\\n')}\\n`;\r\n const outputs = [\r\n ...converted.map(({ asset, contents }) => ({ filePath: path.join(outputDir, `${asset.name}.tsx`), contents })),\r\n { filePath: path.join(outputDir, 'index.ts'), contents: indexContents },\r\n ];\r\n\r\n if (!overwrite) {\r\n const conflicts: string[] = [];\r\n for (const output of outputs) {\r\n try {\r\n await access(output.filePath);\r\n conflicts.push(output.filePath);\r\n } catch {\r\n // A missing destination is expected for a fresh generation.\r\n }\r\n }\r\n if (conflicts.length) throw new Error(`Refusing to overwrite existing generated file(s): ${conflicts.join(', ')}. Use --overwrite to replace them.`);\r\n }\r\n\r\n await mkdir(outputDir, { recursive: true });\r\n for (const output of outputs) {\r\n const temporaryPath = `${output.filePath}.${randomUUID()}.tmp`;\r\n try {\r\n await writeFile(temporaryPath, output.contents, 'utf8');\r\n if (overwrite) await rm(output.filePath, { force: true });\r\n await rename(temporaryPath, output.filePath);\r\n } catch (error) {\r\n await rm(temporaryPath, { force: true });\r\n throw new Error(`Failed to write \"${output.filePath}\": ${errorMessage(error)}`);\r\n }\r\n }\r\n\r\n return {\r\n icons: converted.map(({ asset }) => ({\r\n name: asset.name,\r\n source: path.relative(inputDir, asset.path),\r\n componentFile: path.join(outputDir, `${asset.name}.tsx`),\r\n })),\r\n outputDir,\r\n };\r\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAA8E;AAC9E,uBAAiB;AACjB,yBAA2B;AAC3B,wBAA0B;AAC1B,kBAA0B;AAE1B,IAAM,oBAAsD;AAAA,EAC1D,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AACX;AACA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,MAAM,CAAC;AA8B1C,SAAS,cAAc,UAA0B;AAC/C,QAAM,WAAW,iBAAAA,QAAK,SAAS,UAAU,iBAAAA,QAAK,QAAQ,QAAQ,CAAC;AAC/D,QAAM,QAAQ,SACX,UAAU,MAAM,EAChB,QAAQ,oBAAoB,EAAE,EAC9B,QAAQ,sBAAsB,OAAO,EACrC,MAAM,eAAe;AACxB,QAAM,QAAQ,SAAS,CAAC,GAAG,IAAI,CAAC,SAAS,KAAK,CAAC,EAAG,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE;AACxF,QAAM,WAAW,cAAc,KAAK,IAAI,IAAI,OAAO,OAAO,IAAI;AAC9D,SAAO,YAAY;AACrB;AAEA,SAAS,SAAS,QAAgB,OAAwB;AACxD,QAAM,WAAW,iBAAAA,QAAK,SAAS,QAAQ,KAAK;AAC5C,SAAO,aAAa,MAAO,CAAC,SAAS,WAAW,KAAK,iBAAAA,QAAK,GAAG,EAAE,KAAK,aAAa,QAAQ,CAAC,iBAAAA,QAAK,WAAW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K,IAAI,CAAC,oCAAoC;AAAA,EACrJ;AAEA,YAAM,uBAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,aAAW,UAAU,SAAS;AAC5B,UAAM,gBAAgB,GAAG,OAAO,QAAQ,QAAI,+BAAW,CAAC;AACxD,QAAI;AACF,gBAAM,2BAAU,eAAe,OAAO,UAAU,MAAM;AACtD,UAAI,UAAW,WAAM,oBAAG,OAAO,UAAU,EAAE,OAAO,KAAK,CAAC;AACxD,gBAAM,wBAAO,eAAe,OAAO,QAAQ;AAAA,IAC7C,SAAS,OAAO;AACd,gBAAM,oBAAG,eAAe,EAAE,OAAO,KAAK,CAAC;AACvC,YAAM,IAAI,MAAM,oBAAoB,OAAO,QAAQ,MAAM,aAAa,KAAK,CAAC,EAAE;AAAA,IAChF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,UAAU,IAAI,CAAC,EAAE,MAAM,OAAO;AAAA,MACnC,MAAM,MAAM;AAAA,MACZ,QAAQ,iBAAAA,QAAK,SAAS,UAAU,MAAM,IAAI;AAAA,MAC1C,eAAe,iBAAAA,QAAK,KAAK,WAAW,GAAG,MAAM,IAAI,MAAM;AAAA,IACzD,EAAE;AAAA,IACF;AAAA,EACF;AACF;","names":["path"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
interface GenerateIconsOptions {
|
|
2
|
+
/** Directory containing source image assets. */
|
|
3
|
+
inputDir: string;
|
|
4
|
+
/** Directory where generated React components and their barrel are written. */
|
|
5
|
+
outputDir: string;
|
|
6
|
+
/** Include nested folders. Enabled by default. */
|
|
7
|
+
recursive?: boolean;
|
|
8
|
+
/** Replace generated files that already exist. Disabled by default. */
|
|
9
|
+
overwrite?: boolean;
|
|
10
|
+
}
|
|
11
|
+
interface GeneratedIcon {
|
|
12
|
+
name: string;
|
|
13
|
+
source: string;
|
|
14
|
+
componentFile: string;
|
|
15
|
+
}
|
|
16
|
+
interface GenerateIconsResult {
|
|
17
|
+
icons: GeneratedIcon[];
|
|
18
|
+
outputDir: string;
|
|
19
|
+
}
|
|
20
|
+
/** Generate typed React components and a named-export barrel from image files. */
|
|
21
|
+
declare function generateIcons(options: GenerateIconsOptions): Promise<GenerateIconsResult>;
|
|
22
|
+
|
|
23
|
+
export { type GenerateIconsOptions, type GenerateIconsResult, type GeneratedIcon, generateIcons };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
interface GenerateIconsOptions {
|
|
2
|
+
/** Directory containing source image assets. */
|
|
3
|
+
inputDir: string;
|
|
4
|
+
/** Directory where generated React components and their barrel are written. */
|
|
5
|
+
outputDir: string;
|
|
6
|
+
/** Include nested folders. Enabled by default. */
|
|
7
|
+
recursive?: boolean;
|
|
8
|
+
/** Replace generated files that already exist. Disabled by default. */
|
|
9
|
+
overwrite?: boolean;
|
|
10
|
+
}
|
|
11
|
+
interface GeneratedIcon {
|
|
12
|
+
name: string;
|
|
13
|
+
source: string;
|
|
14
|
+
componentFile: string;
|
|
15
|
+
}
|
|
16
|
+
interface GenerateIconsResult {
|
|
17
|
+
icons: GeneratedIcon[];
|
|
18
|
+
outputDir: string;
|
|
19
|
+
}
|
|
20
|
+
/** Generate typed React components and a named-export barrel from image files. */
|
|
21
|
+
declare function generateIcons(options: GenerateIconsOptions): Promise<GenerateIconsResult>;
|
|
22
|
+
|
|
23
|
+
export { type GenerateIconsOptions, type GenerateIconsResult, type GeneratedIcon, generateIcons };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@taterlaxmi/react-icon-library",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "Generate reusable React icon components from image assets.",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"author": "React Icon Library contributors",
|
|
10
|
+
"type": "module",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=20.0.0"
|
|
13
|
+
},
|
|
14
|
+
"main": "./dist/index.cjs",
|
|
15
|
+
"module": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"import": "./dist/index.js",
|
|
21
|
+
"require": "./dist/index.cjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"bin": {
|
|
25
|
+
"react-icon-library": "dist/cli.js"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"dev": "node ./dist/cli.js ./brand-assets --output ./src/icons --overwrite",
|
|
34
|
+
"generate": "node ./dist/cli.js"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@svgr/core": "^8.1.0",
|
|
38
|
+
"@svgr/plugin-jsx": "^8.1.0",
|
|
39
|
+
"@svgr/plugin-svgo": "^8.1.0",
|
|
40
|
+
"commander": "^13.1.0",
|
|
41
|
+
"image-size": "^2.0.2"
|
|
42
|
+
},
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git+https://github.com/taterlaxmi/react-icon-library.git"
|
|
46
|
+
},
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/taterlaxmi/react-icon-library/issues"
|
|
49
|
+
},
|
|
50
|
+
"homepage": "https://github.com/taterlaxmi/react-icon-library#readme"
|
|
51
|
+
}
|