@wener/utils 1.1.46 → 1.1.48

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.
Files changed (67) hide show
  1. package/README.md +9 -1
  2. package/lib/asyncs/Promises.js +46 -0
  3. package/lib/asyncs/Promises.js.map +1 -0
  4. package/lib/asyncs/isPromise.js +2 -3
  5. package/lib/asyncs/isPromise.js.map +1 -1
  6. package/lib/cn/division/DivisionCode.js +30 -17
  7. package/lib/cn/division/DivisionCode.js.map +1 -1
  8. package/lib/cn/id/{Mod11Checksum.js → Mod11.js} +3 -6
  9. package/lib/cn/id/Mod11.js.map +1 -0
  10. package/lib/cn/id/ResidentIdNumber.js +10 -12
  11. package/lib/cn/id/ResidentIdNumber.js.map +1 -1
  12. package/lib/cn/uscc/{Mod31Checksum.js → Mod31.js} +3 -6
  13. package/lib/cn/uscc/Mod31.js.map +1 -0
  14. package/lib/cn/uscc/USCC.js +6 -9
  15. package/lib/cn/uscc/USCC.js.map +1 -1
  16. package/lib/cn/uscc/isUSCC.js +1 -1
  17. package/lib/cn/uscc/isUSCC.js.map +1 -1
  18. package/lib/crypto/getNodeCrypto.js +13 -10
  19. package/lib/crypto/getNodeCrypto.js.map +1 -1
  20. package/lib/crypto/getRandomValues.js +5 -1
  21. package/lib/crypto/getRandomValues.js.map +1 -1
  22. package/lib/emitter/types.js +3 -0
  23. package/lib/emitter/types.js.map +1 -0
  24. package/lib/fetch/http.types.js +4 -0
  25. package/lib/fetch/http.types.js.map +1 -0
  26. package/lib/index.js +4 -3
  27. package/lib/index.js.map +1 -1
  28. package/lib/io/ArrayBuffers.js +12 -5
  29. package/lib/io/ArrayBuffers.js.map +1 -1
  30. package/lib/io/ByteBuffer.js +4 -13
  31. package/lib/io/ByteBuffer.js.map +1 -1
  32. package/lib/maths/random.js.map +1 -1
  33. package/lib/mitt/index.js +77 -0
  34. package/lib/mitt/index.js.map +1 -0
  35. package/lib/objects/computeIfAbsent.js +1 -1
  36. package/lib/objects/computeIfAbsent.js.map +1 -1
  37. package/package.json +6 -14
  38. package/src/asyncs/Promises.ts +52 -0
  39. package/src/asyncs/isPromise.ts +3 -3
  40. package/src/cn/division/DivisionCode.ts +61 -8
  41. package/src/cn/division/division.test.ts +6 -0
  42. package/src/cn/id/{Mod11Checksum.ts → Mod11.ts} +3 -6
  43. package/src/cn/id/ResidentIdNumber.ts +11 -13
  44. package/src/cn/id/id.test.ts +5 -5
  45. package/src/cn/scripts/gen.test.ts +2 -1
  46. package/src/cn/uscc/{Mod31Checksum.ts → Mod31.ts} +3 -7
  47. package/src/cn/uscc/USCC.ts +7 -11
  48. package/src/cn/uscc/isUSCC.ts +1 -1
  49. package/src/cn/uscc/uscc.test.ts +4 -4
  50. package/src/crypto/getNodeCrypto.ts +15 -11
  51. package/src/crypto/getRandomValues.ts +6 -1
  52. package/src/emitter/types.ts +18 -0
  53. package/src/fetch/http.types.ts +46 -0
  54. package/src/index.ts +5 -3
  55. package/src/io/ArrayBuffers.ts +10 -5
  56. package/src/io/ByteBuffer.test.ts +30 -9
  57. package/src/io/ByteBuffer.ts +4 -13
  58. package/src/langs/mixin.test.ts +39 -0
  59. package/src/maths/random.ts +1 -1
  60. package/src/mitt/README.md +1 -0
  61. package/src/mitt/index.ts +114 -0
  62. package/src/objects/computeIfAbsent.ts +3 -2
  63. package/lib/asyncs/sleep.js +0 -3
  64. package/lib/asyncs/sleep.js.map +0 -1
  65. package/lib/cn/id/Mod11Checksum.js.map +0 -1
  66. package/lib/cn/uscc/Mod31Checksum.js.map +0 -1
  67. package/src/asyncs/sleep.ts +0 -1
