@charcoal-ui/icons-cli 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,891 @@
1
+ import { remove, ensureDir, ensureFile, writeFile, readFile } from 'fs-extra';
2
+ import yargs from 'yargs';
3
+ import path from 'path';
4
+ import camelCase from 'camelcase';
5
+ import Figma from 'figma-js';
6
+ import got from 'got';
7
+ import { match } from 'path-to-regexp';
8
+ import PQueue from 'p-queue';
9
+ import { Octokit } from '@octokit/rest';
10
+ import { promises } from 'fs';
11
+ import { exec } from 'child_process';
12
+ import { Gitlab } from '@gitbeaker/node';
13
+ import { JSDOM } from 'jsdom';
14
+ import { parseToRgb } from 'polished';
15
+ import Svgo from 'svgo';
16
+
17
+ function concurrently(tasks) {
18
+ const queue = new PQueue({
19
+ concurrency: 3
20
+ });
21
+
22
+ for (const task of tasks) {
23
+ void queue.add(task);
24
+ }
25
+
26
+ queue.start();
27
+ return queue.onIdle();
28
+ }
29
+
30
+ const extracter = match('/file/:file/:name');
31
+
32
+ function extractFileId(url) {
33
+ const result = extracter(new URL(url).pathname);
34
+
35
+ if (result === false) {
36
+ throw new Error('no :file in url');
37
+ }
38
+
39
+ return result.params.file;
40
+ }
41
+
42
+ function extractNodeId(url) {
43
+ if (!url.includes('?')) {
44
+ return undefined;
45
+ }
46
+
47
+ const [, query] = url.split('?');
48
+ const params = new URLSearchParams(query);
49
+ const nodeId = params.get('node-id');
50
+
51
+ if (nodeId === null) {
52
+ return undefined;
53
+ }
54
+
55
+ return decodeURIComponent(nodeId);
56
+ }
57
+
58
+ function filenamify(name) {
59
+ return camelCase(name, {
60
+ pascalCase: true
61
+ }).replace(' ', '');
62
+ } // eslint-disable-next-line prefer-named-capture-group
63
+
64
+
65
+ const iconName = /^([0-9]|Inline)+[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\/[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*/;
66
+
67
+ function isIconNode(node) {
68
+ return iconName.test(node.name);
69
+ }
70
+
71
+ function getContentType(exportFormat) {
72
+ switch (exportFormat) {
73
+ case 'svg':
74
+ return 'image/svg+xml';
75
+
76
+ case 'pdf':
77
+ return 'application/pdf';
78
+ }
79
+ }
80
+
81
+ class FigmaFileClient {
82
+ static async runFromCli(url, token, outputRootDir, exportFormat) {
83
+ const client = new this(url, token, exportFormat);
84
+ const root = process.cwd();
85
+ const outputDir = path.join(root, outputRootDir, exportFormat);
86
+ console.log(`Exporting ${url} components`);
87
+ await client.loadSvg(outputDir);
88
+ console.log(`Exporting components type`);
89
+ const typedefDir = path.join(root, outputRootDir, 'src');
90
+ await client.writeTypeDef(typedefDir);
91
+ console.log('success!');
92
+ }
93
+
94
+ constructor(url, personalAccessToken, exportFormat) {
95
+ this.fileId = void 0;
96
+ this.nodeId = void 0;
97
+ this.exportFormat = void 0;
98
+ this.client = void 0;
99
+ this.components = {};
100
+ this.targets = [];
101
+ this.client = Figma.Client({
102
+ personalAccessToken
103
+ });
104
+ this.fileId = extractFileId(url);
105
+ this.nodeId = extractNodeId(url);
106
+ this.exportFormat = exportFormat;
107
+ }
108
+
109
+ async loadSvg(outputDir) {
110
+ await remove(outputDir);
111
+ await ensureDir(outputDir);
112
+ await this.loadComponents();
113
+ await this.loadImageUrls();
114
+ await this.downloadImages(outputDir);
115
+ }
116
+ /**
117
+ * Generate union of file names for typing
118
+ */
119
+
120
+
121
+ async writeTypeDef(outputDir) {
122
+ const fullname = path.resolve(outputDir, 'filenames.ts');
123
+ const KNOWN_ICON_FILES = Object.values(this.components).map(({
124
+ name
125
+ }) => filenamify(name));
126
+ console.log(`writing to ${outputDir}`);
127
+ await ensureFile(fullname);
128
+ await writeFile(fullname, `/** This file is auto generated. DO NOT EDIT BY HAND. */
129
+
130
+ /* eslint-disable */
131
+
132
+ // prettier-ignore
133
+ export const KNOWN_ICON_FILES = ${JSON.stringify(KNOWN_ICON_FILES)} as const;
134
+
135
+ export type KnownIconFile = typeof KNOWN_ICON_FILES[number];
136
+
137
+ /* eslint-enable */
138
+ `, {
139
+ encoding: 'utf8'
140
+ });
141
+ }
142
+
143
+ async loadComponents() {
144
+ const {
145
+ document
146
+ } = await this.getFile();
147
+ this.targets = document.children.filter(node => {
148
+ if (this.nodeId !== undefined) {
149
+ return node.id === this.nodeId;
150
+ }
151
+
152
+ return false;
153
+ });
154
+ this.targets.forEach(child => this.findComponentsRecursively(child));
155
+
156
+ if (Object.values(this.targets).length === 0) {
157
+ throw new Error('No components found!');
158
+ }
159
+ }
160
+
161
+ async loadImageUrls() {
162
+ console.log('Getting export urls');
163
+ const {
164
+ data
165
+ } = await this.client.fileImages(this.fileId, {
166
+ format: this.exportFormat,
167
+ ids: Object.keys(this.components),
168
+ scale: 1
169
+ });
170
+
171
+ for (const [id, image] of Object.entries(data.images)) {
172
+ this.components[id].image = image;
173
+ }
174
+ }
175
+
176
+ async downloadImages(outputDir) {
177
+ var _this = this;
178
+
179
+ return concurrently(Object.values(this.components).map(component => async function () {
180
+ if (component.image === undefined) {
181
+ return;
182
+ }
183
+
184
+ const response = await got.get(component.image, {
185
+ headers: {
186
+ 'Content-Type': getContentType(_this.exportFormat)
187
+ },
188
+ encoding: 'utf8'
189
+ });
190
+ const filename = `${filenamify(component.name)}.${_this.exportFormat}`;
191
+ const fullname = path.join(outputDir, filename);
192
+ const dirname = path.dirname(fullname);
193
+ await ensureDir(dirname);
194
+ console.log(`found: ${filename} => ✅ writing...`);
195
+ await writeFile(fullname, response.body, 'utf8');
196
+ }));
197
+ }
198
+
199
+ async getFile() {
200
+ console.log('Processing response');
201
+ const {
202
+ data
203
+ } = await this.client.file(this.fileId.toString());
204
+ return data;
205
+ }
206
+
207
+ findComponentsRecursively(child) {
208
+ if (child.type === 'COMPONENT') {
209
+ const {
210
+ name,
211
+ id
212
+ } = child;
213
+
214
+ if (isIconNode(child)) {
215
+ this.components[id] = {
216
+ name,
217
+ id
218
+ };
219
+ }
220
+ } else if ('children' in child) {
221
+ child.children.forEach(grandChild => this.findComponentsRecursively(grandChild));
222
+ }
223
+ }
224
+
225
+ }
226
+
227
+ function _asyncIterator(iterable) {
228
+ var method,
229
+ async,
230
+ sync,
231
+ retry = 2;
232
+
233
+ for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) {
234
+ if (async && null != (method = iterable[async])) return method.call(iterable);
235
+ if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
236
+ async = "@@asyncIterator", sync = "@@iterator";
237
+ }
238
+
239
+ throw new TypeError("Object is not async iterable");
240
+ }
241
+
242
+ function AsyncFromSyncIterator(s) {
243
+ function AsyncFromSyncIteratorContinuation(r) {
244
+ if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
245
+ var done = r.done;
246
+ return Promise.resolve(r.value).then(function (value) {
247
+ return {
248
+ value: value,
249
+ done: done
250
+ };
251
+ });
252
+ }
253
+
254
+ return AsyncFromSyncIterator = function (s) {
255
+ this.s = s, this.n = s.next;
256
+ }, AsyncFromSyncIterator.prototype = {
257
+ s: null,
258
+ n: null,
259
+ next: function () {
260
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
261
+ },
262
+ return: function (value) {
263
+ var ret = this.s.return;
264
+ return void 0 === ret ? Promise.resolve({
265
+ value: value,
266
+ done: !0
267
+ }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
268
+ },
269
+ throw: function (value) {
270
+ var thr = this.s.return;
271
+ return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
272
+ }
273
+ }, new AsyncFromSyncIterator(s);
274
+ }
275
+
276
+ function _AwaitValue(value) {
277
+ this.wrapped = value;
278
+ }
279
+
280
+ function _AsyncGenerator(gen) {
281
+ var front, back;
282
+
283
+ function send(key, arg) {
284
+ return new Promise(function (resolve, reject) {
285
+ var request = {
286
+ key: key,
287
+ arg: arg,
288
+ resolve: resolve,
289
+ reject: reject,
290
+ next: null
291
+ };
292
+
293
+ if (back) {
294
+ back = back.next = request;
295
+ } else {
296
+ front = back = request;
297
+ resume(key, arg);
298
+ }
299
+ });
300
+ }
301
+
302
+ function resume(key, arg) {
303
+ try {
304
+ var result = gen[key](arg);
305
+ var value = result.value;
306
+ var wrappedAwait = value instanceof _AwaitValue;
307
+ Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) {
308
+ if (wrappedAwait) {
309
+ resume(key === "return" ? "return" : "next", arg);
310
+ return;
311
+ }
312
+
313
+ settle(result.done ? "return" : "normal", arg);
314
+ }, function (err) {
315
+ resume("throw", err);
316
+ });
317
+ } catch (err) {
318
+ settle("throw", err);
319
+ }
320
+ }
321
+
322
+ function settle(type, value) {
323
+ switch (type) {
324
+ case "return":
325
+ front.resolve({
326
+ value: value,
327
+ done: true
328
+ });
329
+ break;
330
+
331
+ case "throw":
332
+ front.reject(value);
333
+ break;
334
+
335
+ default:
336
+ front.resolve({
337
+ value: value,
338
+ done: false
339
+ });
340
+ break;
341
+ }
342
+
343
+ front = front.next;
344
+
345
+ if (front) {
346
+ resume(front.key, front.arg);
347
+ } else {
348
+ back = null;
349
+ }
350
+ }
351
+
352
+ this._invoke = send;
353
+
354
+ if (typeof gen.return !== "function") {
355
+ this.return = undefined;
356
+ }
357
+ }
358
+
359
+ _AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () {
360
+ return this;
361
+ };
362
+
363
+ _AsyncGenerator.prototype.next = function (arg) {
364
+ return this._invoke("next", arg);
365
+ };
366
+
367
+ _AsyncGenerator.prototype.throw = function (arg) {
368
+ return this._invoke("throw", arg);
369
+ };
370
+
371
+ _AsyncGenerator.prototype.return = function (arg) {
372
+ return this._invoke("return", arg);
373
+ };
374
+
375
+ function _wrapAsyncGenerator(fn) {
376
+ return function () {
377
+ return new _AsyncGenerator(fn.apply(this, arguments));
378
+ };
379
+ }
380
+
381
+ function _awaitAsyncGenerator(value) {
382
+ return new _AwaitValue(value);
383
+ }
384
+
385
+ function _extends() {
386
+ _extends = Object.assign || function (target) {
387
+ for (var i = 1; i < arguments.length; i++) {
388
+ var source = arguments[i];
389
+
390
+ for (var key in source) {
391
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
392
+ target[key] = source[key];
393
+ }
394
+ }
395
+ }
396
+
397
+ return target;
398
+ };
399
+
400
+ return _extends.apply(this, arguments);
401
+ }
402
+
403
+ /**
404
+ * FIXME: util.promisify を使うと node-libs-browser に入っている方が使われてしまい、壊れる
405
+ */
406
+
407
+ const execp = command => new Promise((resolve, reject) => {
408
+ exec(command, (err, stdout) => {
409
+ if (err) {
410
+ return reject(err);
411
+ }
412
+
413
+ return resolve(stdout);
414
+ });
415
+ });
416
+ function mustBeDefined(value, name) {
417
+ if (typeof value === 'undefined') {
418
+ throw new TypeError(`${name} must be defined.`);
419
+ }
420
+ }
421
+
422
+ const targetDir = path.resolve(process.cwd(), 'packages', 'icons', 'svg');
423
+ /**
424
+ * dir 内で変更があったファイル情報を for await で回せるようにするやつ
425
+ */
426
+
427
+ function getChangedFiles() {
428
+ return _getChangedFiles.apply(this, arguments);
429
+ }
430
+
431
+ function _getChangedFiles() {
432
+ _getChangedFiles = _wrapAsyncGenerator(function* (dir = targetDir) {
433
+ const directories = yield _awaitAsyncGenerator(promises.readdir(dir));
434
+ const gitStatus = yield _awaitAsyncGenerator(collectGitStatus());
435
+
436
+ for (const _dir of directories) {
437
+ const directory = path.resolve(targetDir, _dir); // eslint-disable-next-line no-await-in-loop
438
+
439
+ const stat = yield _awaitAsyncGenerator(promises.stat(directory));
440
+
441
+ if (!stat.isDirectory()) {
442
+ continue;
443
+ } // eslint-disable-next-line no-await-in-loop
444
+
445
+
446
+ const files = yield _awaitAsyncGenerator(promises.readdir(directory));
447
+
448
+ for (const file of files) {
449
+ const fullpath = path.resolve(targetDir, _dir, file);
450
+ const relativePath = path.relative(process.cwd(), fullpath);
451
+ const status = gitStatus[relativePath];
452
+
453
+ if (status == null) {
454
+ // Already up-to-date
455
+ continue;
456
+ } // eslint-disable-next-line no-await-in-loop
457
+
458
+
459
+ const content = yield _awaitAsyncGenerator(promises.readFile(fullpath, {
460
+ encoding: 'utf-8'
461
+ }));
462
+ yield {
463
+ relativePath,
464
+ content,
465
+ status
466
+ };
467
+ }
468
+ }
469
+ });
470
+ return _getChangedFiles.apply(this, arguments);
471
+ }
472
+
473
+ async function collectGitStatus() {
474
+ return Object.fromEntries(
475
+ /**
476
+ * @see https://git-scm.com/docs/git-status#_porcelain_format_version_1
477
+ */
478
+ (await execp(`git status --porcelain`)).split('\n').map(s => [s.slice(3), s.startsWith(' M') ? 'modified' : s.startsWith('??') ? 'untracked' : s.startsWith(' D') ? 'deleted' : null]));
479
+ }
480
+
481
+ class GithubClient {
482
+ static async runFromCli(repoOwner, repoName, token, defaultBranch) {
483
+ const client = new this(repoOwner, repoName, token, defaultBranch);
484
+ const diff = await client.createTreeFromDiff();
485
+ console.log(`${diff.length} files are changed`);
486
+
487
+ if (diff.length === 0) {
488
+ console.log('no changes. aborting');
489
+ return;
490
+ }
491
+
492
+ const newBranch = await client.createBranch();
493
+ await client.createCommit(diff, newBranch);
494
+ return client.createPullRequest(newBranch);
495
+ }
496
+
497
+ constructor(repoOwner, repoName, token, defaultBranch, now = new Date()) {
498
+ this.repoOwner = void 0;
499
+ this.repoName = void 0;
500
+ this.defaultBranch = void 0;
501
+ this.api = void 0;
502
+ this.now = void 0;
503
+ this.repoOwner = repoOwner;
504
+ this.repoName = repoName;
505
+ this.defaultBranch = defaultBranch;
506
+ this.api = new Octokit({
507
+ auth: token
508
+ });
509
+ this.now = now;
510
+ }
511
+
512
+ get branch() {
513
+ return `icons/update/${this.now.getTime()}`;
514
+ }
515
+ /**
516
+ * both used for commit message or pull request title
517
+ */
518
+
519
+
520
+ get message() {
521
+ return `[icons-cli] Update icons ${this.now.toDateString()}`;
522
+ }
523
+
524
+ async createTreeFromDiff() {
525
+ const tree = [];
526
+ var _iteratorAbruptCompletion = false;
527
+ var _didIteratorError = false;
528
+
529
+ var _iteratorError;
530
+
531
+ try {
532
+ for (var _iterator = _asyncIterator(getChangedFiles()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
533
+ const file = _step.value;
534
+ const item = {
535
+ path: file.relativePath,
536
+ // 100 はファイル 644 は実行不可なファイルであるという意味
537
+ // @see https://octokit.github.io/rest.js/v18#git-create-tree
538
+ mode: '100644',
539
+ content: file.content
540
+ };
541
+
542
+ if (file.status === 'deleted') {
543
+ // https://stackoverflow.com/questions/23637961/how-do-i-mark-a-file-as-deleted-in-a-tree-using-the-github-api
544
+ tree.push(_extends({}, item, {
545
+ sha: null
546
+ }));
547
+ } else {
548
+ tree.push(item);
549
+ }
550
+ }
551
+ } catch (err) {
552
+ _didIteratorError = true;
553
+ _iteratorError = err;
554
+ } finally {
555
+ try {
556
+ if (_iteratorAbruptCompletion && _iterator.return != null) {
557
+ await _iterator.return();
558
+ }
559
+ } finally {
560
+ if (_didIteratorError) {
561
+ throw _iteratorError;
562
+ }
563
+ }
564
+ }
565
+
566
+ return tree;
567
+ }
568
+
569
+ async createCommit(tree, targetBranch) {
570
+ const parentCommit = await this.api.git.getCommit({
571
+ owner: this.repoOwner,
572
+ repo: this.repoName,
573
+ // eslint-disable-next-line @typescript-eslint/naming-convention
574
+ commit_sha: targetBranch.data.object.sha
575
+ });
576
+ const newTree = await this.api.git.createTree({
577
+ owner: this.repoOwner,
578
+ repo: this.repoName,
579
+ // eslint-disable-next-line @typescript-eslint/naming-convention
580
+ base_tree: parentCommit.data.tree.sha,
581
+ tree
582
+ }); // この時点ではどのブランチにも属さないコミットができる
583
+
584
+ const commit = await this.api.git.createCommit({
585
+ owner: this.repoOwner,
586
+ repo: this.repoName,
587
+ message: this.message,
588
+ tree: newTree.data.sha,
589
+ parents: [parentCommit.data.sha]
590
+ }); // ref を更新することで、commit が targetBranch に属するようになる
591
+
592
+ await this.api.git.updateRef({
593
+ owner: this.repoOwner,
594
+ repo: this.repoName,
595
+ ref: `heads/${this.branch}`,
596
+ sha: commit.data.sha
597
+ });
598
+ return commit;
599
+ }
600
+
601
+ async createPullRequest(targetBranch) {
602
+ const defaultBranch = await this.getDefaultBranchRef();
603
+ return this.api.pulls.create({
604
+ owner: this.repoOwner,
605
+ repo: this.repoName,
606
+ head: targetBranch.data.ref,
607
+ base: defaultBranch.data.ref,
608
+ title: this.message,
609
+ body: ''
610
+ });
611
+ }
612
+
613
+ getDefaultBranchRef() {
614
+ return this.api.git.getRef({
615
+ owner: this.repoOwner,
616
+ repo: this.repoName,
617
+ ref: `heads/${this.defaultBranch}`
618
+ });
619
+ }
620
+
621
+ async createBranch() {
622
+ const defaultBranch = await this.getDefaultBranchRef();
623
+ return this.api.git.createRef({
624
+ owner: this.repoOwner,
625
+ repo: this.repoName,
626
+ ref: `refs/heads/${this.branch}`,
627
+ sha: defaultBranch.data.object.sha
628
+ });
629
+ }
630
+
631
+ }
632
+
633
+ class GitlabClient {
634
+ static async runFromCli(host, projectId, privateToken, defaultBranch) {
635
+ const client = new this(host, projectId, privateToken, defaultBranch);
636
+ const diff = await client.createActionsFromDiff();
637
+ console.log(`${diff.length} files are changed`);
638
+
639
+ if (diff.length === 0) {
640
+ console.log('no changes. aborting');
641
+ return;
642
+ }
643
+
644
+ await client.createCommit(diff);
645
+ return client.createMergeRequest();
646
+ }
647
+
648
+ constructor(host, projectId, privateToken, defaultBranch, now = new Date()) {
649
+ this.host = void 0;
650
+ this.projectId = void 0;
651
+ this.defaultBranch = void 0;
652
+ this.api = void 0;
653
+ this.now = void 0;
654
+ this.host = host;
655
+ this.projectId = projectId;
656
+ this.defaultBranch = defaultBranch;
657
+ this.api = new Gitlab({
658
+ host: this.host,
659
+ token: privateToken
660
+ });
661
+ this.now = now;
662
+ }
663
+
664
+ get branch() {
665
+ return `icons/update/${this.now.getTime()}`;
666
+ }
667
+ /**
668
+ * both used for commit message or merge request title
669
+ */
670
+
671
+
672
+ get message() {
673
+ return `[icons-cli] Update icons ${this.now.toDateString()}`;
674
+ }
675
+
676
+ async createActionsFromDiff() {
677
+ const actions = [];
678
+ var _iteratorAbruptCompletion = false;
679
+ var _didIteratorError = false;
680
+
681
+ var _iteratorError;
682
+
683
+ try {
684
+ for (var _iterator = _asyncIterator(getChangedFiles()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
685
+ const file = _step.value;
686
+ actions.push({
687
+ action: file.status === 'untracked' ? 'create' : file.status === 'deleted' ? 'delete' : 'update',
688
+ filePath: file.relativePath,
689
+ content: file.content
690
+ });
691
+ }
692
+ } catch (err) {
693
+ _didIteratorError = true;
694
+ _iteratorError = err;
695
+ } finally {
696
+ try {
697
+ if (_iteratorAbruptCompletion && _iterator.return != null) {
698
+ await _iterator.return();
699
+ }
700
+ } finally {
701
+ if (_didIteratorError) {
702
+ throw _iteratorError;
703
+ }
704
+ }
705
+ }
706
+
707
+ return actions;
708
+ }
709
+
710
+ async createCommit(diff) {
711
+ return this.api.Commits.create(this.projectId, this.branch, this.message, diff, {
712
+ // eslint-disable-next-line @typescript-eslint/naming-convention
713
+ start_branch: this.defaultBranch
714
+ });
715
+ }
716
+
717
+ createMergeRequest() {
718
+ return this.api.MergeRequests.create(this.projectId, this.branch, this.defaultBranch, this.message);
719
+ }
720
+
721
+ }
722
+
723
+ const DEFAULT_CURRENT_COLOR_TARGET = '#858585';
724
+ const svgo = new Svgo({
725
+ plugins: [// NOTICE: SVGO は「svg 内のすべての fill を currentColor に変える」機能しかない
726
+ // icons-cli に必要なのは「特定の黒っぽい色だけ currentColor に変える」機能
727
+ // なので、convertColors plugin は使わない
728
+ // { convertColors: { currentColor: true } },
729
+ {
730
+ removeViewBox: true
731
+ }, {
732
+ removeAttrs: {
733
+ attrs: ['stroke-opacity', 'fill-opacity']
734
+ }
735
+ }]
736
+ });
737
+ async function optimizeSvg(input, convertedColor) {
738
+ const {
739
+ data
740
+ } = await svgo.optimize(input);
741
+ const {
742
+ document
743
+ } = new JSDOM(data).window;
744
+ const svg = document.querySelector('svg');
745
+
746
+ if (!svg) {
747
+ throw new Error('optimizeSvg: input string seems not to have <svg>');
748
+ }
749
+
750
+ addViewboxToRootSvg(svg);
751
+ convertToCurrentColor(svg, convertedColor);
752
+ return svg.outerHTML;
753
+ }
754
+ const TARGET_ATTRS = ['fill', 'stroke'];
755
+
756
+ function convertToCurrentColor(svg, convertedColor) {
757
+ const targetColor = parseColor(convertedColor);
758
+
759
+ if (!targetColor) {
760
+ throw new Error(`${convertedColor} is not a valid color`);
761
+ }
762
+
763
+ for (const attr of TARGET_ATTRS) {
764
+ const targets = Array.from(svg.querySelectorAll(`[${attr}]`));
765
+
766
+ for (const el of targets) {
767
+ const value = parseColor(el.getAttribute(attr));
768
+
769
+ if (!value) {
770
+ continue;
771
+ }
772
+
773
+ if (!colorEquals(value, targetColor)) {
774
+ continue;
775
+ }
776
+
777
+ el.setAttribute(attr, 'currentColor');
778
+ }
779
+ }
780
+ }
781
+
782
+ function parseColor(value) {
783
+ if (value == null) {
784
+ return null;
785
+ }
786
+
787
+ try {
788
+ return parseToRgb(value);
789
+ } catch (_unused) {
790
+ return null;
791
+ }
792
+ }
793
+
794
+ function colorEquals(self, other) {
795
+ if (self.red !== other.red) {
796
+ return false;
797
+ }
798
+
799
+ if (self.blue !== other.blue) {
800
+ return false;
801
+ }
802
+
803
+ if (self.green !== other.green) {
804
+ return false;
805
+ }
806
+
807
+ if ('alpha' in self) {
808
+ if ('alpha' in other) {
809
+ if (self.alpha !== other.alpha) {
810
+ return false;
811
+ }
812
+ }
813
+ }
814
+
815
+ return true;
816
+ }
817
+
818
+ function addViewboxToRootSvg(svg) {
819
+ const width = svg.getAttribute('width');
820
+ const height = svg.getAttribute('height');
821
+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
822
+ }
823
+
824
+ /**
825
+ * Figma
826
+ */
827
+
828
+ const FIGMA_TOKEN = process.env.FIGMA_TOKEN;
829
+ const FIGMA_FILE_URL = process.env.FIGMA_FILE_URL;
830
+ const OUTPUT_ROOT_DIR = process.env.OUTPUT_ROOT_DIR;
831
+ /**
832
+ * GitLab
833
+ */
834
+
835
+ const GITLAB_ACCESS_TOKEN = process.env.GITLAB_ACCESS_TOKEN;
836
+ const GITLAB_DEFAULT_BRANCH = process.env.GITLAB_DEFAULT_BRANCH;
837
+ const GITLAB_HOST = process.env.GITLAB_HOST;
838
+ const GITLAB_PROJECT_ID = process.env.GITLAB_PROJECT_ID;
839
+ /**
840
+ * GitHub
841
+ */
842
+
843
+ const GITHUB_ACCESS_TOKEN = process.env.GITHUB_ACCESS_TOKEN;
844
+ const GITHUB_REPO_OWNER = process.env.GITHUB_REPO_OWNER;
845
+ const GITHUB_REPO_NAME = process.env.GITHUB_REPO_NAME;
846
+ const GITHUB_DEFAULT_BRANCH = process.env.GITHUB_DEFAULT_BRANCH;
847
+ void yargs.scriptName('icons-cli').command('figma:export', 'Load all icons from Figma and save to files', () => yargs.option('format', {
848
+ default: 'svg',
849
+ choices: ['svg', 'pdf']
850
+ }), ({
851
+ format
852
+ }) => {
853
+ mustBeDefined(FIGMA_FILE_URL, 'FIGMA_FILE_URL');
854
+ mustBeDefined(FIGMA_TOKEN, 'FIGMA_TOKEN');
855
+ mustBeDefined(OUTPUT_ROOT_DIR, 'OUTPUT_ROOT_DIR');
856
+ void FigmaFileClient.runFromCli(FIGMA_FILE_URL, FIGMA_TOKEN, OUTPUT_ROOT_DIR, format).catch(e => {
857
+ console.error(e);
858
+ process.exit(1);
859
+ });
860
+ }).command('svg:optimize', 'Optimize given .svg files and overwrite it', () => yargs.option('file', {
861
+ demandOption: true,
862
+ type: 'string'
863
+ }).option('color', {
864
+ default: DEFAULT_CURRENT_COLOR_TARGET,
865
+ type: 'string',
866
+ defaultDescription: 'Color code that should be converted into `currentColor`'
867
+ }), ({
868
+ file,
869
+ color
870
+ }) => {
871
+ void readFile(file, {
872
+ encoding: 'utf-8'
873
+ }).then(content => optimizeSvg(content, color)).then(optimized => writeFile(file, optimized)).catch(e => {
874
+ console.error(e);
875
+ process.exit(1);
876
+ });
877
+ }).command('gitlab:mr', 'Create a merge request in the name of icons-cli', {}, () => {
878
+ mustBeDefined(GITLAB_PROJECT_ID, 'GITLAB_PROJECT_ID');
879
+ mustBeDefined(GITLAB_ACCESS_TOKEN, 'GITLAB_ACCESS_TOKEN');
880
+ void GitlabClient.runFromCli(GITLAB_HOST != null ? GITLAB_HOST : 'https://gitlab.com', Number(GITLAB_PROJECT_ID), GITLAB_ACCESS_TOKEN, GITLAB_DEFAULT_BRANCH != null ? GITLAB_DEFAULT_BRANCH : 'main').catch(e => {
881
+ console.error(e);
882
+ process.exit(1);
883
+ });
884
+ }).command('github:pr', 'Create a pull request in the name of icons-cli', {}, () => {
885
+ mustBeDefined(GITHUB_ACCESS_TOKEN, 'GITHUB_ACCESS_TOKEN');
886
+ void GithubClient.runFromCli(GITHUB_REPO_OWNER != null ? GITHUB_REPO_OWNER : 'pixiv', GITHUB_REPO_NAME != null ? GITHUB_REPO_NAME : 'charcoal', GITHUB_ACCESS_TOKEN, GITHUB_DEFAULT_BRANCH != null ? GITHUB_DEFAULT_BRANCH : 'main').catch(e => {
887
+ console.error(e);
888
+ process.exit(1);
889
+ });
890
+ }).demandCommand().help().parse();
891
+ //# sourceMappingURL=index.modern.js.map