@sendbird/uikit-utils 2.4.0 → 2.4.2

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 (79) hide show
  1. package/README.md +1 -1
  2. package/lib/commonjs/hooks/index.js +3 -30
  3. package/lib/commonjs/hooks/index.js.map +1 -1
  4. package/lib/commonjs/hooks/react-native.js +2 -11
  5. package/lib/commonjs/hooks/react-native.js.map +1 -1
  6. package/lib/commonjs/index.js +36 -155
  7. package/lib/commonjs/index.js.map +1 -1
  8. package/lib/commonjs/sendbird/attrs.js +8 -11
  9. package/lib/commonjs/sendbird/attrs.js.map +1 -1
  10. package/lib/commonjs/sendbird/channel.js +0 -16
  11. package/lib/commonjs/sendbird/channel.js.map +1 -1
  12. package/lib/commonjs/sendbird/message.js +5 -36
  13. package/lib/commonjs/sendbird/message.js.map +1 -1
  14. package/lib/commonjs/sendbird/user.js +0 -2
  15. package/lib/commonjs/sendbird/user.js.map +1 -1
  16. package/lib/commonjs/shared/arrayToMap.js +0 -6
  17. package/lib/commonjs/shared/arrayToMap.js.map +1 -1
  18. package/lib/commonjs/shared/bufferedRequest.js +5 -26
  19. package/lib/commonjs/shared/bufferedRequest.js.map +1 -1
  20. package/lib/commonjs/shared/file.js +208 -0
  21. package/lib/commonjs/shared/file.js.map +1 -0
  22. package/lib/commonjs/shared/index.js +12 -49
  23. package/lib/commonjs/shared/index.js.map +1 -1
  24. package/lib/commonjs/shared/logger.js +3 -22
  25. package/lib/commonjs/shared/logger.js.map +1 -1
  26. package/lib/commonjs/shared/regex.js +3 -55
  27. package/lib/commonjs/shared/regex.js.map +1 -1
  28. package/lib/commonjs/ui-format/common.js +6 -18
  29. package/lib/commonjs/ui-format/common.js.map +1 -1
  30. package/lib/commonjs/ui-format/groupChannel.js +0 -15
  31. package/lib/commonjs/ui-format/groupChannel.js.map +1 -1
  32. package/lib/commonjs/ui-format/openChannel.js +0 -4
  33. package/lib/commonjs/ui-format/openChannel.js.map +1 -1
  34. package/lib/module/hooks/index.js +3 -7
  35. package/lib/module/hooks/index.js.map +1 -1
  36. package/lib/module/hooks/react-native.js +2 -2
  37. package/lib/module/hooks/react-native.js.map +1 -1
  38. package/lib/module/index.js +3 -3
  39. package/lib/module/index.js.map +1 -1
  40. package/lib/module/sendbird/attrs.js +6 -9
  41. package/lib/module/sendbird/attrs.js.map +1 -1
  42. package/lib/module/sendbird/channel.js +0 -1
  43. package/lib/module/sendbird/channel.js.map +1 -1
  44. package/lib/module/sendbird/message.js +4 -18
  45. package/lib/module/sendbird/message.js.map +1 -1
  46. package/lib/module/sendbird/user.js.map +1 -1
  47. package/lib/module/shared/arrayToMap.js +0 -4
  48. package/lib/module/shared/arrayToMap.js.map +1 -1
  49. package/lib/module/shared/bufferedRequest.js +5 -24
  50. package/lib/module/shared/bufferedRequest.js.map +1 -1
  51. package/lib/module/shared/file.js +187 -0
  52. package/lib/module/shared/file.js.map +1 -0
  53. package/lib/module/shared/index.js +12 -39
  54. package/lib/module/shared/index.js.map +1 -1
  55. package/lib/module/shared/logger.js +3 -21
  56. package/lib/module/shared/logger.js.map +1 -1
  57. package/lib/module/shared/regex.js +3 -35
  58. package/lib/module/shared/regex.js.map +1 -1
  59. package/lib/module/ui-format/common.js +6 -9
  60. package/lib/module/ui-format/common.js.map +1 -1
  61. package/lib/module/ui-format/groupChannel.js +0 -7
  62. package/lib/module/ui-format/groupChannel.js.map +1 -1
  63. package/lib/module/ui-format/openChannel.js.map +1 -1
  64. package/lib/typescript/src/index.d.ts +3 -3
  65. package/lib/typescript/src/shared/file.d.ts +68 -0
  66. package/lib/typescript/src/shared/index.d.ts +10 -16
  67. package/lib/typescript/src/shared/regex.d.ts +0 -6
  68. package/package.json +11 -7
  69. package/src/index.ts +3 -19
  70. package/src/sendbird/message.ts +1 -1
  71. package/src/shared/file.ts +193 -0
  72. package/src/shared/index.ts +10 -37
  73. package/src/shared/regex.ts +0 -34
  74. package/lib/commonjs/shared/pubsub.js +0 -54
  75. package/lib/commonjs/shared/pubsub.js.map +0 -1
  76. package/lib/module/shared/pubsub.js +0 -45
  77. package/lib/module/shared/pubsub.js.map +0 -1
  78. package/lib/typescript/src/shared/pubsub.d.ts +0 -8
  79. package/src/shared/pubsub.ts +0 -42
