@idlebox/common 1.3.6 → 1.3.7

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 (80) hide show
  1. package/lib/string/concatType.generated.cjs +1 -1
  2. package/lib/string/concatType.generated.cjs.map +1 -1
  3. package/lib/string/concatType.generated.js +1 -1
  4. package/lib/string/concatType.generated.js.map +1 -1
  5. package/package.json +1 -1
  6. package/.rush/temp/8ffc60c66c29712a4b0392d78f8ceb08fd99cd43.log +0 -10
  7. package/.rush/temp/shrinkwrap-deps.json +0 -671
  8. package/Gulpfile.js +0 -4
  9. package/build-script.json +0 -55
  10. package/common.build.log +0 -42
  11. package/config/rush-project.json +0 -4
  12. package/docs/common.api.json +0 -21006
  13. package/docs/common.api.md +0 -1125
  14. package/docs/tsdoc-metadata.json +0 -11
  15. package/idlebox-common-v1.3.2.tgz +0 -0
  16. package/idlebox-common-v1.3.3.tgz +0 -0
  17. package/src/array/arrayDiff.ts +0 -31
  18. package/src/array/arraySame.ts +0 -15
  19. package/src/array/arrayUnique.ts +0 -50
  20. package/src/array/normalizeArray.ts +0 -13
  21. package/src/array/sortAlpha.ts +0 -15
  22. package/src/date/consts.ts +0 -5
  23. package/src/date/isInvalid.ts +0 -6
  24. package/src/date/sibling.ts +0 -28
  25. package/src/date/timeString.ts +0 -150
  26. package/src/date/unix.ts +0 -13
  27. package/src/debugging/tryInspect.ts +0 -37
  28. package/src/error/convertUnknown.ts +0 -10
  29. package/src/error/getFrame.ts +0 -13
  30. package/src/function/asyncCallbackList.ts +0 -75
  31. package/src/function/callbackList.ts +0 -84
  32. package/src/function/delayCallbackList.ts +0 -45
  33. package/src/function/functionName.ts +0 -39
  34. package/src/lifecycle/dispose/bridges/rxjs.ts +0 -6
  35. package/src/lifecycle/dispose/disposableEvent.ts +0 -117
  36. package/src/lifecycle/dispose/disposedError.ts +0 -16
  37. package/src/lifecycle/dispose/lifecycle.async.ts +0 -61
  38. package/src/lifecycle/dispose/lifecycle.global.ts +0 -61
  39. package/src/lifecycle/dispose/lifecycle.sync.ts +0 -79
  40. package/src/lifecycle/dispose/lifecycle.ts +0 -28
  41. package/src/lifecycle/event/event.ts +0 -63
  42. package/src/lifecycle/promise/cancel.ts +0 -16
  43. package/src/lifecycle/promise/cancellationToken/driver.browser.ts +0 -55
  44. package/src/lifecycle/promise/cancellationToken/driver.common.ts +0 -43
  45. package/src/lifecycle/promise/cancellationToken/source.ts +0 -48
  46. package/src/lifecycle/promise/deferredPromise.ts +0 -102
  47. package/src/lifecycle/timeout/timeout.ts +0 -48
  48. package/src/lifecycle/timeout/timeoutError.ts +0 -16
  49. package/src/log/logger.ts +0 -148
  50. package/src/mapSet/customSet.ts +0 -91
  51. package/src/mapSet/extendMap.ts +0 -40
  52. package/src/misc/assertNotNull.ts +0 -21
  53. package/src/object/definePublicConstant.ts +0 -10
  54. package/src/object/initOnRead.ts +0 -27
  55. package/src/object/objectPath.ts +0 -10
  56. package/src/object/objectSame.ts +0 -52
  57. package/src/path/isAbsolute.ts +0 -11
  58. package/src/path/normalizePath.ts +0 -8
  59. package/src/path/pathArray.ts +0 -42
  60. package/src/platform/globalObject.ts +0 -18
  61. package/src/platform/globalSingleton.ts +0 -82
  62. package/src/platform/globalSymbol.ts +0 -36
  63. package/src/platform/os.ts +0 -45
  64. package/src/promise/awaitIterator.ts +0 -19
  65. package/src/promise/finishAllPromise.ts +0 -50
  66. package/src/promise/promiseBool.ts +0 -10
  67. package/src/promise/promisePool.ts +0 -40
  68. package/src/promise/timeoutPromisePool.ts +0 -22
  69. package/src/reflection/classes/hookClass.ts +0 -47
  70. package/src/reflection/classes/singleton.ts +0 -33
  71. package/src/reflection/methods/bind.ts +0 -30
  72. package/src/reflection/methods/initOnRead.ts +0 -11
  73. package/src/reflection/methods/memorize.ts +0 -33
  74. package/src/string/castCase.ts +0 -44
  75. package/src/string/concatType.generated.ts +0 -255
  76. package/src/string/concatType.generator.ts +0 -31
  77. package/src/string/escapeRegexp.ts +0 -4
  78. package/src/string/pad2.ts +0 -11
  79. package/src/string/sizeString.ts +0 -52
  80. package/src/tsconfig.json +0 -13
