@powfix/core-js 0.9.22

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 (101) hide show
  1. package/browser.ts +73 -0
  2. package/dist/browser.d.ts +32 -0
  3. package/dist/browser.js +58 -0
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.js +20 -0
  6. package/dist/src/constants/COORDINATE.d.ts +7 -0
  7. package/dist/src/constants/COORDINATE.js +10 -0
  8. package/dist/src/constants/DISTANCE.d.ts +13 -0
  9. package/dist/src/constants/DISTANCE.js +18 -0
  10. package/dist/src/constants/DURATION.d.ts +16 -0
  11. package/dist/src/constants/DURATION.js +21 -0
  12. package/dist/src/interfaces/Coordinate.d.ts +8 -0
  13. package/dist/src/interfaces/Coordinate.js +2 -0
  14. package/dist/src/interfaces/Point2.d.ts +4 -0
  15. package/dist/src/interfaces/Point2.js +2 -0
  16. package/dist/src/interfaces/Point3.d.ts +4 -0
  17. package/dist/src/interfaces/Point3.js +2 -0
  18. package/dist/src/scripts/base64-polyfill.d.ts +1 -0
  19. package/dist/src/scripts/base64-polyfill.js +14 -0
  20. package/dist/src/services/Session.d.ts +27 -0
  21. package/dist/src/services/Session.js +140 -0
  22. package/dist/src/services/browser.d.ts +2 -0
  23. package/dist/src/services/browser.js +20 -0
  24. package/dist/src/services/index.d.ts +2 -0
  25. package/dist/src/services/index.js +19 -0
  26. package/dist/src/services/redis/RedisClient.d.ts +20 -0
  27. package/dist/src/services/redis/RedisClient.js +70 -0
  28. package/dist/src/services/redis/RedisPublisher.d.ts +13 -0
  29. package/dist/src/services/redis/RedisPublisher.js +61 -0
  30. package/dist/src/services/redis/RedisSubscriber.d.ts +11 -0
  31. package/dist/src/services/redis/RedisSubscriber.js +68 -0
  32. package/dist/src/services/redis/index.d.ts +3 -0
  33. package/dist/src/services/redis/index.js +20 -0
  34. package/dist/src/services/time/TimeService.d.ts +64 -0
  35. package/dist/src/services/time/TimeService.js +235 -0
  36. package/dist/src/services/time/index.d.ts +1 -0
  37. package/dist/src/services/time/index.js +17 -0
  38. package/dist/src/types/IntRage.d.ts +3 -0
  39. package/dist/src/types/IntRage.js +2 -0
  40. package/dist/src/utils/ArrayUtils.d.ts +10 -0
  41. package/dist/src/utils/ArrayUtils.js +20 -0
  42. package/dist/src/utils/BooleanUtils.d.ts +1 -0
  43. package/dist/src/utils/BooleanUtils.js +9 -0
  44. package/dist/src/utils/CoordinateUtils.d.ts +8 -0
  45. package/dist/src/utils/CoordinateUtils.js +42 -0
  46. package/dist/src/utils/DateUtils.d.ts +12 -0
  47. package/dist/src/utils/DateUtils.js +212 -0
  48. package/dist/src/utils/JuminNumberUtils.d.ts +4 -0
  49. package/dist/src/utils/JuminNumberUtils.js +50 -0
  50. package/dist/src/utils/NumberUtils.d.ts +4 -0
  51. package/dist/src/utils/NumberUtils.js +25 -0
  52. package/dist/src/utils/Point3Utils.d.ts +4 -0
  53. package/dist/src/utils/Point3Utils.js +12 -0
  54. package/dist/src/utils/RandomUtils.d.ts +8 -0
  55. package/dist/src/utils/RandomUtils.js +64 -0
  56. package/dist/src/utils/Sequencer.d.ts +39 -0
  57. package/dist/src/utils/Sequencer.js +148 -0
  58. package/dist/src/utils/StringUtils.d.ts +5 -0
  59. package/dist/src/utils/StringUtils.js +37 -0
  60. package/dist/src/utils/UuidUtils.d.ts +14 -0
  61. package/dist/src/utils/UuidUtils.js +49 -0
  62. package/dist/src/utils/Validator.d.ts +48 -0
  63. package/dist/src/utils/Validator.js +118 -0
  64. package/dist/src/utils/global/between.d.ts +1 -0
  65. package/dist/src/utils/global/between.js +7 -0
  66. package/dist/src/utils/global/sleep.d.ts +1 -0
  67. package/dist/src/utils/global/sleep.js +21 -0
  68. package/index.ts +5 -0
  69. package/package.json +42 -0
  70. package/src/constants/COORDINATE.ts +9 -0
  71. package/src/constants/DISTANCE.ts +15 -0
  72. package/src/constants/DURATION.ts +18 -0
  73. package/src/interfaces/Coordinate.ts +9 -0
  74. package/src/interfaces/Point2.ts +4 -0
  75. package/src/interfaces/Point3.ts +5 -0
  76. package/src/scripts/base64-polyfill.ts +13 -0
  77. package/src/services/Session.ts +141 -0
  78. package/src/services/browser.ts +5 -0
  79. package/src/services/index.ts +4 -0
  80. package/src/services/redis/RedisClient.ts +79 -0
  81. package/src/services/redis/RedisPublisher.ts +48 -0
  82. package/src/services/redis/RedisSubscriber.ts +49 -0
  83. package/src/services/redis/index.ts +4 -0
  84. package/src/services/time/TimeService.ts +304 -0
  85. package/src/services/time/index.ts +1 -0
  86. package/src/types/IntRage.ts +5 -0
  87. package/src/utils/ArrayUtils.ts +25 -0
  88. package/src/utils/BooleanUtils.ts +4 -0
  89. package/src/utils/CoordinateUtils.ts +50 -0
  90. package/src/utils/DateUtils.ts +213 -0
  91. package/src/utils/JuminNumberUtils.ts +47 -0
  92. package/src/utils/NumberUtils.ts +23 -0
  93. package/src/utils/Point3Utils.ts +11 -0
  94. package/src/utils/RandomUtils.ts +62 -0
  95. package/src/utils/Sequencer.ts +178 -0
  96. package/src/utils/StringUtils.ts +43 -0
  97. package/src/utils/UuidUtils.ts +46 -0
  98. package/src/utils/Validator.ts +162 -0
  99. package/src/utils/global/between.ts +3 -0
  100. package/src/utils/global/sleep.ts +6 -0
  101. package/tsconfig.json +103 -0
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UuidUtils = void 0;
4
+ const uuid = require('uuid');
5
+ function binaryToString(binary) {
6
+ return Buffer.from(binary).toString('hex');
7
+ }
8
+ class UuidUtils {
9
+ static v4() {
10
+ return uuid.v4();
11
+ }
12
+ static format(uuid) {
13
+ if (uuid.length === 32) {
14
+ // Without dash: ca23c587d7f84c76be59f53bbc9f91f8
15
+ return `${uuid.substring(0, 8)}-${uuid.substring(8, 12)}-${uuid.substring(12, 16)}-${uuid.substring(16, 20)}-${uuid.substring(20, 32)}`.toUpperCase();
16
+ }
17
+ else if (uuid.length === 36) {
18
+ // With dash: ca23c587-d7f8-4c76-be59-f53bbc9f91f8
19
+ return uuid.toUpperCase();
20
+ }
21
+ else {
22
+ // Unexpected uuid
23
+ console.warn('Unexpected uuid length', uuid);
24
+ return uuid;
25
+ }
26
+ }
27
+ /**
28
+ * (UUID: Buffer) to (UUID: string)
29
+ * @param binary UUID
30
+ * @returns {string|null} When binary not exists return null
31
+ */
32
+ static toString(binary) {
33
+ if (!binary)
34
+ return null;
35
+ return UuidUtils.format(binaryToString(binary));
36
+ }
37
+ /** (UUID: string) to (UUID: Buffer) */
38
+ static toBuffer(uuid) {
39
+ return Buffer.from(uuid.replace(/-/g, ''), 'hex');
40
+ }
41
+ static isValidUUID(uuid) {
42
+ if (!uuid)
43
+ return false;
44
+ if (typeof uuid !== 'string')
45
+ return false;
46
+ return RegExp(/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/i).test(uuid);
47
+ }
48
+ }
49
+ exports.UuidUtils = UuidUtils;
@@ -0,0 +1,48 @@
1
+ export declare class Validator {
2
+ static validate(value: string | null | undefined, options: Validator.Options): {
3
+ result: boolean;
4
+ validations: Validator.VALIDATION[];
5
+ passes: Validator.VALIDATION[];
6
+ errors: Validator.VALIDATION[];
7
+ };
8
+ }
9
+ export declare namespace Validator {
10
+ enum VALIDATION {
11
+ MIN_LENGTH = "MIN_LENGTH",
12
+ MAX_LENGTH = "MAX_LENGTH",
13
+ SPACE_MIN_COUNT = "SPACE_MIN_COUNT",
14
+ SPACE_MAX_COUNT = "SPACE_MAX_COUNT",
15
+ NUMBER_MIN_COUNT = "NUMBER_MIN_COUNT",
16
+ NUMBER_MAX_COUNT = "NUMBER_MAX_COUNT",
17
+ ALPHABET_MIN_COUNT = "ALPHABET_MIN_COUNT",
18
+ ALPHABET_MAX_COUNT = "ALPHABET_MAX_COUNT",
19
+ ALPHABET_LOWER_CASE_MIN_COUNT = "ALPHABET_LOWER_CASE_MIN_COUNT",
20
+ ALPHABET_LOWER_CASE_MAX_COUNT = "ALPHABET_LOWER_CASE_MAX_COUNT",
21
+ ALPHABET_UPPER_CASE_MIN_COUNT = "ALPHABET_UPPER_CASE_MIN_COUNT",
22
+ ALPHABET_UPPER_CASE_MAX_COUNT = "ALPHABET_UPPER_CASE_MAX_COUNT",
23
+ SPECIAL_CHARACTER_MIN_COUNT = "SPECIAL_CHARACTER_MIN_COUNT",
24
+ SPECIAL_CHARACTER_MAX_COUNT = "SPECIAL_CHARACTER_MAX_COUNT",
25
+ STARTS_WITH_ALPHABET = "STARTS_WITH_ALPHABET",
26
+ STARTS_WITH_NUMBER = "STARTS_WITH_NUMBER",
27
+ STARTS_WITH_SPECIAL_CHARACTER = "STARTS_WITH_SPECIAL_CHARACTER"
28
+ }
29
+ interface Options {
30
+ minLength?: number;
31
+ maxLength?: number;
32
+ spaceMinCount?: number;
33
+ spaceMaxCount?: number;
34
+ numberMinCount?: number;
35
+ numberMaxCount?: number;
36
+ alphabetMinCount?: number;
37
+ alphabetMaxCount?: number;
38
+ alphabetLowerCaseMinCount?: number;
39
+ alphabetLowerCaseMaxCount?: number;
40
+ alphabetUpperCaseMinCount?: number;
41
+ alphabetUpperCaseMaxCount?: number;
42
+ specialCharacterMinCount?: number;
43
+ specialCharacterMaxCount?: number;
44
+ startsWithNumber?: boolean;
45
+ startsWithAlphabet?: boolean;
46
+ startsWithSpecialCharacter?: boolean;
47
+ }
48
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Validator = void 0;
4
+ class Validator {
5
+ static validate(value, options) {
6
+ value = value || '';
7
+ const validations = [];
8
+ const errors = [];
9
+ const { length } = value;
10
+ const spaceCount = (value.match(/\s/g) || []).length;
11
+ const numberCount = (value.match(/\d/g) || []).length;
12
+ const alphabetCount = (value.match(/[A-Za-z]/g) || []).length;
13
+ const alphabetLowerCaseCount = (value.match(/[a-z]/g) || []).length;
14
+ const alphabetUpperCaseCount = (value.match(/[A-Z]/g) || []).length;
15
+ const specialCount = (value.match(/[~`!@#$%^&*()\-+={[}\]|\\:;"'<,>.?/]/g) || []).length;
16
+ const startsWithNumber = /^\d/.test(value);
17
+ const startsWithAlphabet = /^[A-Za-z]/.test(value);
18
+ const startsWithSpecialCharacter = /^[~`!@#$%^&*()\-+={[}\]|\\:;"'<,>.?/]/.test(value);
19
+ // 최소 길이
20
+ if (options.minLength !== undefined && options.minLength > -1) {
21
+ validations.push(Validator.VALIDATION.MIN_LENGTH);
22
+ if (length < options.minLength) {
23
+ errors.push(Validator.VALIDATION.MIN_LENGTH);
24
+ }
25
+ }
26
+ // 최대 길이
27
+ if (options.maxLength !== undefined && options.maxLength > -1) {
28
+ validations.push(Validator.VALIDATION.MAX_LENGTH);
29
+ if (length > options.maxLength) {
30
+ errors.push(Validator.VALIDATION.MAX_LENGTH);
31
+ }
32
+ }
33
+ const validateMin = (option, value, validation) => {
34
+ if (option !== undefined && option > -1) {
35
+ validations.push(validation);
36
+ if (value < option) {
37
+ errors.push(validation);
38
+ }
39
+ }
40
+ };
41
+ const validateMax = (option, value, validation) => {
42
+ if (option !== undefined && option > -1) {
43
+ validations.push(validation);
44
+ if (value > option) {
45
+ errors.push(validation);
46
+ }
47
+ }
48
+ };
49
+ // 공백 개수
50
+ validateMin(options.spaceMinCount, spaceCount, Validator.VALIDATION.SPACE_MIN_COUNT);
51
+ validateMax(options.spaceMaxCount, spaceCount, Validator.VALIDATION.SPACE_MAX_COUNT);
52
+ // 숫자 개수
53
+ validateMin(options.numberMinCount, numberCount, Validator.VALIDATION.NUMBER_MIN_COUNT);
54
+ validateMax(options.numberMaxCount, numberCount, Validator.VALIDATION.NUMBER_MAX_COUNT);
55
+ // 알파벳 개수
56
+ validateMin(options.alphabetMinCount, alphabetCount, Validator.VALIDATION.ALPHABET_MIN_COUNT);
57
+ validateMax(options.alphabetMaxCount, alphabetCount, Validator.VALIDATION.ALPHABET_MAX_COUNT);
58
+ // 알파벳(소문자) 개수
59
+ validateMin(options.alphabetLowerCaseMinCount, alphabetLowerCaseCount, Validator.VALIDATION.ALPHABET_LOWER_CASE_MIN_COUNT);
60
+ validateMax(options.alphabetLowerCaseMaxCount, alphabetLowerCaseCount, Validator.VALIDATION.ALPHABET_LOWER_CASE_MAX_COUNT);
61
+ // 알파벳(대문자) 개수
62
+ validateMin(options.alphabetUpperCaseMinCount, alphabetUpperCaseCount, Validator.VALIDATION.ALPHABET_UPPER_CASE_MIN_COUNT);
63
+ validateMax(options.alphabetUpperCaseMaxCount, alphabetUpperCaseCount, Validator.VALIDATION.ALPHABET_UPPER_CASE_MAX_COUNT);
64
+ // 특수문자 개수
65
+ validateMin(options.specialCharacterMinCount, specialCount, Validator.VALIDATION.SPECIAL_CHARACTER_MIN_COUNT);
66
+ validateMax(options.specialCharacterMaxCount, specialCount, Validator.VALIDATION.SPECIAL_CHARACTER_MAX_COUNT);
67
+ // 숫자로 시작
68
+ if (options.startsWithNumber) {
69
+ validations.push(Validator.VALIDATION.STARTS_WITH_NUMBER);
70
+ if (!startsWithNumber) {
71
+ errors.push(Validator.VALIDATION.STARTS_WITH_NUMBER);
72
+ }
73
+ }
74
+ // 영문으로 시작
75
+ if (options.startsWithAlphabet) {
76
+ validations.push(Validator.VALIDATION.STARTS_WITH_ALPHABET);
77
+ if (!startsWithAlphabet) {
78
+ errors.push(Validator.VALIDATION.STARTS_WITH_ALPHABET);
79
+ }
80
+ }
81
+ // 특수문자로 시작
82
+ if (options.startsWithSpecialCharacter) {
83
+ validations.push(Validator.VALIDATION.STARTS_WITH_SPECIAL_CHARACTER);
84
+ if (!startsWithSpecialCharacter) {
85
+ errors.push(Validator.VALIDATION.STARTS_WITH_SPECIAL_CHARACTER);
86
+ }
87
+ }
88
+ return {
89
+ result: errors.length === 0,
90
+ validations,
91
+ passes: validations.filter(e => !errors.includes(e)),
92
+ errors,
93
+ };
94
+ }
95
+ }
96
+ exports.Validator = Validator;
97
+ (function (Validator) {
98
+ let VALIDATION;
99
+ (function (VALIDATION) {
100
+ VALIDATION["MIN_LENGTH"] = "MIN_LENGTH";
101
+ VALIDATION["MAX_LENGTH"] = "MAX_LENGTH";
102
+ VALIDATION["SPACE_MIN_COUNT"] = "SPACE_MIN_COUNT";
103
+ VALIDATION["SPACE_MAX_COUNT"] = "SPACE_MAX_COUNT";
104
+ VALIDATION["NUMBER_MIN_COUNT"] = "NUMBER_MIN_COUNT";
105
+ VALIDATION["NUMBER_MAX_COUNT"] = "NUMBER_MAX_COUNT";
106
+ VALIDATION["ALPHABET_MIN_COUNT"] = "ALPHABET_MIN_COUNT";
107
+ VALIDATION["ALPHABET_MAX_COUNT"] = "ALPHABET_MAX_COUNT";
108
+ VALIDATION["ALPHABET_LOWER_CASE_MIN_COUNT"] = "ALPHABET_LOWER_CASE_MIN_COUNT";
109
+ VALIDATION["ALPHABET_LOWER_CASE_MAX_COUNT"] = "ALPHABET_LOWER_CASE_MAX_COUNT";
110
+ VALIDATION["ALPHABET_UPPER_CASE_MIN_COUNT"] = "ALPHABET_UPPER_CASE_MIN_COUNT";
111
+ VALIDATION["ALPHABET_UPPER_CASE_MAX_COUNT"] = "ALPHABET_UPPER_CASE_MAX_COUNT";
112
+ VALIDATION["SPECIAL_CHARACTER_MIN_COUNT"] = "SPECIAL_CHARACTER_MIN_COUNT";
113
+ VALIDATION["SPECIAL_CHARACTER_MAX_COUNT"] = "SPECIAL_CHARACTER_MAX_COUNT";
114
+ VALIDATION["STARTS_WITH_ALPHABET"] = "STARTS_WITH_ALPHABET";
115
+ VALIDATION["STARTS_WITH_NUMBER"] = "STARTS_WITH_NUMBER";
116
+ VALIDATION["STARTS_WITH_SPECIAL_CHARACTER"] = "STARTS_WITH_SPECIAL_CHARACTER";
117
+ })(VALIDATION = Validator.VALIDATION || (Validator.VALIDATION = {}));
118
+ })(Validator || (exports.Validator = Validator = {}));
@@ -0,0 +1 @@
1
+ export declare const between: (value: number, from: number, to: number) => boolean;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.between = void 0;
4
+ const between = (value, from, to) => {
5
+ return value >= from && value <= to;
6
+ };
7
+ exports.between = between;
@@ -0,0 +1 @@
1
+ export declare const sleep: (delayInMilliseconds: number, callback?: ((...args: any) => void) | undefined, ...args: any) => Promise<any[]>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.sleep = void 0;
13
+ const sleep = (delayInMilliseconds, callback, ...args) => __awaiter(void 0, void 0, void 0, function* () {
14
+ return new Promise((resolve) => {
15
+ setTimeout(() => {
16
+ callback === null || callback === void 0 ? void 0 : callback(...args);
17
+ resolve(args);
18
+ }, delayInMilliseconds);
19
+ });
20
+ });
21
+ exports.sleep = sleep;
package/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // Extend browser imports & exports
2
+ export * from './browser';
3
+
4
+ // services
5
+ export * from './src/services';
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@powfix/core-js",
3
+ "version": "0.9.22",
4
+ "description": "core package",
5
+ "author": "Kwon Kyung-Min <powfix@gmail.com>",
6
+ "private": false,
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/powfix/core-js"
10
+ },
11
+ "keywords": [
12
+ "javascript",
13
+ "core",
14
+ "util"
15
+ ],
16
+ "homepage": "https://github.com/powfix/core-js",
17
+ "license": "MIT",
18
+ "main": "dist/index.js",
19
+ "browser": "dist/browser.js",
20
+ "scripts": {
21
+ "clean": "rm -rf dist",
22
+ "build": "yarn clean && tsc -p . && git add dist"
23
+ },
24
+ "dependencies": {
25
+ "base-64": "^1.0.0",
26
+ "jwt-decode": "^4.0.0",
27
+ "redis": "^4.6.11",
28
+ "uuid": "9.0.1"
29
+ },
30
+ "devDependencies": {
31
+ "@types/base-64": "1.0.2",
32
+ "@types/node": "20.9.5",
33
+ "@types/uuid": "9.0.7",
34
+ "axios": "^1.7.2",
35
+ "moment": "^2.30.1",
36
+ "typescript": "5.1.6"
37
+ },
38
+ "peerDependencies": {
39
+ "axios": ">=1.7.0",
40
+ "moment": ">=2.0.0"
41
+ }
42
+ }
@@ -0,0 +1,9 @@
1
+ export class COORDINATE {
2
+ public static LATITUDE_MIN_LENGTH = 1;
3
+ public static LATITUDE_MAX_LENGTH = 10;
4
+
5
+ public static LONGITUDE_MIN_LENGTH = 1;
6
+ public static LONGITUDE_MAX_LENGTH = 11;
7
+ }
8
+
9
+ export namespace COORDINATE {}
@@ -0,0 +1,15 @@
1
+ export class DISTANCE {
2
+
3
+ }
4
+
5
+ export namespace DISTANCE {
6
+ export enum UNIT {
7
+ FEET = 'FEET',
8
+ KILOMETERS = 'KILOMETERS',
9
+ MILLIMETERS = 'MILLIMETERS',
10
+ CENTIMETERS = 'CENTIMETERS',
11
+ METERS = 'METERS',
12
+ MILES = 'MILES',
13
+ YARDS = 'YARDS',
14
+ }
15
+ }
@@ -0,0 +1,18 @@
1
+ export class DURATION {
2
+
3
+ }
4
+
5
+ export namespace DURATION {
6
+ export enum UNIT {
7
+ NANOSECONDS = 'NANOSECONDS',
8
+ MICROSECONDS = 'MICROSECONDS',
9
+ MILLISECONDS = 'MILLISECONDS',
10
+ SECONDS = 'SECONDS',
11
+ MINUTES = 'MINUTES',
12
+ HOURS = 'HOURS',
13
+ DAYS = 'DAYS',
14
+ YEARS = 'YEARS',
15
+ DECADES = 'DECADES',
16
+ CENTURIES = 'CENTURIES',
17
+ }
18
+ }
@@ -0,0 +1,9 @@
1
+ export interface Coordinate {
2
+ latitude: number;
3
+ longitude: number;
4
+ }
5
+
6
+ export interface CoordinateM {
7
+ lat: number;
8
+ lon: number;
9
+ }
@@ -0,0 +1,4 @@
1
+ export interface Point2 {
2
+ x: number;
3
+ y: number;
4
+ }
@@ -0,0 +1,5 @@
1
+ import {Point2} from "./Point2";
2
+
3
+ export interface Point3 extends Point2 {
4
+ z: number;
5
+ }
@@ -0,0 +1,13 @@
1
+ import {decode, encode} from 'base-64';
2
+
3
+ export const base64Polyfill = () => {
4
+ if (!global.btoa) {
5
+ global.btoa = encode;
6
+ }
7
+
8
+ if (!global.atob) {
9
+ global.atob = decode;
10
+ }
11
+
12
+ console.log('base64-polyfill initialized', Date.now());
13
+ };
@@ -0,0 +1,141 @@
1
+ import {jwtDecode, JwtPayload} from "jwt-decode";
2
+ import {AxiosInstance} from "axios";
3
+ import moment from "moment";
4
+
5
+ export interface SessionOptions {
6
+ api: AxiosInstance;
7
+ storageProvider: StorageProvider;
8
+ }
9
+
10
+ export interface StorageProvider {
11
+ key?: () => string;
12
+ set: (key: string, value: string) => Promise<void> | void;
13
+ get: (key: string) => Promise<string | null> | (string | null);
14
+ remove: (key: string) => Promise<void> | void;
15
+ clear?: () => Promise<void> | void;
16
+ }
17
+
18
+ const logWithTs = (...p: any) => {
19
+ console.log(Date.now(), ...p);
20
+ }
21
+
22
+ export class Session {
23
+ // Service parameters
24
+ protected api: AxiosInstance;
25
+ protected storageProvider: StorageProvider;
26
+
27
+ // Emitter
28
+ // private emitter = new EventEmitter({});
29
+ // public on = this.emitter.on;
30
+ // public off = this.emitter.off;
31
+ // private emit = this.emitter.emit;
32
+
33
+ public constructor(options: SessionOptions) {
34
+ // Init service parameters
35
+ console.log('Session initialized', Date.now(), options.api);
36
+ this.api = options.api;
37
+ this.storageProvider = options.storageProvider;
38
+ }
39
+
40
+ private getKey(): string {
41
+ try {
42
+ if (this.storageProvider.key) {
43
+ return this.storageProvider.key();
44
+ }
45
+ } catch (e) {
46
+ console.error(e);
47
+ }
48
+
49
+ return Session.STORAGE_KEY.SESSION_AUTHORIZATION;
50
+ }
51
+
52
+ public async hasAuthorization(): Promise<boolean> {
53
+ return !!(await this.getAuthorization());
54
+ }
55
+
56
+ public async getAuthorization(): Promise<string | null> {
57
+ return this.storageProvider.get(this.getKey());
58
+ }
59
+
60
+ public async setAuthorization(authorization?: string | null): Promise<string | null> {
61
+ if (authorization === null) {
62
+ await this.removeAuthorization();
63
+ return null;
64
+ }
65
+
66
+ let nextAuthorization = await (async () => {
67
+ if (authorization === undefined) {
68
+ return await this.getAuthorization();
69
+ }
70
+ return authorization;
71
+ })();
72
+
73
+ if (!nextAuthorization) {
74
+ console.log('nextAuthorization is null or undefined');
75
+ return null;
76
+ }
77
+
78
+ try {
79
+ // Replace Bearer prefix
80
+ nextAuthorization = nextAuthorization.replace(/^Bearer\s+/, '');
81
+
82
+ const decoded = jwtDecode(nextAuthorization) as JwtPayload & {uuid: string};
83
+ if (!decoded) {
84
+ console.warn('JWT decode failed');
85
+ return null;
86
+ }
87
+
88
+ console.log('Session:JWT decoded');
89
+ (() => {
90
+ console.log(' - User', decoded.uuid);
91
+
92
+ console.log(' - IAT', ...(() => {
93
+ if (!decoded.iat) {return [decoded.iat];}
94
+ const iat = moment.unix(decoded.iat);
95
+ if (!iat.isValid()) {return [decoded.iat];}
96
+ return [decoded.iat, iat.format(), iat.diff(Date.now(), 'days'), 'days left'];
97
+ })());
98
+
99
+ console.log(' - NBF', ...(() => {
100
+ if (!decoded.nbf) {return [decoded.nbf];}
101
+ const nbf = moment.unix(decoded.nbf);
102
+ if (!nbf.isValid()) {return [decoded.nbf];}
103
+ return [decoded.nbf, nbf.format(), nbf.diff(Date.now(), 'days'), 'days left'];
104
+ })());
105
+
106
+ console.log(' - EXP', ...(() => {
107
+ if (!decoded.exp) {return [decoded.exp];}
108
+ const exp = moment.unix(decoded.exp);
109
+ if (!exp.isValid()) {return [decoded.exp];}
110
+ return [decoded.exp, exp.format(), exp.diff(Date.now(), 'days'), 'days left'];
111
+ })());
112
+ })();
113
+
114
+ // AsyncStorage 에 토큰 저장
115
+ await this.storageProvider.set(this.getKey(), nextAuthorization);
116
+
117
+ // API Instance header 설정
118
+ this.api.defaults.headers.common.Authorization = `Bearer ${nextAuthorization}`;
119
+
120
+ // Return
121
+ return nextAuthorization;
122
+ } catch (e) {
123
+ console.error(e);
124
+ }
125
+ return null;
126
+ }
127
+
128
+ public async removeAuthorization() {
129
+ // API Instance header 에서 토큰 제거
130
+ delete this.api.defaults.headers.common.Authorization;
131
+
132
+ // 스토리지에서 authorization 제거
133
+ await this.storageProvider.remove(this.getKey());
134
+ }
135
+ }
136
+
137
+ export namespace Session {
138
+ export enum STORAGE_KEY {
139
+ SESSION_AUTHORIZATION = 'SESSION_AUTHORIZATION',
140
+ }
141
+ }
@@ -0,0 +1,5 @@
1
+ // Directories
2
+ export * from './time';
3
+
4
+ // Files
5
+ export * from './Session';
@@ -0,0 +1,4 @@
1
+ export * from './browser';
2
+
3
+ // Directories
4
+ export * from './redis';
@@ -0,0 +1,79 @@
1
+ import redis, {
2
+ createClient,
3
+ RedisClientType,
4
+ RedisDefaultModules,
5
+ RedisFunctions,
6
+ RedisModules,
7
+ RedisScripts
8
+ } from 'redis';
9
+
10
+ const LOG_PREFIX = 'RedisClient';
11
+
12
+ export class RedisClient {
13
+ private readonly options: RedisClient.RedisClientOptions = {};
14
+ private status: RedisClient.Status = RedisClient.Status.STOPPED;
15
+ public readonly client: RedisClientType<RedisDefaultModules & RedisModules, RedisFunctions, RedisScripts>;
16
+
17
+ public constructor(options?: RedisClient.RedisClientOptions) {
18
+ console.log(Date.now(), LOG_PREFIX, 'initialized');
19
+
20
+ if (options) {
21
+ this.options = options;
22
+ }
23
+
24
+ if (options?.redisOptions) {
25
+ this.client = createClient(options.redisOptions);
26
+ } else {
27
+ this.client = createClient({});
28
+ }
29
+ }
30
+
31
+ public async start(): Promise<RedisClient.Status> {
32
+ console.log(LOG_PREFIX, 'trying to start');
33
+
34
+ // register event callback
35
+ this.client.on('connect', this.handleOnConnect);
36
+ this.client.on('error', this.handleOnError);
37
+
38
+ await this.client.connect();
39
+
40
+ this.status = RedisClient.Status.RUNNING;
41
+ console.log(LOG_PREFIX, 'now started');
42
+ return this.status;
43
+ }
44
+
45
+ public async stop(): Promise<RedisClient.Status> {
46
+ console.log(LOG_PREFIX, 'trying to stop');
47
+
48
+ // unregister event callback
49
+ this.client.off('connect', this.handleOnConnect);
50
+ this.client.off('error', this.handleOnError);
51
+
52
+ if (this.client.isOpen) {
53
+ await this.client.disconnect();
54
+ }
55
+
56
+ this.status = RedisClient.Status.STOPPED;
57
+ console.log(LOG_PREFIX, 'now stopped');
58
+ return this.status;
59
+ }
60
+
61
+ private handleOnConnect() {
62
+ console.log(LOG_PREFIX, 'connected');
63
+ }
64
+
65
+ private handleOnError(error: Error) {
66
+ console.error(LOG_PREFIX, error);
67
+ }
68
+ }
69
+
70
+ export namespace RedisClient {
71
+ export enum Status {
72
+ RUNNING,
73
+ STOPPED,
74
+ }
75
+
76
+ export interface RedisClientOptions {
77
+ redisOptions?: redis.RedisClientOptions;
78
+ }
79
+ }
@@ -0,0 +1,48 @@
1
+ import {RedisClient} from "./RedisClient";
2
+
3
+ export class RedisPublisher extends RedisClient {
4
+ private logging: RedisPublisher.LOGGING = 'length';
5
+
6
+ public constructor(options?: RedisClient.RedisClientOptions) {
7
+ super(options);
8
+ console.log(Date.now(), "RedisPublisher", 'initialized');
9
+ }
10
+
11
+ public async start(): Promise<RedisClient.Status> {
12
+ return await super.start();
13
+ }
14
+
15
+ public async stop(): Promise<RedisClient.Status> {
16
+ return await super.stop();
17
+ }
18
+
19
+ public setLogging(logging: RedisPublisher.LOGGING) {
20
+ this.logging = logging;
21
+ }
22
+
23
+ public getLogging(): RedisPublisher.LOGGING {
24
+ return this.logging;
25
+ }
26
+
27
+ // Make public method
28
+ public publish = async (channel: string, data: string | object) => {
29
+ const stringifyData = typeof data !== 'string' ? JSON.stringify(data) : data;
30
+
31
+ switch (this.logging) {
32
+ case "none": {break;}
33
+ case "length": {
34
+ console.log(Date.now(), 'Server ---> Redis', channel, stringifyData.length);
35
+ break;
36
+ }
37
+ case "data": {
38
+ console.log(Date.now(), 'Server ---> Redis', channel, stringifyData);
39
+ break;
40
+ }
41
+ }
42
+ await this.client.publish(channel, stringifyData);
43
+ }
44
+ }
45
+
46
+ export namespace RedisPublisher {
47
+ export type LOGGING = 'none' | 'length' | 'data';
48
+ }