@ddunigma/node 2.1.1 → 2.2.0
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.
- package/README.md +101 -11
- package/dist/DduStream-KO75MEEM.js +2 -0
- package/dist/chunk-CZMUPXSK.js +5 -0
- package/dist/index.cjs +8 -0
- package/dist/index.d.cts +813 -0
- package/dist/index.d.ts +813 -0
- package/dist/index.js +5 -0
- package/package.json +33 -15
- package/dist/cjs/base/BaseDdu.d.ts +0 -53
- package/dist/cjs/base/BaseDdu.js +0 -29
- package/dist/cjs/base/index.d.ts +0 -1
- package/dist/cjs/base/index.js +0 -5
- package/dist/cjs/charSets/index.d.ts +0 -18
- package/dist/cjs/charSets/index.js +0 -4385
- package/dist/cjs/encoders/Ddu64.d.ts +0 -302
- package/dist/cjs/encoders/Ddu64.js +0 -1308
- package/dist/cjs/encoders/index.d.ts +0 -1
- package/dist/cjs/encoders/index.js +0 -5
- package/dist/cjs/index.d.ts +0 -5
- package/dist/cjs/index.js +0 -16
- package/dist/cjs/package.json +0 -3
- package/dist/cjs/types/DduDefaultTypes.d.ts +0 -3
- package/dist/cjs/types/DduDefaultTypes.js +0 -17
- package/dist/cjs/types/DduEnums.d.ts +0 -6
- package/dist/cjs/types/DduEnums.js +0 -10
- package/dist/cjs/types/DduInterface.d.ts +0 -91
- package/dist/cjs/types/DduInterface.js +0 -2
- package/dist/cjs/types/index.d.ts +0 -3
- package/dist/cjs/types/index.js +0 -19
- package/dist/cjs/utils/CharsetBuilder.d.ts +0 -129
- package/dist/cjs/utils/CharsetBuilder.js +0 -246
- package/dist/cjs/utils/DduPipeline.d.ts +0 -114
- package/dist/cjs/utils/DduPipeline.js +0 -229
- package/dist/cjs/utils/DduStream.d.ts +0 -64
- package/dist/cjs/utils/DduStream.js +0 -221
- package/dist/cjs/utils/crypto.d.ts +0 -30
- package/dist/cjs/utils/crypto.js +0 -84
- package/dist/cjs/utils/index.d.ts +0 -3
- package/dist/cjs/utils/index.js +0 -12
- package/dist/mjs/base/BaseDdu.d.ts +0 -53
- package/dist/mjs/base/BaseDdu.js +0 -23
- package/dist/mjs/base/index.d.ts +0 -1
- package/dist/mjs/base/index.js +0 -1
- package/dist/mjs/charSets/index.d.ts +0 -18
- package/dist/mjs/charSets/index.js +0 -4380
- package/dist/mjs/encoders/Ddu64.d.ts +0 -302
- package/dist/mjs/encoders/Ddu64.js +0 -1343
- package/dist/mjs/encoders/index.d.ts +0 -1
- package/dist/mjs/encoders/index.js +0 -1
- package/dist/mjs/index.d.ts +0 -5
- package/dist/mjs/index.js +0 -4
- package/dist/mjs/package.json +0 -3
- package/dist/mjs/types/DduDefaultTypes.d.ts +0 -3
- package/dist/mjs/types/DduDefaultTypes.js +0 -14
- package/dist/mjs/types/DduEnums.d.ts +0 -6
- package/dist/mjs/types/DduEnums.js +0 -7
- package/dist/mjs/types/DduInterface.d.ts +0 -91
- package/dist/mjs/types/DduInterface.js +0 -1
- package/dist/mjs/types/index.d.ts +0 -3
- package/dist/mjs/types/index.js +0 -3
- package/dist/mjs/utils/CharsetBuilder.d.ts +0 -129
- package/dist/mjs/utils/CharsetBuilder.js +0 -241
- package/dist/mjs/utils/DduPipeline.d.ts +0 -114
- package/dist/mjs/utils/DduPipeline.js +0 -223
- package/dist/mjs/utils/DduStream.d.ts +0 -64
- package/dist/mjs/utils/DduStream.js +0 -225
- package/dist/mjs/utils/crypto.d.ts +0 -30
- package/dist/mjs/utils/crypto.js +0 -78
- package/dist/mjs/utils/index.d.ts +0 -3
- package/dist/mjs/utils/index.js +0 -3
|
@@ -1,1308 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Ddu64 = void 0;
|
|
4
|
-
const zlib_1 = require("zlib");
|
|
5
|
-
const BaseDdu_1 = require("../base/BaseDdu");
|
|
6
|
-
const types_1 = require("../types");
|
|
7
|
-
const charSets_1 = require("../charSets");
|
|
8
|
-
const crypto_1 = require("../utils/crypto");
|
|
9
|
-
// ============================================================================
|
|
10
|
-
// 상수 정의
|
|
11
|
-
// ============================================================================
|
|
12
|
-
/** 바이트당 비트 수 */
|
|
13
|
-
const BYTE_BITS = 8;
|
|
14
|
-
/** 일반 정수 연산이 가능한 최대 비트 길이 (초과 시 BigInt 사용) */
|
|
15
|
-
const MAX_FAST_BITS = 16;
|
|
16
|
-
/** 바이트 마스크 (0xFF) */
|
|
17
|
-
const BYTE_MASK = 0xff;
|
|
18
|
-
/** 압축 데이터 식별 마커 */
|
|
19
|
-
const COMPRESS_MARKER = "ELYSIA";
|
|
20
|
-
/** 체크섬 마커 */
|
|
21
|
-
const CHECKSUM_MARKER = "CHK";
|
|
22
|
-
/** 암호화 마커 */
|
|
23
|
-
const ENCRYPT_MARKER = "ENC";
|
|
24
|
-
/** 기본 최대 디코딩 바이트 수 (64MB) */
|
|
25
|
-
const DEFAULT_MAX_DECODED_BYTES = 64 * 1024 * 1024;
|
|
26
|
-
/** 기본 최대 압축해제 바이트 수 (64MB) */
|
|
27
|
-
const DEFAULT_MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024;
|
|
28
|
-
/** CRC32 룩업 테이블 (바이트 단위 연산으로 비트 루프 대비 4~8배 빠름) */
|
|
29
|
-
const CRC32_TABLE = (() => {
|
|
30
|
-
const table = new Uint32Array(256);
|
|
31
|
-
for (let i = 0; i < 256; i++) {
|
|
32
|
-
let crc = i;
|
|
33
|
-
for (let j = 0; j < 8; j++) {
|
|
34
|
-
crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
|
|
35
|
-
}
|
|
36
|
-
table[i] = crc;
|
|
37
|
-
}
|
|
38
|
-
return table;
|
|
39
|
-
})();
|
|
40
|
-
/** URL-Safe 문자 매핑 */
|
|
41
|
-
const URL_SAFE_MAP = {
|
|
42
|
-
"+": "-",
|
|
43
|
-
"/": "_",
|
|
44
|
-
"=": ".",
|
|
45
|
-
};
|
|
46
|
-
/** URL-Safe 역방향 매핑 */
|
|
47
|
-
const URL_SAFE_REVERSE_MAP = {
|
|
48
|
-
"-": "+",
|
|
49
|
-
"_": "/",
|
|
50
|
-
".": "=",
|
|
51
|
-
};
|
|
52
|
-
/** 인코딩 진행률 단계별 퍼센트 */
|
|
53
|
-
const ENCODE_PROGRESS = {
|
|
54
|
-
START: 0,
|
|
55
|
-
ENCRYPT: 15,
|
|
56
|
-
CHECKSUM: 20,
|
|
57
|
-
COMPRESS: 40,
|
|
58
|
-
ENCODE: 50,
|
|
59
|
-
DONE: 100,
|
|
60
|
-
};
|
|
61
|
-
/** 디코딩 진행률 단계별 퍼센트 */
|
|
62
|
-
const DECODE_PROGRESS = {
|
|
63
|
-
START: 0,
|
|
64
|
-
DECODE: 20,
|
|
65
|
-
DECOMPRESS: 50,
|
|
66
|
-
CHECKSUM: 70,
|
|
67
|
-
DECRYPT: 85,
|
|
68
|
-
DONE: 100,
|
|
69
|
-
};
|
|
70
|
-
// ============================================================================
|
|
71
|
-
// Ddu64 클래스
|
|
72
|
-
// ============================================================================
|
|
73
|
-
/**
|
|
74
|
-
* 커스텀 charset을 사용하는 Base64 스타일 인코더
|
|
75
|
-
*
|
|
76
|
-
* @description
|
|
77
|
-
* 바이너리 데이터를 지정된 charset으로 인코딩/디코딩합니다.
|
|
78
|
-
* 2의 제곱수 charset과 가변 길이 charset 모두 지원하며,
|
|
79
|
-
* 압축 옵션을 통해 데이터 크기를 줄일 수 있습니다.
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* // 기본 사용
|
|
83
|
-
* const encoder = new Ddu64("우따야", "뭐");
|
|
84
|
-
* const encoded = encoder.encode("Hello");
|
|
85
|
-
* const decoded = encoder.decode(encoded);
|
|
86
|
-
*
|
|
87
|
-
* @example
|
|
88
|
-
* // 압축 사용
|
|
89
|
-
* const encoder = new Ddu64(undefined, undefined, { compress: true });
|
|
90
|
-
* const encoded = encoder.encode(longText);
|
|
91
|
-
*/
|
|
92
|
-
class Ddu64 extends BaseDdu_1.BaseDdu {
|
|
93
|
-
// --------------------------------------------------------------------------
|
|
94
|
-
// 생성자
|
|
95
|
-
// --------------------------------------------------------------------------
|
|
96
|
-
/**
|
|
97
|
-
* Ddu64 인코더 인스턴스를 생성합니다.
|
|
98
|
-
*
|
|
99
|
-
* @param dduChar - charset 문자열 또는 배열 (미지정 시 옵션의 dduSetSymbol 사용)
|
|
100
|
-
* @param paddingChar - 패딩 문자 (dduChar 지정 시 필수)
|
|
101
|
-
* @param dduOptions - 생성자 옵션
|
|
102
|
-
*
|
|
103
|
-
* @throws dduChar 지정 시 paddingChar가 없으면 에러
|
|
104
|
-
* @throws charset 문자 수가 부족하면 에러
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* // 커스텀 charset
|
|
108
|
-
* new Ddu64("우따야", "뭐");
|
|
109
|
-
*
|
|
110
|
-
* @example
|
|
111
|
-
* // 미리 정의된 charset
|
|
112
|
-
* new Ddu64(undefined, undefined, { dduSetSymbol: DduSetSymbol.ONECHARSET });
|
|
113
|
-
*/
|
|
114
|
-
constructor(dduChar, paddingChar, dduOptions) {
|
|
115
|
-
super();
|
|
116
|
-
/** 문자 → 인덱스 역방향 룩업 맵 */
|
|
117
|
-
this.dduBinaryLookup = new Map();
|
|
118
|
-
/** ASCII 문자 빠른 룩업 테이블 */
|
|
119
|
-
this.fastAsciiLookup = null;
|
|
120
|
-
/** ASCII 룩업 사용 여부 */
|
|
121
|
-
this.useAsciiLookup = false;
|
|
122
|
-
// throwOnError 우선, useBuildErrorReturn은 하위 호환
|
|
123
|
-
const shouldThrow = dduOptions?.throwOnError ?? dduOptions?.useBuildErrorReturn ?? false;
|
|
124
|
-
// charset 초기화
|
|
125
|
-
const initial = this.resolveInitialCharSet(dduChar, paddingChar, dduOptions, shouldThrow);
|
|
126
|
-
const normalized = this.normalizeCharSet(initial, shouldThrow, dduOptions);
|
|
127
|
-
this.dduChar = normalized.charSet;
|
|
128
|
-
this.paddingChar = normalized.padding;
|
|
129
|
-
this.charLength = normalized.charLength;
|
|
130
|
-
this.isPredefinedCharSet = normalized.isPredefined;
|
|
131
|
-
this.encoding = dduOptions?.encoding ?? this.defaultEncoding;
|
|
132
|
-
this.defaultCompress = dduOptions?.compress ?? false;
|
|
133
|
-
// 제한값 설정
|
|
134
|
-
this.defaultMaxDecodedBytes = this.normalizeLimit(dduOptions?.maxDecodedBytes, DEFAULT_MAX_DECODED_BYTES, shouldThrow, "maxDecodedBytes");
|
|
135
|
-
this.defaultMaxDecompressedBytes = this.normalizeLimit(dduOptions?.maxDecompressedBytes, DEFAULT_MAX_DECOMPRESSED_BYTES, shouldThrow, "maxDecompressedBytes");
|
|
136
|
-
// 비트 길이 계산
|
|
137
|
-
const dduLength = this.dduChar.length;
|
|
138
|
-
this.usePowerOfTwo =
|
|
139
|
-
dduLength > 0 && (dduLength & (dduLength - 1)) === 0;
|
|
140
|
-
const computedBitLength = this.getBitLength(dduLength);
|
|
141
|
-
this.bitLength = this.usePowerOfTwo
|
|
142
|
-
? this.getLargestPowerOfTwoExponent(dduLength)
|
|
143
|
-
: computedBitLength;
|
|
144
|
-
this.effectiveBitLength = this.usePowerOfTwo
|
|
145
|
-
? this.bitLength
|
|
146
|
-
: computedBitLength;
|
|
147
|
-
this.maxBinaryValue =
|
|
148
|
-
this.effectiveBitLength < 31
|
|
149
|
-
? 1 << this.effectiveBitLength
|
|
150
|
-
: Math.pow(2, this.effectiveBitLength);
|
|
151
|
-
// ASCII 룩업 테이블 초기화 (성능 최적화)
|
|
152
|
-
if (this.charLength === 1) {
|
|
153
|
-
let allAscii = true;
|
|
154
|
-
for (let i = 0; i < dduLength; i++) {
|
|
155
|
-
if (this.dduChar[i].charCodeAt(0) >= 128) {
|
|
156
|
-
allAscii = false;
|
|
157
|
-
break;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
if (allAscii) {
|
|
161
|
-
this.fastAsciiLookup = new Int16Array(128).fill(-1);
|
|
162
|
-
for (let i = 0; i < dduLength; i++) {
|
|
163
|
-
this.fastAsciiLookup[this.dduChar[i].charCodeAt(0)] = i;
|
|
164
|
-
}
|
|
165
|
-
this.useAsciiLookup = true;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
// 역방향 룩업 맵 생성
|
|
169
|
-
for (let i = 0; i < dduLength; i++) {
|
|
170
|
-
this.dduBinaryLookup.set(this.dduChar[i], i);
|
|
171
|
-
}
|
|
172
|
-
// 커스텀 charset 중복 조합 검증
|
|
173
|
-
if (this.charLength === 1 && !this.isPredefinedCharSet) {
|
|
174
|
-
this.validateCombinationDuplicates(this.dduChar, this.paddingChar, dduLength);
|
|
175
|
-
}
|
|
176
|
-
// 새로운 옵션들 초기화
|
|
177
|
-
const requestUrlSafe = dduOptions?.urlSafe ?? false;
|
|
178
|
-
this.urlSafe = requestUrlSafe
|
|
179
|
-
? this.isUrlSafeCompatible(this.dduChar, this.paddingChar, shouldThrow)
|
|
180
|
-
: false;
|
|
181
|
-
this.encryptionKeyHash = dduOptions?.encryptionKey
|
|
182
|
-
? (0, crypto_1.deriveKey)(dduOptions.encryptionKey)
|
|
183
|
-
: undefined;
|
|
184
|
-
this.defaultChecksum = dduOptions?.checksum ?? false;
|
|
185
|
-
this.defaultChunkSize = dduOptions?.chunkSize;
|
|
186
|
-
this.defaultChunkSeparator = dduOptions?.chunkSeparator ?? "\n";
|
|
187
|
-
this.defaultCompressionLevel = Math.min(9, Math.max(1, Math.floor(dduOptions?.compressionLevel ?? 6)));
|
|
188
|
-
}
|
|
189
|
-
// --------------------------------------------------------------------------
|
|
190
|
-
// 공개 메서드
|
|
191
|
-
// --------------------------------------------------------------------------
|
|
192
|
-
/**
|
|
193
|
-
* 입력 데이터를 인코딩합니다.
|
|
194
|
-
*
|
|
195
|
-
* @param input - 인코딩할 문자열 또는 Buffer
|
|
196
|
-
* @param options - 인코딩 옵션
|
|
197
|
-
* @param options.compress - 압축 사용 여부 (기본값: 생성자 설정)
|
|
198
|
-
* @param options.checksum - 체크섬 추가 여부
|
|
199
|
-
* @param options.chunkSize - 청크 분할 크기
|
|
200
|
-
* @param options.chunkSeparator - 청크 구분자
|
|
201
|
-
* @param options.onProgress - 진행률 콜백
|
|
202
|
-
* @returns 인코딩된 문자열
|
|
203
|
-
*
|
|
204
|
-
* @example
|
|
205
|
-
* encoder.encode("Hello World!");
|
|
206
|
-
* encoder.encode(buffer, { compress: true });
|
|
207
|
-
* encoder.encode(data, { checksum: true, chunkSize: 76 });
|
|
208
|
-
*/
|
|
209
|
-
encode(input, options) {
|
|
210
|
-
return this.encodeInternal(input, options).encoded;
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* 인코딩 핵심 로직. encode()와 getStats()가 공유합니다.
|
|
214
|
-
* 압축 크기 등 메타데이터도 함께 반환하여 중복 deflateSync 호출을 방지합니다.
|
|
215
|
-
*/
|
|
216
|
-
encodeInternal(input, options) {
|
|
217
|
-
const shouldCompress = options?.compress ?? this.defaultCompress;
|
|
218
|
-
const shouldChecksum = options?.checksum ?? this.defaultChecksum;
|
|
219
|
-
const chunkSize = options?.chunkSize ?? this.defaultChunkSize;
|
|
220
|
-
const chunkSeparator = options?.chunkSeparator ?? this.defaultChunkSeparator;
|
|
221
|
-
const onProgress = options?.onProgress;
|
|
222
|
-
let workingBuffer = typeof input === "string" ? Buffer.from(input, this.encoding) : input;
|
|
223
|
-
const totalBytes = workingBuffer.length;
|
|
224
|
-
// 진행률 콜백 호출 (시작)
|
|
225
|
-
if (onProgress) {
|
|
226
|
-
onProgress({ processedBytes: 0, totalBytes, percent: ENCODE_PROGRESS.START, stage: "start" });
|
|
227
|
-
}
|
|
228
|
-
// 암호화 처리
|
|
229
|
-
let isEncrypted = false;
|
|
230
|
-
if (this.encryptionKeyHash) {
|
|
231
|
-
workingBuffer = this.encryptData(workingBuffer);
|
|
232
|
-
isEncrypted = true;
|
|
233
|
-
if (onProgress) {
|
|
234
|
-
onProgress({ processedBytes: 0, totalBytes, percent: ENCODE_PROGRESS.ENCRYPT, stage: "encrypt" });
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
// 체크섬 계산
|
|
238
|
-
let checksum = "";
|
|
239
|
-
if (shouldChecksum) {
|
|
240
|
-
checksum = this.calculateCRC32(workingBuffer);
|
|
241
|
-
if (onProgress) {
|
|
242
|
-
onProgress({ processedBytes: 0, totalBytes, percent: ENCODE_PROGRESS.CHECKSUM, stage: "checksum" });
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
// 압축 처리
|
|
246
|
-
let useCompression = false;
|
|
247
|
-
let compressedSize;
|
|
248
|
-
if (shouldCompress) {
|
|
249
|
-
const level = options?.compressionLevel ?? this.defaultCompressionLevel;
|
|
250
|
-
const compressedBuffer = (0, zlib_1.deflateSync)(workingBuffer, { level: Math.min(9, Math.max(1, level)) });
|
|
251
|
-
compressedSize = compressedBuffer.length;
|
|
252
|
-
if (compressedBuffer.length < workingBuffer.length) {
|
|
253
|
-
workingBuffer = compressedBuffer;
|
|
254
|
-
useCompression = true;
|
|
255
|
-
}
|
|
256
|
-
if (onProgress) {
|
|
257
|
-
onProgress({ processedBytes: Math.floor(totalBytes * 0.4), totalBytes, percent: ENCODE_PROGRESS.COMPRESS, stage: "compress" });
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
// 인코딩 수행
|
|
261
|
-
if (onProgress) {
|
|
262
|
-
onProgress({ processedBytes: Math.floor(totalBytes * 0.5), totalBytes, percent: ENCODE_PROGRESS.ENCODE, stage: "encode" });
|
|
263
|
-
}
|
|
264
|
-
let result = this.effectiveBitLength <= MAX_FAST_BITS
|
|
265
|
-
? this.encodeFast(workingBuffer, useCompression, isEncrypted)
|
|
266
|
-
: this.encodeBigInt(workingBuffer, useCompression, isEncrypted);
|
|
267
|
-
// 체크섬 추가
|
|
268
|
-
if (shouldChecksum && checksum) {
|
|
269
|
-
result = result + CHECKSUM_MARKER + checksum;
|
|
270
|
-
}
|
|
271
|
-
// URL-Safe 변환
|
|
272
|
-
if (this.urlSafe) {
|
|
273
|
-
result = this.toUrlSafe(result);
|
|
274
|
-
}
|
|
275
|
-
// 청크 분할
|
|
276
|
-
if (chunkSize && chunkSize > 0) {
|
|
277
|
-
result = this.splitIntoChunks(result, chunkSize, chunkSeparator);
|
|
278
|
-
}
|
|
279
|
-
// 진행률 콜백 호출 (완료)
|
|
280
|
-
if (onProgress) {
|
|
281
|
-
onProgress({ processedBytes: totalBytes, totalBytes, percent: ENCODE_PROGRESS.DONE, stage: "done" });
|
|
282
|
-
}
|
|
283
|
-
return { encoded: result, compressedSize };
|
|
284
|
-
}
|
|
285
|
-
/**
|
|
286
|
-
* 인코딩된 문자열을 Buffer로 디코딩합니다.
|
|
287
|
-
*
|
|
288
|
-
* @param input - 디코딩할 인코딩된 문자열
|
|
289
|
-
* @param options - 디코딩 옵션
|
|
290
|
-
* @param options.maxDecodedBytes - 최대 디코딩 바이트 수
|
|
291
|
-
* @param options.maxDecompressedBytes - 최대 압축해제 바이트 수
|
|
292
|
-
* @param options.onProgress - 진행률 콜백
|
|
293
|
-
* @returns 디코딩된 Buffer
|
|
294
|
-
*
|
|
295
|
-
* @throws 잘못된 문자가 포함된 경우
|
|
296
|
-
* @throws 패딩 형식이 잘못된 경우
|
|
297
|
-
* @throws 크기 제한 초과 시
|
|
298
|
-
* @throws 체크섬 불일치 시
|
|
299
|
-
*/
|
|
300
|
-
decodeToBuffer(input, options) {
|
|
301
|
-
const shouldChecksum = options?.checksum ?? this.defaultChecksum;
|
|
302
|
-
const onProgress = options?.onProgress;
|
|
303
|
-
let workingInput = input;
|
|
304
|
-
const inputLength = input.length;
|
|
305
|
-
// 진행률 콜백 호출 (시작)
|
|
306
|
-
if (onProgress) {
|
|
307
|
-
onProgress({ processedBytes: 0, totalBytes: inputLength, percent: DECODE_PROGRESS.START, stage: "start" });
|
|
308
|
-
}
|
|
309
|
-
// 청크 제거 (줄바꿈 등 구분자 제거)
|
|
310
|
-
workingInput = this.removeChunks(workingInput);
|
|
311
|
-
// URL-Safe 역변환
|
|
312
|
-
if (this.urlSafe) {
|
|
313
|
-
workingInput = this.fromUrlSafe(workingInput);
|
|
314
|
-
}
|
|
315
|
-
// 체크섬 추출 (체크섬이 활성화된 경우에만 수행하여 오탐지 방지)
|
|
316
|
-
let extractedChecksum = null;
|
|
317
|
-
if (shouldChecksum) {
|
|
318
|
-
const result = this.extractChecksum(workingInput);
|
|
319
|
-
extractedChecksum = result.checksum;
|
|
320
|
-
workingInput = result.data;
|
|
321
|
-
}
|
|
322
|
-
const { cleanedInput, paddingBits, isCompressed, isEncrypted } = this.parseFooter(workingInput);
|
|
323
|
-
this.assertEncodedInputAligned(cleanedInput);
|
|
324
|
-
// 디코딩 크기 검증
|
|
325
|
-
const maxDecodedBytes = this.normalizeLimit(options?.maxDecodedBytes, this.defaultMaxDecodedBytes, true, "maxDecodedBytes");
|
|
326
|
-
const estimatedDecodedBytes = this.estimateDecodedBytes(cleanedInput.length, paddingBits);
|
|
327
|
-
if (estimatedDecodedBytes > maxDecodedBytes) {
|
|
328
|
-
throw new Error(`[Ddu64 decode] Decoded output exceeds limit. Estimated: ${estimatedDecodedBytes} bytes, Limit: ${maxDecodedBytes} bytes`);
|
|
329
|
-
}
|
|
330
|
-
// 디코딩 수행
|
|
331
|
-
if (onProgress) {
|
|
332
|
-
onProgress({ processedBytes: Math.floor(inputLength * 0.2), totalBytes: inputLength, percent: DECODE_PROGRESS.DECODE, stage: "decode" });
|
|
333
|
-
}
|
|
334
|
-
let decoded = this.effectiveBitLength <= MAX_FAST_BITS
|
|
335
|
-
? this.decodeFast(cleanedInput, paddingBits)
|
|
336
|
-
: this.decodeBigInt(cleanedInput, paddingBits);
|
|
337
|
-
// 압축 해제
|
|
338
|
-
if (isCompressed) {
|
|
339
|
-
if (onProgress) {
|
|
340
|
-
onProgress({ processedBytes: Math.floor(inputLength * 0.5), totalBytes: inputLength, percent: DECODE_PROGRESS.DECOMPRESS, stage: "decompress" });
|
|
341
|
-
}
|
|
342
|
-
const maxDecompressedBytes = this.normalizeLimit(options?.maxDecompressedBytes, this.defaultMaxDecompressedBytes, true, "maxDecompressedBytes");
|
|
343
|
-
decoded = this.inflateWithLimit(decoded, maxDecompressedBytes);
|
|
344
|
-
}
|
|
345
|
-
// 체크섬 검증
|
|
346
|
-
if (extractedChecksum) {
|
|
347
|
-
if (onProgress) {
|
|
348
|
-
onProgress({ processedBytes: Math.floor(inputLength * 0.7), totalBytes: inputLength, percent: DECODE_PROGRESS.CHECKSUM, stage: "checksum" });
|
|
349
|
-
}
|
|
350
|
-
const calculatedChecksum = this.calculateCRC32(decoded);
|
|
351
|
-
if (calculatedChecksum !== extractedChecksum) {
|
|
352
|
-
throw new Error(`[Ddu64 decode] Checksum mismatch. Expected: ${extractedChecksum}, Got: ${calculatedChecksum}`);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
// 복호화
|
|
356
|
-
if (isEncrypted && this.encryptionKeyHash) {
|
|
357
|
-
if (onProgress) {
|
|
358
|
-
onProgress({ processedBytes: Math.floor(inputLength * 0.85), totalBytes: inputLength, percent: DECODE_PROGRESS.DECRYPT, stage: "decrypt" });
|
|
359
|
-
}
|
|
360
|
-
decoded = this.decryptData(decoded);
|
|
361
|
-
}
|
|
362
|
-
// 진행률 콜백 호출 (완료)
|
|
363
|
-
if (onProgress) {
|
|
364
|
-
onProgress({ processedBytes: inputLength, totalBytes: inputLength, percent: DECODE_PROGRESS.DONE, stage: "done" });
|
|
365
|
-
}
|
|
366
|
-
return decoded;
|
|
367
|
-
}
|
|
368
|
-
/**
|
|
369
|
-
* 인코딩된 문자열을 원본 문자열로 디코딩합니다.
|
|
370
|
-
*
|
|
371
|
-
* @param input - 디코딩할 인코딩된 문자열
|
|
372
|
-
* @param options - 디코딩 옵션
|
|
373
|
-
* @returns 디코딩된 문자열
|
|
374
|
-
*
|
|
375
|
-
* @throws 잘못된 문자나 패딩 형식일 경우 에러
|
|
376
|
-
*/
|
|
377
|
-
decode(input, options) {
|
|
378
|
-
return this.decodeToBuffer(input, options).toString(this.encoding);
|
|
379
|
-
}
|
|
380
|
-
/**
|
|
381
|
-
* 현재 인코더의 charset 정보를 반환합니다.
|
|
382
|
-
*
|
|
383
|
-
* @returns charset 설정 정보 객체
|
|
384
|
-
*/
|
|
385
|
-
getCharSetInfo() {
|
|
386
|
-
return {
|
|
387
|
-
charSet: [...this.dduChar],
|
|
388
|
-
paddingChar: this.paddingChar,
|
|
389
|
-
charLength: this.charLength,
|
|
390
|
-
bitLength: this.bitLength,
|
|
391
|
-
usePowerOfTwo: this.usePowerOfTwo,
|
|
392
|
-
encoding: this.encoding,
|
|
393
|
-
defaultCompress: this.defaultCompress,
|
|
394
|
-
defaultMaxDecodedBytes: this.defaultMaxDecodedBytes,
|
|
395
|
-
defaultMaxDecompressedBytes: this.defaultMaxDecompressedBytes,
|
|
396
|
-
urlSafe: this.urlSafe,
|
|
397
|
-
hasEncryptionKey: !!this.encryptionKeyHash,
|
|
398
|
-
defaultChecksum: this.defaultChecksum,
|
|
399
|
-
defaultChunkSize: this.defaultChunkSize,
|
|
400
|
-
};
|
|
401
|
-
}
|
|
402
|
-
/**
|
|
403
|
-
* 인코딩 통계 정보를 반환합니다.
|
|
404
|
-
*
|
|
405
|
-
* @param input - 분석할 데이터
|
|
406
|
-
* @param options - 인코딩 옵션
|
|
407
|
-
* @returns 통계 정보 객체
|
|
408
|
-
*/
|
|
409
|
-
getStats(input, options) {
|
|
410
|
-
const shouldCompress = options?.compress ?? this.defaultCompress;
|
|
411
|
-
const originalBuffer = typeof input === "string" ? Buffer.from(input, this.encoding) : input;
|
|
412
|
-
const originalSize = originalBuffer.length;
|
|
413
|
-
// encodeInternal을 통해 인코딩과 압축 크기를 한 번에 얻어 중복 deflateSync 방지
|
|
414
|
-
const { encoded, compressedSize } = this.encodeInternal(input, options);
|
|
415
|
-
const encodedSize = encoded.length;
|
|
416
|
-
const expansionRatio = originalSize > 0 ? encodedSize / originalSize : 0;
|
|
417
|
-
const compressionRatio = shouldCompress && compressedSize !== undefined && originalSize > 0
|
|
418
|
-
? compressedSize / originalSize
|
|
419
|
-
: undefined;
|
|
420
|
-
return {
|
|
421
|
-
originalSize,
|
|
422
|
-
encodedSize,
|
|
423
|
-
compressedSize,
|
|
424
|
-
compressionRatio,
|
|
425
|
-
expansionRatio,
|
|
426
|
-
charsetSize: this.dduChar.length,
|
|
427
|
-
bitLength: this.bitLength,
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* 비동기 인코딩을 수행합니다.
|
|
432
|
-
*
|
|
433
|
-
* 내부적으로 동기 encode()를 setImmediate로 이벤트 루프에 양보한 뒤 실행합니다.
|
|
434
|
-
* 호출자가 즉시 블로킹되지 않도록 보장하지만, 인코딩 자체는 단일 동기 작업으로
|
|
435
|
-
* 수행되므로 대용량 데이터(수 MB 이상) 처리 시 이벤트 루프가 블로킹될 수 있습니다.
|
|
436
|
-
* 대용량 처리가 필요한 경우 스트림 API(createEncodeStream) 사용을 권장합니다.
|
|
437
|
-
*
|
|
438
|
-
* @param input - 인코딩할 데이터
|
|
439
|
-
* @param options - 인코딩 옵션
|
|
440
|
-
* @returns 인코딩된 문자열 Promise
|
|
441
|
-
*/
|
|
442
|
-
async encodeAsync(input, options) {
|
|
443
|
-
return new Promise((resolve, reject) => {
|
|
444
|
-
setImmediate(() => {
|
|
445
|
-
try {
|
|
446
|
-
resolve(this.encode(input, options));
|
|
447
|
-
}
|
|
448
|
-
catch (e) {
|
|
449
|
-
reject(e);
|
|
450
|
-
}
|
|
451
|
-
});
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
|
-
/**
|
|
455
|
-
* 비동기 디코딩을 수행합니다.
|
|
456
|
-
*
|
|
457
|
-
* 내부적으로 동기 decode()를 setImmediate로 이벤트 루프에 양보한 뒤 실행합니다.
|
|
458
|
-
* 대용량 처리가 필요한 경우 스트림 API(createDecodeStream) 사용을 권장합니다.
|
|
459
|
-
*
|
|
460
|
-
* @param input - 디코딩할 인코딩된 문자열
|
|
461
|
-
* @param options - 디코딩 옵션
|
|
462
|
-
* @returns 디코딩된 문자열 Promise
|
|
463
|
-
*/
|
|
464
|
-
async decodeAsync(input, options) {
|
|
465
|
-
return new Promise((resolve, reject) => {
|
|
466
|
-
setImmediate(() => {
|
|
467
|
-
try {
|
|
468
|
-
resolve(this.decode(input, options));
|
|
469
|
-
}
|
|
470
|
-
catch (e) {
|
|
471
|
-
reject(e);
|
|
472
|
-
}
|
|
473
|
-
});
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* 비동기 디코딩을 Buffer로 수행합니다.
|
|
478
|
-
*
|
|
479
|
-
* 내부적으로 동기 decodeToBuffer()를 setImmediate로 이벤트 루프에 양보한 뒤 실행합니다.
|
|
480
|
-
* 대용량 처리가 필요한 경우 스트림 API(createDecodeStream) 사용을 권장합니다.
|
|
481
|
-
*
|
|
482
|
-
* @param input - 디코딩할 인코딩된 문자열
|
|
483
|
-
* @param options - 디코딩 옵션
|
|
484
|
-
* @returns 디코딩된 Buffer Promise
|
|
485
|
-
*/
|
|
486
|
-
async decodeToBufferAsync(input, options) {
|
|
487
|
-
return new Promise((resolve, reject) => {
|
|
488
|
-
setImmediate(() => {
|
|
489
|
-
try {
|
|
490
|
-
resolve(this.decodeToBuffer(input, options));
|
|
491
|
-
}
|
|
492
|
-
catch (e) {
|
|
493
|
-
reject(e);
|
|
494
|
-
}
|
|
495
|
-
});
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
// --------------------------------------------------------------------------
|
|
499
|
-
// URL-Safe 메서드
|
|
500
|
-
// --------------------------------------------------------------------------
|
|
501
|
-
/**
|
|
502
|
-
* 문자열을 URL-Safe 형식으로 변환합니다.
|
|
503
|
-
* 단일 정규식 패스로 처리하여 split/join 3회 반복 대비 메모리/속도 개선
|
|
504
|
-
*/
|
|
505
|
-
toUrlSafe(input) {
|
|
506
|
-
return input.replace(/[+/=]/g, (c) => URL_SAFE_MAP[c]);
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* URL-Safe 형식에서 원래 형식으로 복원합니다.
|
|
510
|
-
*/
|
|
511
|
-
fromUrlSafe(input) {
|
|
512
|
-
return input.replace(/[-_.]/g, (c) => URL_SAFE_REVERSE_MAP[c]);
|
|
513
|
-
}
|
|
514
|
-
// --------------------------------------------------------------------------
|
|
515
|
-
// 체크섬 메서드
|
|
516
|
-
// --------------------------------------------------------------------------
|
|
517
|
-
/**
|
|
518
|
-
* CRC32 체크섬을 계산합니다. (룩업 테이블 사용)
|
|
519
|
-
*/
|
|
520
|
-
calculateCRC32(data) {
|
|
521
|
-
let crc = 0xffffffff;
|
|
522
|
-
for (let i = 0; i < data.length; i++) {
|
|
523
|
-
crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ data[i]) & 0xff];
|
|
524
|
-
}
|
|
525
|
-
return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, "0");
|
|
526
|
-
}
|
|
527
|
-
/**
|
|
528
|
-
* 인코딩된 문자열에서 체크섬을 추출합니다.
|
|
529
|
-
*/
|
|
530
|
-
extractChecksum(input) {
|
|
531
|
-
const markerIndex = input.lastIndexOf(CHECKSUM_MARKER);
|
|
532
|
-
if (markerIndex === -1) {
|
|
533
|
-
return { data: input, checksum: null };
|
|
534
|
-
}
|
|
535
|
-
const checksum = input.slice(markerIndex + CHECKSUM_MARKER.length);
|
|
536
|
-
if (checksum.length !== 8 || !/^[0-9a-f]+$/i.test(checksum)) {
|
|
537
|
-
return { data: input, checksum: null };
|
|
538
|
-
}
|
|
539
|
-
return {
|
|
540
|
-
data: input.slice(0, markerIndex),
|
|
541
|
-
checksum: checksum.toLowerCase(),
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
// --------------------------------------------------------------------------
|
|
545
|
-
// 청크 분할 메서드
|
|
546
|
-
// --------------------------------------------------------------------------
|
|
547
|
-
/**
|
|
548
|
-
* 문자열을 청크로 분할합니다.
|
|
549
|
-
*/
|
|
550
|
-
splitIntoChunks(input, chunkSize, separator) {
|
|
551
|
-
if (chunkSize <= 0)
|
|
552
|
-
return input;
|
|
553
|
-
const chunks = [];
|
|
554
|
-
for (let i = 0; i < input.length; i += chunkSize) {
|
|
555
|
-
chunks.push(input.slice(i, i + chunkSize));
|
|
556
|
-
}
|
|
557
|
-
return chunks.join(separator);
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* 청크 구분자를 제거합니다.
|
|
561
|
-
* 줄바꿈(\r, \n)과 인스턴스에 설정된 청크 구분자만 제거합니다.
|
|
562
|
-
* 공백/탭 등은 charset에 포함될 수 있으므로 제거하지 않습니다.
|
|
563
|
-
*/
|
|
564
|
-
removeChunks(input) {
|
|
565
|
-
// 줄바꿈 문자(\r, \n)는 항상 제거 (기본 구분자 및 일반적 라인 구분)
|
|
566
|
-
let result = input.replace(/[\r\n]/g, "");
|
|
567
|
-
// 커스텀 구분자가 줄바꿈이 아닌 경우 추가로 제거
|
|
568
|
-
const sep = this.defaultChunkSeparator;
|
|
569
|
-
if (sep && sep !== "\n" && sep !== "\r\n" && sep !== "\r") {
|
|
570
|
-
result = result.split(sep).join("");
|
|
571
|
-
}
|
|
572
|
-
return result;
|
|
573
|
-
}
|
|
574
|
-
// --------------------------------------------------------------------------
|
|
575
|
-
// 암호화 메서드
|
|
576
|
-
// --------------------------------------------------------------------------
|
|
577
|
-
/**
|
|
578
|
-
* 데이터를 AES-256-GCM으로 암호화합니다.
|
|
579
|
-
*/
|
|
580
|
-
encryptData(data) {
|
|
581
|
-
if (!this.encryptionKeyHash) {
|
|
582
|
-
throw new Error("[Ddu64 encrypt] Encryption key is not set");
|
|
583
|
-
}
|
|
584
|
-
return (0, crypto_1.encryptAes256Gcm)(data, this.encryptionKeyHash);
|
|
585
|
-
}
|
|
586
|
-
/**
|
|
587
|
-
* AES-256-GCM으로 암호화된 데이터를 복호화합니다.
|
|
588
|
-
*/
|
|
589
|
-
decryptData(data) {
|
|
590
|
-
if (!this.encryptionKeyHash) {
|
|
591
|
-
throw new Error("[Ddu64 decrypt] Encryption key is not set");
|
|
592
|
-
}
|
|
593
|
-
return (0, crypto_1.decryptAes256Gcm)(data, this.encryptionKeyHash);
|
|
594
|
-
}
|
|
595
|
-
// --------------------------------------------------------------------------
|
|
596
|
-
// 유틸리티 메서드
|
|
597
|
-
// --------------------------------------------------------------------------
|
|
598
|
-
/**
|
|
599
|
-
* 옵션 값을 정규화합니다.
|
|
600
|
-
*/
|
|
601
|
-
normalizeLimit(value, fallback, shouldThrow, name) {
|
|
602
|
-
if (value === undefined)
|
|
603
|
-
return fallback;
|
|
604
|
-
if (value === Number.POSITIVE_INFINITY)
|
|
605
|
-
return Number.POSITIVE_INFINITY;
|
|
606
|
-
if (!Number.isFinite(value) || value <= 0) {
|
|
607
|
-
if (shouldThrow) {
|
|
608
|
-
throw new Error(`[Ddu64 options] Invalid ${name}. Must be a positive finite number or Infinity.`);
|
|
609
|
-
}
|
|
610
|
-
return fallback;
|
|
611
|
-
}
|
|
612
|
-
return Math.floor(value);
|
|
613
|
-
}
|
|
614
|
-
/**
|
|
615
|
-
* 디코딩 결과 바이트 수를 추정합니다.
|
|
616
|
-
*/
|
|
617
|
-
estimateDecodedBytes(cleanedInputLen, paddingBits) {
|
|
618
|
-
if (cleanedInputLen === 0)
|
|
619
|
-
return 0;
|
|
620
|
-
if (paddingBits < 0 || paddingBits >= this.effectiveBitLength) {
|
|
621
|
-
throw new Error(`[Ddu64 decode] Invalid padding bits: ${paddingBits}`);
|
|
622
|
-
}
|
|
623
|
-
const chunkSize = this.usePowerOfTwo ? this.charLength : this.charLength * 2;
|
|
624
|
-
const numChunks = Math.ceil(cleanedInputLen / chunkSize);
|
|
625
|
-
const bits = numChunks * this.effectiveBitLength - paddingBits;
|
|
626
|
-
if (bits < 0)
|
|
627
|
-
throw new Error(`[Ddu64 decode] Invalid decoded bit length`);
|
|
628
|
-
return Math.ceil(bits / BYTE_BITS);
|
|
629
|
-
}
|
|
630
|
-
/**
|
|
631
|
-
* 인코딩된 입력의 정렬을 검증합니다.
|
|
632
|
-
*/
|
|
633
|
-
assertEncodedInputAligned(cleanedInput) {
|
|
634
|
-
const { charLength } = this;
|
|
635
|
-
if (charLength <= 0)
|
|
636
|
-
return;
|
|
637
|
-
if (cleanedInput.length % charLength !== 0) {
|
|
638
|
-
throw new Error(`[Ddu64 decode] Invalid encoded length. Expected multiple of ${charLength}, got ${cleanedInput.length}`);
|
|
639
|
-
}
|
|
640
|
-
if (!this.usePowerOfTwo) {
|
|
641
|
-
const chunkSize = charLength * 2;
|
|
642
|
-
if (cleanedInput.length % chunkSize !== 0) {
|
|
643
|
-
throw new Error(`[Ddu64 decode] Invalid encoded length for variable charset. Expected multiple of ${chunkSize}, got ${cleanedInput.length}`);
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
/**
|
|
648
|
-
* 크기 제한을 적용하여 압축을 해제합니다.
|
|
649
|
-
*/
|
|
650
|
-
inflateWithLimit(data, maxBytes) {
|
|
651
|
-
return (0, crypto_1.inflateWithLimit)(data, maxBytes, "Ddu64 decode");
|
|
652
|
-
}
|
|
653
|
-
// --------------------------------------------------------------------------
|
|
654
|
-
// 푸터 파싱
|
|
655
|
-
// --------------------------------------------------------------------------
|
|
656
|
-
/**
|
|
657
|
-
* 인코딩된 문자열의 푸터(패딩 정보)를 파싱합니다.
|
|
658
|
-
*
|
|
659
|
-
* 푸터 형식: {encodedData}{paddingChar}[ELYSIA][ENC]{digits}
|
|
660
|
-
* 끝에서부터 역순으로 파싱하여 paddingChar가 숫자인 경우도 안전하게 처리합니다.
|
|
661
|
-
*/
|
|
662
|
-
parseFooter(input) {
|
|
663
|
-
const inputLen = input.length;
|
|
664
|
-
const pad = this.paddingChar;
|
|
665
|
-
const padLen = pad.length;
|
|
666
|
-
const noFooter = { cleanedInput: input, paddingBits: 0, isCompressed: false, isEncrypted: false };
|
|
667
|
-
if (inputLen < padLen)
|
|
668
|
-
return noFooter;
|
|
669
|
-
const maxPaddingBits = Math.max(0, this.effectiveBitLength - 1);
|
|
670
|
-
const maxDigits = maxPaddingBits.toString().length;
|
|
671
|
-
// 끝에서부터 역순 파싱: digits → ENC → ELYSIA → paddingChar
|
|
672
|
-
for (let digitCount = Math.min(maxDigits, inputLen); digitCount >= 1; digitCount--) {
|
|
673
|
-
const digitsStart = inputLen - digitCount;
|
|
674
|
-
// 1) trailing digits 확인
|
|
675
|
-
let allDigits = true;
|
|
676
|
-
for (let i = digitsStart; i < inputLen; i++) {
|
|
677
|
-
const c = input.charCodeAt(i);
|
|
678
|
-
if (c < 48 || c > 57) {
|
|
679
|
-
allDigits = false;
|
|
680
|
-
break;
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
if (!allDigits)
|
|
684
|
-
continue;
|
|
685
|
-
const digitStr = input.substring(digitsStart);
|
|
686
|
-
const paddingBits = parseInt(digitStr, 10);
|
|
687
|
-
if (Number.isNaN(paddingBits) ||
|
|
688
|
-
paddingBits < 0 ||
|
|
689
|
-
paddingBits >= this.effectiveBitLength ||
|
|
690
|
-
digitStr !== paddingBits.toString())
|
|
691
|
-
continue;
|
|
692
|
-
// 2) digits 앞에서 마커들 역순 확인
|
|
693
|
-
let pos = digitsStart;
|
|
694
|
-
let isEncrypted = false;
|
|
695
|
-
let isCompressed = false;
|
|
696
|
-
if (pos >= ENCRYPT_MARKER.length && input.substring(pos - ENCRYPT_MARKER.length, pos) === ENCRYPT_MARKER) {
|
|
697
|
-
isEncrypted = true;
|
|
698
|
-
pos -= ENCRYPT_MARKER.length;
|
|
699
|
-
}
|
|
700
|
-
if (pos >= COMPRESS_MARKER.length && input.substring(pos - COMPRESS_MARKER.length, pos) === COMPRESS_MARKER) {
|
|
701
|
-
isCompressed = true;
|
|
702
|
-
pos -= COMPRESS_MARKER.length;
|
|
703
|
-
}
|
|
704
|
-
// 3) 마커 앞에서 padding 문자 확인
|
|
705
|
-
const padStart = pos - padLen;
|
|
706
|
-
if (padStart >= 0 && input.substring(padStart, pos) === pad) {
|
|
707
|
-
if (padStart % this.charLength !== 0) {
|
|
708
|
-
throw new Error(`[Ddu64 decode] Invalid padding format. Misaligned padding marker`);
|
|
709
|
-
}
|
|
710
|
-
return {
|
|
711
|
-
cleanedInput: input.substring(0, padStart),
|
|
712
|
-
paddingBits,
|
|
713
|
-
isCompressed,
|
|
714
|
-
isEncrypted,
|
|
715
|
-
};
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
// Fallback: 역순 탐색이 유효한 패딩을 찾지 못한 경우,
|
|
719
|
-
// padding 문자가 존재하지만 tail이 잘못된 형식인지 확인하여 에러 보고
|
|
720
|
-
const lastPadIdx = input.lastIndexOf(pad);
|
|
721
|
-
if (lastPadIdx >= 0 && lastPadIdx % this.charLength === 0) {
|
|
722
|
-
const tailStart = lastPadIdx + padLen;
|
|
723
|
-
if (tailStart >= inputLen) {
|
|
724
|
-
throw new Error(`[Ddu64 decode] Invalid padding format. Missing padding length`);
|
|
725
|
-
}
|
|
726
|
-
const tail = input.substring(tailStart);
|
|
727
|
-
throw new Error(`[Ddu64 decode] Invalid padding format. Got: "${tail}"`);
|
|
728
|
-
}
|
|
729
|
-
return noFooter;
|
|
730
|
-
}
|
|
731
|
-
// --------------------------------------------------------------------------
|
|
732
|
-
// 인코딩 (Fast 모드 - 16비트 이하)
|
|
733
|
-
// --------------------------------------------------------------------------
|
|
734
|
-
/**
|
|
735
|
-
* 일반 정수 연산을 사용한 빠른 인코딩
|
|
736
|
-
*/
|
|
737
|
-
encodeFast(bufferInput, compress, encrypt) {
|
|
738
|
-
const inputLen = bufferInput.length;
|
|
739
|
-
if (inputLen === 0)
|
|
740
|
-
return "";
|
|
741
|
-
const { dduChar, effectiveBitLength: bitLength, paddingChar } = this;
|
|
742
|
-
const dduLength = dduChar.length;
|
|
743
|
-
const totalBits = inputLen * BYTE_BITS;
|
|
744
|
-
const estimatedChunks = Math.ceil(totalBits / bitLength);
|
|
745
|
-
const estimatedSymbols = this.usePowerOfTwo
|
|
746
|
-
? estimatedChunks
|
|
747
|
-
: estimatedChunks * 2;
|
|
748
|
-
const resultParts = new Array(estimatedSymbols + 3);
|
|
749
|
-
let resultIdx = 0;
|
|
750
|
-
let accumulator = 0;
|
|
751
|
-
let accumulatorBits = 0;
|
|
752
|
-
if (this.usePowerOfTwo) {
|
|
753
|
-
const mask = (1 << bitLength) - 1;
|
|
754
|
-
for (let i = 0; i < inputLen; i++) {
|
|
755
|
-
accumulator = (accumulator << BYTE_BITS) | bufferInput[i];
|
|
756
|
-
accumulatorBits += BYTE_BITS;
|
|
757
|
-
while (accumulatorBits >= bitLength) {
|
|
758
|
-
accumulatorBits -= bitLength;
|
|
759
|
-
resultParts[resultIdx++] =
|
|
760
|
-
dduChar[(accumulator >> accumulatorBits) & mask];
|
|
761
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
else {
|
|
766
|
-
for (let i = 0; i < inputLen; i++) {
|
|
767
|
-
accumulator = (accumulator << BYTE_BITS) | bufferInput[i];
|
|
768
|
-
accumulatorBits += BYTE_BITS;
|
|
769
|
-
while (accumulatorBits >= bitLength) {
|
|
770
|
-
accumulatorBits -= bitLength;
|
|
771
|
-
const index = accumulator >> accumulatorBits;
|
|
772
|
-
const div = (index / dduLength) | 0;
|
|
773
|
-
resultParts[resultIdx++] = dduChar[div];
|
|
774
|
-
resultParts[resultIdx++] = dduChar[index - div * dduLength];
|
|
775
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
// 남은 비트 처리 (패딩)
|
|
780
|
-
if (accumulatorBits > 0) {
|
|
781
|
-
const paddingBits = bitLength - accumulatorBits;
|
|
782
|
-
const index = accumulator << paddingBits;
|
|
783
|
-
if (this.usePowerOfTwo) {
|
|
784
|
-
resultParts[resultIdx++] = dduChar[index];
|
|
785
|
-
}
|
|
786
|
-
else {
|
|
787
|
-
const div = (index / dduLength) | 0;
|
|
788
|
-
resultParts[resultIdx++] = dduChar[div];
|
|
789
|
-
resultParts[resultIdx++] = dduChar[index - div * dduLength];
|
|
790
|
-
}
|
|
791
|
-
resultParts[resultIdx++] = paddingChar;
|
|
792
|
-
resultParts[resultIdx++] = (compress ? COMPRESS_MARKER : "") + (encrypt ? ENCRYPT_MARKER : "") + paddingBits.toString();
|
|
793
|
-
}
|
|
794
|
-
else if (compress || encrypt) {
|
|
795
|
-
resultParts[resultIdx++] = paddingChar;
|
|
796
|
-
resultParts[resultIdx++] = (compress ? COMPRESS_MARKER : "") + (encrypt ? ENCRYPT_MARKER : "") + "0";
|
|
797
|
-
}
|
|
798
|
-
resultParts.length = resultIdx;
|
|
799
|
-
return resultParts.join("");
|
|
800
|
-
}
|
|
801
|
-
// --------------------------------------------------------------------------
|
|
802
|
-
// 디코딩 (Fast 모드 - 16비트 이하)
|
|
803
|
-
// --------------------------------------------------------------------------
|
|
804
|
-
/**
|
|
805
|
-
* 일반 정수 연산을 사용한 빠른 디코딩
|
|
806
|
-
*/
|
|
807
|
-
decodeFast(cleanedInput, paddingBits) {
|
|
808
|
-
const inputLen = cleanedInput.length;
|
|
809
|
-
if (inputLen === 0)
|
|
810
|
-
return Buffer.alloc(0);
|
|
811
|
-
const { effectiveBitLength: bitLength, charLength } = this;
|
|
812
|
-
const dduLength = this.dduChar.length;
|
|
813
|
-
const chunkSize = this.usePowerOfTwo ? charLength : charLength * 2;
|
|
814
|
-
const numChunks = Math.ceil(inputLen / chunkSize);
|
|
815
|
-
const estimatedBytes = Math.ceil((numChunks * bitLength - paddingBits) / BYTE_BITS);
|
|
816
|
-
const buffer = new Uint8Array(estimatedBytes + 1);
|
|
817
|
-
let bufIdx = 0;
|
|
818
|
-
let accumulator = 0;
|
|
819
|
-
let accumulatorBits = 0;
|
|
820
|
-
if (this.usePowerOfTwo) {
|
|
821
|
-
if (this.useAsciiLookup && this.fastAsciiLookup) {
|
|
822
|
-
// ASCII 최적화 경로
|
|
823
|
-
const lookup = this.fastAsciiLookup;
|
|
824
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
825
|
-
const code = cleanedInput.charCodeAt(i);
|
|
826
|
-
const val = code < 128 ? lookup[code] : -1;
|
|
827
|
-
if (val < 0) {
|
|
828
|
-
throw new Error(`[Ddu64 decode] Invalid character "${cleanedInput[i]}" at ${i}`);
|
|
829
|
-
}
|
|
830
|
-
accumulator = (accumulator << bitLength) | val;
|
|
831
|
-
accumulatorBits += bitLength;
|
|
832
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
833
|
-
accumulator >>= paddingBits;
|
|
834
|
-
accumulatorBits -= paddingBits;
|
|
835
|
-
}
|
|
836
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
837
|
-
accumulatorBits -= BYTE_BITS;
|
|
838
|
-
buffer[bufIdx++] = (accumulator >> accumulatorBits) & BYTE_MASK;
|
|
839
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
else {
|
|
844
|
-
// 일반 룩업 경로
|
|
845
|
-
const lookup = this.dduBinaryLookup;
|
|
846
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
847
|
-
const chunk = cleanedInput.slice(i, i + charLength);
|
|
848
|
-
const val = lookup.get(chunk);
|
|
849
|
-
if (val === undefined) {
|
|
850
|
-
throw new Error(`[Ddu64 decode] Invalid character "${chunk}" at ${i}`);
|
|
851
|
-
}
|
|
852
|
-
accumulator = (accumulator << bitLength) | val;
|
|
853
|
-
accumulatorBits += bitLength;
|
|
854
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
855
|
-
accumulator >>= paddingBits;
|
|
856
|
-
accumulatorBits -= paddingBits;
|
|
857
|
-
}
|
|
858
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
859
|
-
accumulatorBits -= BYTE_BITS;
|
|
860
|
-
buffer[bufIdx++] = (accumulator >> accumulatorBits) & BYTE_MASK;
|
|
861
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
else if (this.useAsciiLookup && this.fastAsciiLookup && charLength === 1) {
|
|
867
|
-
// 가변 길이 charset - ASCII 최적화 경로
|
|
868
|
-
const asciiLookup = this.fastAsciiLookup;
|
|
869
|
-
const maxVal = this.maxBinaryValue;
|
|
870
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
871
|
-
const code1 = cleanedInput.charCodeAt(i);
|
|
872
|
-
const code2 = cleanedInput.charCodeAt(i + 1);
|
|
873
|
-
const v1 = code1 < 128 ? asciiLookup[code1] : -1;
|
|
874
|
-
const v2 = code2 < 128 ? asciiLookup[code2] : -1;
|
|
875
|
-
if (v1 < 0) {
|
|
876
|
-
throw new Error(`[Ddu64 decode] Invalid character "${cleanedInput[i]}" at ${i}`);
|
|
877
|
-
}
|
|
878
|
-
if (v2 < 0) {
|
|
879
|
-
throw new Error(`[Ddu64 decode] Invalid character "${cleanedInput[i + 1]}" at ${i + charLength}`);
|
|
880
|
-
}
|
|
881
|
-
const value = v1 * dduLength + v2;
|
|
882
|
-
if (value >= maxVal) {
|
|
883
|
-
throw new Error(`[Ddu64 decode] Value ${value} exceeds range`);
|
|
884
|
-
}
|
|
885
|
-
accumulator = (accumulator << bitLength) | value;
|
|
886
|
-
accumulatorBits += bitLength;
|
|
887
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
888
|
-
accumulator >>= paddingBits;
|
|
889
|
-
accumulatorBits -= paddingBits;
|
|
890
|
-
}
|
|
891
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
892
|
-
accumulatorBits -= BYTE_BITS;
|
|
893
|
-
buffer[bufIdx++] = (accumulator >> accumulatorBits) & BYTE_MASK;
|
|
894
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
else {
|
|
899
|
-
// 가변 길이 charset - 일반 룩업 경로
|
|
900
|
-
const lookup = this.dduBinaryLookup;
|
|
901
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
902
|
-
const c1 = cleanedInput.slice(i, i + charLength);
|
|
903
|
-
const c2 = cleanedInput.slice(i + charLength, i + chunkSize);
|
|
904
|
-
const v1 = lookup.get(c1);
|
|
905
|
-
const v2 = lookup.get(c2);
|
|
906
|
-
if (v1 === undefined) {
|
|
907
|
-
throw new Error(`[Ddu64 decode] Invalid character "${c1}" at ${i}`);
|
|
908
|
-
}
|
|
909
|
-
if (v2 === undefined) {
|
|
910
|
-
throw new Error(`[Ddu64 decode] Invalid character "${c2}" at ${i + charLength}`);
|
|
911
|
-
}
|
|
912
|
-
const value = v1 * dduLength + v2;
|
|
913
|
-
if (value >= this.maxBinaryValue) {
|
|
914
|
-
throw new Error(`[Ddu64 decode] Value ${value} exceeds range`);
|
|
915
|
-
}
|
|
916
|
-
accumulator = (accumulator << bitLength) | value;
|
|
917
|
-
accumulatorBits += bitLength;
|
|
918
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
919
|
-
accumulator >>= paddingBits;
|
|
920
|
-
accumulatorBits -= paddingBits;
|
|
921
|
-
}
|
|
922
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
923
|
-
accumulatorBits -= BYTE_BITS;
|
|
924
|
-
buffer[bufIdx++] = (accumulator >> accumulatorBits) & BYTE_MASK;
|
|
925
|
-
accumulator &= (1 << accumulatorBits) - 1;
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
return Buffer.from(buffer.subarray(0, bufIdx));
|
|
930
|
-
}
|
|
931
|
-
// --------------------------------------------------------------------------
|
|
932
|
-
// 인코딩 (BigInt 모드 - 17비트 이상)
|
|
933
|
-
// --------------------------------------------------------------------------
|
|
934
|
-
/**
|
|
935
|
-
* BigInt를 사용한 대형 비트 인코딩
|
|
936
|
-
*/
|
|
937
|
-
encodeBigInt(bufferInput, compress, encrypt) {
|
|
938
|
-
const inputLen = bufferInput.length;
|
|
939
|
-
if (inputLen === 0)
|
|
940
|
-
return "";
|
|
941
|
-
const { dduChar, effectiveBitLength: bitLength } = this;
|
|
942
|
-
const dduLength = dduChar.length;
|
|
943
|
-
const estimatedChunks = Math.ceil((inputLen * BYTE_BITS) / bitLength);
|
|
944
|
-
const estimatedSymbols = this.usePowerOfTwo
|
|
945
|
-
? estimatedChunks
|
|
946
|
-
: estimatedChunks * 2;
|
|
947
|
-
const resultParts = new Array(estimatedSymbols + 3);
|
|
948
|
-
let resultIdx = 0;
|
|
949
|
-
let accumulator = 0n;
|
|
950
|
-
let accumulatorBits = 0;
|
|
951
|
-
if (this.usePowerOfTwo) {
|
|
952
|
-
for (let i = 0; i < inputLen; i++) {
|
|
953
|
-
accumulator = (accumulator << 8n) | BigInt(bufferInput[i]);
|
|
954
|
-
accumulatorBits += BYTE_BITS;
|
|
955
|
-
while (accumulatorBits >= bitLength) {
|
|
956
|
-
const shift = accumulatorBits - bitLength;
|
|
957
|
-
resultParts[resultIdx++] =
|
|
958
|
-
dduChar[Number(accumulator >> BigInt(shift))];
|
|
959
|
-
accumulator &= (1n << BigInt(shift)) - 1n;
|
|
960
|
-
accumulatorBits -= bitLength;
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
else {
|
|
965
|
-
for (let i = 0; i < inputLen; i++) {
|
|
966
|
-
accumulator = (accumulator << 8n) | BigInt(bufferInput[i]);
|
|
967
|
-
accumulatorBits += BYTE_BITS;
|
|
968
|
-
while (accumulatorBits >= bitLength) {
|
|
969
|
-
const shift = accumulatorBits - bitLength;
|
|
970
|
-
const idx = Number(accumulator >> BigInt(shift));
|
|
971
|
-
const div = Math.floor(idx / dduLength);
|
|
972
|
-
resultParts[resultIdx++] = dduChar[div];
|
|
973
|
-
resultParts[resultIdx++] = dduChar[idx - div * dduLength];
|
|
974
|
-
accumulator &= (1n << BigInt(shift)) - 1n;
|
|
975
|
-
accumulatorBits -= bitLength;
|
|
976
|
-
}
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
// 남은 비트 처리 (패딩)
|
|
980
|
-
if (accumulatorBits > 0) {
|
|
981
|
-
const paddingBits = bitLength - accumulatorBits;
|
|
982
|
-
const index = Number(accumulator << BigInt(paddingBits));
|
|
983
|
-
if (this.usePowerOfTwo) {
|
|
984
|
-
resultParts[resultIdx++] = dduChar[index];
|
|
985
|
-
}
|
|
986
|
-
else {
|
|
987
|
-
const div = Math.floor(index / dduLength);
|
|
988
|
-
resultParts[resultIdx++] = dduChar[div];
|
|
989
|
-
resultParts[resultIdx++] = dduChar[index - div * dduLength];
|
|
990
|
-
}
|
|
991
|
-
resultParts[resultIdx++] = this.paddingChar;
|
|
992
|
-
resultParts[resultIdx++] = (compress ? COMPRESS_MARKER : "") + (encrypt ? ENCRYPT_MARKER : "") + paddingBits.toString();
|
|
993
|
-
}
|
|
994
|
-
else if (compress || encrypt) {
|
|
995
|
-
resultParts[resultIdx++] = this.paddingChar;
|
|
996
|
-
resultParts[resultIdx++] = (compress ? COMPRESS_MARKER : "") + (encrypt ? ENCRYPT_MARKER : "") + "0";
|
|
997
|
-
}
|
|
998
|
-
resultParts.length = resultIdx;
|
|
999
|
-
return resultParts.join("");
|
|
1000
|
-
}
|
|
1001
|
-
// --------------------------------------------------------------------------
|
|
1002
|
-
// 디코딩 (BigInt 모드 - 17비트 이상)
|
|
1003
|
-
// --------------------------------------------------------------------------
|
|
1004
|
-
/**
|
|
1005
|
-
* BigInt를 사용한 대형 비트 디코딩
|
|
1006
|
-
*/
|
|
1007
|
-
decodeBigInt(cleanedInput, paddingBits) {
|
|
1008
|
-
const inputLen = cleanedInput.length;
|
|
1009
|
-
if (inputLen === 0)
|
|
1010
|
-
return Buffer.alloc(0);
|
|
1011
|
-
const { effectiveBitLength: bitLength, dduBinaryLookup: lookup, charLength, } = this;
|
|
1012
|
-
const bigBitLength = BigInt(bitLength);
|
|
1013
|
-
const dduLength = this.dduChar.length;
|
|
1014
|
-
const chunkSize = this.usePowerOfTwo ? charLength : charLength * 2;
|
|
1015
|
-
const numChunks = Math.ceil(inputLen / chunkSize);
|
|
1016
|
-
const estimatedBytes = Math.ceil((numChunks * bitLength - paddingBits) / BYTE_BITS);
|
|
1017
|
-
const buffer = new Uint8Array(estimatedBytes + 1);
|
|
1018
|
-
let bufIdx = 0;
|
|
1019
|
-
let accumulator = 0n;
|
|
1020
|
-
let accumulatorBits = 0;
|
|
1021
|
-
if (this.usePowerOfTwo) {
|
|
1022
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
1023
|
-
const chunk = cleanedInput.slice(i, i + charLength);
|
|
1024
|
-
const val = lookup.get(chunk);
|
|
1025
|
-
if (val === undefined) {
|
|
1026
|
-
throw new Error(`[Ddu64 decode] Invalid character "${chunk}" at ${i}`);
|
|
1027
|
-
}
|
|
1028
|
-
accumulator = (accumulator << bigBitLength) | BigInt(val);
|
|
1029
|
-
accumulatorBits += bitLength;
|
|
1030
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
1031
|
-
accumulator >>= BigInt(paddingBits);
|
|
1032
|
-
accumulatorBits -= paddingBits;
|
|
1033
|
-
}
|
|
1034
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
1035
|
-
const shift = accumulatorBits - BYTE_BITS;
|
|
1036
|
-
buffer[bufIdx++] = Number((accumulator >> BigInt(shift)) & 0xffn);
|
|
1037
|
-
accumulator &= (1n << BigInt(shift)) - 1n;
|
|
1038
|
-
accumulatorBits -= BYTE_BITS;
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
else {
|
|
1043
|
-
for (let i = 0; i < inputLen; i += chunkSize) {
|
|
1044
|
-
const c1 = cleanedInput.slice(i, i + charLength);
|
|
1045
|
-
const c2 = cleanedInput.slice(i + charLength, i + chunkSize);
|
|
1046
|
-
const v1 = lookup.get(c1);
|
|
1047
|
-
const v2 = lookup.get(c2);
|
|
1048
|
-
if (v1 === undefined) {
|
|
1049
|
-
throw new Error(`[Ddu64 decode] Invalid character "${c1}" at ${i}`);
|
|
1050
|
-
}
|
|
1051
|
-
if (v2 === undefined) {
|
|
1052
|
-
throw new Error(`[Ddu64 decode] Invalid character "${c2}" at ${i + charLength}`);
|
|
1053
|
-
}
|
|
1054
|
-
const value = v1 * dduLength + v2;
|
|
1055
|
-
if (value >= this.maxBinaryValue) {
|
|
1056
|
-
throw new Error(`[Ddu64 decode] Value ${value} exceeds range`);
|
|
1057
|
-
}
|
|
1058
|
-
accumulator = (accumulator << bigBitLength) | BigInt(value);
|
|
1059
|
-
accumulatorBits += bitLength;
|
|
1060
|
-
if (i + chunkSize >= inputLen && paddingBits > 0) {
|
|
1061
|
-
accumulator >>= BigInt(paddingBits);
|
|
1062
|
-
accumulatorBits -= paddingBits;
|
|
1063
|
-
}
|
|
1064
|
-
while (accumulatorBits >= BYTE_BITS) {
|
|
1065
|
-
const shift = accumulatorBits - BYTE_BITS;
|
|
1066
|
-
buffer[bufIdx++] = Number((accumulator >> BigInt(shift)) & 0xffn);
|
|
1067
|
-
accumulator &= (1n << BigInt(shift)) - 1n;
|
|
1068
|
-
accumulatorBits -= BYTE_BITS;
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
return Buffer.from(buffer.subarray(0, bufIdx));
|
|
1073
|
-
}
|
|
1074
|
-
// --------------------------------------------------------------------------
|
|
1075
|
-
// Charset 초기화 메서드
|
|
1076
|
-
// --------------------------------------------------------------------------
|
|
1077
|
-
/**
|
|
1078
|
-
* Charset을 정규화합니다.
|
|
1079
|
-
*/
|
|
1080
|
-
normalizeCharSet(current, shouldThrow, dduOptions) {
|
|
1081
|
-
// 1차 시도: 주어진 charset으로 정규화
|
|
1082
|
-
// 실패 시 1회만 fallback 시도 (동일 fallback을 반복해도 결과는 동일)
|
|
1083
|
-
const attempts = [current, null];
|
|
1084
|
-
for (const attempt of attempts) {
|
|
1085
|
-
const state = attempt ? { ...attempt } : this.getFallbackCharSet(dduOptions);
|
|
1086
|
-
try {
|
|
1087
|
-
// 중복 문자 제거
|
|
1088
|
-
let charSet = state.charSet;
|
|
1089
|
-
let requiredLength = state.requiredLength;
|
|
1090
|
-
const uniqueChars = Array.from(new Set(charSet));
|
|
1091
|
-
if (uniqueChars.length !== charSet.length) {
|
|
1092
|
-
if (shouldThrow) {
|
|
1093
|
-
const duplicates = charSet.filter((c, i) => charSet.indexOf(c) !== i);
|
|
1094
|
-
throw new Error(`[Ddu64 normalizeCharSet] Character set contains duplicate characters: [${[...new Set(duplicates)].join(", ")}]`);
|
|
1095
|
-
}
|
|
1096
|
-
charSet = uniqueChars;
|
|
1097
|
-
if (!state.isPredefined)
|
|
1098
|
-
requiredLength = charSet.length;
|
|
1099
|
-
}
|
|
1100
|
-
// 문자 수 검증
|
|
1101
|
-
if (charSet.length < requiredLength) {
|
|
1102
|
-
throw new Error(`[Ddu64 normalizeCharSet] Insufficient characters. Required: ${requiredLength}, Has: ${charSet.length}`);
|
|
1103
|
-
}
|
|
1104
|
-
if (requiredLength < 2) {
|
|
1105
|
-
throw new Error(`[Ddu64 normalizeCharSet] At least 2 unique characters required.`);
|
|
1106
|
-
}
|
|
1107
|
-
if (charSet.length === 0) {
|
|
1108
|
-
throw new Error(`[Ddu64 normalizeCharSet] Empty charset.`);
|
|
1109
|
-
}
|
|
1110
|
-
// 문자 길이 일관성 검증
|
|
1111
|
-
const charLength = charSet[0].length;
|
|
1112
|
-
const invalidChar = charSet.find((c) => c.length !== charLength);
|
|
1113
|
-
if (invalidChar) {
|
|
1114
|
-
if (shouldThrow) {
|
|
1115
|
-
throw new Error(`[Ddu64 normalizeCharSet] Inconsistent char length. Expected ${charLength}, found "${invalidChar}" (${invalidChar.length})`);
|
|
1116
|
-
}
|
|
1117
|
-
continue; // fallback으로 재시도
|
|
1118
|
-
}
|
|
1119
|
-
// 패딩 검증
|
|
1120
|
-
if (state.padding.length !== charLength) {
|
|
1121
|
-
throw new Error(`[Ddu64 normalizeCharSet] Padding length mismatch. Expected ${charLength}, got ${state.padding.length}`);
|
|
1122
|
-
}
|
|
1123
|
-
if (charSet.includes(state.padding)) {
|
|
1124
|
-
if (shouldThrow) {
|
|
1125
|
-
throw new Error(`[Ddu64 normalizeCharSet] Padding character "${state.padding}" conflicts with charset.`);
|
|
1126
|
-
}
|
|
1127
|
-
charSet = charSet.filter((c) => c !== state.padding);
|
|
1128
|
-
}
|
|
1129
|
-
// 불필요한 배열 복사 방지
|
|
1130
|
-
const finalSet = charSet.length === requiredLength
|
|
1131
|
-
? charSet
|
|
1132
|
-
: charSet.slice(0, requiredLength);
|
|
1133
|
-
return {
|
|
1134
|
-
charSet: finalSet,
|
|
1135
|
-
padding: state.padding,
|
|
1136
|
-
charLength,
|
|
1137
|
-
isPredefined: state.isPredefined,
|
|
1138
|
-
};
|
|
1139
|
-
}
|
|
1140
|
-
catch (e) {
|
|
1141
|
-
if (shouldThrow)
|
|
1142
|
-
throw e;
|
|
1143
|
-
// fallback 시도로 continue
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
// 최종 fallback (이론상 도달 불가, 방어 코드)
|
|
1147
|
-
const fallback = this.getFallbackCharSet(dduOptions);
|
|
1148
|
-
return {
|
|
1149
|
-
charSet: fallback.charSet.slice(0, fallback.requiredLength),
|
|
1150
|
-
padding: fallback.padding,
|
|
1151
|
-
charLength: fallback.charSet[0]?.length ?? 1,
|
|
1152
|
-
isPredefined: true,
|
|
1153
|
-
};
|
|
1154
|
-
}
|
|
1155
|
-
/**
|
|
1156
|
-
* 초기 charset을 결정합니다.
|
|
1157
|
-
*/
|
|
1158
|
-
resolveInitialCharSet(dduChar, paddingChar, dduOptions, shouldThrow) {
|
|
1159
|
-
const buildMeta = (set, padding, length, isPredefined) => {
|
|
1160
|
-
const usePow2 = this.shouldUsePowerOfTwo(length, dduOptions?.usePowerOfTwo);
|
|
1161
|
-
if (usePow2 && length > 0) {
|
|
1162
|
-
const exponent = this.getLargestPowerOfTwoExponent(length);
|
|
1163
|
-
const pow2Length = 1 << exponent;
|
|
1164
|
-
const selected = set.length === pow2Length ? set : set.slice(0, pow2Length);
|
|
1165
|
-
return {
|
|
1166
|
-
charSet: selected,
|
|
1167
|
-
padding,
|
|
1168
|
-
requiredLength: pow2Length,
|
|
1169
|
-
bitLength: exponent,
|
|
1170
|
-
isPredefined,
|
|
1171
|
-
};
|
|
1172
|
-
}
|
|
1173
|
-
const selected = set.length === length ? set : set.slice(0, length);
|
|
1174
|
-
return {
|
|
1175
|
-
charSet: selected,
|
|
1176
|
-
padding,
|
|
1177
|
-
requiredLength: length,
|
|
1178
|
-
bitLength: length > 0 ? this.getBitLength(length) : 0,
|
|
1179
|
-
isPredefined,
|
|
1180
|
-
};
|
|
1181
|
-
};
|
|
1182
|
-
try {
|
|
1183
|
-
const finalDduChar = dduChar ?? dduOptions?.dduChar;
|
|
1184
|
-
const finalPadding = paddingChar ?? dduOptions?.paddingChar;
|
|
1185
|
-
if (finalDduChar) {
|
|
1186
|
-
if (!finalPadding) {
|
|
1187
|
-
throw new Error(`[Ddu64 Constructor] paddingChar is required when dduChar is provided.`);
|
|
1188
|
-
}
|
|
1189
|
-
const arr = typeof finalDduChar === "string"
|
|
1190
|
-
? [...finalDduChar.trim()]
|
|
1191
|
-
: [...finalDduChar];
|
|
1192
|
-
if (shouldThrow) {
|
|
1193
|
-
const uniqueSize = new Set(arr).size;
|
|
1194
|
-
if (uniqueSize !== arr.length) {
|
|
1195
|
-
const duplicates = arr.filter((c, i) => arr.indexOf(c) !== i);
|
|
1196
|
-
throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters: [${[...new Set(duplicates)].join(", ")}]`);
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
const reqLen = dduOptions?.requiredLength ?? arr.length;
|
|
1200
|
-
if (arr.length < reqLen) {
|
|
1201
|
-
throw new Error(`[Ddu64 Constructor] Insufficient characters.`);
|
|
1202
|
-
}
|
|
1203
|
-
return buildMeta(arr, finalPadding, reqLen, false);
|
|
1204
|
-
}
|
|
1205
|
-
const symbol = dduOptions?.dduSetSymbol ??
|
|
1206
|
-
types_1.dduDefaultConstructorOptions.dduSetSymbol ??
|
|
1207
|
-
types_1.DduSetSymbol.DDU;
|
|
1208
|
-
const cs = this.getCharSetOrThrow(symbol);
|
|
1209
|
-
return buildMeta(cs.charSet, cs.paddingChar, cs.maxRequiredLength, true);
|
|
1210
|
-
}
|
|
1211
|
-
catch (error) {
|
|
1212
|
-
if (shouldThrow)
|
|
1213
|
-
throw error;
|
|
1214
|
-
return this.getFallbackCharSet(dduOptions);
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
/**
|
|
1218
|
-
* Fallback charset을 반환합니다.
|
|
1219
|
-
*/
|
|
1220
|
-
getFallbackCharSet(dduOptions) {
|
|
1221
|
-
const symbol = dduOptions?.dduSetSymbol ??
|
|
1222
|
-
types_1.dduDefaultConstructorOptions.dduSetSymbol ??
|
|
1223
|
-
types_1.DduSetSymbol.ONECHARSET;
|
|
1224
|
-
const cs = (0, charSets_1.getCharSet)(symbol) ?? (0, charSets_1.getCharSet)(types_1.DduSetSymbol.ONECHARSET);
|
|
1225
|
-
if (!cs)
|
|
1226
|
-
throw new Error(`Critical: No fallback CharSet available`);
|
|
1227
|
-
return {
|
|
1228
|
-
charSet: cs.charSet,
|
|
1229
|
-
padding: cs.paddingChar,
|
|
1230
|
-
requiredLength: cs.maxRequiredLength,
|
|
1231
|
-
bitLength: cs.bitLength,
|
|
1232
|
-
isPredefined: true,
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
/**
|
|
1236
|
-
* 2의 제곱수 사용 여부를 결정합니다.
|
|
1237
|
-
*/
|
|
1238
|
-
shouldUsePowerOfTwo(length, preference) {
|
|
1239
|
-
if (preference !== undefined)
|
|
1240
|
-
return preference ? length > 0 : false;
|
|
1241
|
-
return length > 0 && (length & (length - 1)) === 0;
|
|
1242
|
-
}
|
|
1243
|
-
/**
|
|
1244
|
-
* charset을 가져오거나 에러를 발생시킵니다.
|
|
1245
|
-
*/
|
|
1246
|
-
getCharSetOrThrow(symbol) {
|
|
1247
|
-
const cs = (0, charSets_1.getCharSet)(symbol);
|
|
1248
|
-
if (!cs)
|
|
1249
|
-
throw new Error(`CharSet with symbol ${symbol} not found`);
|
|
1250
|
-
return cs;
|
|
1251
|
-
}
|
|
1252
|
-
/**
|
|
1253
|
-
* URL-Safe 모드 시 charset/padding이 역변환 대상 문자를 포함하지 않는지 검증합니다.
|
|
1254
|
-
* 역변환 대상 문자("-", "_", ".")가 charset이나 padding에 있으면
|
|
1255
|
-
* fromUrlSafe 시 해당 문자가 "+", "/", "="로 변환되어 데이터가 손상됩니다.
|
|
1256
|
-
*
|
|
1257
|
-
* @returns URL-Safe 모드를 활성화해도 안전한 경우 true
|
|
1258
|
-
*/
|
|
1259
|
-
isUrlSafeCompatible(charSet, paddingChar, shouldThrow) {
|
|
1260
|
-
const conflictChars = Object.keys(URL_SAFE_REVERSE_MAP); // ["-", "_", "."]
|
|
1261
|
-
for (const ch of conflictChars) {
|
|
1262
|
-
for (const c of charSet) {
|
|
1263
|
-
if (c.includes(ch)) {
|
|
1264
|
-
const msg = `[Ddu64 Constructor] URL-Safe mode conflict: charset character "${c}" contains "${ch}" which would be transformed to "${URL_SAFE_REVERSE_MAP[ch]}" during decoding.`;
|
|
1265
|
-
if (shouldThrow)
|
|
1266
|
-
throw new Error(msg);
|
|
1267
|
-
return false;
|
|
1268
|
-
}
|
|
1269
|
-
}
|
|
1270
|
-
if (paddingChar.includes(ch)) {
|
|
1271
|
-
const msg = `[Ddu64 Constructor] URL-Safe mode conflict: padding character "${paddingChar}" contains "${ch}" which would be transformed to "${URL_SAFE_REVERSE_MAP[ch]}" during decoding.`;
|
|
1272
|
-
if (shouldThrow)
|
|
1273
|
-
throw new Error(msg);
|
|
1274
|
-
return false;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
return true;
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* 커스텀 charset의 조합 중복을 검증합니다.
|
|
1281
|
-
*/
|
|
1282
|
-
validateCombinationDuplicates(charSet, paddingChar, requiredLength) {
|
|
1283
|
-
if (charSet[0].length !== 1 || requiredLength > 256)
|
|
1284
|
-
return;
|
|
1285
|
-
const limit = Math.min(charSet.length, requiredLength);
|
|
1286
|
-
const targetChars = charSet.slice(0, limit);
|
|
1287
|
-
const combinations = new Set();
|
|
1288
|
-
const add = (s, context) => {
|
|
1289
|
-
if (combinations.has(s))
|
|
1290
|
-
throw new Error(`Combination conflict: ${context}`);
|
|
1291
|
-
combinations.add(s);
|
|
1292
|
-
};
|
|
1293
|
-
for (let i = 0; i < targetChars.length; i++) {
|
|
1294
|
-
combinations.add(targetChars[i]);
|
|
1295
|
-
}
|
|
1296
|
-
combinations.add(paddingChar);
|
|
1297
|
-
for (let i = 0; i < targetChars.length; i++) {
|
|
1298
|
-
const c1 = targetChars[i];
|
|
1299
|
-
for (let j = 0; j < targetChars.length; j++) {
|
|
1300
|
-
add(c1 + targetChars[j], `"${c1}" + "${targetChars[j]}"`);
|
|
1301
|
-
}
|
|
1302
|
-
add(c1 + paddingChar, `"${c1}" + padding`);
|
|
1303
|
-
add(paddingChar + c1, `padding + "${c1}"`);
|
|
1304
|
-
}
|
|
1305
|
-
add(paddingChar + paddingChar, "double padding");
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
exports.Ddu64 = Ddu64;
|