-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.cjs.js
811 lines (798 loc) · 24.5 KB
/
utils.cjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var c = require('chalk');
var fse = require('fs-extra');
var fetch = require('node-fetch');
var normalizePath = require('normalize-path');
var portfinder = require('portfinder');
var path = require('path');
var execa = require('execa');
var os = require('os');
var child_process = require('child_process');
var traverse = require('@babel/traverse');
var generate = require('@babel/generator');
var parser = require('@babel/parser');
var types = require('@babel/types');
var ora = require('ora');
var C = require('crypto');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
for (var k in e) {
n[k] = e[k];
}
}
n["default"] = e;
return Object.freeze(n);
}
var c__default = /*#__PURE__*/_interopDefaultLegacy(c);
var fse__default = /*#__PURE__*/_interopDefaultLegacy(fse);
var fse__namespace = /*#__PURE__*/_interopNamespace(fse);
var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
var fetch__namespace = /*#__PURE__*/_interopNamespace(fetch);
var normalizePath__default = /*#__PURE__*/_interopDefaultLegacy(normalizePath);
var portfinder__default = /*#__PURE__*/_interopDefaultLegacy(portfinder);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
var execa__default = /*#__PURE__*/_interopDefaultLegacy(execa);
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
var traverse__default = /*#__PURE__*/_interopDefaultLegacy(traverse);
var generate__default = /*#__PURE__*/_interopDefaultLegacy(generate);
var types__default = /*#__PURE__*/_interopDefaultLegacy(types);
var ora__default = /*#__PURE__*/_interopDefaultLegacy(ora);
var C__default = /*#__PURE__*/_interopDefaultLegacy(C);
exports.Types = void 0;
(function (Types) {
Types["info"] = "info";
Types["warn"] = "warn";
Types["error"] = "error";
Types["done"] = "done";
})(exports.Types || (exports.Types = {}));
const logTypeMap = {
[exports.Types.info]: ['bgCyan', ''],
[exports.Types.warn]: ['bgYellow', 'yellow'],
[exports.Types.error]: ['bgRed', 'red'],
[exports.Types.done]: ['bgGreen', '']
};
const cTag = (tag) => tag ? c__default.magenta(`${tag}`) : '';
const cType = (bg, type) => c__default[bg].black(` ${type.toUpperCase()} `);
const createLogFn = (logType) => {
return function (msg, tag) {
const [bg, color] = logTypeMap[logType];
const agrs = [
cType(bg, logType)
];
const hasTag = cTag(tag);
if (hasTag) {
agrs.push(hasTag);
}
agrs.push(color ? c__default[color](msg) : msg);
console.log(...agrs);
};
};
const log = {
[exports.Types.info]: createLogFn(exports.Types.info),
[exports.Types.warn]: createLogFn(exports.Types.warn),
[exports.Types.error]: createLogFn(exports.Types.error),
[exports.Types.done]: createLogFn(exports.Types.done),
};
// type tag? msg
// log.info('info...', 'lint');
// log.warn('warn...', 'lint');
// log.error('error...', 'lint');
// log.done('success...', 'init');
// log.success('s');
exports.AgrsTypes = void 0;
(function (AgrsTypes) {
AgrsTypes["isArray"] = "isArray";
AgrsTypes["isBoolean"] = "isBoolean";
AgrsTypes["isNumber"] = "isNumber";
AgrsTypes["isObject"] = "isObject";
AgrsTypes["isPromise"] = "isPromise";
AgrsTypes["isString"] = "isString";
AgrsTypes["isMap"] = "isMap";
AgrsTypes["isRegExp"] = "isRegExp";
AgrsTypes["isSet"] = "isSet";
AgrsTypes["isWeakmap"] = "isWeakmap";
AgrsTypes["isWeakset"] = "isWeakset";
AgrsTypes["isSymbol"] = "isSymbol";
AgrsTypes["isNull"] = "isNull";
AgrsTypes["isUndefined"] = "isUndefined";
AgrsTypes["isFunction"] = "isFunction";
})(exports.AgrsTypes || (exports.AgrsTypes = {}));
function compareAgrsType(a, b) {
return a.replace(/^is/i, '').toLowerCase() === b;
}
/**
* 优雅的判断参数类型
*/
function getArgType(agr) {
const type = Object.prototype.toString.call(agr).split(/\s/)[1].slice(0, -1).toLowerCase();
const obj = {
isArray: compareAgrsType(exports.AgrsTypes.isArray, type),
isBoolean: compareAgrsType(exports.AgrsTypes.isBoolean, type),
isNumber: compareAgrsType(exports.AgrsTypes.isNumber, type),
isObject: compareAgrsType(exports.AgrsTypes.isObject, type),
isPromise: compareAgrsType(exports.AgrsTypes.isPromise, type),
isString: compareAgrsType(exports.AgrsTypes.isString, type),
isMap: compareAgrsType(exports.AgrsTypes.isMap, type),
isRegExp: compareAgrsType(exports.AgrsTypes.isRegExp, type),
isSet: compareAgrsType(exports.AgrsTypes.isSet, type),
isWeakmap: compareAgrsType(exports.AgrsTypes.isWeakmap, type),
isWeakset: compareAgrsType(exports.AgrsTypes.isWeakset, type),
isSymbol: compareAgrsType(exports.AgrsTypes.isSymbol, type),
isNull: compareAgrsType(exports.AgrsTypes.isNull, type),
isUndefined: compareAgrsType(exports.AgrsTypes.isUndefined, type),
isFunction: ['asyncfunction', 'generatorfunction', 'function'].indexOf(type) >= 0
};
return obj;
}
/**
* 解析函数的参数名
* @param {function} fn
* @example
* getArgsFromFunc($a, $b)
* => ['$a', '$b']
*/
function getArgsFromFunc(fn) {
// reference from angular
const ARROW_ARG = /^([^\(]+?)=>/;
const FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
const fnText = fn.toString().replace(STRIP_COMMENTS, '');
const args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
if (args) {
return args[1].split(',').map(arg => arg.toString().trim());
}
return [];
}
/**
* 对象转map
* @param {object} obj
*/
function objToMap(obj) {
const map = new Map();
for (const k of Object.keys(obj)) {
map.set(k, obj[k]);
}
return map;
}
/**
* 是否支持yarn
*/
function hasYarn() {
let hasYarn = false;
try {
child_process.execSync('yarn -v');
hasYarn = true;
}
catch (e) {
hasYarn = false;
}
return hasYarn;
}
// execCmd([cmd])([agruments]);
const createExecCmd = (type, tip) => (cmd) => (agrs) => {
if (!agrs) {
agrs = [];
}
const agrType = getArgType(agrs);
if (!agrType.isArray) {
log.error(tip, type);
process.exit(0);
}
if (cmd) {
agrs.unshift(cmd);
}
return execa__default.sync(type, agrs);
};
/**
* 获取区间的随机整数
*/
function numRange(min, max) {
return Math.random() * (max - min) + min;
}
/**
* 生成可用的端口号
*/
async function getPort() {
let port = Number(process.env.PORT);
if (!port) {
try {
port = await portfinder__default.getPortPromise();
}
catch (e) {
port = numRange(1024, 65535);
}
}
return port;
}
const resolve = normalizePathFn('resolve');
const join = normalizePathFn('join');
function resolveCWD(...target) {
target.unshift(cwd);
return _util.resolve(...target);
}
function resolveHome(...target) {
target.unshift(getHomedir());
return _util.resolve(...target);
}
function joinCWD(...target) {
target.unshift(cwd);
return _util.join(...target);
}
function joinHome(...target) {
target.unshift(getHomedir());
return _util.join(...target);
}
/**
* 获取不同平台的home目录
*/
function getHomedir() {
return (typeof os__default.homedir == 'function' ? os__default.homedir() :
process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME']) || '~';
}
/**
* 兼容windows和linux的文件路径格式化
*/
function normalizePathFn(method) {
return function (...agrs) {
return normalizePath__default(path__default[method](...agrs));
};
}
/**
* 获取项目根目录的package.json,如果有lerna.json的话,会合并到一起
*/
function resolvePkg() {
let pkg = {};
let lernaJson = {};
try {
pkg = require(_util.resolveCWD('package.json'));
}
catch (e) {
log.error(e);
process.exit(0);
}
try {
lernaJson = require(_util.resolveCWD('lerna.json'));
}
catch (e) { }
return { ...pkg, ...lernaJson };
}
const cwd = process.cwd();
const _util = {
cwd,
hasYarn,
numRange,
resolvePkg,
getArgType,
getHomedir,
createExecCmd,
getArgsFromFunc,
objToMap,
getPort,
resolve,
join,
/**
* 从根目录resolve
*/
resolveCWD,
/**
* 从home目录resolve
*/
resolveHome,
/**
* 从根目录join
*/
joinCWD,
/**
* 从home目录join
*/
joinHome
};
/**
* AST操作, 节点操作时需要收集数据的话,可以将数据挂到extra对象上
* @param {string} filepath 文件路径
* @param {function} visitorCreater visitor生成函数
* visitorCreater:({
* types,
* traverse,
* generate,
* parse
* }, extra) => { code, extra }
* @returns {object} 返回新生成的code和extra信息
*/
function astCtrl(filepath, visitorCreater) {
if (!fse__default.existsSync(filepath)) {
log.error(`can not resolve the filepath: ${filepath}`, 'astCtrl');
process.exit();
}
const extra = {};
const codes = fse__default.readFileSync(filepath).toString();
if (!getArgType(visitorCreater).isFunction) {
log.error(`'visitorCreater' should be a function`, 'astCtrl');
process.exit();
}
const _babel = {
types: types__default,
traverse: traverse__default,
generate: generate__default,
parse: parser.parse
};
const visitor = visitorCreater(_babel, extra);
if (!getArgType(visitor).isObject) {
log.error(`expect 'visitorCreater' return an Object`, 'astCtrl');
process.exit();
}
const ast = parser.parse(codes, {
sourceType: "module"
});
traverse__default(ast, visitor);
const generatorOpts = {
jsescOption: {
minimal: true
},
};
const { code } = generate__default(ast, generatorOpts, codes);
return {
code,
extra: extra
};
}
const AGRS_TIP$1 = 'arguments of the command should be an array.';
const execCmd$1 = createExecCmd('npm', AGRS_TIP$1);
const npmClient = {
get version() {
const { stdout } = execCmd$1()(['-v']);
return stdout;
},
get config() {
let conf = {
registry: '',
username: '',
email: ''
};
try {
const { stdout } = execCmd$1('config')(['list', '--json']);
conf = JSON.parse(stdout);
}
catch (e) {
console.log(e);
}
const registry = conf.registry;
const uInfo = (key) => {
return conf[(`${registry.replace(/^https?:/, '') + (registry.endsWith('/') ? '' : '/')}:${key}`)];
};
conf.username = uInfo('username');
conf.email = uInfo('email');
return conf;
},
setConfig(key, value) {
execCmd$1('config')(['set', `${key}`, `${value}`]);
return this.config;
},
addDistTag(pkg, version, tag = 'latest') {
return this.tag.add(pkg, version, tag);
},
get tag() {
return {
list(pkg) {
const agrs = ['list'];
if (pkg) {
agrs.push(pkg);
}
const { stdout } = execCmd$1('dist-tag')(agrs);
return stdout;
},
add(pkg, version, tag = 'latest') {
const { stdout } = execCmd$1('dist-tag')(['add', `${pkg}@${version}`, tag]);
return stdout;
},
remove(pkg, tag = 'latest') {
const { stdout } = execCmd$1('dist-tag')(['rm', pkg, tag]);
return stdout;
}
};
}
};
const AGRS_TIP = 'arguments of the command should be an array.';
const execCmd = createExecCmd('git', AGRS_TIP);
exports.GitConfigLevelType = void 0;
(function (GitConfigLevelType) {
GitConfigLevelType["local"] = "local";
GitConfigLevelType["global"] = "global";
GitConfigLevelType["system"] = "system";
})(exports.GitConfigLevelType || (exports.GitConfigLevelType = {}));
const gitClient = {
get config() {
// git.config.local.add(key, value);
const config = {
local: configCtrl(exports.GitConfigLevelType.local),
global: configCtrl(exports.GitConfigLevelType.global),
system: configCtrl(exports.GitConfigLevelType.system)
};
return config;
},
init(agrs) {
return execCmd('init')(agrs);
},
add(agrs) {
if (!agrs || !agrs.length) {
agrs = ['.'];
}
execCmd('add')(agrs);
return this;
},
commit(msg, agrs = []) {
const { clean } = this.hasChanges;
if (clean)
return this;
assertAgrs(!getArgType(agrs).isArray, AGRS_TIP);
if (msg) {
execCmd('commit')(['-m', msg].concat(agrs));
}
else {
assertAgrs(true, 'please commit with some message.');
}
return this;
},
commitAll(msg, agrs) {
return this.add().commit(msg, agrs);
},
status(agrs) {
const { stdout } = execCmd('status')(agrs);
return {
clean: !!!stdout,
files: stdout
};
},
get hasChanges() {
return this.status(['--porcelain']);
},
checkClean(tag) {
const { clean, files } = this.hasChanges;
if (!clean) {
log.error(`git tree not clean: \n${files}`, tag);
process.exit(0);
}
},
fetch(agrs) {
if (!agrs) {
agrs = [];
}
assertAgrs(!getArgType(agrs).isArray, AGRS_TIP);
this.checkClean('git fetch');
const pullAgrs = [this.defaultRemote, this.currentBranch].concat(agrs);
execCmd('fetch')(pullAgrs);
},
pull(agrs) {
if (!agrs) {
agrs = [];
}
assertAgrs(!getArgType(agrs).isArray, AGRS_TIP);
this.checkClean('git pull');
const hasRemoteBranch = this.branches.includes(`remotes/${this.remoteAndBranch}`);
if (hasRemoteBranch) {
const pullAgrs = [this.defaultRemote, this.currentBranch].concat(agrs);
try {
execCmd('pull')(pullAgrs);
}
catch (e) {
// conflict
console.log(e.message);
process.exit(0);
}
}
else {
log.warn(`couldn't find remote ref`, this.currentBranch);
}
},
push(remote, branch, agrs) {
if (!branch && !agrs && getArgType(remote).isArray) {
agrs = remote;
}
if (!agrs) {
agrs = [];
}
assertAgrs(!getArgType(agrs).isArray, AGRS_TIP);
this.checkClean('git push');
const pushAgrs = [remote || this.defaultRemote, branch || this.currentBranch];
execCmd('push')(pushAgrs.concat(agrs));
},
log(agrs) {
const { stdout } = execCmd('log')(agrs);
return stdout;
},
merge(agrs) {
execCmd('merge')(agrs);
},
get branch() {
return {
has: (name) => {
return this.branches.includes(name);
},
add: (name, base) => {
if (!name)
return;
const agrs = ['-b', name];
if (base) {
agrs.push(base);
}
execCmd('checkout')(agrs);
},
switch: (name) => {
execCmd('checkout')([name]);
},
removeLocal: (name) => {
execCmd('branch')(['-D', name]);
},
removeRemote: (name) => {
execCmd('push')([this.defaultRemote, '-d', name]);
}
};
},
get maybePull() {
const [behind] = this.behindAndAhead;
return Boolean(behind);
},
get behindAndAhead() {
this.remote.update(this.defaultRemote);
const { stdout } = execCmd('rev-list')(["--left-right", "--count", `${this.remoteAndBranch}...${this.currentBranch}`]);
return stdout.split("\t").map(val => parseInt(val, 10));
},
get remote() {
const remoteCtrl = execCmd('remote');
const $this = this;
return {
update: (name) => remoteCtrl(['update'].concat(name || [])),
add: (name, url, agrs = []) => remoteCtrl(['add', ...agrs, name, url]),
rename: (old, newname) => remoteCtrl(['rename', old, newname]),
remove: (name) => remoteCtrl(['remove', name]),
setUrl: (name, newurl) => remoteCtrl(['set-url', name, newurl]),
getUrl: (name) => remoteCtrl(['get-url', name]),
get list() {
return $this.remotes;
}
};
},
newTag(name) {
this.tag.add(name).push(name.name || name);
},
get tag() {
const tagCtrl = execCmd('tag');
const gitTag = {
get list() {
let list = [];
const { stdout, failed } = tagCtrl();
if (!failed) {
list = splitOut(stdout);
}
return list;
},
filter: (pattern) => {
let list = [];
const { stdout, failed } = tagCtrl(['-l', pattern]);
if (!failed) {
list = splitOut(stdout);
}
return list;
},
add: (opts = '') => {
const agrsType = getArgType(opts);
const exists = (name) => this.tag.list.includes(name);
if (agrsType.isString) {
if (exists(opts))
return gitTag;
tagCtrl([opts]);
}
else if (agrsType.isObject) {
if (exists(opts.name))
return gitTag;
const { name, msg, commit } = opts || {};
let agrs = [];
if (name) {
agrs = agrs.concat(['-a', name]);
}
if (msg) {
agrs = agrs.concat(['-m', msg]);
}
if (commit) {
agrs.push(commit);
}
tagCtrl(agrs);
}
return gitTag;
},
show(name) {
const { stdout, failed } = execCmd('show')([name]);
if (!failed) {
return stdout;
}
return '';
},
push: (name) => {
execCmd('push')([this.defaultRemote, name]);
}
};
return gitTag;
},
get branches() {
const { stdout } = execCmd('branch')(['-a']);
return splitOut(stdout).map(str => str.trim());
},
get mayHaveConflict() {
const hasRemoteBranch = this.branches.includes(`remotes/${this.remoteAndBranch}`);
if (hasRemoteBranch) {
const preCommit = this.currRemoteCommit;
this.fetch();
const newCommit = this.currRemoteCommit;
return preCommit !== newCommit;
}
else {
return false;
}
},
get remoteAndBranch() {
return `${this.defaultRemote}/${this.currentBranch}`;
},
get currRemoteCommit() {
return splitOut(this.log([this.remoteAndBranch, '--pretty=format:%h']))[0];
},
get remotes() {
return splitOut(execCmd('remote')(['-v']).stdout)
.filter(item => item.endsWith('(fetch)'))
.map(item => {
const values = item.split('\t');
values[1] = values[1].replace(/\s+\(fetch\)$/, '');
return values;
});
},
get defaultRemote() {
let defaultRemote = '';
const remotes = this.remotes;
if (remotes.length) {
defaultRemote = remotes[0][0];
}
return defaultRemote;
},
get currentBranch() {
const { stdout: branch } = execCmd('symbolic-ref')(['--short', 'HEAD']);
return branch;
}
};
// const { stdout } = git.addAll().commit('msg').push();
// console.log(gitClient.defaultRemote);
// const a = gitClient.currRemoteCommit;
// console.log(a);
// gitClient.fetch();
// console.log(gitClient.log(['--pretty=format:%H']).split(/[\r\n]/)[0]);
// const b = gitClient.tag.list;
// console.log(b);
// console.log(gitClient.newTag('v1.0.3'))
// console.log(gitClient.config.local.list);
function configCtrl(level) {
return {
add(key, value) {
return execCmd('config')([`--${level}`, key, value]);
},
get(key) {
return execCmd('config')([`--${level}`, key]);
},
remove(key) {
return execCmd('config')([`--${level}`, '--unset', key]);
},
get list() {
const { stdout, failed } = execCmd('config')([`--${level}`, '-l']);
if (!failed) {
return splitOut(stdout);
}
else {
return [];
}
}
};
}
function assertAgrs(bool, msg) {
if (bool) {
log.error(msg, 'git');
process.exit(0);
}
}
function splitOut(stdout = '') {
return stdout.toString().trim().split(/[\r\n]/);
}
// 不能和同步的child_process方法一起使用
// 使用promise的execa和await
class Spinner {
_spinner;
constructor(options) {
this._spinner = ora__default(options).start();
}
step(txt) {
this._spinner.text = txt;
}
clear() {
this._spinner.clear();
return this._spinner;
}
stop() {
this._spinner.clear().stop();
}
succeed(txt) {
this._spinner.clear().succeed(txt);
}
fail(txt) {
this._spinner.clear().fail(txt);
}
}
class DDWebhook {
secret;
webhook;
timestamp;
constructor(option) {
const { secret, webhook } = option;
if (!secret || !webhook) {
log.error('secret or webhook excepted!');
process.exit(1);
}
this.secret = secret;
this.webhook = webhook;
this.timestamp = Date.now();
}
createSignature() {
const stringToSign = `${this.timestamp}\n${this.secret}`;
const hmac = C__default.createHmac('sha256', this.secret);
hmac.update(stringToSign, 'utf8');
const sign = encodeURIComponent(hmac.digest('base64'));
return sign;
}
sendMessage(body) {
const openapi = `${this.webhook}&sign=${this.createSignature()}×tamp=${this.timestamp}`;
return fetch__default(openapi, {
method: 'post',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json());
}
}
// const secret = 'SEC...';
// const webhook = 'webhook...';
// new DDWebhook({
// secret,
// webhook
// }).sendMessage({
// msgtype: "text",
// text: {
// content: '测试用'
// }
// })
// .then(console.log)
// .catch(console.log);
exports.c = c__default;
exports.fse = fse__namespace;
exports.fetch = fetch__namespace;
exports.DDWebhook = DDWebhook;
exports.Spinner = Spinner;
exports.astCtrl = astCtrl;
exports.createExecCmd = createExecCmd;
exports.cwd = cwd;
exports.getArgType = getArgType;
exports.getArgsFromFunc = getArgsFromFunc;
exports.getHomedir = getHomedir;
exports.gitClient = gitClient;
exports.hasYarn = hasYarn;
exports.join = join;
exports.joinCWD = joinCWD;
exports.joinHome = joinHome;
exports.log = log;
exports.normalizePathFn = normalizePathFn;
exports.npmClient = npmClient;
exports.objToMap = objToMap;
exports.resolve = resolve;
exports.resolveCWD = resolveCWD;
exports.resolveHome = resolveHome;
exports.resolvePkg = resolvePkg;