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