@@ -1,48 +0,0 @@
1
- import { TimeoutError } from './timeoutError';
2
- import { DeferredPromise } from '../promise/deferredPromise';
3
-
4
- /**
5
- * @returns promise reject with TimeoutError after specific time
6
- */
7
- export function timeout(ms: number, error = 'no response'): Promise<never> {
8
- return new Promise((_, reject) => {
9
- setTimeout(() => {
10
- reject(new TimeoutError(ms, error));
11
- }, ms);
12
- });
13
- }
14
-
15
- /**
16
- * @returns promise resolve after specific time
17
- */
18
- export function sleep(ms: number): Promise<void> {
19
- return new Promise((resolve) => {
20
- setTimeout(() => {
21
- resolve();
22
- }, ms);
23
- });
24
- }
25
-
26
- export function timeoutPromise<T>(ms: number, p: Promise<T>): Promise<T>;
27
- export function timeoutPromise<T>(ms: number, message: string, p: Promise<T>): Promise<T>;
28
- export function timeoutPromise<T, PT = any>(ms: number, p: DeferredPromise<T, PT>): DeferredPromise<T, PT>;
29
- export function timeoutPromise<T, PT = any>(
30
- ms: number,
31
- message: string,
32
- p: DeferredPromise<T, PT>
33
- ): DeferredPromise<T, PT>;
34
-
35
- export function timeoutPromise<T>(ms: number, message: string | T, p?: T): T {
36
- let msg: string | undefined;
37
- if (typeof message !== 'string') {
38
- p = message;
39
- msg = undefined;
40
- } else {
41
- msg = message;
42
- }
43
- if (p instanceof DeferredPromise) {
44
- return Promise.race([p.p, timeout(ms, msg)]).then(() => p) as any;
45
- } else {
46
- return Promise.race([p, timeout(ms, msg)]).then(() => p) as any;
47
- }
48
- }
@@ -1,16 +0,0 @@
1
- import { humanDate } from '../../date/timeString';
2
-
3
- /**
4
- * Error when timeout() done
5
- * @public
6
- */
7
- export class TimeoutError extends Error {
8
- constructor(time: number, what: string = 'no response') {
9
- super(`Timeout: ${what} in ${humanDate.deltaTiny(time)}`);
10
- }
11
- }
12
-
13
- /** @public */
14
- export function isTimeoutError(error: Error): error is TimeoutError {
15
- return error instanceof TimeoutError;
16
- }
package/src/log/logger.ts DELETED
@@ -1,148 +0,0 @@
1
- import { nameFunction } from '../function/functionName';
2
- import { isWeb } from '../platform/os';
3
-
4
- export enum ColorKind {
5
- DISABLE,
6
- TERMINAL,
7
- WEB,
8
- DETECT,
9
- }
10
-
11
- export interface WrappedConsoleOptions {
12
- parent?: Console;
13
- bind?: boolean;
14
- }
15
-
16
- export abstract class WrappedConsole {
17
- public declare info: Console['info'];
18
- public declare log: Console['log'];
19
- public declare success: Console['log'];
20
- public declare debug: Console['debug'];
21
- public declare error: Console['error'];
22
- public declare trace: Console['trace'];
23
- public declare warn: Console['warn'];
24
- public declare assert: Console['assert'];
25
-
26
- public declare time: Console['time'];
27
- public declare timeEnd: Console['timeEnd'];
28
- public declare timeLog: Console['timeLog'];
29
- public declare count: Console['count'];
30
- public declare countReset: Console['countReset'];
31
- public declare group: Console['group'];
32
- public declare groupCollapsed: Console['groupCollapsed'];
33
- public declare groupEnd: Console['groupEnd'];
34
-
35
- public declare table: Console['table'];
36
- public declare dir: Console['dir'];
37
- public declare clear: Console['clear'];
38
-
39
- protected readonly title: string;
40
- protected readonly parent: Console;
41
- protected readonly bind: boolean;
42
-
43
- constructor(title: string, { parent, bind }: WrappedConsoleOptions = {}) {
44
- this.title = title;
45
- this.parent = parent || console;
46
- this.bind = bind || false;
47
-
48
- this.info = this.wrapMessageAt('info', 0);
49
- this.log = this.wrapMessageAt('log', 0);
50
- this.success = this.wrapMessageAt('log', 0);
51
- this.debug = this.wrapMessageAt('debug', 0);
52
- this.error = this.wrapMessageAt('error', 0);
53
- this.trace = this.wrapMessageAt('trace', 0);
54
- this.warn = this.wrapMessageAt('warn', 0);
55
- this.assert = this.wrapMessageAt('assert', 1);
56
-
57
- this.time = this.wrapMessageAt('time', 0);
58
- this.timeEnd = this.wrapMessageAt('timeEnd', 0);
59
- this.timeLog = this.wrapMessageAt('timeLog', 0);
60
- this.count = this.wrapMessageAt('count', 0);
61
- this.countReset = this.wrapMessageAt('countReset', 0);
62
- this.group = this.wrapMessageAt('group', 0);
63
- this.groupCollapsed = this.wrapMessageAt('groupCollapsed', 0);
64
-
65
- this.groupEnd = this.wrapSimple('groupEnd');
66
- this.table = this.wrapExtra('table', ' <<table>>');
67
- this.dir = this.wrapExtra('dir', ' <<dir>>');
68
- this.clear = this.wrapExtra('clear', ' <<clear>>');
69
- }
70
-
71
- protected wrap<T extends keyof Omit<Console & { Console: any }, 'Console'>>(original: T): Function {
72
- if (this.bind) {
73
- return this.parent[original].bind(this.parent) as any;
74
- } else {
75
- return this.parent[original];
76
- }
77
- }
78
-
79
- private wrapSimple<T extends keyof Omit<Console & { Console: any }, 'Console'>>(original: T): Console[T] {
80
- return nameFunction('console:' + original, this.wrap(original) as any);
81
- }
82
-
83
- private wrapExtra<T extends keyof Omit<Console & { Console: any }, 'Console'>>(
84
- original: T,
85
- exMessage: string
86
- ): Console[T] {
87
- const bindedFn = this.wrap(original);
88
- return nameFunction('console:' + original, (...args: any[]) => {
89
- this.log(exMessage);
90
- bindedFn(...args);
91
- });
92
- }
93
-
94
- protected createPrefix(message: string) {
95
- let prefix = `[${this.title}]`;
96
- if (message) {
97
- prefix += `[${message}] `;
98
- } else {
99
- prefix += ' ';
100
- }
101
- return prefix;
102
- }
103
-
104
- private wrapMessageAt<T extends keyof Omit<Console & { Console: any }, 'Console'>>(
105
- original: T,
106
- messageLoc: number,
107
- additionalPrefix?: string
108
- ): Console[T] {
109
- let prefix = `[${this.title}]`;
110
- if (additionalPrefix) {
111
- prefix += `[${additionalPrefix}] `;
112
- } else {
113
- prefix += ' ';
114
- }
115
-
116
- const fn = this.wrap(original);
117
-
118
- return nameFunction('console:' + original, (...args: any[]) => {
119
- this.convertObjectArg(args, messageLoc);
120
- this.processColorLabel(args, messageLoc, original, prefix);
121
- fn(...args);
122
- });
123
- }
124
-
125
- private convertObjectArg(args: any[], pos: number) {
126
- const msg = args[pos];
127
- if (args.length > pos) {
128
- if (typeof msg === 'string') {
129
- return;
130
- }
131
-
132
- args.splice(pos, 0, (isWeb ? ' %o' : ' %j').repeat(args.length - pos).substr(1));
133
- } else {
134
- args[pos] = '';
135
- }
136
- }
137
-
138
- protected abstract processColorLabel(
139
- normalizedArguments: any[],
140
- messageLoc: number,
141
- level: string,
142
- prefix: string
143
- ): void;
144
-
145
- protected uncolor(args: any[], pos: number, prefix: string, postfix: string) {
146
- args[pos] = prefix + args[pos] + postfix;
147
- }
148
- }
@@ -1,91 +0,0 @@
1
- /** Find the index of given item */
2
- export interface Finder<Type> {
3
- (this: Type[], item: Type): number;
4
- }
5
-
6
- type MyFinder<Type> = (item: Type) => number;
7
-
8
- export function RegexpFinder(this: RegExp[], item: RegExp): number {
9
- return this.findIndex((e) => e.toString() === item.toString());
10
- }
11
-
12
- /**
13
- * Like a Set, but use custom compare function insteadof ===
14
- */
15
- export class CustomSet<Type = string> {
16
- protected registry: Type[];
17
- private finder: MyFinder<Type>;
18
-
19
- constructor(finder: Finder<Type> = Array.prototype.indexOf) {
20
- this.registry = [];
21
- this.finder = finder.bind(this.registry);
22
- }
23
-
24
- setFinder(finder: Finder<Type>) {
25
- this.finder = finder.bind(this.registry);
26
- }
27
-
28
- has(item: Type): boolean {
29
- return this.finder(item) !== -1;
30
- }
31
-
32
- add(item: Type): boolean {
33
- const index = this.finder(item);
34
- if (index === -1) {
35
- this.registry.push(item);
36
- return true;
37
- } else {
38
- return false;
39
- }
40
- }
41
-
42
- /**
43
- * @returns all added values
44
- */
45
- addAll(items: Type[]): Type[] {
46
- return items.filter((e) => this.add(e));
47
- }
48
-
49
- delete(item: Type): boolean {
50
- const index = this.finder(item);
51
- if (index === -1) {
52
- return false;
53
- } else {
54
- this.registry.splice(index, 1);
55
- return true;
56
- }
57
- }
58
-
59
- /**
60
- * @returns all deleted values
61
- */
62
- deleteAll(items: Type[]): Type[] {
63
- return items.filter((e) => this.delete(e));
64
- }
65
-
66
- clear() {
67
- this.registry.length = 0;
68
- }
69
-
70
- get length() {
71
- return this.registry.length;
72
- }
73
-
74
- get size() {
75
- return this.registry.length;
76
- }
77
-
78
- [Symbol.iterator](): Iterator<Type> {
79
- return this.registry[Symbol.iterator]();
80
- }
81
- keys(): Iterator<Type> {
82
- return this.registry[Symbol.iterator]();
83
- }
84
- values(): Iterator<Type> {
85
- return this.registry[Symbol.iterator]();
86
- }
87
-
88
- toArray() {
89
- return this.registry.slice();
90
- }
91
- }
@@ -1,40 +0,0 @@
1
- export interface MapLike<V> {
2
- [id: string]: V;
3
- }
4
-
5
- /**
6
- * A map, will throw error when try to get not exists key
7
- */
8
- export class ExtendMap<K, V> extends Map<K, V> {
9
- /**
10
- * Get value from map, if not exists, throw an error
11
- */
12
- public get(id: K): V;
13
- /**
14
- * Get value from map, if not exists, return def instead (not insert it into map)
15
- */
16
- public get(id: K, def: V): V;
17
-
18
- public get(id: K, def?: V): V {
19
- if (super.has(id)) {
20
- return super.get(id)!;
21
- } else if (arguments.length === 2) {
22
- return def!;
23
- } else {
24
- throw new Error(`Unknown key {${id}} in map.`);
25
- }
26
- }
27
-
28
- /**
29
- * Get a value, if not exists, call init() and set to map
30
- */
31
- public entry(id: K, init: (id: K) => V): V {
32
- if (super.has(id)) {
33
- return super.get(id)!;
34
- } else {
35
- const nv = init(id);
36
- super.set(id, nv);
37
- return nv;
38
- }
39
- }
40
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * assert value is not null or undefined or NaN
3
- * @public
4
- */
5
- export function assertNotNull<T>(val: T | null | undefined): T {
6
- console.assert(val !== undefined && val !== null, 'AssertValue failed, got %s(%s).', typeof val, val);
7
- return val!;
8
- }
9
-
10
- /**
11
- * assert value is not null or undefined or NaN
12
- * @throws Value is null or undefined
13
- * @public
14
- */
15
- export function throwNull<T>(val: T) {
16
- if (val === undefined || val === null) {
17
- return val!;
18
- } else {
19
- throw new Error('Value is ' + typeof val);
20
- }
21
- }
@@ -1,10 +0,0 @@
1
- export function definePublicConstant(object: any, propertyKey: string | symbol, value: any) {
2
- if (object[propertyKey] === value) return;
3
- delete object[propertyKey];
4
- Object.defineProperty(object, propertyKey, {
5
- configurable: false,
6
- enumerable: true,
7
- writable: false,
8
- value,
9
- });
10
- }
@@ -1,27 +0,0 @@
1
- /** @public */
2
- export interface InitFunc<O, T> {
3
- (this: O): T;
4
- }
5
-
6
- /**
7
- * Define property on target, call init it when first use, them memorize
8
- * @public
9
- */
10
- export function initOnRead<O, T extends keyof O>(target: any, propertyKey: T, init: InitFunc<O, O[T]>) {
11
- if (target.hasOwnProperty(propertyKey)) {
12
- return;
13
- }
14
- Object.defineProperty(target, propertyKey, {
15
- configurable: true,
16
- get: function (): O[T] {
17
- const data = init.call(this);
18
- delete target[propertyKey];
19
- target[propertyKey] = data;
20
- return data;
21
- },
22
- set(v: T) {
23
- delete target[propertyKey];
24
- target[propertyKey] = v;
25
- },
26
- });
27
- }
@@ -1,10 +0,0 @@
1
- /**
2
- * Get deep child property of an object
3
- * @param path object path seprate by "."
4
- */
5
- export function objectPath(obj: object, path: string): any {
6
- path.split('.').every((name) => {
7
- return (obj = (obj as any)[name]);
8
- });
9
- return obj;
10
- }
@@ -1,52 +0,0 @@
1
- import { isArraySame } from '../array/arraySame';
2
-
3
- /**
4
- * Should ensure a and b is none-null before call this
5
- * @returns true when a and b has EXACTLY same keys and values
6
- */
7
- export function isObjectSame(a: any, b: any) {
8
- if (a === b) {
9
- return true;
10
- }
11
- const aks = Object.keys(a);
12
- if (!isArraySame(aks, Object.keys(b))) {
13
- return false;
14
- }
15
-
16
- for (const k of aks) {
17
- if (a[k] !== b[k]) {
18
- return false;
19
- }
20
- }
21
- return true;
22
- }
23
-
24
- /**
25
- * Should ensure a and b is none-null before call this
26
- * @returns true when a and b has EXACTLY same keys and values, recursive compare all object values
27
- */
28
- export function isObjectSameRecursive(a: any, b: any) {
29
- const aks = Object.keys(a);
30
- if (!isArraySame(aks, Object.keys(b))) {
31
- return false;
32
- }
33
-
34
- for (const k of aks) {
35
- if (a[k] !== b[k]) {
36
- const av = a[k],
37
- bv = b[k];
38
- if (av && bv && typeof av === 'object' && typeof bv === 'object') {
39
- if (Array.isArray(av)) {
40
- if (Array.isArray(bv)) {
41
- if (isArraySame(av, bv)) continue;
42
- }
43
- } else if (!Array.isArray(bv)) {
44
- if (isObjectSameRecursive(a[k], b[k])) continue;
45
- }
46
- }
47
-
48
- return false;
49
- }
50
- }
51
- return true;
52
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * return true if a path is absolute:
3
- * - /xxxx
4
- * - \xxxx
5
- * - c:/
6
- * - c:\
7
- * - http://
8
- */
9
- export function isAbsolute(path: string) {
10
- return /^\/|^\\|^[a-z]:[\\/]|^[^:]{1,10}:\/\//i.test(path);
11
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * replace // to /
3
- * replace \ to /
4
- * remove ending /
5
- */
6
- export function normalizePath(p: string) {
7
- return p.replace(/\\+/, '/').replace(/\/\/+/, '/').replace(/\/+$/, '');
8
- }
@@ -1,42 +0,0 @@
1
- import { normalizePath } from './normalizePath';
2
-
3
- /**
4
- * Work on "PATH"-like values
5
- */
6
- export class PathArray extends Set<string> {
7
- constructor(init: string, private readonly sep: ':' | ';') {
8
- super();
9
- if (init) this.add(init);
10
- }
11
-
12
- add(paths: string) {
13
- for (const p of paths.split(this.sep)) {
14
- if (!p) continue;
15
- super.add(normalizePath(p));
16
- }
17
- return this;
18
- }
19
-
20
- delete(paths: string) {
21
- let anyRet = false;
22
- for (const p of paths.split(this.sep)) {
23
- anyRet = anyRet || super.delete(normalizePath(p));
24
- }
25
- return anyRet;
26
- }
27
-
28
- has(path: string): boolean {
29
- return super.has(normalizePath(path));
30
- }
31
-
32
- toString() {
33
- return [...this.values()].join(this.sep);
34
- }
35
-
36
- /**
37
- * @returns an array with `part` append to every element
38
- */
39
- join(part: string) {
40
- return [...this.values()].map((p) => normalizePath(p + '/' + part));
41
- }
42
- }
@@ -1,18 +0,0 @@
1
- declare const global: any;
2
- declare const window: any;
3
-
4
- /**
5
- * globalThis when supported.
6
- * if not, window in browser, global in nodejs
7
- * @public
8
- */
9
- export const globalObject: any =
10
- typeof globalThis === 'undefined' ? (typeof window === 'undefined' ? global : window) : globalThis;
11
-
12
- export function ensureGlobalObject<T>(symbol: string, constructor: () => T): T {
13
- const sm = Symbol.for(symbol);
14
- if (!globalObject[sm]) {
15
- globalObject[sm] = constructor();
16
- }
17
- return globalObject[sm];
18
- }
@@ -1,82 +0,0 @@
1
- import { functionName } from '../function/functionName';
2
- import { ensureGlobalObject } from './globalObject';
3
-
4
- const singletonRegistry = ensureGlobalObject(`@@idlebox/global-singleton`, () => {
5
- return new Map<string | symbol, any>();
6
- });
7
-
8
- /**
9
- * Get an singleton instance from window/global space
10
- * if symbol did not exists, create it and assign to window/global
11
- * @public
12
- */
13
- export function globalSingletonStrong<T>(symbol: symbol | string, constructor: () => T): T;
14
- /**
15
- * Get an singleton instance from window/global space
16
- * @public
17
- */
18
- export function globalSingletonStrong<T>(symbol: symbol | string): T | undefined;
19
-
20
- export function globalSingletonStrong<T>(symbol: symbol | string, constructor?: () => T): T | undefined {
21
- let object = singletonRegistry.get(symbol);
22
- if (object instanceof WeakRef) {
23
- const target = object.deref();
24
- if (target !== undefined) {
25
- object = target;
26
- } else if (constructor) {
27
- object = constructor();
28
- if (object === undefined)
29
- throw new TypeError(`singleton constructor (${functionName(constructor)}) returned undefined.`);
30
- } else {
31
- singletonRegistry.delete(symbol);
32
- return undefined;
33
- }
34
- singletonRegistry.set(symbol, object);
35
- } else if (object === undefined && constructor) {
36
- object = constructor();
37
- if (object === undefined)
38
- throw new TypeError(`singleton constructor (${functionName(constructor)}) returned undefined.`);
39
- singletonRegistry.set(symbol, object);
40
- }
41
- return object;
42
- }
43
-
44
- /**
45
- * Delete a key from window/global space
46
- * use with care
47
- * @public
48
- */
49
- export function globalSingletonDelete(symbol: symbol | string) {
50
- singletonRegistry.delete(symbol);
51
- }
52
-
53
- /**
54
- * Same with globalSingletonStrong, but save instance in a WeakMap, so it maybe delete by gc if no reference
55
- * @public
56
- */
57
- export function globalSingleton<T>(symbol: symbol | string, constructor: () => T): T;
58
- /**
59
- * Same with globalSingletonStrong, but save instance in a WeakMap, so it maybe delete by gc if no reference
60
- * @public
61
- */
62
- export function globalSingleton<T>(symbol: symbol | string): T | undefined;
63
- export function globalSingleton<T>(symbol: symbol | string, constructor?: () => T): T | undefined {
64
- if (singletonRegistry.has(symbol)) {
65
- let object = singletonRegistry.get(symbol);
66
- if (object instanceof WeakRef) {
67
- object = object.deref();
68
- if (object) return object;
69
- singletonRegistry.delete(symbol);
70
- } else {
71
- return object; // strong
72
- }
73
- }
74
-
75
- if (constructor) {
76
- const object = new WeakRef(constructor() as any);
77
- singletonRegistry.set(symbol, object);
78
- return object.deref();
79
- }
80
-
81
- return undefined;
82
- }
@@ -1,36 +0,0 @@
1
- import { ensureGlobalObject } from './globalObject';
2
-
3
- const symbolRegistry = ensureGlobalObject(`@@idlebox/global-symbol`, () => {
4
- return {} as Record<string, Record<string, symbol>>;
5
- });
6
-
7
- /**
8
- * Get a symbol singleton, if not exists, create it
9
- *
10
- * this is very like Symbol.for, but not real global symbol
11
- * @public
12
- */
13
- export function createSymbol(category: string, name: string): symbol {
14
- if (symbolRegistry[category] && symbolRegistry[category][name]) {
15
- return symbolRegistry[category][name];
16
- } else {
17
- if (!symbolRegistry[category]) {
18
- symbolRegistry[category] = {};
19
- }
20
- symbolRegistry[category][name] = Symbol(name);
21
- return symbolRegistry[category][name];
22
- }
23
- }
24
-
25
- /**
26
- * Delete a symbol from window/global object
27
- * @public
28
- */
29
- export function deleteSymbol(category: string, name: string) {
30
- if (symbolRegistry[category] && symbolRegistry[category][name]) {
31
- delete symbolRegistry[category][name];
32
- if (Object.keys(symbolRegistry[category]).length === 0) {
33
- delete symbolRegistry[category];
34
- }
35
- }
36
- }