@@ -1,7 +1,7 @@
1
- import { Mod11Checksum } from './Mod11Checksum';
1
+ import { Mod11 } from './Mod11';
2
2
 
3
- export class ResidentIdNumber {
4
- checksum = Mod11Checksum.get();
3
+ class ResidentIdNumberFormat {
4
+ checksum = Mod11;
5
5
 
6
6
  // 9 https://zh.wikipedia.org/wiki/中华人民共和国外国人永久居留身份证
7
7
  // 9 标识码
@@ -11,19 +11,15 @@ export class ResidentIdNumber {
11
11
  regex =
12
12
  /^(?<division>[1-9]\d{5})(?<year>18|19|20)\d{2}(?<month>0[1-9]|1[0-2])(?<day>0[1-9]|[12]\d|3[01])(?<sequence>\d{3})(?<checksum>[0-9Xx])$/;
13
13
 
14
- private static instance: ResidentIdNumber;
15
-
16
- static get() {
17
- return (this.instance ||= new ResidentIdNumber());
18
- }
19
-
20
- verify(s: string) {
14
+ validate(s: string) {
21
15
  if (!s) return false;
22
- return this.regex.test(s) && this.checksum.verify(s.toUpperCase());
16
+ return this.regex.test(s) && this.checksum.validate(s.toUpperCase());
23
17
  }
24
18
 
19
+ generate(opts: { sex?: 'Male' | 'Female'; age?: number; birthDate?: Date; division?: string }) {}
20
+
25
21
  parse(s: string): IdNumber | undefined {
26
- if (!this.verify(s)) {
22
+ if (!this.validate(s)) {
27
23
  return;
28
24
  }
29
25
 
@@ -86,7 +82,7 @@ class IdNumber {
86
82
  }
87
83
 
88
84
  get valid() {
89
- return ResidentIdNumber.get().verify(this.toString());
85
+ return ResidentIdNumber.validate(this.toString());
90
86
  }
91
87
 
92
88
  get male() {
@@ -126,3 +122,5 @@ function formatDate(date: Date, format = 'YYYYMMDD') {
126
122
  throw new Error(`Invalid format`);
127
123
  }
128
124
  }
125
+
126
+ export const ResidentIdNumber = new ResidentIdNumberFormat();
@@ -1,19 +1,19 @@
1
1
  import { assert, expect, test } from 'vitest';
2
- import { Mod11Checksum } from './Mod11Checksum';
2
+ import { Mod11 } from './Mod11';
3
3
  import { ResidentIdNumber } from './ResidentIdNumber';
4
4
 
5
5
  test('id', (t) => {
6
6
  const ids = ['11010519491231002X', '11010219840406970X'];
7
7
 
8
- let cs = Mod11Checksum.get();
8
+ let cs = Mod11;
9
9
  for (const id of ids) {
10
10
  assert.equal(cs.generate(id.slice(0, -1)), id.at(-1));
11
11
  }
12
12
 
13
- let parse = ResidentIdNumber.get().parse(ids[0]);
14
- expect(parse?.toObject()).toEqual({
13
+ let parse = ResidentIdNumber.parse(ids[0]);
14
+ expect(parse?.toObject()).toMatchObject({
15
15
  division: '110105',
16
- date: new Date('1949-12-31'),
16
+ birthDate: new Date('1949-12-31'),
17
17
  sequence: 2,
18
18
  checksum: 'X',
19
19
  });
@@ -15,7 +15,8 @@ test(
15
15
  timeout: 1000 * 60 * 30,
16
16
  },
17
17
  async () => {
18
- await generate();
18
+ // missing parent 4419003 for 441900003001
19
+ // await generate();
19
20
  },
20
21
  );
21
22
 
@@ -14,12 +14,6 @@ export class Mod31Checksum {
14
14
  {} as Record<string, number>,
15
15
  );
16
16
 
17
- private static instance: Mod31Checksum;
18
-
19
- static get() {
20
- return this.instance || (this.instance = new Mod31Checksum());
21
- }
22
-
23
17
  toChar(n: number) {
24
18
  return this.chars[n];
25
19
  }
@@ -28,7 +22,7 @@ export class Mod31Checksum {
28
22
  return this.numbers[c];
29
23
  }
30
24
 
31
- verify(s: string) {
25
+ validate(s: string) {
32
26
  return s.at(-1) === this.generate(s.slice(0, s.length - 1));
33
27
  }
34
28
 
@@ -40,3 +34,5 @@ export class Mod31Checksum {
40
34
  return this.toChar(31 - (sum % 31));
41
35
  }
42
36
  }
37
+
38
+ export const Mod31 = new Mod31Checksum();
@@ -1,4 +1,4 @@
1
- import { Mod31Checksum } from './Mod31Checksum';
1
+ import { Mod31 } from './Mod31';
2
2
 
3
3
  /**
4
4
  * - GB 32100-2015 法人和其他组织统一社会信用代码编码规则
@@ -8,7 +8,7 @@ import { Mod31Checksum } from './Mod31Checksum';
8
8
  *
9
9
  * @see https://en.wikipedia.org/wiki/Unified_Social_Credit_Identifier
10
10
  */
11
- export class USCC {
11
+ export class UnifiedSocialCreditCodeFormat {
12
12
  registryCodeLabels: Record<string, Code> = {
13
13
  1: {
14
14
  label: '机构编制',
@@ -47,13 +47,7 @@ export class USCC {
47
47
 
48
48
  /* 16 位 */
49
49
  regex = /^([159][1239]|Y1)[0-9]{6}[0-9A-HJ-NP-RTUWXY]{10}$/; // 无 I O Z S V
50
- checksum = Mod31Checksum.get();
51
-
52
- static instance: USCC;
53
-
54
- static get() {
55
- return (this.instance ||= new USCC());
56
- }
50
+ checksum = Mod31;
57
51
 
58
52
  parse(s: string): ParsedUSCC {
59
53
  let registryCode = s[0];
@@ -71,8 +65,8 @@ export class USCC {
71
65
  };
72
66
  }
73
67
 
74
- verify(s: string) {
75
- return this.regex.test(s) && this.checksum.verify(s);
68
+ validate(s: string) {
69
+ return this.regex.test(s) && this.checksum.validate(s);
76
70
  }
77
71
  }
78
72
 
@@ -96,3 +90,5 @@ interface ParsedUSCC {
96
90
  // 校验码
97
91
  checksum: string;
98
92
  }
93
+
94
+ export const USCC = new UnifiedSocialCreditCodeFormat();
@@ -4,5 +4,5 @@ import { USCC } from './USCC';
4
4
  * USCC - 统一社会信用代码
5
5
  */
6
6
  export function isUSCC(s: string) {
7
- return USCC.get().verify(s);
7
+ return USCC.validate(s);
8
8
  }
@@ -1,16 +1,16 @@
1
1
  import { expect, test } from 'vitest';
2
2
  import { isUSCC } from './isUSCC';
3
- import { Mod31Checksum } from './Mod31Checksum';
3
+ import { Mod31 } from './Mod31';
4
4
  import { USCC } from './USCC';
5
5
 
6
6
  test('uscc', () => {
7
- let cs = Mod31Checksum.get();
7
+ let cs = Mod31;
8
8
 
9
9
  // 阿里云计算
10
- expect(cs.verify('91330106673959654P')).toBeTruthy();
10
+ expect(cs.validate('91330106673959654P')).toBeTruthy();
11
11
  expect(cs.generate('91330106673959654')).toBe('P');
12
12
 
13
13
  expect(isUSCC('91330106673959654P')).toBeTruthy();
14
14
 
15
- console.log(USCC.get().parse('91330106673959654P'));
15
+ console.log(USCC.parse('91330106673959654P'));
16
16
  });
@@ -1,17 +1,21 @@
1
- let nodeCrypto: Awaited<typeof import('node:crypto')>;
1
+ import { getGlobalThis } from '../runtime/getGlobalThis';
2
+
3
+ let nodeCrypto;
2
4
  // globalThis.process?.release?.name
3
5
 
6
+ // avoid import node
4
7
  // avoid process.browser
5
- if (typeof window === 'undefined') {
6
- try {
7
- // avoid `node:` UnhandledSchemeError https://github.com/vercel/next.js/issues/28774
8
- if (typeof require === 'undefined') {
9
- void import('crypto').then((v) => (nodeCrypto = v.default));
10
- } else {
11
- nodeCrypto = require('crypto');
12
- }
13
- } catch (e) {}
14
- }
8
+ // if (typeof window === 'undefined') {
9
+ // try {
10
+ // // avoid `node:` UnhandledSchemeError https://github.com/vercel/next.js/issues/28774
11
+ // if (typeof require === 'undefined') {
12
+ // void import('crypto').then((v) => (nodeCrypto = v.default));
13
+ // } else {
14
+ // nodeCrypto = require('crypto');
15
+ // }
16
+ // } catch (e) {}
17
+ // }
15
18
  export function getNodeCrypto() {
19
+ nodeCrypto ||= getGlobalThis().crypto;
16
20
  return nodeCrypto;
17
21
  }
@@ -4,10 +4,15 @@ import { getGlobalThis } from '../runtime/getGlobalThis';
4
4
  import { getNodeCrypto } from './getNodeCrypto';
5
5
 
6
6
  const globalThis = getGlobalThis();
7
+
8
+ // chrome 11+, safari 5+, nodejs 17.4+
9
+ // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
7
10
  export let getRandomValues: <T extends Exclude<TypedArray, Float32Array | Float64Array>>(typedArray: T) => T =
8
11
  globalThis.crypto?.getRandomValues?.bind(globalThis.crypto) ||
9
12
  (globalThis as any).msCrypto?.getRandomValues?.bind((globalThis as any).msCrypto) ||
10
- _getRandomValues;
13
+ (() => {
14
+ throw new Error('[getRandomValues]: No secure random number generator available.');
15
+ });
11
16
 
12
17
  function _getRandomValues<T extends Exclude<TypedArray, Float32Array | Float64Array>>(buf: T) {
13
18
  const nodeCrypto = getNodeCrypto();
@@ -0,0 +1,18 @@
1
+ export type EventType = string | symbol;
2
+
3
+ export type Handler<E extends keyof T, T = Record<string, unknown>> = (evt: { type: E; payload: T[E] }) => void;
4
+ export type WildcardHandler<T = Record<string, unknown>> = <E extends keyof T>(evt: { type: E; payload: T[E] }) => void;
5
+
6
+ export interface Emitter<Events extends Record<EventType, unknown>> {
7
+ on<Key extends keyof Events>(type: Key, handler: Handler<Key, Events>): void;
8
+
9
+ on(type: '*', handler: WildcardHandler<Events>): void;
10
+
11
+ off<Key extends keyof Events>(type: Key, handler?: Handler<Key, Events>): void;
12
+
13
+ off(type: '*', handler: WildcardHandler<Events>): void;
14
+
15
+ emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
16
+
17
+ emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
18
+ }
@@ -0,0 +1,46 @@
1
+ // from hono
2
+
3
+ export type InfoStatusCode = 100 | 101 | 102 | 103;
4
+ export type SuccessStatusCode = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226;
5
+ export type DeprecatedStatusCode = 305 | 306;
6
+ export type RedirectStatusCode = 300 | 301 | 302 | 303 | 304 | DeprecatedStatusCode | 307 | 308;
7
+ export type ClientErrorStatusCode =
8
+ | 400
9
+ | 401
10
+ | 402
11
+ | 403
12
+ | 404
13
+ | 405
14
+ | 406
15
+ | 407
16
+ | 408
17
+ | 409
18
+ | 410
19
+ | 411
20
+ | 412
21
+ | 413
22
+ | 414
23
+ | 415
24
+ | 416
25
+ | 417
26
+ | 418
27
+ | 421
28
+ | 422
29
+ | 423
30
+ | 424
31
+ | 425
32
+ | 426
33
+ | 428
34
+ | 429
35
+ | 431
36
+ | 451;
37
+ export type ServerErrorStatusCode = 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
38
+
39
+ export type UnofficialStatusCode = -1;
40
+ export type StatusCode =
41
+ | InfoStatusCode
42
+ | SuccessStatusCode
43
+ | RedirectStatusCode
44
+ | ClientErrorStatusCode
45
+ | ServerErrorStatusCode
46
+ | UnofficialStatusCode;
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Promises } from './asyncs/Promises';
2
+
1
3
  // arrays
2
4
  export {
3
5
  firstOfMaybeArray,
@@ -25,10 +27,10 @@ export { firstOfAsyncIterator } from './asyncs/firstOfAsyncIterator';
25
27
  export { nextOfAsyncIterator } from './asyncs/nextOfAsyncIterator';
26
28
  export { isIterator } from './asyncs/isIterator';
27
29
 
28
- export { sleep } from './asyncs/sleep';
30
+ export { Promises } from './asyncs/Promises';
31
+ export const sleep = Promises.sleep;
32
+ export const isPromise = Promises.isPromise;
29
33
  export { timeout, TimeoutError } from './asyncs/timeout';
30
- export { isPromise } from './asyncs/isPromise';
31
- // export * from './async/promiseOfCallback';
32
34
 
33
35
  // langs
34
36
  export { shallowEqual } from './langs/shallowEqual';
@@ -157,18 +157,23 @@ export class ArrayBuffers {
157
157
  return this.toUint8Array(ArrayBuffers.from(v, 'hex'));
158
158
  };
159
159
 
160
- static resize = (v: ArrayBufferLike, newByteLength?: number) => {
160
+ static resize = (v: ArrayBufferLike, newByteLength?: number, maxByteLength?: number): ArrayBuffer => {
161
161
  if (newByteLength === undefined || newByteLength === null) {
162
162
  return v;
163
163
  }
164
164
 
165
- if ('resize' in v && (v as any).resizable) {
166
- (v as any).resize(newByteLength);
167
- return v;
165
+ // Chrome 111, Nodejs 20
166
+ if ('resize' in v && typeof v.resize === 'function') {
167
+ if ('resizable' in v && v.resizable) {
168
+ if ('maxByteLength' in v && typeof v.maxByteLength === 'number' && v.maxByteLength >= newByteLength) {
169
+ v.resize(newByteLength);
170
+ return v;
171
+ }
172
+ }
168
173
  }
169
174
 
170
175
  const old = v;
171
- const newBuf = new ArrayBuffer(newByteLength);
176
+ const newBuf = new ArrayBuffer(newByteLength, { maxByteLength: maxByteLength });
172
177
  const oldView = new Uint8Array(old);
173
178
  const newView = new Uint8Array(newBuf);
174
179
  newView.set(oldView);
@@ -2,13 +2,34 @@ import { assert, test } from 'vitest';
2
2
  import { ByteBuffer } from './ByteBuffer';
3
3
 
4
4
  test('ByteBuffer', async () => {
5
- let buf = new ByteBuffer();
6
- buf.writeString('Hello');
7
- buf.writeString('World');
8
- assert.equal(buf.length, 10);
9
- assert.equal(buf.position, 10);
10
- buf.length = 5;
11
- assert.equal(buf.length, 5);
12
- buf.position = 0;
13
- assert.equal(buf.readString(5), 'Hello');
5
+ {
6
+ let buf = new ByteBuffer();
7
+ buf.writeString('Hello');
8
+ buf.writeString('World');
9
+ assert.equal(buf.length, 10);
10
+ assert.equal(buf.position, 10);
11
+ buf.length = 5;
12
+ assert.equal(buf.length, 5);
13
+ buf.position = 0;
14
+ assert.equal(buf.readString(5), 'Hello');
15
+ }
16
+ {
17
+ // overflow max length
18
+ let buf = new ByteBuffer();
19
+ buf.writeBytes(new Uint8Array(1025));
20
+ }
21
+ {
22
+ // overflow max length
23
+ let buf = new ByteBuffer();
24
+ buf.writeBytes(new Uint8Array([1, 2]));
25
+ buf.position = 0;
26
+ console.log('X', buf.position, buf.length, buf.remaining());
27
+
28
+ // truncate to size fill zero
29
+ buf.writeBytes(new Uint8Array(1), 10);
30
+ console.log('X', buf.position, buf.length, buf.remaining());
31
+
32
+ assert.equal(buf.view.getInt8(1), 2);
33
+ assert.equal(buf.length, 10);
34
+ }
14
35
  });
@@ -1,4 +1,3 @@
1
- import { isDefined } from '../langs/isDefined';
2
1
  import { ArrayBuffers } from './ArrayBuffers';
3
2
 
4
3
  type AnyBuffer = BufferSource | ArrayBufferLike;
@@ -72,20 +71,12 @@ export class ByteBuffer {
72
71
 
73
72
  private willWrite(length: number) {
74
73
  if (this.remaining() < length) {
75
- this.resize(this.length + length);
74
+ this.resize(this.position + length);
76
75
  }
77
76
  }
78
77
 
79
78
  resize(newLength: number) {
80
- // Chrome 111, Nodejs 20
81
- let buf = this.buffer;
82
- if (buf.resize && (!isDefined(buf.resizable) || buf.resizable)) {
83
- buf.resize(newLength);
84
- } else {
85
- let newBuffer = new ArrayBuffer(newLength);
86
- new Uint8Array(newBuffer).set(new Uint8Array(buf));
87
- this.buffer = newBuffer;
88
- }
79
+ this.buffer = ArrayBuffers.resize(this.buffer, newLength, Math.ceil(newLength * 1.2));
89
80
  }
90
81
 
91
82
  writeByte(value: number) {
@@ -97,7 +88,7 @@ export class ByteBuffer {
97
88
  this.willWrite(len);
98
89
  if (len !== bytes.byteLength) bytes = bytes.slice(0, len);
99
90
  new Uint8Array(this.buffer).set(new Uint8Array(bytes), this.position);
100
- this.position += bytes.byteLength;
91
+ this.position += len;
101
92
  }
102
93
 
103
94
  writeInt8(value: number) {
@@ -333,7 +324,7 @@ export class ByteBuffer {
333
324
  }
334
325
 
335
326
  remaining() {
336
- return this.view.byteLength - this.position;
327
+ return this.length - this.position;
337
328
  }
338
329
 
339
330
  toUint8Array() {
@@ -0,0 +1,39 @@
1
+ import { expect, test } from 'vitest';
2
+ import { mixin } from './mixin';
3
+
4
+ export type Constructor<T = {}> = new (...args: any[]) => T;
5
+
6
+ test('mixin', () => {
7
+ class User extends mixin(BaseResource, createBarFields()) {}
8
+
9
+ let usr = new User();
10
+ // type not working
11
+ expect(usr.foo, 'foo');
12
+ expect(usr).toEqual({
13
+ foo: 'foo',
14
+ bar: 'bar',
15
+ id: '',
16
+ });
17
+ });
18
+
19
+ class BaseResource {
20
+ id?: string = '';
21
+ }
22
+
23
+ function createBarFields() {
24
+ return <TBase extends Constructor>(Base: TBase) => {
25
+ class HasBarMixin extends mixin(Base, withFooFields) {
26
+ bar?: string = 'bar';
27
+ }
28
+
29
+ return HasBarMixin;
30
+ };
31
+ }
32
+
33
+ function withFooFields<TBase extends Constructor>(Base: TBase) {
34
+ class HasFieldFooMixin extends Base {
35
+ foo?: string = 'foo';
36
+ }
37
+
38
+ return HasFieldFooMixin;
39
+ }
@@ -1,6 +1,6 @@
1
1
  /// javascript pseudo random
2
2
  export function createRandom(o: { seed?: string | number } = {}) {
3
- let seed = typeof o.seed === 'string' ? 0 : o.seed ?? 0;
3
+ let seed = typeof o.seed === 'string' ? 0 : (o.seed ?? 0);
4
4
  if (typeof o.seed === 'string') {
5
5
  let sum = 0;
6
6
  for (let i = 0; i < o.seed.length; i++) {
@@ -0,0 +1 @@
1
+ - https://github.com/developit/mitt/blob/main/src/index.ts
@@ -0,0 +1,114 @@
1
+ export type EventType = string | symbol;
2
+
3
+ type EventPayload<T = EventType, E = unknown> = { type: T; event: E };
4
+
5
+ export type Handler<T = EventType, E = unknown> = (evt: { type: T; event: E }) => void;
6
+
7
+ // An array of all currently registered event handlers for a type
8
+ export type EventHandlerList<T = unknown> = Array<Handler<EventType, T>>;
9
+
10
+ // A map of event types and their corresponding event handlers.
11
+ export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<
12
+ keyof Events | '*',
13
+ EventHandlerList<Events[keyof Events]>
14
+ >;
15
+
16
+ export interface Emitter<Events extends Record<EventType, unknown>> {
17
+ all: EventHandlerMap<Events>;
18
+
19
+ on<Key extends keyof Events>(type: Key, handler: Handler<Key, Events[Key]>): void;
20
+
21
+ on(type: '*', handler: Handler<Events>): void;
22
+
23
+ once<Key extends keyof Events>(type: Key, handler: Handler<Key, Events[Key]>): void;
24
+
25
+ once(type: '*', handler: Handler<Events>): void;
26
+
27
+ off<Key extends keyof Events>(type: Key, handler?: Handler<Key, Events[Key]>): void;
28
+
29
+ off(type: '*', handler: Handler<Events>): void;
30
+
31
+ emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
32
+
33
+ emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
34
+ }
35
+
36
+ /**
37
+ * Mitt: Tiny (~200b) functional event emitter / pubsub.
38
+ * @name createEmitter
39
+ * @returns {Emitter}
40
+ */
41
+ export default function createEmitter<Events extends Record<EventType, unknown>>(
42
+ all?: EventHandlerMap<Events>,
43
+ ): Emitter<Events> {
44
+ type GenericEventHandler = Handler<EventType, Events[keyof Events]>;
45
+ all = all || new Map();
46
+ let evt: Emitter<Events>;
47
+ return (evt = {
48
+ /**
49
+ * A Map of event names to registered handler functions.
50
+ */
51
+ all,
52
+
53
+ on(type: EventType, handler: GenericEventHandler) {
54
+ const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
55
+ if (handlers) {
56
+ handlers.push(handler);
57
+ } else {
58
+ all!.set(type, [handler]);
59
+ }
60
+ },
61
+
62
+ once(type: EventType, handler: GenericEventHandler) {
63
+ let fn = handler;
64
+ handler = (...args) => {
65
+ evt.off(type, fn);
66
+ fn(...args);
67
+ };
68
+ const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
69
+ if (handlers) {
70
+ handlers.push(handler);
71
+ } else {
72
+ all!.set(type, [handler]);
73
+ }
74
+ },
75
+
76
+ off(type: EventType, handler?: GenericEventHandler) {
77
+ const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
78
+ if (handlers) {
79
+ if (handler) {
80
+ handlers.splice(handlers.indexOf(handler) >>> 0, 1);
81
+ } else {
82
+ all!.set(type, []);
83
+ }
84
+ }
85
+ },
86
+
87
+ /**
88
+ * Invoke all handlers for the given type.
89
+ * If present, `'*'` handlers are invoked after type-matched handlers.
90
+ *
91
+ * Note: Manually firing '*' handlers is not supported.
92
+ *
93
+ * @param {string|symbol} type The event type to invoke
94
+ * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
95
+ * @memberOf createEmitter
96
+ */
97
+ emit(type: EventType, evt?: any) {
98
+ let handlers = all!.get(type);
99
+ let ctx: EventPayload = { type, event: evt };
100
+ if (handlers) {
101
+ (handlers as EventHandlerList).slice().map((handler) => {
102
+ handler(ctx);
103
+ });
104
+ }
105
+
106
+ handlers = all!.get('*');
107
+ if (handlers) {
108
+ (handlers as EventHandlerList).slice().map((handler) => {
109
+ handler(ctx);
110
+ });
111
+ }
112
+ },
113
+ } as Emitter<Events>);
114
+ }
@@ -1,7 +1,8 @@
1
+ export function computeIfAbsent<K extends WeakKey, V>(map: WeakMap<K, V>, key: K, fn: () => V): V;
1
2
  export function computeIfAbsent<K, V>(map: Map<K, V>, key: K, fn: () => V): V;
2
3
  export function computeIfAbsent<K extends string | symbol | number, V>(map: Record<K, V>, key: K, fn: () => V): V;
3
- export function computeIfAbsent<K, V>(map: any, key: K, fn: () => V): V {
4
- if (map instanceof Map) {
4
+ export function computeIfAbsent(map: any, key: any, fn: () => any): any {
5
+ if (map instanceof Map || map instanceof WeakMap) {
5
6
  if (!map.has(key)) {
6
7
  map.set(key, fn());
7
8
  }
@@ -1,3 +0,0 @@
1
- export const sleep = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms));
2
-
3
- //# sourceMappingURL=sleep.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/asyncs/sleep.ts"],"sourcesContent":["export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n"],"names":["sleep","ms","Promise","resolve","setTimeout"],"rangeMappings":"","mappings":"AAAA,OAAO,MAAMA,QAAQ,CAACC,KAAe,IAAIC,QAAQ,CAACC,UAAYC,WAAWD,SAASF,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/cn/id/Mod11Checksum.ts"],"sourcesContent":["/**\n * ISO 7064:1983, MOD 11-2.\n */\nexport class Mod11Checksum {\n weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];\n private static instance: Mod11Checksum;\n\n static get() {\n return this.instance || (this.instance = new Mod11Checksum());\n }\n\n verify(s: string) {\n return s.at(-1) === this.generate(s.slice(0, s.length - 1));\n }\n\n generate(s: string) {\n const { weights } = this;\n let sum = 0;\n for (let i = 0; i < s.length; i++) {\n sum += parseInt(s[i]) * weights[i];\n }\n const num = (12 - (sum % 11)) % 11;\n if (num < 10) {\n return num.toString();\n } else {\n return 'X';\n }\n }\n}\n"],"names":["Mod11Checksum","weights","instance","get","verify","s","at","generate","slice","length","sum","i","parseInt","num","toString"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;CAEC,GACD,OAAO,MAAMA;IACXC,UAAU;QAAC;QAAG;QAAG;QAAI;QAAG;QAAG;QAAG;QAAG;QAAG;QAAG;QAAG;QAAG;QAAG;QAAI;QAAG;QAAG;QAAG;QAAG;KAAE,CAAC;IACnE,OAAeC,SAAwB;IAEvC,OAAOC,MAAM;QACX,OAAO,IAAI,CAACD,QAAQ,IAAK,CAAA,IAAI,CAACA,QAAQ,GAAG,IAAIF,eAAc;IAC7D;IAEAI,OAAOC,CAAS,EAAE;QAChB,OAAOA,EAAEC,EAAE,CAAC,CAAC,OAAO,IAAI,CAACC,QAAQ,CAACF,EAAEG,KAAK,CAAC,GAAGH,EAAEI,MAAM,GAAG;IAC1D;IAEAF,SAASF,CAAS,EAAE;QAClB,MAAM,EAAEJ,OAAO,EAAE,GAAG,IAAI;QACxB,IAAIS,MAAM;QACV,IAAK,IAAIC,IAAI,GAAGA,IAAIN,EAAEI,MAAM,EAAEE,IAAK;YACjCD,OAAOE,SAASP,CAAC,CAACM,EAAE,IAAIV,OAAO,CAACU,EAAE;QACpC;QACA,MAAME,MAAM,AAAC,CAAA,KAAMH,MAAM,EAAE,IAAK;QAChC,IAAIG,MAAM,IAAI;YACZ,OAAOA,IAAIC,QAAQ;QACrB,OAAO;YACL,OAAO;QACT;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/cn/uscc/Mod31Checksum.ts"],"sourcesContent":["/**\n * GB/T 17710(采ISO 7064)的模31校验码\n *\n * Mod31-3\n */\nexport class Mod31Checksum {\n weights = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];\n chars = '0123456789ABCDEFGHJKLMNPQRTUWXY';\n numbers: Record<string, number> = this.chars.split('').reduce(\n (acc, cur, i) => {\n acc[cur] = i;\n return acc;\n },\n {} as Record<string, number>,\n );\n\n private static instance: Mod31Checksum;\n\n static get() {\n return this.instance || (this.instance = new Mod31Checksum());\n }\n\n toChar(n: number) {\n return this.chars[n];\n }\n\n toNumber(c: string) {\n return this.numbers[c];\n }\n\n verify(s: string) {\n return s.at(-1) === this.generate(s.slice(0, s.length - 1));\n }\n\n generate(s: string) {\n let sum = 0;\n for (let i = 0; i < s.length; i++) {\n sum += this.numbers[s[i]] * this.weights[i];\n }\n return this.toChar(31 - (sum % 31));\n }\n}\n"],"names":["Mod31Checksum","weights","chars","numbers","split","reduce","acc","cur","i","instance","get","toChar","n","toNumber","c","verify","s","at","generate","slice","length","sum"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;CAIC,GACD,OAAO,MAAMA;IACXC,UAAU;QAAC;QAAG;QAAG;QAAG;QAAI;QAAI;QAAI;QAAI;QAAI;QAAI;QAAI;QAAI;QAAI;QAAG;QAAI;QAAI;QAAI;KAAG,CAAC;IAC3EC,QAAQ,kCAAkC;IAC1CC,UAAkC,IAAI,CAACD,KAAK,CAACE,KAAK,CAAC,IAAIC,MAAM,CAC3D,CAACC,KAAKC,KAAKC;QACTF,GAAG,CAACC,IAAI,GAAGC;QACX,OAAOF;IACT,GACA,CAAC,GACD;IAEF,OAAeG,SAAwB;IAEvC,OAAOC,MAAM;QACX,OAAO,IAAI,CAACD,QAAQ,IAAK,CAAA,IAAI,CAACA,QAAQ,GAAG,IAAIT,eAAc;IAC7D;IAEAW,OAAOC,CAAS,EAAE;QAChB,OAAO,IAAI,CAACV,KAAK,CAACU,EAAE;IACtB;IAEAC,SAASC,CAAS,EAAE;QAClB,OAAO,IAAI,CAACX,OAAO,CAACW,EAAE;IACxB;IAEAC,OAAOC,CAAS,EAAE;QAChB,OAAOA,EAAEC,EAAE,CAAC,CAAC,OAAO,IAAI,CAACC,QAAQ,CAACF,EAAEG,KAAK,CAAC,GAAGH,EAAEI,MAAM,GAAG;IAC1D;IAEAF,SAASF,CAAS,EAAE;QAClB,IAAIK,MAAM;QACV,IAAK,IAAIb,IAAI,GAAGA,IAAIQ,EAAEI,MAAM,EAAEZ,IAAK;YACjCa,OAAO,IAAI,CAAClB,OAAO,CAACa,CAAC,CAACR,EAAE,CAAC,GAAG,IAAI,CAACP,OAAO,CAACO,EAAE;QAC7C;QACA,OAAO,IAAI,CAACG,MAAM,CAAC,KAAMU,MAAM;IACjC;AACF"}
@@ -1 +0,0 @@
1
- export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));