code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); },
Initializes a newly created hasher. @param {Object} cfg (Optional) The configuration options to use for this hash computation. @example var hasher = CryptoJS.algo.SHA256.create();
init ( cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); },
Resets this hasher to its initial state. @example hasher.reset();
reset ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; },
Updates this hasher with a message. @param {WordArray|string} messageUpdate The message to append. @return {Hasher} This hasher. @example hasher.update('message'); hasher.update(wordArray);
update ( messageUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; },
Finalizes the hash computation. Note that the finalize operation is effectively a destructive, read-once operation. @param {WordArray|string} messageUpdate (Optional) A final message update. @return {WordArray} The hash. @example var hash = hasher.finalize(); var hash = hasher.finalize('message'); var hash = hasher.finalize(wordArray);
finalize ( messageUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; },
Creates a shortcut function to a hasher's object interface. @param {Hasher} hasher The hasher to create a helper for. @return {Function} The shortcut function. @static @example var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
_createHelper ( hasher )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
_createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; }
Creates a shortcut function to the HMAC's object interface. @param {Hasher} hasher The hasher to use in this HMAC helper. @return {Function} The shortcut function. @static @example var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
_createHmacHelper ( hasher )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); },
Converts a word array to a Base64 string. @param {WordArray} wordArray The word array. @return {string} The Base64 string. @static @example var base64String = CryptoJS.enc.Base64.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map.length; j++) { reverseMap[map.charCodeAt(j)] = j; } } // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } // Convert return parseLoop(base64Str, base64StrLength, reverseMap); },
Converts a Base64 string to a word array. @param {string} base64Str The Base64 string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Base64.parse(base64String);
parse ( base64Str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); },
Converts a word array to a UTF-16 BE string. @param {WordArray} wordArray The word array. @return {string} The UTF-16 BE string. @static @example var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); }
Converts a UTF-16 BE string to a word array. @param {string} utf16Str The UTF-16 BE string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
parse ( utf16Str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); },
Converts a word array to a UTF-16 LE string. @param {WordArray} wordArray The word array. @return {string} The UTF-16 LE string. @static @example var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
stringify ( wordArray )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); }
Converts a UTF-16 LE string to a word array. @param {string} utf16Str The UTF-16 LE string. @return {WordArray} The word array. @static @example var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
parse ( utf16Str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (cfg) { this.cfg = this.cfg.extend(cfg); },
Initializes a newly created key derivation function. @param {Object} cfg (Optional) The configuration options to use for the derivation. @example var kdf = CryptoJS.algo.EvpKDF.create(); var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
init ( cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; }
Derives a key from a password. @param {WordArray|string} password The password. @param {WordArray|string} salt A salt. @return {WordArray} The derived key. @example var key = kdf.compute(password, salt);
compute ( password , salt )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); };
Derives a key from a password. @param {WordArray|string} password The password. @param {WordArray|string} salt A salt. @param {Object} cfg (Optional) The configuration options to use for this computation. @return {WordArray} The derived key. @static @example var key = CryptoJS.EvpKDF(password, salt); var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
C.EvpKDF ( password , salt , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }());
Configuration options. @property {number} keySize The key size in words to generate. Default: 4 (128 bits) @property {Hasher} hasher The hash algorithm to use. Default: MD5 @property {number} iterations The number of iterations to perform. Default: 1
Base.extend ( { keySize : 128 / 32 , hasher : MD5 , iterations : 1 } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); },
Converts the ciphertext of a cipher params object to a hexadecimally encoded string. @param {CipherParams} cipherParams The cipher params object. @return {string} The hexadecimally encoded string. @static @example var hexString = CryptoJS.format.Hex.stringify(cipherParams);
stringify ( cipherParams )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); }
Converts a hexadecimally encoded ciphertext string to a cipher params object. @param {string} input The hexadecimally encoded string. @return {CipherParams} The cipher params object. @static @example var cipherParams = CryptoJS.format.Hex.parse(hexString);
parse ( input )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); },
Initializes a newly created HMAC. @param {Hasher} hasher The hash algorithm to use. @param {WordArray|string} key The secret key. @example var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
init ( hasher , key )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); },
Resets this HMAC to its initial state. @example hmacHasher.reset();
reset ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; },
Updates this HMAC with a message. @param {WordArray|string} messageUpdate The message to append. @return {HMAC} This HMAC instance. @example hmacHasher.update('message'); hmacHasher.update(wordArray);
update ( messageUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; }
Finalizes the HMAC computation. Note that the finalize operation is effectively a destructive, read-once operation. @param {WordArray|string} messageUpdate (Optional) A final message update. @return {WordArray} The HMAC. @example var hmac = hmacHasher.finalize(); var hmac = hmacHasher.finalize('message'); var hmac = hmacHasher.finalize(wordArray);
finalize ( messageUpdate )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } if (this._mode && this._mode.__creator == modeCreator) { this._mode.init(this, iv && iv.words); } else { this._mode = modeCreator.call(mode, this, iv && iv.words); this._mode.__creator = modeCreator; } }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":195,"./evpkdf":198}],195:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /* * Local polyfil of Object.create */ var create = Object.create || (function () { function F() {}; return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()) /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],196:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map.length; j++) { reverseMap[map.charCodeAt(j)] = j; } } // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } // Convert return parseLoop(base64Str, base64StrLength, reverseMap); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); } }()); return CryptoJS.enc.Base64; })); },{"./core":195}],197:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":195}],198:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":195,"./hmac":200,"./sha1":219}],199:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core"), require("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":194,"./core":195}],200:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(require("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); }));
Configuration options. @property {WordArray} iv The IV to use for this operation.
Base.extend ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }());
@preserve Counter block mode compatible with Dr Brian Gladman fileenc.c derived from CryptoJS.mode.CTR Jan Hruby [email protected]
(anonymous) ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; }
Computes the Password-Based Key Derivation Function 2. @param {WordArray|string} password The password. @param {WordArray|string} salt A salt. @return {WordArray} The derived key. @example var key = kdf.compute(password, salt);
compute ( password , salt )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); };
Computes the Password-Based Key Derivation Function 2. @param {WordArray|string} password The password. @param {WordArray|string} salt A salt. @param {Object} cfg (Optional) The configuration options to use for this computation. @return {WordArray} The derived key. @static @example var key = CryptoJS.PBKDF2(password, salt); var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
C.PBKDF2 ( password , salt , cfg )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }());
Configuration options. @property {number} keySize The key size in words to generate. Default: 4 (128 bits) @property {Hasher} hasher The hasher to use. Default: SHA1 @property {number} iterations The number of iterations to perform. Default: 1
Base.extend ( { keySize : 128 / 32 , hasher : SHA1 , iterations : 1 } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }());
Configuration options. @property {number} drop The number of keystream words to drop. Default 192
RC4.cfg.extend ( { drop : 192 } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math));
Configuration options. @property {number} outputLength The desired number of bits in the output hash. Only values permitted are: 224, 256, 384, 512. Default: 512
Hasher.cfg.extend ( { outputLength : 512 } )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (high, low) { this.high = high; this.low = low; }
Initializes a newly created 64-bit word. @param {number} high The high 32 bits. @param {number} low The low 32 bits. @example var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
init ( high , low )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } },
Initializes a newly created word array. @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. @param {number} sigBytes (Optional) The number of significant bytes in the words. @example var wordArray = CryptoJS.x64.WordArray.create(); var wordArray = CryptoJS.x64.WordArray.create([ CryptoJS.x64.Word.create(0x00010203, 0x04050607), CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) ]); var wordArray = CryptoJS.x64.WordArray.create([ CryptoJS.x64.Word.create(0x00010203, 0x04050607), CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) ], 10);
init ( words , sigBytes )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); },
Converts this 64-bit word array to a 32-bit word array. @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. @example var x32WordArray = x64WordArray.toX32();
toX32 ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; }
Creates a copy of this word array. @return {X64WordArray} The clone. @example var clone = x64WordArray.clone();
clone ( )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
match(str) { var self = this; return { *[Symbol.iterator]() { var state = INITIAL_STATE; var startRun = null; var lastAccepting = null; var lastState = null; for (var p = 0; p < str.length; p++) { var c = str[p]; lastState = state; state = self.stateTable[state][c]; if (state === FAIL_STATE) { // yield the last match if any if (startRun != null && lastAccepting != null && lastAccepting >= startRun) { yield [startRun, lastAccepting, self.tags[lastState]]; } // reset the state as if we started over from the initial state state = self.stateTable[INITIAL_STATE][c]; startRun = null; } // start a run if not in the failure state if (state !== FAIL_STATE && startRun == null) { startRun = p; } // if accepting, mark the potential match end if (self.accepting[state]) { lastAccepting = p; } // reset the state to the initial state if we get into the failure state if (state === FAIL_STATE) { state = INITIAL_STATE; } } // yield the last match if any if (startRun != null && lastAccepting != null && lastAccepting >= startRun) { yield [startRun, lastAccepting, self.tags[state]]; } } }; }
Returns an iterable object that yields pattern matches over the input sequence. Matches are of the form [startIndex, endIndex, tags].
match ( str )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
apply(str, actions) { for (var [start, end, tags] of this.match(str)) { for (var tag of tags) { if (typeof actions[tag] === 'function') { actions[tag](start, end, str.slice(start, end + 1)); } } } }
For each match over the input sequence, action functions matching the tag definitions in the input pattern are called with the startIndex, endIndex, and sub-match sequence.
apply ( str , actions )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
const bidirectional_l = [0x0041, 0x005a, 0x0061, 0x007a, 0x00aa, 0x00aa, 0x00b5, 0x00b5, 0x00ba, 0x00ba, 0x00c0, 0x00d6, 0x00d8, 0x00f6, 0x00f8, 0x0220, 0x0222, 0x0233, 0x0250, 0x02ad, 0x02b0, 0x02b8, 0x02bb, 0x02c1, 0x02d0, 0x02d1, 0x02e0, 0x02e4, 0x02ee, 0x02ee, 0x037a, 0x037a, 0x0386, 0x0386, 0x0388, 0x038a, 0x038c, 0x038c, 0x038e, 0x03a1, 0x03a3, 0x03ce, 0x03d0, 0x03f5, 0x0400, 0x0482, 0x048a, 0x04ce, 0x04d0, 0x04f5, 0x04f8, 0x04f9, 0x0500, 0x050f, 0x0531, 0x0556, 0x0559, 0x055f, 0x0561, 0x0587, 0x0589, 0x0589, 0x0903, 0x0903, 0x0905, 0x0939, 0x093d, 0x0940, 0x0949, 0x094c, 0x0950, 0x0950, 0x0958, 0x0961, 0x0964, 0x0970, 0x0982, 0x0983, 0x0985, 0x098c, 0x098f, 0x0990, 0x0993, 0x09a8, 0x09aa, 0x09b0, 0x09b2, 0x09b2, 0x09b6, 0x09b9, 0x09be, 0x09c0, 0x09c7, 0x09c8, 0x09cb, 0x09cc, 0x09d7, 0x09d7, 0x09dc, 0x09dd, 0x09df, 0x09e1, 0x09e6, 0x09f1, 0x09f4, 0x09fa, 0x0a05, 0x0a0a, 0x0a0f, 0x0a10, 0x0a13, 0x0a28, 0x0a2a, 0x0a30, 0x0a32, 0x0a33, 0x0a35, 0x0a36, 0x0a38, 0x0a39, 0x0a3e, 0x0a40, 0x0a59, 0x0a5c, 0x0a5e, 0x0a5e, 0x0a66, 0x0a6f, 0x0a72, 0x0a74, 0x0a83, 0x0a83, 0x0a85, 0x0a8b, 0x0a8d, 0x0a8d, 0x0a8f, 0x0a91, 0x0a93, 0x0aa8, 0x0aaa, 0x0ab0, 0x0ab2, 0x0ab3, 0x0ab5, 0x0ab9, 0x0abd, 0x0ac0, 0x0ac9, 0x0ac9, 0x0acb, 0x0acc, 0x0ad0, 0x0ad0, 0x0ae0, 0x0ae0, 0x0ae6, 0x0aef, 0x0b02, 0x0b03, 0x0b05, 0x0b0c, 0x0b0f, 0x0b10, 0x0b13, 0x0b28, 0x0b2a, 0x0b30, 0x0b32, 0x0b33, 0x0b36, 0x0b39, 0x0b3d, 0x0b3e, 0x0b40, 0x0b40, 0x0b47, 0x0b48, 0x0b4b, 0x0b4c, 0x0b57, 0x0b57, 0x0b5c, 0x0b5d, 0x0b5f, 0x0b61, 0x0b66, 0x0b70, 0x0b83, 0x0b83, 0x0b85, 0x0b8a, 0x0b8e, 0x0b90, 0x0b92, 0x0b95, 0x0b99, 0x0b9a, 0x0b9c, 0x0b9c, 0x0b9e, 0x0b9f, 0x0ba3, 0x0ba4, 0x0ba8, 0x0baa, 0x0bae, 0x0bb5, 0x0bb7, 0x0bb9, 0x0bbe, 0x0bbf, 0x0bc1, 0x0bc2, 0x0bc6, 0x0bc8, 0x0bca, 0x0bcc, 0x0bd7, 0x0bd7, 0x0be7, 0x0bf2, 0x0c01, 0x0c03, 0x0c05, 0x0c0c, 0x0c0e, 0x0c10, 0x0c12, 0x0c28, 0x0c2a, 0x0c33, 0x0c35, 0x0c39, 0x0c41, 0x0c44, 0x0c60, 0x0c61, 0x0c66, 0x0c6f, 0x0c82, 0x0c83, 0x0c85, 0x0c8c, 0x0c8e, 0x0c90, 0x0c92, 0x0ca8, 0x0caa, 0x0cb3, 0x0cb5, 0x0cb9, 0x0cbe, 0x0cbe, 0x0cc0, 0x0cc4, 0x0cc7, 0x0cc8, 0x0cca, 0x0ccb, 0x0cd5, 0x0cd6, 0x0cde, 0x0cde, 0x0ce0, 0x0ce1, 0x0ce6, 0x0cef, 0x0d02, 0x0d03, 0x0d05, 0x0d0c, 0x0d0e, 0x0d10, 0x0d12, 0x0d28, 0x0d2a, 0x0d39, 0x0d3e, 0x0d40, 0x0d46, 0x0d48, 0x0d4a, 0x0d4c, 0x0d57, 0x0d57, 0x0d60, 0x0d61, 0x0d66, 0x0d6f, 0x0d82, 0x0d83, 0x0d85, 0x0d96, 0x0d9a, 0x0db1, 0x0db3, 0x0dbb, 0x0dbd, 0x0dbd, 0x0dc0, 0x0dc6, 0x0dcf, 0x0dd1, 0x0dd8, 0x0ddf, 0x0df2, 0x0df4, 0x0e01, 0x0e30, 0x0e32, 0x0e33, 0x0e40, 0x0e46, 0x0e4f, 0x0e5b, 0x0e81, 0x0e82, 0x0e84, 0x0e84, 0x0e87, 0x0e88, 0x0e8a, 0x0e8a, 0x0e8d, 0x0e8d, 0x0e94, 0x0e97, 0x0e99, 0x0e9f, 0x0ea1, 0x0ea3, 0x0ea5, 0x0ea5, 0x0ea7, 0x0ea7, 0x0eaa, 0x0eab, 0x0ead, 0x0eb0, 0x0eb2, 0x0eb3, 0x0ebd, 0x0ebd, 0x0ec0, 0x0ec4, 0x0ec6, 0x0ec6, 0x0ed0, 0x0ed9, 0x0edc, 0x0edd, 0x0f00, 0x0f17, 0x0f1a, 0x0f34, 0x0f36, 0x0f36, 0x0f38, 0x0f38, 0x0f3e, 0x0f47, 0x0f49, 0x0f6a, 0x0f7f, 0x0f7f, 0x0f85, 0x0f85, 0x0f88, 0x0f8b, 0x0fbe, 0x0fc5, 0x0fc7, 0x0fcc, 0x0fcf, 0x0fcf, 0x1000, 0x1021, 0x1023, 0x1027, 0x1029, 0x102a, 0x102c, 0x102c, 0x1031, 0x1031, 0x1038, 0x1038, 0x1040, 0x1057, 0x10a0, 0x10c5, 0x10d0, 0x10f8, 0x10fb, 0x10fb, 0x1100, 0x1159, 0x115f, 0x11a2, 0x11a8, 0x11f9, 0x1200, 0x1206, 0x1208, 0x1246, 0x1248, 0x1248, 0x124a, 0x124d, 0x1250, 0x1256, 0x1258, 0x1258, 0x125a, 0x125d, 0x1260, 0x1286, 0x1288, 0x1288, 0x128a, 0x128d, 0x1290, 0x12ae, 0x12b0, 0x12b0, 0x12b2, 0x12b5, 0x12b8, 0x12be, 0x12c0, 0x12c0, 0x12c2, 0x12c5, 0x12c8, 0x12ce, 0x12d0, 0x12d6, 0x12d8, 0x12ee, 0x12f0, 0x130e, 0x1310, 0x1310, 0x1312, 0x1315, 0x1318, 0x131e, 0x1320, 0x1346, 0x1348, 0x135a, 0x1361, 0x137c, 0x13a0, 0x13f4, 0x1401, 0x1676, 0x1681, 0x169a, 0x16a0, 0x16f0, 0x1700, 0x170c, 0x170e, 0x1711, 0x1720, 0x1731, 0x1735, 0x1736, 0x1740, 0x1751, 0x1760, 0x176c, 0x176e, 0x1770, 0x1780, 0x17b6, 0x17be, 0x17c5, 0x17c7, 0x17c8, 0x17d4, 0x17da, 0x17dc, 0x17dc, 0x17e0, 0x17e9, 0x1810, 0x1819, 0x1820, 0x1877, 0x1880, 0x18a8, 0x1e00, 0x1e9b, 0x1ea0, 0x1ef9, 0x1f00, 0x1f15, 0x1f18, 0x1f1d, 0x1f20, 0x1f45, 0x1f48, 0x1f4d, 0x1f50, 0x1f57, 0x1f59, 0x1f59, 0x1f5b, 0x1f5b, 0x1f5d, 0x1f5d, 0x1f5f, 0x1f7d, 0x1f80, 0x1fb4, 0x1fb6, 0x1fbc, 0x1fbe, 0x1fbe, 0x1fc2, 0x1fc4, 0x1fc6, 0x1fcc, 0x1fd0, 0x1fd3, 0x1fd6, 0x1fdb, 0x1fe0, 0x1fec, 0x1ff2, 0x1ff4, 0x1ff6, 0x1ffc, 0x200e, 0x200e, 0x2071, 0x2071, 0x207f, 0x207f, 0x2102, 0x2102, 0x2107, 0x2107, 0x210a, 0x2113, 0x2115, 0x2115, 0x2119, 0x211d, 0x2124, 0x2124, 0x2126, 0x2126, 0x2128, 0x2128, 0x212a, 0x212d, 0x212f, 0x2131, 0x2133, 0x2139, 0x213d, 0x213f, 0x2145, 0x2149, 0x2160, 0x2183, 0x2336, 0x237a, 0x2395, 0x2395, 0x249c, 0x24e9, 0x3005, 0x3007, 0x3021, 0x3029, 0x3031, 0x3035, 0x3038, 0x303c, 0x3041, 0x3096, 0x309d, 0x309f, 0x30a1, 0x30fa, 0x30fc, 0x30ff, 0x3105, 0x312c, 0x3131, 0x318e, 0x3190, 0x31b7, 0x31f0, 0x321c, 0x3220, 0x3243, 0x3260, 0x327b, 0x327f, 0x32b0, 0x32c0, 0x32cb, 0x32d0, 0x32fe, 0x3300, 0x3376, 0x337b, 0x33dd, 0x33e0, 0x33fe, 0x3400, 0x4db5, 0x4e00, 0x9fa5, 0xa000, 0xa48c, 0xac00, 0xd7a3, 0xd800, 0xfa2d, 0xfa30, 0xfa6a, 0xfb00, 0xfb06, 0xfb13, 0xfb17, 0xff21, 0xff3a, 0xff41, 0xff5a, 0xff66, 0xffbe, 0xffc2, 0xffc7, 0xffca, 0xffcf, 0xffd2, 0xffd7, 0xffda, 0xffdc, 0x10300, 0x1031e, 0x10320, 0x10323, 0x10330, 0x1034a, 0x10400, 0x10425, 0x10428, 0x1044d, 0x1d000, 0x1d0f5, 0x1d100, 0x1d126, 0x1d12a, 0x1d166, 0x1d16a, 0x1d172, 0x1d183, 0x1d184, 0x1d18c, 0x1d1a9, 0x1d1ae, 0x1d1dd, 0x1d400, 0x1d454, 0x1d456, 0x1d49c, 0x1d49e, 0x1d49f, 0x1d4a2, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d4a9, 0x1d4ac, 0x1d4ae, 0x1d4b9, 0x1d4bb, 0x1d4bb, 0x1d4bd, 0x1d4c0, 0x1d4c2, 0x1d4c3, 0x1d4c5, 0x1d505, 0x1d507, 0x1d50a, 0x1d50d, 0x1d514, 0x1d516, 0x1d51c, 0x1d51e, 0x1d539, 0x1d53b, 0x1d53e, 0x1d540, 0x1d544, 0x1d546, 0x1d546, 0x1d54a, 0x1d550, 0x1d552, 0x1d6a3, 0x1d6a8, 0x1d7c9, 0x20000, 0x2a6d6, 0x2f800, 0x2fa1d, 0xf0000, 0xffffd, 0x100000, 0x10fffd];
D.2 Characters with bidirectional property "L" @link https://tools.ietf.org/html/rfc3454#appendix-D.2
last
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
const mapping2space = isNonASCIISpaceCharacter; /** * the "commonly mapped to nothing" characters [StringPrep, B.1] * that can be mapped to nothing. */ const mapping2nothing = isCommonlyMappedToNothing; // utils const getCodePoint = character => character.codePointAt(0); const first = x => x[0]; const last = x => x[x.length - 1]; /** * Convert provided string into an array of Unicode Code Points. * Based on https://stackoverflow.com/a/21409165/1556249 * and https://www.npmjs.com/package/code-point-at. * @param {string} input * @returns {number[]} */
non-ASCII space characters [StringPrep, C.1.2] that can be mapped to SPACE (U+0020)
toCodePoints ( input )
javascript
ShizukuIchi/pdf-editor
public/makeTextPDF.js
https://github.com/ShizukuIchi/pdf-editor/blob/master/public/makeTextPDF.js
MIT
exports.parseOpts = function (args) { var pos for (var i = 0, len = badArgs.length; i < len; i++) { if ((pos = args.indexOf(badArgs[i])) !== -1) { args.splice(pos, 1) } } return args }
Helps parse options used in youtube-dl command. @param {Array.<String>} @return {Array.<String>}
exports.parseOpts ( args )
javascript
przemyslawpluta/node-youtube-dl
lib/util.js
https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/util.js
MIT
exports.formatDuration = function (seconds) { var parts = [] parts.push(seconds % 60) var minutes = Math.floor(seconds / 60) if (minutes > 0) { parts.push(minutes % 60) var hours = Math.floor(minutes / 60) if (hours > 0) { parts.push(hours) } } return parts.reverse().join(':') }
Converts seconds to format hh:mm:ss @param {Number} seconds @return {String}
exports.formatDuration ( seconds )
javascript
przemyslawpluta/node-youtube-dl
lib/util.js
https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/util.js
MIT
exports.isString = str => typeof str === 'string' /** * Checks arr contains value * * @param {Array} arr * @param {string|number} arr * @return {Boolean} */ exports.has = (arr, value) => arr && arr.indexOf(value) > -1
Checks wether str is a string or not @param {String} str @return {Boolean}
exports.isString
javascript
przemyslawpluta/node-youtube-dl
lib/util.js
https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/util.js
MIT
exports.has = (arr, value) => arr && arr.indexOf(value) > -1 exports.isYouTubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\//
Checks arr contains value @param {Array} arr @param {string|number} arr @return {Boolean}
exports.has
javascript
przemyslawpluta/node-youtube-dl
lib/util.js
https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/util.js
MIT
const ytdl = (module.exports = function (videoUrl, args, options) { const stream = streamify({ superCtor: http.ClientResponse, readable: true, writable: false }) if (!isString(videoUrl)) { processData(videoUrl, args, options, stream) return stream } ytdl.getInfo(videoUrl, args, options, function getInfo (err, data) { return err ? stream.emit('error', err) : processData(data, args, options, stream) }) return stream })
Downloads a video. @param {String} videoUrl @param {!Array.<String>} args @param {!Object} options
module.exports ( videoUrl , args , options )
javascript
przemyslawpluta/node-youtube-dl
lib/youtube-dl.js
https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/youtube-dl.js
MIT
function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; }
Create key-value caches of limited size @returns {Function(string, Object)} Returns the Object data after storing it on itself with property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) deleting the oldest entry
createCache ( )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function markFunction( fn ) { fn[ expando ] = true; return fn; }
Mark a function for special use by Sizzle @param {Function} fn The function to mark
markFunction ( fn )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } }
Support testing using an element @param {Function} fn Passed the created div and expects a boolean result
assert ( fn )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } }
Adds the same handler for all of the specified attrs @param {String} attrs Pipe-separated list of attributes @param {Function} handler The method that will be applied
addHandle ( attrs , handler )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; }
Checks document order of two siblings @param {Element} a @param {Element} b @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
siblingCheck ( a , b )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; }
Returns a function to use in pseudos for input types @param {String} type
createInputPseudo ( type )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }
Returns a function to use in pseudos for buttons @param {String} type
createButtonPseudo ( type )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); }
Returns a function to use in pseudos for positionals @param {Function} fn
createPositionalPseudo ( fn )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; };
Detect xml @param {Element|Object} elem An element or a document
Sizzle.isXML ( elem )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; };
Document sorting and removing duplicates @param {ArrayLike} results
Sizzle.uniqueSort ( results )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; };
Utility function for retrieving the text value of an array of DOM nodes @param {Array|Element} elem
Sizzle.getText ( elem )
javascript
LinkedInAttic/hopscotch
demo/js/jquery-1.10.2.js
https://github.com/LinkedInAttic/hopscotch/blob/master/demo/js/jquery-1.10.2.js
Apache-2.0
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.hopscotch = factory()); }(this, (function () { 'use strict';
! hopscotch - v0.3.1 Copyright 2017 LinkedIn Corp. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
(anonymous) ( global , factory )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
winLoadHandler = function winLoadHandler() { if (waitingToStart) { winHopscotch.startTour(); } };
Called when the page is done loading. @private
winLoadHandler ( )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
invokeCallbackArrayHelper: function invokeCallbackArrayHelper(arr) { // Logic for a single callback var fn; if (Array.isArray(arr)) { fn = helpers[arr[0]]; if (typeof fn === 'function') { return fn.apply(this, arr.slice(1)); } } },
Invokes a single callback represented by an array. Example input: ["my_fn", "arg1", 2, "arg3"] @private
invokeCallbackArrayHelper ( arr )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
invokeCallbackArray: function invokeCallbackArray(arr) { var i, len; if (Array.isArray(arr)) { if (typeof arr[0] === 'string') { // Assume there are no nested arrays. This is the one and only callback. return utils.invokeCallbackArrayHelper(arr); } else { // assume an array for (i = 0, len = arr.length; i < len; ++i) { utils.invokeCallback(arr[i]); } } } },
Invokes one or more callbacks. Array should have at most one level of nesting. Example input: ["my_fn", "arg1", 2, "arg3"] [["my_fn_1", "arg1", "arg2"], ["my_fn_2", "arg2-1", "arg2-2"]] [["my_fn_1", "arg1", "arg2"], function() { ... }] @private
invokeCallbackArray ( arr )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
invokeCallback: function invokeCallback(cb) { if (typeof cb === 'function') { return cb(); } if (typeof cb === 'string' && helpers[cb]) { // name of a helper return helpers[cb](); } else { // assuming array return utils.invokeCallbackArray(cb); } },
Helper function for invoking a callback, whether defined as a function literal or an array that references a registered helper function. @private
invokeCallback ( cb )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
invokeEventCallbacks: function invokeEventCallbacks(evtType, stepCb) { var cbArr = callbacks[evtType], callback, fn, i, len; if (stepCb) { return this.invokeCallback(stepCb); } for (i = 0, len = cbArr.length; i < len; ++i) { this.invokeCallback(cbArr[i].cb); } },
If stepCb (the step-specific helper callback) is passed in, then invoke it first. Then invoke tour-wide helper. @private
invokeEventCallbacks ( evtType , stepCb )
javascript
LinkedInAttic/hopscotch
dist/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/dist/js/hopscotch.js
Apache-2.0
valOrDefault: function(val, valDefault) { return typeof val !== undefinedStr ? val : valDefault; },
Inspired by Python... returns val if it's defined, otherwise returns the default. @private
valOrDefault ( val , valDefault )
javascript
LinkedInAttic/hopscotch
src/js/hopscotch.js
https://github.com/LinkedInAttic/hopscotch/blob/master/src/js/hopscotch.js
Apache-2.0
logger.missingOptimizePackages = () => { let message = 'No package found which can optimize images.' message += '\nFor help during the setup and installation, please read `https://marquez.co/docs/nuxt-optimized-images#optimization-packages`' message += '\nIf this is on purpose and you don\'t want this plugin to optimize the images, set the option `optimizeImages: false` to hide this warning.' logger.warn(message) }
Output a warning when images should get optimized (prod build) but no optimization package is installed.
logger.missingOptimizePackages
javascript
juliomrqz/nuxt-optimized-images
lib/logger.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/logger.js
MIT
logger.imageOptimizationInDevMode = () => { logger.warn('Image Optimization is activated in development mode.\n`This could increase the build time`.') }
Output a warning when images optimization is activated in dev mode
logger.imageOptimizationInDevMode
javascript
juliomrqz/nuxt-optimized-images
lib/logger.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/logger.js
MIT
const getFileLoaderOptions = (moduleConfig) => { let name if (moduleConfig.optimizeInCurrentState) { name = moduleConfig.imagesName(moduleConfig).replace('[hash:optimized]', '--[hash:7]') } else { name = moduleConfig.imagesName(moduleConfig).replace('[hash:optimized]', '') } return { name } }
Build options for the webpack file loader @param {object} moduleConfig - @aceforth/nuxt-optimized-images configuration @returns {object}
getFileLoaderOptions
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/file-loader.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/file-loader.js
MIT
const getWebpLoaderOptions = ({ webp }) => webp || {}
Build options for the webp loader @param {object} moduleConfig - @aceforth/nuxt-optimized-images configuration @returns {object}
getWebpLoaderOptions
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/webp-loader.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/webp-loader.js
MIT
const requireImageminPlugin = (plugin, moduleConfig) => { let moduleName = plugin if (moduleConfig.overwriteImageLoaderPaths) { moduleName = require.resolve(plugin, { paths: [moduleConfig.overwriteImageLoaderPaths] }) } /* eslint global-require: "off", import/no-dynamic-require: "off" */ return require(moduleName)(moduleConfig[plugin.replace('imagemin-', '')] || {}) }
Requires an imagemin plugin and configures it @param {string} plugin - plugin name @param {*} moduleConfig - @aceforth/nuxt-optimized-images configuration @return {function}
requireImageminPlugin
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/img-loader.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/img-loader.js
MIT
const getHandledFilesRegex = (handledImageTypes) => { const handledFiles = [ handledImageTypes.jpeg ? 'jpe?g' : null, handledImageTypes.png ? 'png' : null, handledImageTypes.svg ? 'svg' : null, handledImageTypes.gif ? 'gif' : null ] return new RegExp(`\\.(${handledFiles.filter(Boolean).join('|')})$`, 'i') }
Build the regex for all handled image types @param {object} handledImageTypes - handled image types @return {RegExp}
getHandledFilesRegex
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/img-loader.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/img-loader.js
MIT
const isModuleInstalled = (name) => { try { require.resolve(name) return true } catch (e) { return false } }
Checks if a node module is installed in the current context @param {string} name - module name @returns {boolean}
isModuleInstalled
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/index.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/index.js
MIT
const detectLoaders = () => { const jpeg = isModuleInstalled('imagemin-mozjpeg') ? 'imagemin-mozjpeg' : false const gif = isModuleInstalled('imagemin-gifsicle') ? 'imagemin-gifsicle' : false const svg = isModuleInstalled('imagemin-svgo') ? 'imagemin-svgo' : false const webp = isModuleInstalled('webp-loader') ? 'webp-loader' : false const lqip = isModuleInstalled('lqip-loader') ? 'lqip-loader' : false const sqip = isModuleInstalled('sqip-loader') ? 'sqip-loader' : false let png = false let responsive = false let responsiveAdapter = false if (isModuleInstalled('imagemin-pngquant')) { png = 'imagemin-pngquant' } else if (isModuleInstalled('imagemin-optipng')) { png = 'imagemin-optipng' } if (isModuleInstalled('responsive-loader')) { responsive = require.resolve('responsive-loader').replace(/(\/|\\)lib(\/|\\)cjs.js$/g, '') if (isModuleInstalled('sharp')) { responsiveAdapter = 'sharp' } else if (isModuleInstalled('jimp')) { responsiveAdapter = 'jimp' } } return { jpeg, gif, svg, webp, png, lqip, sqip, responsive, responsiveAdapter } }
Detects all currently installed image optimization loaders @returns {object}
detectLoaders
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/index.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/index.js
MIT
const getNumOptimizationLoadersInstalled = loaders => Object.values(loaders) .filter(loader => loader && ( loader.startsWith('imagemin-') || loader.startsWith('webp-') || loader.startsWith('lqip-') || loader.startsWith('sqip-') || loader.startsWith('responsive-') )).length /** * Appends all loaders to the webpack configuration * * @param {object} webpackConfig - webpack configuration * @param {object} moduleConfig - @aceforth/nuxt-optimized-images configuration * @param {object} detectedLoaders - detected loaders * @param {boolean} optimize - if images should get optimized or just copied * @returns {object} */ const appendLoaders = (
Returns the number of image optimization loaders installed @param {object} loaders - detected loaders @returns {number}
getNumOptimizationLoadersInstalled
javascript
juliomrqz/nuxt-optimized-images
lib/loaders/index.js
https://github.com/juliomrqz/nuxt-optimized-images/blob/master/lib/loaders/index.js
MIT
constructor(renderRules, style) { this._renderRules = renderRules; this._style = style; }
@param {Object.<string, function>} renderRules @param {any} style
constructor ( renderRules , style )
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/AstRenderer.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/AstRenderer.js
MIT
getRenderFunction = type => { const renderFunction = this._renderRules[type]; if (!renderFunction) { throw new Error( `${type} renderRule not defined example: <Markdown rules={renderRules}>` ); } return renderFunction; };
@param {string} type @return {string}
getRenderFunction
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/AstRenderer.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/AstRenderer.js
MIT
renderNode = (node, parentNodes) => { const renderFunction = this.getRenderFunction(node.type); const parents = [...parentNodes]; parents.unshift(node); if (node.type === "text") { return renderFunction(node, [], parentNodes, this._style); } const children = node.children.map(value => { return this.renderNode(value, parents); }); return renderFunction(node, children, parentNodes, this._style); };
@param node @param parentNodes @return {*}
=
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/AstRenderer.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/AstRenderer.js
MIT
export default function parser(source, renderer, markdownIt) { let tokens = stringToTokens(source, markdownIt); tokens = cleanupTokens(tokens); tokens = groupTextTokens(tokens); const astTree = tokensToAST(tokens); return renderer(astTree); }
@param {string} source @param {function} [renderer] @param {AstRenderer} [markdownIt] @return {View}
parser ( source , renderer , markdownIt )
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/parser.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/parser.js
MIT
export default function tokensToAST(tokens) { let stack = []; let children = []; if (!tokens || tokens.length === 0) { return []; } for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; const astNode = createNode(token, i); if (!(astNode.type === 'text' && astNode.children.length === 0 && astNode.content === '')) { astNode.index = children.length; if (token.nesting === 1) { children.push(astNode); stack.push(children); children = astNode.children; } else if (token.nesting === -1) { children = stack.pop(); } else if (token.nesting === 0) { children.push(astNode); } } } return children; }
@param {Array<{type: string, tag:string, content: string, children: *, attrs: Array}>}tokens @return {Array}
tokensToAST ( tokens )
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/util/tokensToAST.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/util/tokensToAST.js
MIT
export default function hasParents(parents, type) { return parents.findIndex(el => el.type === type) > -1; }
@param {Array} parents @param {string} type @return {boolean}
hasParents ( parents , type )
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/util/hasParents.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/util/hasParents.js
MIT
export default function blockPlugin(md, name, options) { function validateDefault(params) { return params.trim().split(' ', 2)[0] === name; } function renderDefault(tokens, idx, _options, env, self) { return self.renderToken(tokens, idx, _options, env, self); } options = options || {}; let min_markers = 1; let marker_str = options.marker || `[${name}]`; let marker_end_str = options.marker_end || `[/${name}]`; let marker_char = marker_str.charCodeAt(0); let marker_len = marker_str.length; let marker_end_len = marker_end_str.length; let validate = options.validate || validateDefault; let render = options.render || renderDefault; function container(state, startLine, endLine, silent) {
How to use? new PluginContainer(blockPlugin, '__name_of_block__', {}) @param md @param name @param options
blockPlugin ( md , name , options )
javascript
mientjan/react-native-markdown-renderer
example/react-native-markdown-renderer/lib/plugin/blockPlugin.js
https://github.com/mientjan/react-native-markdown-renderer/blob/master/example/react-native-markdown-renderer/lib/plugin/blockPlugin.js
MIT
function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; }
Checks a node for validity as a Sizzle context @param {Element|Object=} context @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
testContext ( context )
javascript
headjs/headjs
site/assets/libs/jquery/jquery.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/jquery/jquery.js
MIT
function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }
Clean-up method for dom ready events
detach ( )
javascript
headjs/headjs
site/assets/libs/jquery/jquery.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/jquery/jquery.js
MIT
function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }
The ready event handler and self cleanup method
completed ( )
javascript
headjs/headjs
site/assets/libs/jquery/jquery.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/jquery/jquery.js
MIT
jQuery.acceptData = function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; };
Determines whether an object can have data
jQuery.acceptData ( elem )
javascript
headjs/headjs
site/assets/libs/jquery/jquery.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/jquery/jquery.js
MIT
function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; }
Try to determine the default display value of an element @param {String} nodeName
defaultDisplay ( nodeName )
javascript
headjs/headjs
site/assets/libs/jquery/jquery.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/jquery/jquery.js
MIT
QUnit.jsDump = (function() { function quote( str ) { return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\"";
jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 @projectDescription Advanced and extensible data dumping for Javascript. @version 1.0.0 @author Ariel Flesler @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
quote ( str )
javascript
headjs/headjs
site/assets/libs/qunit/qunit.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/qunit/qunit.js
MIT
step: function (expected, message) { // increment internal step counter. QUnit.config.current.step++; if (typeof message === "undefined") { message = "step " + expected; } var actual = QUnit.config.current.step; QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }
Check the sequence/order @example test('Example unit test', function(assert) { assert.step(1); setTimeout(function () { assert.step(3); start(); }, 100); assert.step(2); stop(); }); @param Number expected The excepted step within the test() @param String message (optional)
step ( expected , message )
javascript
headjs/headjs
site/assets/libs/qunit/qunit-assert-step.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/qunit/qunit-assert-step.js
MIT
QUnit.testStart(function () { QUnit.config.current.step = 0; });
Reset the step counter for every test()
(anonymous) ( )
javascript
headjs/headjs
site/assets/libs/qunit/qunit-assert-step.js
https://github.com/headjs/headjs/blob/master/site/assets/libs/qunit/qunit-assert-step.js
MIT
.filter('highlight', function() { function escapeRegexp(queryToEscape) { return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } return function(matchItem, query) { return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem; }; })
Highlights text that matches $select.search. Taken from AngularUI Bootstrap Typeahead See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
(anonymous) ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/ui-select.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/ui-select.js
Apache-2.0
ctrl.refresh = function(refreshAttr) { if (refreshAttr !== undefined) { // Debounce // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155 // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177 if (_refreshDelayPromise) { $timeout.cancel(_refreshDelayPromise); } _refreshDelayPromise = $timeout(function() { if ($scope.$select.search.length >= $scope.$select.minimumInputLength) { var refreshPromise = $scope.$eval(refreshAttr); if (refreshPromise && angular.isFunction(refreshPromise.then) && !ctrl.refreshing) { ctrl.refreshing = true; refreshPromise.finally(function() { ctrl.refreshing = false; }); } } }, ctrl.refreshDelay); } };
Typeahead mode: lets the user refresh the collection using his own function. See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
ctrl.refresh ( refreshAttr )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/ui-select.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/ui-select.js
Apache-2.0
uis.factory('$$uisDebounce', ['$timeout', function($timeout) { return function(callback, debounceTime) { var timeoutPromise; return function() { var self = this; var args = Array.prototype.slice.call(arguments); if (timeoutPromise) { $timeout.cancel(timeoutPromise); } timeoutPromise = $timeout(function() { callback.apply(self, args); }, debounceTime); }; }; }]);
Debounces functions Taken from UI Bootstrap $$debounce source code See https://github.com/angular-ui/bootstrap/blob/master/src/debounce/debounce.js
uis.factory ( '$$uisDebounce' , [ '$timeout' , function ( $timeout )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/ui-select.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/ui-select.js
Apache-2.0
(function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) {
Author: Koh Zi Han, based on implementation by Koh Zi Chun
(anonymous) ( mod )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/codemirror/mode/scheme/scheme.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/codemirror/mode/scheme/scheme.js
Apache-2.0
(function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js")); else if (typeof define == "function" && define.amd) // AMD define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) {
Supported keybindings: Too many to list. Refer to defaultKeymap below. Supported Ex commands: Refer to defaultExCommandMap below. Registers: unnamed, -, a-z, A-Z, 0-9 (Does not respect the special case for number registers when delete operator is made with these commands: %, (, ), , /, ?, n, N, {, } ) TODO: Implement the remaining registers. Marks: a-z, A-Z, and 0-9 TODO: Implement the remaining special marks. They have more complex behavior. Events: 'vim-mode-change' - raised on the editor anytime the current mode changes, Event object: {mode: "visual", subMode: "linewise"} Code structure: 1. Default keymap 2. Variable declarations and short basic helpers 3. Instance (External API) implementation 4. Internal state tracking objects (input state, counter) implementation and instantiation 5. Key handler (the main command dispatcher) implementation 6. Motion, operator, and action implementations 7. Helper functions for the key handler, motions, operators, and actions 8. Set up Vim to work as a keymap for CodeMirror. 9. Ex command implementations.
(anonymous) ( mod )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/codemirror/keymap/vim.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/codemirror/keymap/vim.js
Apache-2.0
function defineRegister(name, register) { var registers = vimGlobalState.registerController.registers; if (!name || name.length != 1) { throw Error('Register name must be 1 character'); } if (registers[name]) { throw Error('Register already defined ' + name); } registers[name] = register; validRegisters.push(name); }
Defines an external register. The name should be a single character that will be used to reference the register. The register should support setText, pushText, clear, and toString(). See Register for a reference implementation.
defineRegister ( name , register )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/codemirror/keymap/vim.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/codemirror/keymap/vim.js
Apache-2.0
(function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../fold/xml-fold")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../fold/xml-fold"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) {
Tag-closer extension for CodeMirror. This extension adds an "autoCloseTags" option that can be set to either true to get the default behavior, or an object to further configure its behavior. These are supported options: `whenClosing` (default true) Whether to autoclose when the '/' of a closing tag is typed. `whenOpening` (default true) Whether to autoclose the tag when the final '>' of an opening tag is typed. `dontCloseTags` (default is empty tags for HTML, none for XML) An array of tag names that should not be autoclosed. `indentTags` (default is block tags for HTML, none for XML) An array of tag names that should, when opened, cause a blank line to be added inside the tag, and the blank line and closing line to be indented. See demos/closetag.html for a usage example.
(anonymous) ( mod )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/js/codemirror/addon/edit/closetag.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/js/codemirror/addon/edit/closetag.js
Apache-2.0
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(require('jquery')); } else if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(root.jQuery); } }(this, function($) {
! easyPieChart Lightweight plugin to render simple, animated and retina optimized pie charts @license @author Robert Fleischmann <[email protected]> (http://robert-fleischmann.de) @version 2.1.6 *
(anonymous) ( root , factory )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
var drawCircle = function(color, lineWidth, percent) { percent = Math.min(Math.max(-1, percent || 0), 1); var isNegative = percent <= 0 ? true : false; ctx.beginPath(); ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, isNegative); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; ctx.stroke(); };
Draw a circle around the center of the canvas @param {strong} color Valid CSS color string @param {number} lineWidth Width of the line in px @param {number} percent Percentage to draw (float between -1 and 1)
drawCircle ( color , lineWidth , percent )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
var reqAnimationFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; }());
Request animation frame wrapper with polyfill @return {function} Request animation frame method or timeout fallback
(anonymous) ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
var drawBackground = function() { if(options.scaleColor) drawScale(); if(options.trackColor) drawCircle(options.trackColor, options.trackWidth || options.lineWidth, 1); };
Draw the background of the plugin including the scale and the track
drawBackground ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
this.draw = function(percent) { // do we need to render a background if (!!options.scaleColor || !!options.trackColor) { // getImageData and putImageData are supported if (ctx.getImageData && ctx.putImageData) { if (!cachedBackground) { drawBackground(); cachedBackground = ctx.getImageData(0, 0, options.size * scaleBy, options.size * scaleBy); } else { ctx.putImageData(cachedBackground, 0, 0); } } else { this.clear(); drawBackground(); } } else { this.clear(); } ctx.lineCap = options.lineCap; // if barcolor is a function execute it and pass the percent as a value var color; if (typeof(options.barColor) === 'function') { color = options.barColor(percent); } else { color = options.barColor; } // draw bar drawCircle(color, options.lineWidth, percent / 100); }.bind(this);
Draw the complete chart @param {number} percent Percent shown by the chart between -100 and 100
this.draw ( percent )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
this.animate = function(from, to) { var startTime = Date.now(); options.onStart(from, to); var animation = function() { var process = Math.min(Date.now() - startTime, options.animate.duration); var currentValue = options.easing(this, process, from, to - from, options.animate.duration); this.draw(currentValue); options.onStep(from, to, currentValue); if (process >= options.animate.duration) { options.onStop(from, to); } else { reqAnimationFrame(animation); } }.bind(this); reqAnimationFrame(animation); }.bind(this);
Animate from some percent to some other percentage @param {number} from Starting percentage @param {number} to Final percentage
this.animate ( from , to )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
var CanvasRenderer = function(el, options) { var cachedBackground; var canvas = document.createElement('canvas'); el.appendChild(canvas); if (typeof(G_vmlCanvasManager) !== 'undefined') { G_vmlCanvasManager.initElement(canvas); } var ctx = canvas.getContext('2d'); canvas.width = canvas.height = options.size; // canvas on retina devices var scaleBy = 1; if (window.devicePixelRatio > 1) { scaleBy = window.devicePixelRatio; canvas.style.width = canvas.style.height = [options.size, 'px'].join(''); canvas.width = canvas.height = options.size * scaleBy; ctx.scale(scaleBy, scaleBy); } // move 0,0 coordinates to the center ctx.translate(options.size / 2, options.size / 2); // rotate canvas -90deg ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); var radius = (options.size - options.lineWidth) / 2; if (options.scaleColor && options.scaleLength) { radius -= options.scaleLength + 2; // 2 is the distance between scale and bar } // IE polyfill for Date Date.now = Date.now || function() { return +(new Date()); }; /** * Draw a circle around the center of the canvas * @param {strong} color Valid CSS color string * @param {number} lineWidth Width of the line in px * @param {number} percent Percentage to draw (float between -1 and 1) */ var drawCircle = function(color, lineWidth, percent) { percent = Math.min(Math.max(-1, percent || 0), 1); var isNegative = percent <= 0 ? true : false; ctx.beginPath(); ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, isNegative); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; ctx.stroke(); }; /** * Draw the scale of the chart */ var drawScale = function() { var offset; var length; ctx.lineWidth = 1; ctx.fillStyle = options.scaleColor; ctx.save(); for (var i = 24; i > 0; --i) { if (i % 6 === 0) { length = options.scaleLength; offset = 0; } else { length = options.scaleLength * 0.6; offset = options.scaleLength - length; } ctx.fillRect(-options.size/2 + offset, 0, length, 1); ctx.rotate(Math.PI / 12); } ctx.restore(); }; /** * Request animation frame wrapper with polyfill * @return {function} Request animation frame method or timeout fallback */ var reqAnimationFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; }()); /** * Draw the background of the plugin including the scale and the track */ var drawBackground = function() { if(options.scaleColor) drawScale(); if(options.trackColor) drawCircle(options.trackColor, options.trackWidth || options.lineWidth, 1); }; /** * Canvas accessor */ this.getCanvas = function() { return canvas; }; /** * Canvas 2D context 'ctx' accessor */ this.getCtx = function() { return ctx; }; /** * Clear the complete canvas */ this.clear = function() { ctx.clearRect(options.size / -2, options.size / -2, options.size, options.size); }; /** * Draw the complete chart * @param {number} percent Percent shown by the chart between -100 and 100 */ this.draw = function(percent) { // do we need to render a background if (!!options.scaleColor || !!options.trackColor) { // getImageData and putImageData are supported if (ctx.getImageData && ctx.putImageData) { if (!cachedBackground) { drawBackground(); cachedBackground = ctx.getImageData(0, 0, options.size * scaleBy, options.size * scaleBy); } else { ctx.putImageData(cachedBackground, 0, 0); } } else { this.clear(); drawBackground(); } } else { this.clear(); } ctx.lineCap = options.lineCap; // if barcolor is a function execute it and pass the percent as a value var color; if (typeof(options.barColor) === 'function') { color = options.barColor(percent); } else { color = options.barColor; } // draw bar drawCircle(color, options.lineWidth, percent / 100); }.bind(this); /** * Animate from some percent to some other percentage * @param {number} from Starting percentage * @param {number} to Final percentage */ this.animate = function(from, to) { var startTime = Date.now(); options.onStart(from, to); var animation = function() { var process = Math.min(Date.now() - startTime, options.animate.duration); var currentValue = options.easing(this, process, from, to - from, options.animate.duration); this.draw(currentValue); options.onStep(from, to, currentValue); if (process >= options.animate.duration) { options.onStop(from, to); } else { reqAnimationFrame(animation); } }.bind(this); reqAnimationFrame(animation); }.bind(this); };
Renderer to render the chart on a canvas object @param {DOMElement} el DOM element to host the canvas (root of the plugin) @param {object} options options object of the plugin
CanvasRenderer ( el , options )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
var init = function() { this.el = el; this.options = options; // merge user options into default options for (var i in defaultOptions) { if (defaultOptions.hasOwnProperty(i)) { options[i] = opts && typeof(opts[i]) !== 'undefined' ? opts[i] : defaultOptions[i]; if (typeof(options[i]) === 'function') { options[i] = options[i].bind(this); } } } // check for jQuery easing if (typeof(options.easing) === 'string' && typeof(jQuery) !== 'undefined' && jQuery.isFunction(jQuery.easing[options.easing])) { options.easing = jQuery.easing[options.easing]; } else { options.easing = defaultOptions.easing; } // process earlier animate option to avoid bc breaks if (typeof(options.animate) === 'number') { options.animate = { duration: options.animate, enabled: true }; } if (typeof(options.animate) === 'boolean' && !options.animate) { options.animate = { duration: 1000, enabled: options.animate }; } // create renderer this.renderer = new options.renderer(el, options); // initial draw this.renderer.draw(currentValue); // initial update if (el.dataset && el.dataset.percent) { this.update(parseFloat(el.dataset.percent)); } else if (el.getAttribute && el.getAttribute('data-percent')) { this.update(parseFloat(el.getAttribute('data-percent'))); } }.bind(this);
Initialize the plugin by creating the options object and initialize rendering
init ( )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0
this.update = function(newValue) { newValue = parseFloat(newValue); if (options.animate.enabled) { this.renderer.animate(currentValue, newValue); } else { this.renderer.draw(newValue); } currentValue = newValue; return this; }.bind(this);
Update the value of the chart @param {number} newValue Number between 0 and 100 @return {object} Instance of the plugin for method chaining
this.update ( newValue )
javascript
alibaba/intelligent-test-platform
src/main/resources/static/wel/js/jquery.easypiechart.js
https://github.com/alibaba/intelligent-test-platform/blob/master/src/main/resources/static/wel/js/jquery.easypiechart.js
Apache-2.0