@@ -11,22 +11,16 @@ export declare function replace(str: string, start: number, end: number, text: s
11
11
  * */
12
12
  export declare function conditionChaining<T, V>(conditions: T[], values: V[]): V;
13
13
  /**
14
- * Calculates the downscale size.
15
- * */
16
- type Size = {
17
- width: number;
18
- height: number;
19
- };
20
- export declare function getDownscaleSize(origin: Size, resizing: Partial<Size>): {
21
- width: number;
22
- height: number;
23
- };
24
- export declare function isImage(filePath: string, mimeType?: string): boolean;
25
- export declare function shouldCompressImage(filePath: string, compressionEnabled?: boolean): boolean;
26
- /**
27
- * Returns the picked data from object.
28
- * */
14
+ * Returns a new object with only the specified keys from the input object.
15
+ *
16
+ * @param {Object} obj - The input object to pick keys from.
17
+ * @param {Array<string>} keys - An array of keys to pick from the input object.
18
+ * @returns {Object} - A new object containing only the specified keys from the input object.
19
+ * @example
20
+ * ```ts
21
+ * pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }
22
+ * ```
23
+ */
29
24
  export declare function pick<T extends {
30
25
  [key: string]: unknown;
31
26
  }, Keys extends keyof T>(obj: T, keys: Keys[]): { [key in Keys]: T[key]; };
32
- export {};
@@ -12,9 +12,3 @@ export declare const replaceWithRegex: <T>(text: string, regex: RegExp, replacer
12
12
  keyPrefix: string;
13
13
  }) => T, keyPrefix: string) => (string | T)[];
14
14
  export declare const replaceUrlAsComponents: <T>(originText: string, replacer: (url: string) => T, strict?: boolean) => (string | T)[];
15
- export declare const imageExtRegex: RegExp;
16
- export declare const audioExtRegex: RegExp;
17
- export declare const videoExtRegex: RegExp;
18
- export declare const getFileType: (extOrType: string) => "video" | "audio" | "image" | "file";
19
- export declare function getFileExtension(filePath: string): string;
20
- export declare function normalizeFileName(fileName: string, extension: string): string;
package/package.json CHANGED
@@ -1,7 +1,15 @@
1
1
  {
2
2
  "name": "@sendbird/uikit-utils",
3
- "version": "2.4.0",
4
- "description": "UIKit utilities",
3
+ "version": "2.4.2",
4
+ "description": "A collection of utility functions and constants for building chat UI components with Sendbird UIKit.",
5
+ "keywords": [
6
+ "sendbird",
7
+ "uikit",
8
+ "chat",
9
+ "UI components",
10
+ "utility functions",
11
+ "constants"
12
+ ],
5
13
  "main": "lib/commonjs/index",
6
14
  "module": "lib/module/index",
7
15
  "types": "lib/typescript/src/index.d.ts",
@@ -18,10 +26,6 @@
18
26
  "build": "bob build",
19
27
  "clean": "del lib"
20
28
  },
21
- "keywords": [
22
- "react",
23
- "sendbird"
24
- ],
25
29
  "repository": {
26
30
  "type": "git",
27
31
  "url": "https://github.com/sendbird/sendbird-uikit-react-native.git",
@@ -77,5 +81,5 @@
77
81
  "readmeFile": "./README.md",
78
82
  "displayName": "@sendbird/uikit-utils"
79
83
  },
80
- "gitHead": "05ec076e3a2433089586870c9a7e7bf7639b06be"
84
+ "gitHead": "ae9e60edc60cdd4f6e9b0e4019e84584e807bc2c"
81
85
  }
package/src/index.ts CHANGED
@@ -1,24 +1,8 @@
1
1
  export { Logger } from './shared/logger';
2
2
  export { default as arrayToMap, arrayToMapWithGetter } from './shared/arrayToMap';
