@catbee/utils 0.0.2 → 0.0.4
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 +1 -4
- package/build/esm/config.d.ts +1 -5
- package/build/esm/config.js +6 -10
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -19
- package/build/esm/index.js +20 -19
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +2 -2
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +1 -1
- package/build/esm/utils/array.utils.js +17 -27
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +1 -5
- package/build/esm/utils/async.utils.js +17 -20
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +2 -2
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +8 -8
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +2 -2
- package/build/esm/utils/crypto.utils.js +37 -45
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +2 -18
- package/build/esm/utils/decorators.utils.js +31 -31
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.d.ts +4 -4
- package/build/esm/utils/dir.utils.js +18 -20
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +22 -26
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +1 -1
- package/build/esm/utils/exception.utils.js +26 -29
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +3 -3
- package/build/esm/utils/fs.utils.js +19 -23
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +8 -8
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +13 -4
- package/build/esm/utils/logger.utils.js +16 -18
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +15 -26
- package/build/esm/utils/middleware.utils.js +80 -59
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.js +16 -27
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +2 -2
- package/build/esm/utils/response.utils.js +11 -11
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +17 -17
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +20 -22
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.js +11 -15
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +1 -5
- package/build/esnext/config.js +6 -10
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -19
- package/build/esnext/index.js +20 -19
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +2 -2
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +1 -1
- package/build/esnext/utils/array.utils.js +23 -31
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +1 -5
- package/build/esnext/utils/async.utils.js +22 -22
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +3 -3
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +10 -10
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +2 -2
- package/build/esnext/utils/crypto.utils.js +37 -47
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +2 -18
- package/build/esnext/utils/decorators.utils.js +33 -33
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.d.ts +4 -4
- package/build/esnext/utils/dir.utils.js +22 -24
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +24 -26
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +1 -1
- package/build/esnext/utils/exception.utils.js +26 -29
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +3 -3
- package/build/esnext/utils/fs.utils.js +21 -25
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +8 -8
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +13 -4
- package/build/esnext/utils/logger.utils.js +16 -18
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +15 -26
- package/build/esnext/utils/middleware.utils.js +78 -59
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.js +17 -26
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +2 -2
- package/build/esnext/utils/response.utils.js +11 -11
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +17 -17
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +21 -23
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.js +14 -16
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +1 -5
- package/build/src/config.js +5 -9
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -19
- package/build/src/index.js +1 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +2 -2
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +1 -1
- package/build/src/utils/array.utils.js +22 -30
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +1 -5
- package/build/src/utils/async.utils.js +22 -22
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +2 -2
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +9 -9
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +2 -2
- package/build/src/utils/crypto.utils.js +35 -45
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +2 -18
- package/build/src/utils/decorators.utils.js +32 -32
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.d.ts +4 -4
- package/build/src/utils/dir.utils.js +16 -18
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +22 -24
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +1 -1
- package/build/src/utils/exception.utils.js +23 -26
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +3 -3
- package/build/src/utils/fs.utils.js +15 -19
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +7 -7
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +13 -4
- package/build/src/utils/logger.utils.js +13 -15
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +15 -26
- package/build/src/utils/middleware.utils.js +72 -52
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.js +17 -26
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +2 -2
- package/build/src/utils/response.utils.js +9 -9
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +17 -17
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +20 -22
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.js +14 -16
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;AAqCA,oBAOC;AAUD,oBAMC;AASD,gCAEC;AASD,oBAKC;AASD,wBAKC;AAQD,kBAEC;AAOD,oCAEC;AAQD,kDAEC;AASD,kEAKC;AASD,wCAUC;AASD,kCA6BC;AAqDD,0BA+CC;AAUD,0BA2CC;AAUD,8CAsBC;AASD,8CA2BC;AApaD,mCAWgB;AAChB,+BAAiC;AAgBjC;;;;;;;;GAQG;AACH,SAAgB,IAAI,CAClB,SAAiB,EACjB,KAAa,EACb,MAAc,EACd,WAAiC,KAAK;IAEtC,OAAO,IAAA,mBAAU,EAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,IAAI,CAClB,SAAiB,EACjB,KAAa,EACb,WAAiC,KAAK;IAEtC,OAAO,IAAA,mBAAU,EAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,KAAa,EAAE,MAAc;IACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,IAAI,CAClB,KAAa,EACb,WAAiC,KAAK;IAEtC,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACvC,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CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes,\n} from \"crypto\";\nimport { promisify } from \"util\";\n\nexport type BufferEncoding =\n | \"ascii\"\n | \"utf8\"\n | \"utf-8\"\n | \"utf16le\"\n | \"utf-16le\"\n | \"ucs2\"\n | \"ucs-2\"\n | \"base64\"\n | \"base64url\"\n | \"latin1\"\n | \"binary\"\n | \"hex\";\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(\n algorithm: string,\n input: string,\n secret: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(\n algorithm: string,\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac(\"sha256\", input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return hash(\"sha1\", input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return hash(\"sha256\", input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash(\"md5\", input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(\n byteLength: number = 32,\n encoding: BinaryToTextEncoding = \"hex\",\n): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(\n prefix: string = \"\",\n byteLength: number = 24,\n): string {\n const randomString = generateRandomBytesAsString(byteLength, \"base64\");\n const key = randomString\n .replace(/[+/=]/g, \"\") // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(\n a: string | Buffer | Uint8Array,\n b: string | Buffer | Uint8Array,\n): boolean {\n if (typeof a === \"string\" && typeof b === \"string\") {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if (\n (a instanceof Buffer || a instanceof Uint8Array) &&\n (b instanceof Buffer || b instanceof Uint8Array)\n ) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(\n a instanceof Buffer ? a : Buffer.from(a),\n b instanceof Buffer ? b : Buffer.from(b),\n );\n }\n\n throw new Error(\n \"Cannot compare: inputs must be strings, Buffers, or Uint8Arrays\",\n );\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(\n scrypt,\n);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {},\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || \"aes-256-gcm\";\n const inputEncoding = options.inputEncoding || \"utf8\";\n const outputEncoding = options.outputEncoding || \"hex\";\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey =\n typeof key === \"string\" ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === \"string\") {\n ciphertext = cipher.update(\n data,\n inputEncoding,\n outputEncoding as BufferEncoding,\n );\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding\n ? encrypted.toString(outputEncoding)\n : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes(\"gcm\")\n ? (cipher as any).getAuthTag()\n : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm,\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {},\n): Promise<string | Buffer> {\n const algorithm =\n options.algorithm || encryptedData.algorithm || \"aes-256-gcm\";\n const inputEncoding = options.inputEncoding || \"hex\";\n const outputEncoding = options.outputEncoding || \"utf8\";\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey =\n typeof key === \"string\"\n ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32)\n : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes(\"gcm\")) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === \"string\") {\n decrypted = decipher.update(\n encryptedData.ciphertext,\n inputEncoding as BufferEncoding,\n outputEncoding,\n );\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([\n decipher.update(encryptedData.ciphertext),\n decipher.final(),\n ]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600,\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds,\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString(\"base64url\");\n\n // Create signature\n const signature = hmac(\"sha256\", base64Payload, secret, \"base64url\");\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(\n token: string,\n secret: string,\n): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split(\".\");\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac(\"sha256\", payloadB64, secret, \"base64url\");\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\");\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;AAqCA,oBAEC;AAUD,oBAEC;AASD,gCAEC;AASD,oBAEC;AASD,wBAEC;AAQD,kBAEC;AAOD,oCAEC;AAQD,kDAEC;AASD,kEAEC;AASD,wCAOC;AASD,kCAkBC;AAmDD,0BAsCC;AAUD,0BAgCC;AAUD,8CAsBC;AASD,8CAwBC;AA3WD,mCAWgB;AAChB,+BAAiC;AAgBjC;;;;;;;;GAQG;AACH,SAAgB,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,WAAiC,KAAK;IAC3G,OAAO,IAAA,mBAAU,EAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,WAAiC,KAAK;IAC3F,OAAO,IAAA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C,UAAU,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAE3C,mBAAmB;QACnB,MAAM,iBAAiB,GAAG,IAAI,CAAC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QAC1E,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
@@ -1,21 +1,5 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
query: any;
|
|
4
|
-
params: any;
|
|
5
|
-
body?: any;
|
|
6
|
-
[key: string]: any;
|
|
7
|
-
}
|
|
8
|
-
export interface Response {
|
|
9
|
-
json: (body: any) => void;
|
|
10
|
-
headersSent: boolean;
|
|
11
|
-
[key: string]: any;
|
|
12
|
-
}
|
|
13
|
-
export type NextFunction = (err?: any) => void;
|
|
14
|
-
export type RequestHandler = (req: Request, res: Response, next: NextFunction) => any;
|
|
15
|
-
export interface Router {
|
|
16
|
-
[method: string]: (path: string, ...handlers: RequestHandler[]) => void;
|
|
17
|
-
}
|
|
18
|
-
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete" | "options" | "head" | "trace" | "connect";
|
|
1
|
+
import type { RequestHandler, Router } from 'express';
|
|
2
|
+
import 'reflect-metadata';
|
|
19
3
|
export declare const Get: (path: string) => MethodDecorator;
|
|
20
4
|
export declare const Post: (path: string) => MethodDecorator;
|
|
21
5
|
export declare const Put: (path: string) => MethodDecorator;
|
|
@@ -11,9 +11,9 @@ exports.After = After;
|
|
|
11
11
|
exports.registerControllers = registerControllers;
|
|
12
12
|
require("reflect-metadata");
|
|
13
13
|
// --- End sample Express interfaces ---
|
|
14
|
-
const ROUTES_KEY = Symbol(
|
|
15
|
-
const MIDDLEWARE_KEY = Symbol(
|
|
16
|
-
const PARAMS_KEY = Symbol(
|
|
14
|
+
const ROUTES_KEY = Symbol('routes');
|
|
15
|
+
const MIDDLEWARE_KEY = Symbol('middlewares');
|
|
16
|
+
const PARAMS_KEY = Symbol('params');
|
|
17
17
|
// ---- Route Decorators ----
|
|
18
18
|
function createRouteDecorator(method) {
|
|
19
19
|
return (path) => {
|
|
@@ -22,25 +22,25 @@ function createRouteDecorator(method) {
|
|
|
22
22
|
routes.push({
|
|
23
23
|
path,
|
|
24
24
|
method,
|
|
25
|
-
handlerName: propertyKey
|
|
25
|
+
handlerName: propertyKey
|
|
26
26
|
});
|
|
27
27
|
Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
-
exports.Get = createRouteDecorator(
|
|
32
|
-
exports.Post = createRouteDecorator(
|
|
33
|
-
exports.Put = createRouteDecorator(
|
|
34
|
-
exports.Patch = createRouteDecorator(
|
|
35
|
-
exports.Delete = createRouteDecorator(
|
|
36
|
-
exports.Options = createRouteDecorator(
|
|
37
|
-
exports.Head = createRouteDecorator(
|
|
38
|
-
exports.Trace = createRouteDecorator(
|
|
39
|
-
exports.Connect = createRouteDecorator(
|
|
31
|
+
exports.Get = createRouteDecorator('get');
|
|
32
|
+
exports.Post = createRouteDecorator('post');
|
|
33
|
+
exports.Put = createRouteDecorator('put');
|
|
34
|
+
exports.Patch = createRouteDecorator('patch');
|
|
35
|
+
exports.Delete = createRouteDecorator('delete');
|
|
36
|
+
exports.Options = createRouteDecorator('options');
|
|
37
|
+
exports.Head = createRouteDecorator('head');
|
|
38
|
+
exports.Trace = createRouteDecorator('trace');
|
|
39
|
+
exports.Connect = createRouteDecorator('connect');
|
|
40
40
|
// ---- Controller Decorator ----
|
|
41
41
|
function Controller(basePath) {
|
|
42
|
-
return
|
|
43
|
-
Reflect.defineMetadata(
|
|
42
|
+
return target => {
|
|
43
|
+
Reflect.defineMetadata('basePath', basePath, target);
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
46
|
// ---- Middleware Decorator ----
|
|
@@ -62,20 +62,20 @@ function createParamDecorator(type, key) {
|
|
|
62
62
|
};
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
|
-
exports.Query = createParamDecorator(
|
|
66
|
-
exports.Param = createParamDecorator(
|
|
67
|
-
exports.Body = createParamDecorator(
|
|
68
|
-
exports.Req = createParamDecorator(
|
|
69
|
-
exports.Res = createParamDecorator(
|
|
65
|
+
exports.Query = createParamDecorator('query');
|
|
66
|
+
exports.Param = createParamDecorator('param');
|
|
67
|
+
exports.Body = createParamDecorator('body');
|
|
68
|
+
exports.Req = createParamDecorator('req');
|
|
69
|
+
exports.Res = createParamDecorator('res');
|
|
70
70
|
// Custom HTTP status code decorator
|
|
71
|
-
const HTTP_CODE_KEY = Symbol(
|
|
71
|
+
const HTTP_CODE_KEY = Symbol('httpCode');
|
|
72
72
|
function HttpCode(status) {
|
|
73
73
|
return (target, propertyKey, descriptor) => {
|
|
74
74
|
Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
// Custom header decorator
|
|
78
|
-
const HEADER_KEY = Symbol(
|
|
78
|
+
const HEADER_KEY = Symbol('headers');
|
|
79
79
|
function Header(name, value) {
|
|
80
80
|
return (target, propertyKey, descriptor) => {
|
|
81
81
|
const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
|
|
@@ -84,8 +84,8 @@ function Header(name, value) {
|
|
|
84
84
|
};
|
|
85
85
|
}
|
|
86
86
|
// Before/After hooks (not Express middleware, but can be used for logging, etc.)
|
|
87
|
-
const BEFORE_KEY = Symbol(
|
|
88
|
-
const AFTER_KEY = Symbol(
|
|
87
|
+
const BEFORE_KEY = Symbol('before');
|
|
88
|
+
const AFTER_KEY = Symbol('after');
|
|
89
89
|
function Before(fn) {
|
|
90
90
|
return (target, propertyKey, descriptor) => {
|
|
91
91
|
const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
|
|
@@ -102,9 +102,9 @@ function After(fn) {
|
|
|
102
102
|
}
|
|
103
103
|
// ---- Register Controllers ----
|
|
104
104
|
function registerControllers(router, controllers) {
|
|
105
|
-
controllers.forEach(
|
|
105
|
+
controllers.forEach(ControllerClass => {
|
|
106
106
|
const instance = new ControllerClass();
|
|
107
|
-
const basePath = Reflect.getMetadata(
|
|
107
|
+
const basePath = Reflect.getMetadata('basePath', ControllerClass) || '';
|
|
108
108
|
const routes = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];
|
|
109
109
|
routes.forEach(({ path, method, handlerName }) => {
|
|
110
110
|
const middlewares = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];
|
|
@@ -123,19 +123,19 @@ function registerControllers(router, controllers) {
|
|
|
123
123
|
params.forEach(({ index, type, key }) => {
|
|
124
124
|
var _a;
|
|
125
125
|
switch (type) {
|
|
126
|
-
case
|
|
126
|
+
case 'query':
|
|
127
127
|
args[index] = key ? req.query[key] : req.query;
|
|
128
128
|
break;
|
|
129
|
-
case
|
|
129
|
+
case 'param':
|
|
130
130
|
args[index] = key ? req.params[key] : req.params;
|
|
131
131
|
break;
|
|
132
|
-
case
|
|
132
|
+
case 'body':
|
|
133
133
|
args[index] = key ? (_a = req.body) === null || _a === void 0 ? void 0 : _a[key] : req.body;
|
|
134
134
|
break;
|
|
135
|
-
case
|
|
135
|
+
case 'req':
|
|
136
136
|
args[index] = req;
|
|
137
137
|
break;
|
|
138
|
-
case
|
|
138
|
+
case 'res':
|
|
139
139
|
args[index] = res;
|
|
140
140
|
break;
|
|
141
141
|
}
|
|
@@ -144,7 +144,7 @@ function registerControllers(router, controllers) {
|
|
|
144
144
|
const result = instance[handlerName](...args);
|
|
145
145
|
// Support both sync and async handlers
|
|
146
146
|
const awaited = result instanceof Promise ? await result : result;
|
|
147
|
-
if (!res.headersSent && typeof awaited !==
|
|
147
|
+
if (!res.headersSent && typeof awaited !== 'undefined') {
|
|
148
148
|
if (httpCode)
|
|
149
149
|
(_a = res.status) === null || _a === void 0 ? void 0 : _a.call(res, httpCode);
|
|
150
150
|
for (const [k, v] of Object.entries(headers))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AAiFtD,gCAIC;AAGD,kBAWC;AAwBD,4BASC;AAID,wBAOC;AAKD,wBAOC;AACD,sBAOC;AAGD,kDAoEC;AAxOD,4BAA0B;AAuB1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAyBpC,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GACV,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC5D,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI;gBACJ,MAAM;gBACN,WAAW,EAAE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;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport \"reflect-metadata\";\n\n// --- Sample Express interfaces for type safety ---\nexport interface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\nexport interface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\nexport type NextFunction = (err?: any) => void;\nexport type RequestHandler = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => any;\nexport interface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol(\"routes\");\nconst MIDDLEWARE_KEY = Symbol(\"middlewares\");\nconst PARAMS_KEY = Symbol(\"params\");\n\nexport type HttpMethod =\n | \"get\"\n | \"post\"\n | \"put\"\n | \"patch\"\n | \"delete\"\n | \"options\"\n | \"head\"\n | \"trace\"\n | \"connect\";\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: \"query\" | \"param\" | \"body\" | \"req\" | \"res\";\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] =\n Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string,\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator(\"get\");\nexport const Post = createRouteDecorator(\"post\");\nexport const Put = createRouteDecorator(\"put\");\nexport const Patch = createRouteDecorator(\"patch\");\nexport const Delete = createRouteDecorator(\"delete\");\nexport const Options = createRouteDecorator(\"options\");\nexport const Head = createRouteDecorator(\"head\");\nexport const Trace = createRouteDecorator(\"trace\");\nexport const Connect = createRouteDecorator(\"connect\");\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(\"basePath\", basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] =\n Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(\n MIDDLEWARE_KEY,\n [...existing, ...middlewares],\n target,\n propertyKey as string,\n );\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition[\"type\"], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] =\n Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator(\"query\");\nexport const Param = createParamDecorator(\"param\");\nexport const Body = createParamDecorator(\"body\");\nexport const Req = createParamDecorator(\"req\");\nexport const Res = createParamDecorator(\"res\");\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol(\"httpCode\");\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(\n HTTP_CODE_KEY,\n status,\n target,\n propertyKey as string,\n );\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol(\"headers\");\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> =\n Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol(\"before\");\nconst AFTER_KEY = Symbol(\"after\");\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] =\n Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] =\n Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach((ControllerClass) => {\n const instance = new ControllerClass();\n const basePath: string =\n Reflect.getMetadata(\"basePath\", ControllerClass) || \"\";\n const routes: RouteDefinition[] =\n Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] =\n Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] =\n Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(\n HTTP_CODE_KEY,\n instance,\n handlerName,\n );\n const headers: Record<string, string> =\n Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] =\n Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] =\n Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case \"query\":\n args[index] = key ? req.query[key] : req.query;\n break;\n case \"param\":\n args[index] = key ? req.params[key] : req.params;\n break;\n case \"body\":\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case \"req\":\n args[index] = req;\n break;\n case \"res\":\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== \"undefined\") {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AAmDtD,gCAIC;AAGD,kBAKC;AAuBD,4BAIC;AAID,wBAMC;AAKD,wBAMC;AACD,sBAMC;AAGD,kDAyDC;AA/KD,4BAA0B;AAE1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,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AAC;oCAClB,MAAM;gCACR,KAAK,KAAK;oCACR,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;oCAClB,MAAM;4BACV,CAAC;wBACH,CAAC,CAAC,CAAC;oBACL,CAAC;oBACD,MAAM,MAAM,GAAI,QAAgB,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;oBACvD,uCAAuC;oBACvC,MAAM,OAAO,GAAG,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;oBAClE,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\n\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import fs from
|
|
1
|
+
import fs from 'fs';
|
|
2
2
|
/**
|
|
3
3
|
* Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).
|
|
4
4
|
*
|
|
@@ -72,7 +72,7 @@ export declare function getDirSize(dirPath: string): Promise<number>;
|
|
|
72
72
|
* @param {(eventType: "rename" | "change", filename: string | null) => void} callback - Callback for each change event.
|
|
73
73
|
* @returns {() => void} A function to stop watching the directory.
|
|
74
74
|
*/
|
|
75
|
-
export declare function watchDir(dirPath: string, callback: (eventType:
|
|
75
|
+
export declare function watchDir(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string | null) => void): () => void;
|
|
76
76
|
/**
|
|
77
77
|
* Finds files matching a glob pattern.
|
|
78
78
|
*
|
|
@@ -161,7 +161,7 @@ export declare function findInDir(dirPath: string, predicate: (path: string, sta
|
|
|
161
161
|
* @returns {Promise<() => void>} A function to stop watching the directory.
|
|
162
162
|
* @throws {Error} If directory cannot be watched.
|
|
163
163
|
*/
|
|
164
|
-
export declare function watchDirRecursive(dirPath: string, callback: (eventType:
|
|
164
|
+
export declare function watchDirRecursive(dirPath: string, callback: (eventType: 'rename' | 'change', filename: string) => void, includeSubdirs?: boolean): Promise<() => void>;
|
|
165
165
|
/**
|
|
166
166
|
* Gets detailed directory statistics including file count, directory count, and size.
|
|
167
167
|
*
|
|
@@ -191,6 +191,6 @@ export declare function walkDir(dirPath: string, options: {
|
|
|
191
191
|
isDirectory: boolean;
|
|
192
192
|
stats: fs.Stats;
|
|
193
193
|
}) => boolean | void | Promise<boolean | void>;
|
|
194
|
-
traversalOrder?:
|
|
194
|
+
traversalOrder?: 'pre' | 'post';
|
|
195
195
|
}): Promise<void>;
|
|
196
196
|
//# sourceMappingURL=dir.utils.d.ts.map
|
|
@@ -199,11 +199,9 @@ async function findFilesByPattern(pattern, options = {}) {
|
|
|
199
199
|
*/
|
|
200
200
|
async function getSubdirectories(dirPath, recursive = false) {
|
|
201
201
|
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
202
|
-
const dirs = entries
|
|
203
|
-
.filter((entry) => entry.isDirectory())
|
|
204
|
-
.map((entry) => path_1.default.join(dirPath, entry.name));
|
|
202
|
+
const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path_1.default.join(dirPath, entry.name));
|
|
205
203
|
if (recursive && dirs.length > 0) {
|
|
206
|
-
const nestedDirs = await Promise.all(dirs.map(
|
|
204
|
+
const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));
|
|
207
205
|
return [...dirs, ...nestedDirs.flat()];
|
|
208
206
|
}
|
|
209
207
|
return dirs;
|
|
@@ -225,7 +223,7 @@ async function ensureEmptyDir(dirPath) {
|
|
|
225
223
|
}
|
|
226
224
|
catch (error) {
|
|
227
225
|
// Ignore if file doesn't exist
|
|
228
|
-
if (error.code !==
|
|
226
|
+
if (error.code !== 'ENOENT') {
|
|
229
227
|
throw error;
|
|
230
228
|
}
|
|
231
229
|
}
|
|
@@ -243,9 +241,9 @@ async function ensureEmptyDir(dirPath) {
|
|
|
243
241
|
* @throws {Error} If directory cannot be created.
|
|
244
242
|
*/
|
|
245
243
|
async function createTempDir(options = {}) {
|
|
246
|
-
const prefix = options.prefix ||
|
|
244
|
+
const prefix = options.prefix || 'tmp-';
|
|
247
245
|
const parentDir = options.parentDir || os_1.default.tmpdir();
|
|
248
|
-
const dirName = `${prefix}${(0, crypto_1.randomBytes)(6).toString(
|
|
246
|
+
const dirName = `${prefix}${(0, crypto_1.randomBytes)(6).toString('hex')}`;
|
|
249
247
|
const tempDirPath = path_1.default.join(parentDir, dirName);
|
|
250
248
|
await ensureDir(tempDirPath);
|
|
251
249
|
const cleanup = async () => {
|
|
@@ -257,7 +255,7 @@ async function createTempDir(options = {}) {
|
|
|
257
255
|
}
|
|
258
256
|
};
|
|
259
257
|
if (options.cleanup) {
|
|
260
|
-
process.once(
|
|
258
|
+
process.once('exit', () => {
|
|
261
259
|
try {
|
|
262
260
|
fs_1.default.rmSync(tempDirPath, { recursive: true, force: true });
|
|
263
261
|
}
|
|
@@ -266,7 +264,7 @@ async function createTempDir(options = {}) {
|
|
|
266
264
|
}
|
|
267
265
|
});
|
|
268
266
|
// Handle signals for better cleanup
|
|
269
|
-
[
|
|
267
|
+
['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {
|
|
270
268
|
process.once(signal, () => {
|
|
271
269
|
cleanup().then(() => process.exit());
|
|
272
270
|
});
|
|
@@ -288,7 +286,7 @@ async function findNewestFile(dirPath, recursive = false) {
|
|
|
288
286
|
return null;
|
|
289
287
|
const stats = await Promise.all(files.map(async (file) => ({
|
|
290
288
|
path: file,
|
|
291
|
-
mtime: (await promises_1.default.stat(file)).mtime
|
|
289
|
+
mtime: (await promises_1.default.stat(file)).mtime
|
|
292
290
|
})));
|
|
293
291
|
return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;
|
|
294
292
|
}
|
|
@@ -306,7 +304,7 @@ async function findOldestFile(dirPath, recursive = false) {
|
|
|
306
304
|
return null;
|
|
307
305
|
const stats = await Promise.all(files.map(async (file) => ({
|
|
308
306
|
path: file,
|
|
309
|
-
mtime: (await promises_1.default.stat(file)).mtime
|
|
307
|
+
mtime: (await promises_1.default.stat(file)).mtime
|
|
310
308
|
})));
|
|
311
309
|
return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;
|
|
312
310
|
}
|
|
@@ -360,7 +358,7 @@ async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
|
|
|
360
358
|
const relativePath = path_1.default.relative(normalizedBasePath, fullPath);
|
|
361
359
|
callback(eventType, relativePath);
|
|
362
360
|
// If a new directory is created, we should watch it
|
|
363
|
-
if (eventType ===
|
|
361
|
+
if (eventType === 'rename' && includeSubdirs) {
|
|
364
362
|
setTimeout(async () => {
|
|
365
363
|
try {
|
|
366
364
|
if (await isDirectory(fullPath)) {
|
|
@@ -390,7 +388,7 @@ async function watchDirRecursive(dirPath, callback, includeSubdirs = true) {
|
|
|
390
388
|
}
|
|
391
389
|
// Return a function to close all watchers
|
|
392
390
|
return () => {
|
|
393
|
-
watchers.forEach(
|
|
391
|
+
watchers.forEach(watcher => watcher.close());
|
|
394
392
|
};
|
|
395
393
|
}
|
|
396
394
|
/**
|
|
@@ -433,7 +431,7 @@ async function getDirStats(dirPath) {
|
|
|
433
431
|
* @throws {Error} If directory cannot be read.
|
|
434
432
|
*/
|
|
435
433
|
async function walkDir(dirPath, options) {
|
|
436
|
-
const traversalOrder = options.traversalOrder ||
|
|
434
|
+
const traversalOrder = options.traversalOrder || 'pre';
|
|
437
435
|
const entries = await promises_1.default.readdir(dirPath, { withFileTypes: true });
|
|
438
436
|
for (const entry of entries) {
|
|
439
437
|
const entryPath = path_1.default.join(dirPath, entry.name);
|
|
@@ -442,11 +440,11 @@ async function walkDir(dirPath, options) {
|
|
|
442
440
|
path: entryPath,
|
|
443
441
|
name: entry.name,
|
|
444
442
|
isDirectory: entry.isDirectory(),
|
|
445
|
-
stats
|
|
443
|
+
stats
|
|
446
444
|
};
|
|
447
445
|
if (entry.isDirectory()) {
|
|
448
446
|
// Pre-order: visit directory before its contents
|
|
449
|
-
if (traversalOrder ===
|
|
447
|
+
if (traversalOrder === 'pre') {
|
|
450
448
|
const shouldContinue = await options.visitorFn(entryInfo);
|
|
451
449
|
// If the visitor returns false, don't recurse into this directory
|
|
452
450
|
if (shouldContinue !== false) {
|
|
@@ -464,7 +462,7 @@ async function walkDir(dirPath, options) {
|
|
|
464
462
|
await options.visitorFn(entryInfo);
|
|
465
463
|
}
|
|
466
464
|
}
|
|
467
|
-
if (traversalOrder ===
|
|
465
|
+
if (traversalOrder === 'post') {
|
|
468
466
|
// Only visit the root if this is the top-level call (not for subdirectories)
|
|
469
467
|
// But since this function is always called recursively, always visit after children
|
|
470
468
|
const stats = await promises_1.default.stat(dirPath);
|
|
@@ -472,7 +470,7 @@ async function walkDir(dirPath, options) {
|
|
|
472
470
|
path: dirPath,
|
|
473
471
|
name: path_1.default.basename(dirPath),
|
|
474
472
|
isDirectory: true,
|
|
475
|
-
stats
|
|
473
|
+
stats
|
|
476
474
|
};
|
|
477
475
|
await options.visitorFn(entryInfo);
|
|
478
476
|
}
|