3
- export { createPubSub } from './shared/pubsub';
4
- export {
5
- urlRegexStrict,
6
- urlRegexRough,
7
- newLineRegex,
8
- audioExtRegex,
9
- videoExtRegex,
10
- imageExtRegex,
11
- getFileType,
12
- getFileExtension,
13
- replaceUrlAsComponents,
14
- normalizeFileName,
15
- emailRegex,
16
- phoneRegex,
17
- replaceWithRegex,
18
- createMentionTemplateRegex,
19
- } from './shared/regex';
20
- export { BufferedRequest } from './shared/bufferedRequest';
21
-
3
+ export * from './shared/regex';
4
+ export * from './shared/bufferedRequest';
5
+ export * from './shared/file';
22
6
  export * from './shared';
23
7
 
24
8
  export * from './hooks';
@@ -1,4 +1,4 @@
1
- import { getFileExtension, getFileType } from '../shared/regex';
1
+ import { getFileExtension, getFileType } from '../shared/file';
2
2
  import type {
3
3
  SendbirdBaseChannel,
4
4
  SendbirdBaseMessage,
@@ -0,0 +1,193 @@
1
+ const EXTENSION_MIME_MAP = {
2
+ // Image
3
+ 'jpeg': 'image/jpeg',
4
+ 'jpg': 'image/jpeg',
5
+ 'png': 'image/png',
6
+ 'gif': 'image/gif',
7
+ 'webp': 'image/webp',
8
+ 'svg': 'image/svg+xml',
9
+
10
+ // Video
11
+ '3gp': 'video/3gpp',
12
+ 'mp4': 'video/mp4',
13
+ 'mpeg': 'video/mpeg',
14
+ 'ogv': 'video/ogg',
15
+ 'video/quicktime': 'mov',
16
+ 'webm': 'video/webm',
17
+ 'avi': 'video/x-msvideo',
18
+
19
+ // Audio
20
+ 'aac': 'audio/aac',
21
+ 'mid': 'audio/midi',
22
+ 'mp3': 'audio/mpeg',
23
+ 'ogg': 'audio/ogg',
24
+ 'wav': 'audio/wav',
25
+ 'weba': 'audio/webm',
26
+
27
+ // Files
28
+ 'txt': 'text/plain',
29
+ 'pdf': 'application/pdf',
30
+ 'doc': 'application/msword',
31
+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
32
+ 'xls': 'application/vnd.ms-excel',
33
+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
34
+ 'ppt': 'application/vnd.ms-powerpoint',
35
+ 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
36
+ 'zip': 'application/zip',
37
+ 'json': 'application/json',
38
+ 'gzip': 'application/x-gzip',
39
+ } as Record<string, string>;
40
+
41
+ export const imageExtRegex = /jpeg|jpg|png|webp|gif/i;
42
+ export const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav/i;
43
+ export const videoExtRegex = /mov|vod|mp4|avi/i;
44
+ export const getFileType = (extOrType: string) => {
45
+ if (extOrType.indexOf('/') > -1) {
46
+ const type = extOrType.split('/')[0];
47
+ if (type === 'video') return 'video';
48
+ if (type === 'audio') return 'audio';
49
+ if (type === 'image') return 'image';
50
+ return 'file';
51
+ }
52
+
53
+ if (extOrType.match(imageExtRegex)) return 'image';
54
+ if (extOrType.match(audioExtRegex)) return 'audio';
55
+ if (extOrType.match(videoExtRegex)) return 'video';
56
+ return 'file';
57
+ };
58
+
59
+ /**
60
+ * Calculates the downscaled size of an image while preserving its aspect ratio.
61
+ *
62
+ * @param {Object} origin - The original size object with `width` and `height` properties.
63
+ * @param {Object} resizing - The resizing object with optional `width` and `height` properties.
64
+ * @returns {Object} - A new size object with the downscaled `width` and `height` properties.
65
+ * @example
66
+ * ```ts
67
+ * getDownscaleSize({ width: 1200, height: 800 }, { width: 600 }); // returns { width: 600, height: 400 }
68
+ * ```
69
+ */
70
+ type Size = { width: number; height: number };
71
+ export function getDownscaleSize(origin: Size, resizing: Partial<Size>) {
72
+ let ratio: number;
73
+
74
+ const maxWidth = resizing.width || origin.width,
75
+ maxHeight = resizing.height || origin.height;
76
+
77
+ if (origin.width <= maxWidth && origin.height <= maxHeight) {
78
+ ratio = 1;
79
+ } else if (origin.width > maxWidth && origin.height <= maxHeight) {
80
+ ratio = maxWidth / origin.width;
81
+ } else if (origin.width <= maxWidth && origin.height > maxHeight) {
82
+ ratio = maxHeight / origin.height;
83
+ } else {
84
+ ratio = Math.min(maxWidth / origin.width, maxHeight / origin.height);
85
+ }
86
+
87
+ return { width: origin.width * ratio, height: origin.height * ratio };
88
+ }
89
+
90
+ /**
91
+ * Normalize a file name by ensuring it has the given extension, if it doesn't already.
92
+ *
93
+ * @param {string} fileName - The file name to normalize.
94
+ * @param {string} extension - The desired extension, without a leading period.
95
+ * @returns {string} - The normalized file name, with the extension.
96
+ */
97
+ export function normalizeFileName(fileName: string, extension: string) {
98
+ if (!extension) return fileName;
99
+
100
+ // .extension
101
+ let _extension = extension.toLowerCase();
102
+ if (_extension.indexOf('.') !== 0) {
103
+ _extension = '.' + _extension;
104
+ }
105
+
106
+ // filename.extension | filename
107
+ const _filename = fileName.toLowerCase();
108
+ const hasExtension = _filename.lastIndexOf(_extension) === _filename.length - _extension.length;
109
+ if (!hasExtension) {
110
+ // filename.extension
111
+ return fileName + _extension;
112
+ } else {
113
+ // filename.extension
114
+ return fileName;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Parses a MIME type string into its components.
120
+ *
121
+ * @param mimeType - The MIME type string to parse.
122
+ * @returns An object containing the type, subtype, and parameters of the MIME type.
123
+ */
124
+ type MimeType = { type: string; subtype: string; parameters: Record<string, string> };
125
+ export function parseMimeType(mimeType: string): MimeType {
126
+ const [fullType, ...parts] = mimeType.split(';');
127
+ const [type, subtype] = fullType.split('/');
128
+ const parameters: MimeType['parameters'] = {};
129
+
130
+ for (const part of parts) {
131
+ const [name, value] = part.trim().split('=');
132
+ parameters[name] = value;
133
+ }
134
+
135
+ return { type, subtype, parameters };
136
+ }
137
+
138
+ /**
139
+ * Returns the file extension based on the MIME type.
140
+ *
141
+ * @param {string | null | undefined} mimeType - The MIME type to look up.
142
+ * @returns {string} - The file extension for the given MIME type, or an empty string if no matching file extension was found.
143
+ */
144
+ export function getFileExtensionFromMime(mimeType?: string | null): string {
145
+ if (!mimeType) return '';
146
+ const MIME_EXTENSION_MAP = Object.entries(EXTENSION_MIME_MAP).reduce((acc, [key, value]) => {
147
+ acc[value] = key;
148
+ return acc;
149
+ }, {} as Record<string, string>);
150
+ return MIME_EXTENSION_MAP[mimeType.toLowerCase()] || '';
151
+ }
152
+
153
+ /**
154
+ * Returns the MIME type based on the file extension.
155
+ *
156
+ * @param {string | null | undefined} ext - The file extension to look up.
157
+ * @returns {string} - The MIME type for the given file extension, or an empty string if no matching MIME type was found.
158
+ */
159
+ export function getMimeFromFileExtension(ext?: string | null) {
160
+ if (!ext) return '';
161
+ return EXTENSION_MIME_MAP[ext.toLowerCase()] || '';
162
+ }
163
+
164
+ /**
165
+ * Returns the file extension of a file path.
166
+ *
167
+ * @param {string} filePath - The file path to extract the extension from.
168
+ * @returns {string} - The file extension, or an empty string if the file path does not have an extension.
169
+ */
170
+ export function getFileExtension(filePath: string) {
171
+ const pathWithoutParams = filePath.split('?')[0];
172
+
173
+ const idx = pathWithoutParams.lastIndexOf('.');
174
+ if (idx === -1) return '';
175
+
176
+ const result = pathWithoutParams.slice(idx - pathWithoutParams.length).toLowerCase();
177
+ if (result === '.') return '';
178
+ else return result;
179
+ }
180
+
181
+ export function getFileExtensionFromUri(uri: string) {
182
+ return fetch(uri).then((response) => response.headers.get('content-type'));
183
+ }
184
+
185
+ export function isImage(filePath: string, mimeType?: string) {
186
+ const type = getFileType(mimeType || getFileExtension(filePath));
187
+ return type === 'image';
188
+ }
189
+
190
+ export function shouldCompressImage(mime: string, compressionEnabled = true) {
191
+ const extension = getFileExtensionFromMime(mime);
192
+ return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);
193
+ }
@@ -1,5 +1,3 @@
1
- import { getFileExtension, getFileType } from './regex';
2
-
3
1
  /**
4
2
  * Converts a given string to a hashed string.
5
3
  * */
@@ -23,41 +21,16 @@ export function conditionChaining<T, V>(conditions: T[], values: V[]) {
23
21
  }
24
22
 
25
23
  /**
26
- * Calculates the downscale size.
27
- * */
28
- type Size = { width: number; height: number };
29
- export function getDownscaleSize(origin: Size, resizing: Partial<Size>) {
30
- let ratio;
31
-
32
- const maxWidth = resizing.width || origin.width,
33
- maxHeight = resizing.height || origin.height;
34
-
35
- if (origin.width <= maxWidth && origin.height <= maxHeight) {
36
- ratio = 1;
37
- } else if (origin.width > maxWidth && origin.height <= maxHeight) {
38
- ratio = maxWidth / origin.width;
39
- } else if (origin.width <= maxWidth && origin.height > maxHeight) {
40
- ratio = maxHeight / origin.height;
41
- } else {
42
- ratio = Math.max(maxWidth / origin.width, maxHeight / origin.height);
43
- }
44
-
45
- return { width: origin.width * ratio, height: origin.height * ratio };
46
- }
47
-
48
- export function isImage(filePath: string, mimeType?: string) {
49
- const type = getFileType(mimeType || getFileExtension(filePath));
50
- return type === 'image';
51
- }
52
-
53
- export function shouldCompressImage(filePath: string, compressionEnabled = true) {
54
- const extension = getFileExtension(filePath);
55
- return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);
56
- }
57
-
58
- /**
59
- * Returns the picked data from object.
60
- * */
24
+ * Returns a new object with only the specified keys from the input object.
25
+ *
26
+ * @param {Object} obj - The input object to pick keys from.
27
+ * @param {Array<string>} keys - An array of keys to pick from the input object.
28
+ * @returns {Object} - A new object containing only the specified keys from the input object.
29
+ * @example
30
+ * ```ts
31
+ * pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }
32
+ * ```
33
+ */
61
34
  export function pick<T extends { [key: string]: unknown }, Keys extends keyof T>(obj: T, keys: Keys[]) {
62
35
  return keys.reduce((pickedObj, key) => {
63
36
  pickedObj[key] = obj[key];
@@ -84,37 +84,3 @@ export const replaceUrlAsComponents = <T>(originText: string, replacer: (url: st
84
84
  });
85
85
  return items;
86
86
  };
87
-
88
- export const imageExtRegex = /jpeg|jpg|png|webp|gif/i;
89
- export const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav/i;
90
- export const videoExtRegex = /mov|vod|mp4|avi/i;
91
- export const getFileType = (extOrType: string) => {
92
- if (extOrType.indexOf('/') > -1) {
93
- const type = extOrType.split('/')[0];
94
- if (type === 'video') return 'video';
95
- if (type === 'audio') return 'audio';
96
- if (type === 'image') return 'image';
97
- return 'file';
98
- }
99
-
100
- if (extOrType.match(imageExtRegex)) return 'image';
101
- if (extOrType.match(audioExtRegex)) return 'audio';
102
- if (extOrType.match(videoExtRegex)) return 'video';
103
- return 'file';
104
- };
105
- export function getFileExtension(filePath: string) {
106
- const idx = filePath.lastIndexOf('.');
107
- if (idx === -1) return '';
108
- return filePath.slice(idx - filePath.length).toLowerCase();
109
- }
110
- export function normalizeFileName(fileName: string, extension: string) {
111
- if (fileName.indexOf(extension) > -1) {
112
- return fileName;
113
- } else {
114
- if (extension.indexOf('.') === 0) {
115
- return `${fileName}${extension}`;
116
- } else {
117
- return `${fileName}.${extension}`;
118
- }
119
- }
120
- }
@@ -1,54 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.createPubSub = void 0;
7
-
8
- const createPubSub = function () {
9
- let label = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pubsub';
10
- const eventPool = {};
11
-
12
- const getSubscribeListenerPool = event => {
13
- if (!eventPool[event]) eventPool[event] = {};
14
- return eventPool[event];
15
- };
16
-
17
- return {
18
- subscribe: function (event, listener) {
19
- let subscriber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
20
- const name = `${label}_${event}_${subscriber}`;
21
- const id = Symbol(name);
22
- const subscribeListenerPool = getSubscribeListenerPool(event);
23
- subscribeListenerPool[id] = listener;
24
- return () => {
25
- delete getSubscribeListenerPool(event)[id];
26
- };
27
- },
28
- publish: function (event) {
29
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
30
- args[_key - 1] = arguments[_key];
31
- }
32
-
33
- const subscribeListenerPool = getSubscribeListenerPool(event);
34
- const ids = Object.getOwnPropertySymbols(subscribeListenerPool);
35
- setTimeout(() => {
36
- ids.forEach(id => {
37
- const listener = subscribeListenerPool[id];
38
-
39
- try {
40
- listener(...args);
41
- } catch (err) {
42
- if (listener.onError) {
43
- err.stack += `\npubsub error: ${id.description}`;
44
- listener.onError(err);
45
- }
46
- }
47
- });
48
- }, 0);
49
- }
50
- };
51
- };
52
-
53
- exports.createPubSub = createPubSub;
54
- //# sourceMappingURL=pubsub.js.map
@@ -1 +0,0 @@
1
- {"version":3,"names":["createPubSub","label","eventPool","getSubscribeListenerPool","event","subscribe","listener","subscriber","name","id","Symbol","subscribeListenerPool","publish","args","ids","Object","getOwnPropertySymbols","setTimeout","forEach","err","onError","stack","description"],"sources":["pubsub.ts"],"sourcesContent":["export type SubscribeListener = ((...args: unknown[]) => void) & { onError?: (error: unknown) => void };\nexport type SubscribeListenerPool = Record<symbol, SubscribeListener>;\n\nexport const createPubSub = (label = 'pubsub') => {\n const eventPool: Record<string, SubscribeListenerPool> = {};\n\n const getSubscribeListenerPool = (event: string) => {\n if (!eventPool[event]) eventPool[event] = {};\n return eventPool[event];\n };\n\n return {\n subscribe: (event: string, listener: SubscribeListener, subscriber = '') => {\n const name = `${label}_${event}_${subscriber}`;\n const id = Symbol(name);\n\n const subscribeListenerPool = getSubscribeListenerPool(event);\n subscribeListenerPool[id] = listener;\n\n return () => {\n delete getSubscribeListenerPool(event)[id];\n };\n },\n publish: (event: string, ...args: unknown[]) => {\n const subscribeListenerPool = getSubscribeListenerPool(event);\n const ids = Object.getOwnPropertySymbols(subscribeListenerPool);\n setTimeout(() => {\n ids.forEach((id) => {\n const listener = subscribeListenerPool[id];\n try {\n listener(...args);\n } catch (err: unknown) {\n if (listener.onError) {\n (err as Error).stack += `\\npubsub error: ${id.description}`;\n listener.onError(err);\n }\n }\n });\n }, 0);\n },\n };\n};\n"],"mappings":";;;;;;;AAGO,MAAMA,YAAY,GAAG,YAAsB;EAAA,IAArBC,KAAqB,uEAAb,QAAa;EAChD,MAAMC,SAAgD,GAAG,EAAzD;;EAEA,MAAMC,wBAAwB,GAAIC,KAAD,IAAmB;IAClD,IAAI,CAACF,SAAS,CAACE,KAAD,CAAd,EAAuBF,SAAS,CAACE,KAAD,CAAT,GAAmB,EAAnB;IACvB,OAAOF,SAAS,CAACE,KAAD,CAAhB;EACD,CAHD;;EAKA,OAAO;IACLC,SAAS,EAAE,UAACD,KAAD,EAAgBE,QAAhB,EAAiE;MAAA,IAApBC,UAAoB,uEAAP,EAAO;MAC1E,MAAMC,IAAI,GAAI,GAAEP,KAAM,IAAGG,KAAM,IAAGG,UAAW,EAA7C;MACA,MAAME,EAAE,GAAGC,MAAM,CAACF,IAAD,CAAjB;MAEA,MAAMG,qBAAqB,GAAGR,wBAAwB,CAACC,KAAD,CAAtD;MACAO,qBAAqB,CAACF,EAAD,CAArB,GAA4BH,QAA5B;MAEA,OAAO,MAAM;QACX,OAAOH,wBAAwB,CAACC,KAAD,CAAxB,CAAgCK,EAAhC,CAAP;MACD,CAFD;IAGD,CAXI;IAYLG,OAAO,EAAE,UAACR,KAAD,EAAuC;MAAA,kCAApBS,IAAoB;QAApBA,IAAoB;MAAA;;MAC9C,MAAMF,qBAAqB,GAAGR,wBAAwB,CAACC,KAAD,CAAtD;MACA,MAAMU,GAAG,GAAGC,MAAM,CAACC,qBAAP,CAA6BL,qBAA7B,CAAZ;MACAM,UAAU,CAAC,MAAM;QACfH,GAAG,CAACI,OAAJ,CAAaT,EAAD,IAAQ;UAClB,MAAMH,QAAQ,GAAGK,qBAAqB,CAACF,EAAD,CAAtC;;UACA,IAAI;YACFH,QAAQ,CAAC,GAAGO,IAAJ,CAAR;UACD,CAFD,CAEE,OAAOM,GAAP,EAAqB;YACrB,IAAIb,QAAQ,CAACc,OAAb,EAAsB;cACnBD,GAAD,CAAeE,KAAf,IAAyB,mBAAkBZ,EAAE,CAACa,WAAY,EAA1D;cACAhB,QAAQ,CAACc,OAAT,CAAiBD,GAAjB;YACD;UACF;QACF,CAVD;MAWD,CAZS,EAYP,CAZO,CAAV;IAaD;EA5BI,CAAP;AA8BD,CAtCM"}
@@ -1,45 +0,0 @@
1
- export const createPubSub = function () {
2
- let label = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pubsub';
3
- const eventPool = {};
4
-
5
- const getSubscribeListenerPool = event => {
6
- if (!eventPool[event]) eventPool[event] = {};
7
- return eventPool[event];
8
- };
9
-
10
- return {
11
- subscribe: function (event, listener) {
12
- let subscriber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
13
- const name = `${label}_${event}_${subscriber}`;
14
- const id = Symbol(name);
15
- const subscribeListenerPool = getSubscribeListenerPool(event);
16
- subscribeListenerPool[id] = listener;
17
- return () => {
18
- delete getSubscribeListenerPool(event)[id];
19
- };
20
- },
21
- publish: function (event) {
22
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
23
- args[_key - 1] = arguments[_key];
24
- }
25
-
26
- const subscribeListenerPool = getSubscribeListenerPool(event);
27
- const ids = Object.getOwnPropertySymbols(subscribeListenerPool);
28
- setTimeout(() => {
29
- ids.forEach(id => {
30
- const listener = subscribeListenerPool[id];
31
-
32
- try {
33
- listener(...args);
34
- } catch (err) {
35
- if (listener.onError) {
36
- err.stack += `\npubsub error: ${id.description}`;
37
- listener.onError(err);
38
- }
39
- }
40
- });
41
- }, 0);
42
- }
43
- };
44
- };
45
- //# sourceMappingURL=pubsub.js.map
@@ -1 +0,0 @@
1
- {"version":3,"names":["createPubSub","label","eventPool","getSubscribeListenerPool","event","subscribe","listener","subscriber","name","id","Symbol","subscribeListenerPool","publish","args","ids","Object","getOwnPropertySymbols","setTimeout","forEach","err","onError","stack","description"],"sources":["pubsub.ts"],"sourcesContent":["export type SubscribeListener = ((...args: unknown[]) => void) & { onError?: (error: unknown) => void };\nexport type SubscribeListenerPool = Record<symbol, SubscribeListener>;\n\nexport const createPubSub = (label = 'pubsub') => {\n const eventPool: Record<string, SubscribeListenerPool> = {};\n\n const getSubscribeListenerPool = (event: string) => {\n if (!eventPool[event]) eventPool[event] = {};\n return eventPool[event];\n };\n\n return {\n subscribe: (event: string, listener: SubscribeListener, subscriber = '') => {\n const name = `${label}_${event}_${subscriber}`;\n const id = Symbol(name);\n\n const subscribeListenerPool = getSubscribeListenerPool(event);\n subscribeListenerPool[id] = listener;\n\n return () => {\n delete getSubscribeListenerPool(event)[id];\n };\n },\n publish: (event: string, ...args: unknown[]) => {\n const subscribeListenerPool = getSubscribeListenerPool(event);\n const ids = Object.getOwnPropertySymbols(subscribeListenerPool);\n setTimeout(() => {\n ids.forEach((id) => {\n const listener = subscribeListenerPool[id];\n try {\n listener(...args);\n } catch (err: unknown) {\n if (listener.onError) {\n (err as Error).stack += `\\npubsub error: ${id.description}`;\n listener.onError(err);\n }\n }\n });\n }, 0);\n },\n };\n};\n"],"mappings":"AAGA,OAAO,MAAMA,YAAY,GAAG,YAAsB;EAAA,IAArBC,KAAqB,uEAAb,QAAa;EAChD,MAAMC,SAAgD,GAAG,EAAzD;;EAEA,MAAMC,wBAAwB,GAAIC,KAAD,IAAmB;IAClD,IAAI,CAACF,SAAS,CAACE,KAAD,CAAd,EAAuBF,SAAS,CAACE,KAAD,CAAT,GAAmB,EAAnB;IACvB,OAAOF,SAAS,CAACE,KAAD,CAAhB;EACD,CAHD;;EAKA,OAAO;IACLC,SAAS,EAAE,UAACD,KAAD,EAAgBE,QAAhB,EAAiE;MAAA,IAApBC,UAAoB,uEAAP,EAAO;MAC1E,MAAMC,IAAI,GAAI,GAAEP,KAAM,IAAGG,KAAM,IAAGG,UAAW,EAA7C;MACA,MAAME,EAAE,GAAGC,MAAM,CAACF,IAAD,CAAjB;MAEA,MAAMG,qBAAqB,GAAGR,wBAAwB,CAACC,KAAD,CAAtD;MACAO,qBAAqB,CAACF,EAAD,CAArB,GAA4BH,QAA5B;MAEA,OAAO,MAAM;QACX,OAAOH,wBAAwB,CAACC,KAAD,CAAxB,CAAgCK,EAAhC,CAAP;MACD,CAFD;IAGD,CAXI;IAYLG,OAAO,EAAE,UAACR,KAAD,EAAuC;MAAA,kCAApBS,IAAoB;QAApBA,IAAoB;MAAA;;MAC9C,MAAMF,qBAAqB,GAAGR,wBAAwB,CAACC,KAAD,CAAtD;MACA,MAAMU,GAAG,GAAGC,MAAM,CAACC,qBAAP,CAA6BL,qBAA7B,CAAZ;MACAM,UAAU,CAAC,MAAM;QACfH,GAAG,CAACI,OAAJ,CAAaT,EAAD,IAAQ;UAClB,MAAMH,QAAQ,GAAGK,qBAAqB,CAACF,EAAD,CAAtC;;UACA,IAAI;YACFH,QAAQ,CAAC,GAAGO,IAAJ,CAAR;UACD,CAFD,CAEE,OAAOM,GAAP,EAAqB;YACrB,IAAIb,QAAQ,CAACc,OAAb,EAAsB;cACnBD,GAAD,CAAeE,KAAf,IAAyB,mBAAkBZ,EAAE,CAACa,WAAY,EAA1D;cACAhB,QAAQ,CAACc,OAAT,CAAiBD,GAAjB;YACD;UACF;QACF,CAVD;MAWD,CAZS,EAYP,CAZO,CAAV;IAaD;EA5BI,CAAP;AA8BD,CAtCM"}
@@ -1,8 +0,0 @@
1
- export type SubscribeListener = ((...args: unknown[]) => void) & {
2
- onError?: (error: unknown) => void;
3
- };
4
- export type SubscribeListenerPool = Record<symbol, SubscribeListener>;
5
- export declare const createPubSub: (label?: string) => {
6
- subscribe: (event: string, listener: SubscribeListener, subscriber?: string) => () => void;
7
- publish: (event: string, ...args: unknown[]) => void;
8
- };
@@ -1,42 +0,0 @@
1
- export type SubscribeListener = ((...args: unknown[]) => void) & { onError?: (error: unknown) => void };
2
- export type SubscribeListenerPool = Record<symbol, SubscribeListener>;
3
-
4
- export const createPubSub = (label = 'pubsub') => {
5
- const eventPool: Record<string, SubscribeListenerPool> = {};
6
-
7
- const getSubscribeListenerPool = (event: string) => {
8
- if (!eventPool[event]) eventPool[event] = {};
9
- return eventPool[event];
10
- };
11
-
12
- return {
13
- subscribe: (event: string, listener: SubscribeListener, subscriber = '') => {
14
- const name = `${label}_${event}_${subscriber}`;
15
- const id = Symbol(name);
16
-
17
- const subscribeListenerPool = getSubscribeListenerPool(event);
18
- subscribeListenerPool[id] = listener;
19
-
20
- return () => {
21
- delete getSubscribeListenerPool(event)[id];
22
- };
23
- },
24
- publish: (event: string, ...args: unknown[]) => {
25
- const subscribeListenerPool = getSubscribeListenerPool(event);
26
- const ids = Object.getOwnPropertySymbols(subscribeListenerPool);
27
- setTimeout(() => {
28
- ids.forEach((id) => {
29
- const listener = subscribeListenerPool[id];
30
- try {
31
- listener(...args);
32
- } catch (err: unknown) {
33
- if (listener.onError) {
34
- (err as Error).stack += `\npubsub error: ${id.description}`;
35
- listener.onError(err);
36
- }
37
- }
38
- });
39
- }, 0);
40
- },
41
- };
42
- };