├── .babelrc ├── .eslintrc ├── .gitignore ├── package.json ├── readme.md ├── rollup.config.js ├── src ├── browser.js ├── global.js ├── index.js └── inject │ ├── index.js │ └── makeLegalIdentifier.js ├── test ├── __snapshots__ │ ├── conditional.test.js.snap │ └── form.test.js.snap ├── conditional.test.js ├── fixtures │ ├── buffer-import.js │ ├── buffer-isBuffer.js │ ├── buffer.js │ ├── dirname.js │ ├── global.js │ ├── mixed.js │ ├── process-browser.js │ ├── process-env.js │ ├── process-generic.js │ ├── process-nexttick.js │ └── process-sneaky.js ├── form.test.js └── index.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [["env", { "modules": false }]] 3 | } 4 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "rules": { 4 | "indent": [ 2, "tab", { "SwitchCase": 1 } ], 5 | "semi": [ 2, "always" ], 6 | "keyword-spacing": [ 2, { "before": true, "after": true } ], 7 | "space-before-blocks": [ 2, "always" ], 8 | "space-before-function-paren": [ 2, "always" ], 9 | "no-mixed-spaces-and-tabs": [ 2, "smart-tabs" ], 10 | "no-cond-assign": 0, 11 | "no-unused-vars": 2, 12 | "object-shorthand": [ 2, "always" ], 13 | "no-const-assign": 2, 14 | "no-class-assign": 2, 15 | "no-this-before-super": 2, 16 | "no-var": 2, 17 | "no-unreachable": 2, 18 | "valid-typeof": 2, 19 | "quote-props": [ 2, "as-needed" ], 20 | "one-var": [ 2, "never" ], 21 | "prefer-arrow-callback": 2, 22 | "prefer-const": [ 2, { "destructuring": "all" } ], 23 | "arrow-spacing": 2 24 | }, 25 | "env": { 26 | "es6": true, 27 | "browser": true, 28 | "node": true 29 | }, 30 | "extends": "eslint:recommended", 31 | "parserOptions": { 32 | "ecmaVersion": 6, 33 | "sourceType": "module" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rollup-plugin-node-globals", 3 | "main": "dist/rollup-plugin-node-globals.cjs.js", 4 | "jsnext:main": "dist/rollup-plugin-node-globals.es6.js", 5 | "version": "1.4.0", 6 | "description": "insert the same globals browserify does", 7 | "files": [ 8 | "src", 9 | "dist", 10 | "README.md" 11 | ], 12 | "scripts": { 13 | "test": "mocha test/index.js && jest", 14 | "pretest": "npm run build", 15 | "build": "rollup -c -f cjs -o dist/rollup-plugin-node-globals.cjs.js && rollup -c -f es -o dist/rollup-plugin-node-globals.es6.js", 16 | "prebuild": "rimraf dist", 17 | "prepublish": "npm run build" 18 | }, 19 | "author": "Calvin Metcalf ", 20 | "license": "MIT", 21 | "dependencies": { 22 | "acorn": "^5.7.3", 23 | "buffer-es6": "^4.9.3", 24 | "estree-walker": "^0.5.2", 25 | "magic-string": "^0.22.5", 26 | "process-es6": "^0.11.6", 27 | "rollup-pluginutils": "^2.3.1" 28 | }, 29 | "keywords": [ 30 | "rollup-plugin" 31 | ], 32 | "devDependencies": { 33 | "babel-core": "^6.26.0", 34 | "babel-preset-env": "^1.7.0", 35 | "browserify": "^16.1.0", 36 | "jest": "^23.5.0", 37 | "mkdirp": "^0.5.1", 38 | "mocha": "^5.0.1", 39 | "rimraf": "^2.6.2", 40 | "rollup": "^0.64.1", 41 | "rollup-plugin-babel": "^3.0.3", 42 | "rollup-plugin-node-resolve": "^3.0.3" 43 | }, 44 | "repository": { 45 | "type": "git", 46 | "url": "git@github.com:calvinmetcalf/rollup-plugin-node-globals.git" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | rollup-plugin-node-globals 2 | === 3 | 4 | Plugin to insert node globals including so code that works with browserify should work even if it uses process or buffers. This is based on [rollup-plugin-inject 5 | ](https://github.com/rollup/rollup-plugin-inject). 6 | 7 | - process 8 | - global 9 | - Buffer 10 | - `__dirname` 11 | - `__filename` 12 | 13 | Plus `process.nextTick` and `process.browser` are optimized to only pull in 14 | themselves and `__dirname` and `__filename` point to the file on disk 15 | 16 | There are a few options to control output 17 | - `process` - pass `false` to disable process polyfilling 18 | - `global` - pass `false` to disable global polyfilling 19 | - `buffer` - pass `false` to disable Buffer polyfilling 20 | - `dirname` - pass `false` to disable `__dirname` polyfilling 21 | - `filename` - pass `false` to disable `__filename` polyfilling 22 | - `baseDir` which is used for resolving `__dirname` and `__filename`. 23 | 24 | # examples 25 | 26 | ```js 27 | var foo; 28 | if (process.browser) { 29 | foo = 'bar'; 30 | } else { 31 | foo = 'baz'; 32 | } 33 | ``` 34 | 35 | turns into 36 | 37 | ```js 38 | import {browser} from 'path/to/process'; 39 | var foo; 40 | if (browser) { 41 | foo = 'bar'; 42 | } else { 43 | foo = 'baz'; 44 | } 45 | ``` 46 | 47 | but with rollup that ends up being 48 | 49 | ```js 50 | var browser = true; 51 | var foo; 52 | if (browser) { 53 | foo = 'bar'; 54 | } else { 55 | foo = 'baz'; 56 | } 57 | ``` 58 | 59 | or 60 | 61 | ```js 62 | var timeout; 63 | if (global.setImmediate) { 64 | timeout = global.setImmediate; 65 | } else { 66 | timeout = global.setTimeout; 67 | } 68 | export default timeout; 69 | ``` 70 | 71 | turns into 72 | 73 | ```js 74 | import {_global} from 'path/to/global.js'; 75 | var timeout; 76 | if (_global.setImmediate) { 77 | timeout = _global.setImmediate; 78 | } else { 79 | timeout = _global.setTimeout; 80 | } 81 | export default timeout; 82 | 83 | ``` 84 | 85 | which rollup turns into 86 | 87 | ```js 88 | var _global = typeof global !== "undefined" ? global : 89 | typeof self !== "undefined" ? self : 90 | typeof window !== "undefined" ? window : {} 91 | 92 | var timeout; 93 | if (_global.setImmediate) { 94 | timeout = _global.setImmediate; 95 | } else { 96 | timeout = _global.setTimeout; 97 | } 98 | var timeout$1 = timeout; 99 | 100 | export default timeout$1; 101 | ``` 102 | 103 | With that top piece only showing up once no matter how many times global was used. 104 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | 3 | var external = Object.keys( require( './package.json' ).dependencies ).concat( 4 | 'path', 5 | 'crypto' 6 | ); 7 | 8 | export default { 9 | input: 'src/index.js', 10 | plugins: [ babel() ], 11 | external 12 | }; 13 | -------------------------------------------------------------------------------- /src/browser.js: -------------------------------------------------------------------------------- 1 | export var browser = true; 2 | -------------------------------------------------------------------------------- /src/global.js: -------------------------------------------------------------------------------- 1 | export default (typeof global !== "undefined" ? global : 2 | typeof self !== "undefined" ? self : 3 | typeof window !== "undefined" ? window : {}); 4 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import inject from './inject/index'; 2 | import { join, relative, dirname } from 'path'; 3 | import {randomBytes} from 'crypto'; 4 | import {createFilter} from 'rollup-pluginutils'; 5 | 6 | const PROCESS_PATH = require.resolve('process-es6'); 7 | const BUFFER_PATH = require.resolve('buffer-es6'); 8 | const GLOBAL_PATH = join(__dirname, '..', 'src', 'global.js'); 9 | const BROWSER_PATH = join(__dirname, '..', 'src', 'browser.js'); 10 | const DIRNAME = '\0node-globals:dirname'; 11 | const FILENAME = '\0node-globals:filename'; 12 | 13 | function clone(obj) { 14 | var out = {}; 15 | Object.keys(obj).forEach(function(key) { 16 | if (Array.isArray(obj[key])) { 17 | out[key] = obj[key].slice(); 18 | } else { 19 | out[key] = obj[key]; 20 | } 21 | }); 22 | return out; 23 | } 24 | 25 | const getMods = options => { 26 | const _mods1 = {}; 27 | const _mods2 = {}; 28 | 29 | if (options.global !== false || options.process !== false) { 30 | _mods2.global = GLOBAL_PATH; 31 | } 32 | 33 | if (options.process !== false) { 34 | _mods1['process.nextTick'] = [PROCESS_PATH, 'nextTick']; 35 | _mods1['process.browser'] = [BROWSER_PATH, 'browser']; 36 | _mods2.process = PROCESS_PATH; 37 | } 38 | 39 | if (options.buffer !== false) { 40 | _mods1['Buffer.isBuffer'] = [BUFFER_PATH, 'isBuffer']; 41 | _mods2.Buffer = [BUFFER_PATH, 'Buffer']; 42 | } 43 | 44 | if (options.filename !== false) { 45 | _mods2.__filename = FILENAME; 46 | } 47 | 48 | if (options.dirname !== false) { 49 | _mods2.__dirname = DIRNAME; 50 | } 51 | 52 | var mods1 = new Map(); 53 | var mods2 = new Map(); 54 | 55 | Object.keys(_mods1).forEach(key=>{ 56 | mods1.set(key, _mods1[key]); 57 | }); 58 | 59 | Object.keys(_mods2).forEach(key=>{ 60 | mods2.set(key, _mods2[key]); 61 | }); 62 | 63 | const mods = Object.keys(_mods1).concat(Object.keys(_mods2)); 64 | const firstpass = new RegExp(`(?:${ mods.map( escape ).join( '|')})`, 'g'); 65 | 66 | return { mods1, mods2, firstpass }; 67 | } 68 | 69 | const escape = ( str ) => { 70 | return str.replace( /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&' ); 71 | } 72 | 73 | export default function nodeGlobals(options) { 74 | options = options || {}; 75 | const basedir = options.baseDir || '/'; 76 | const dirs = new Map(); 77 | const opts = clone(options); 78 | const exclude = (opts.exclude || []).concat(GLOBAL_PATH); 79 | const filter = createFilter(options.include, exclude); 80 | const sourceMap = options.sourceMap !== false; 81 | 82 | const { mods1, mods2, firstpass } = getMods(options); 83 | 84 | const buf = new Map(); 85 | buf.set('global', GLOBAL_PATH); 86 | 87 | return { 88 | load(id) { 89 | if (dirs.has(id)) { 90 | return `export default '${dirs.get(id)}'`; 91 | } 92 | }, 93 | resolveId(importee, importer) { 94 | if (importee === DIRNAME) { 95 | let id = randomBytes(15).toString('hex'); 96 | dirs.set(id, dirname('/' + relative(basedir, importer))); 97 | return id; 98 | } 99 | if (importee === FILENAME) { 100 | let id = randomBytes(15).toString('hex'); 101 | dirs.set(id, '/' + relative(basedir, importer)); 102 | return id; 103 | } 104 | }, 105 | transform(code, id) { 106 | if (id === BUFFER_PATH) { 107 | return inject(code, id, buf, new Map(), sourceMap); 108 | } 109 | if (!filter(id)) return null; 110 | if (code.search(firstpass) === -1) return null; 111 | if (id.slice(-3) !== '.js') return null; 112 | 113 | var out = inject(code, id, mods1, mods2, sourceMap); 114 | return out; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/inject/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | attachScopes 3 | } from 'rollup-pluginutils'; 4 | import { 5 | walk 6 | } from 'estree-walker'; 7 | import { 8 | parse 9 | } from 'acorn'; 10 | import makeLegalIdentifier from './makeLegalIdentifier'; 11 | import MagicString from 'magic-string'; 12 | 13 | function isReference(node, parent) { 14 | if (node.type === 'MemberExpression') { 15 | return !node.computed && isReference(node.object, node); 16 | } 17 | 18 | if (node.type === 'Identifier') { 19 | // TODO is this right? 20 | if (parent.type === 'MemberExpression') return parent.computed || node === parent.object; 21 | 22 | // disregard the `bar` in { bar: foo } 23 | if (parent.type === 'Property' && node !== parent.value) return false; 24 | 25 | // disregard the `bar` in `class Foo { bar () {...} }` 26 | if (parent.type === 'MethodDefinition') return false; 27 | 28 | // disregard the `bar` in `export { foo as bar }` 29 | if (parent.type === 'ExportSpecifier' && node !== parent.local) return; 30 | 31 | return true; 32 | } 33 | } 34 | 35 | function flatten(node) { 36 | let name; 37 | let parts = []; 38 | 39 | while (node.type === 'MemberExpression') { 40 | parts.unshift(node.property.name); 41 | node = node.object; 42 | } 43 | 44 | name = node.name; 45 | parts.unshift(name); 46 | 47 | return { 48 | name, 49 | keypath: parts.join('.') 50 | }; 51 | } 52 | 53 | 54 | export default function(code, id, mod1, mod2, sourceMap) { 55 | let ast; 56 | 57 | try { 58 | ast = parse(code, { 59 | ecmaVersion: 9, 60 | sourceType: 'module' 61 | }); 62 | } catch (err) { 63 | err.message += ` in ${id}`; 64 | throw err; 65 | } 66 | // analyse scopes 67 | let scope = attachScopes(ast, 'scope'); 68 | 69 | let imports = {}; 70 | ast.body.forEach(node => { 71 | if (node.type === 'ImportDeclaration') { 72 | node.specifiers.forEach(specifier => { 73 | imports[specifier.local.name] = true; 74 | }); 75 | } 76 | }); 77 | 78 | const magicString = new MagicString(code); 79 | 80 | let newImports = {}; 81 | 82 | function handleReference(node, name, keypath, parent) { 83 | if ((mod1.has(keypath) || mod2.has(keypath)) && !scope.contains(name) && !imports[name]) { 84 | if (mod2.has(keypath) && parent.__handled) { 85 | return; 86 | } 87 | let module = mod1.has(keypath) ? mod1.get(keypath) : mod2.get(keypath); 88 | let moduleName, hash; 89 | if (typeof module === 'string') { 90 | moduleName = module; 91 | hash = `${keypath}:${moduleName}:default`; 92 | } else { 93 | moduleName = module[0]; 94 | hash = `${keypath}:${moduleName}:${module[1]}`; 95 | } 96 | // prevent module from importing itself 97 | if (moduleName === id) return; 98 | 99 | const importLocalName = name === keypath ? name : makeLegalIdentifier(`$inject_${keypath}`); 100 | 101 | if (!newImports[hash]) { 102 | newImports[hash] = `import ${typeof module === 'string' ? importLocalName : `{ ${module[1]} as ${importLocalName} }`} from ${JSON.stringify(moduleName)};`; 103 | } 104 | 105 | if (name !== keypath) { 106 | magicString.overwrite(node.start, node.end, importLocalName, {storeName: true}); 107 | } 108 | if (mod1.has(keypath)) { 109 | node.__handled = true; 110 | } 111 | } 112 | } 113 | 114 | walk(ast, { 115 | enter(node, parent) { 116 | if (sourceMap) { 117 | magicString.addSourcemapLocation(node.start); 118 | magicString.addSourcemapLocation(node.end); 119 | } 120 | 121 | if (node.scope) scope = node.scope; 122 | 123 | // special case – shorthand properties. because node.key === node.value, 124 | // we can't differentiate once we've descended into the node 125 | if (node.type === 'Property' && node.shorthand) { 126 | const name = node.key.name; 127 | handleReference(node, name, name); 128 | return this.skip(); 129 | } 130 | 131 | if (isReference(node, parent)) { 132 | const { 133 | name, 134 | keypath 135 | } = flatten(node); 136 | handleReference(node, name, keypath, parent); 137 | } 138 | }, 139 | leave(node) { 140 | if (node.scope) scope = scope.parent; 141 | } 142 | }); 143 | 144 | const keys = Object.keys(newImports); 145 | if (!keys.length) return null; 146 | 147 | const importBlock = keys.map(hash => newImports[hash]).join('\n\n'); 148 | magicString.prepend(importBlock + '\n\n'); 149 | 150 | return { 151 | code: magicString.toString(), 152 | map: sourceMap ? magicString.generateMap() : null 153 | }; 154 | } 155 | -------------------------------------------------------------------------------- /src/inject/makeLegalIdentifier.js: -------------------------------------------------------------------------------- 1 | const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split( ' ' ); 2 | const builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split( ' ' ); 3 | 4 | let blacklisted = Object.create( null ); 5 | reservedWords.concat( builtins ).forEach( word => blacklisted[ word ] = true ); 6 | 7 | export default function makeLegalIdentifier ( str ) { 8 | str = str 9 | .replace( /-(\w)/g, ( _, letter ) => letter.toUpperCase() ) 10 | .replace( /[^$_a-zA-Z0-9]/g, '_' ); 11 | 12 | if ( /\d/.test( str[0] ) || blacklisted[ str ] ) str = `_${str}`; 13 | 14 | return str; 15 | } 16 | -------------------------------------------------------------------------------- /test/__snapshots__/conditional.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`conditionally polyfills buffer 1`] = ` 4 | "var global$1 = (typeof global !== \\"undefined\\" ? global : 5 | typeof self !== \\"undefined\\" ? self : 6 | typeof window !== \\"undefined\\" ? window : {}); 7 | 8 | var lookup = []; 9 | var revLookup = []; 10 | var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; 11 | var inited = false; 12 | function init () { 13 | inited = true; 14 | var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 15 | for (var i = 0, len = code.length; i < len; ++i) { 16 | lookup[i] = code[i]; 17 | revLookup[code.charCodeAt(i)] = i; 18 | } 19 | 20 | revLookup['-'.charCodeAt(0)] = 62; 21 | revLookup['_'.charCodeAt(0)] = 63; 22 | } 23 | 24 | function toByteArray (b64) { 25 | if (!inited) { 26 | init(); 27 | } 28 | var i, j, l, tmp, placeHolders, arr; 29 | var len = b64.length; 30 | 31 | if (len % 4 > 0) { 32 | throw new Error('Invalid string. Length must be a multiple of 4') 33 | } 34 | 35 | // the number of equal signs (place holders) 36 | // if there are two placeholders, than the two characters before it 37 | // represent one byte 38 | // if there is only one, then the three characters before it represent 2 bytes 39 | // this is just a cheap hack to not do indexOf twice 40 | placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; 41 | 42 | // base64 is 4/3 + up to two characters of the original data 43 | arr = new Arr(len * 3 / 4 - placeHolders); 44 | 45 | // if there are placeholders, only get up to the last complete 4 chars 46 | l = placeHolders > 0 ? len - 4 : len; 47 | 48 | var L = 0; 49 | 50 | for (i = 0, j = 0; i < l; i += 4, j += 3) { 51 | tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; 52 | arr[L++] = (tmp >> 16) & 0xFF; 53 | arr[L++] = (tmp >> 8) & 0xFF; 54 | arr[L++] = tmp & 0xFF; 55 | } 56 | 57 | if (placeHolders === 2) { 58 | tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); 59 | arr[L++] = tmp & 0xFF; 60 | } else if (placeHolders === 1) { 61 | tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); 62 | arr[L++] = (tmp >> 8) & 0xFF; 63 | arr[L++] = tmp & 0xFF; 64 | } 65 | 66 | return arr 67 | } 68 | 69 | function tripletToBase64 (num) { 70 | return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] 71 | } 72 | 73 | function encodeChunk (uint8, start, end) { 74 | var tmp; 75 | var output = []; 76 | for (var i = start; i < end; i += 3) { 77 | tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); 78 | output.push(tripletToBase64(tmp)); 79 | } 80 | return output.join('') 81 | } 82 | 83 | function fromByteArray (uint8) { 84 | if (!inited) { 85 | init(); 86 | } 87 | var tmp; 88 | var len = uint8.length; 89 | var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes 90 | var output = ''; 91 | var parts = []; 92 | var maxChunkLength = 16383; // must be multiple of 3 93 | 94 | // go through the array every three bytes, we'll deal with trailing stuff later 95 | for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { 96 | parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); 97 | } 98 | 99 | // pad the end with zeros, but make sure to not forget the extra bytes 100 | if (extraBytes === 1) { 101 | tmp = uint8[len - 1]; 102 | output += lookup[tmp >> 2]; 103 | output += lookup[(tmp << 4) & 0x3F]; 104 | output += '=='; 105 | } else if (extraBytes === 2) { 106 | tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); 107 | output += lookup[tmp >> 10]; 108 | output += lookup[(tmp >> 4) & 0x3F]; 109 | output += lookup[(tmp << 2) & 0x3F]; 110 | output += '='; 111 | } 112 | 113 | parts.push(output); 114 | 115 | return parts.join('') 116 | } 117 | 118 | function read (buffer, offset, isLE, mLen, nBytes) { 119 | var e, m; 120 | var eLen = nBytes * 8 - mLen - 1; 121 | var eMax = (1 << eLen) - 1; 122 | var eBias = eMax >> 1; 123 | var nBits = -7; 124 | var i = isLE ? (nBytes - 1) : 0; 125 | var d = isLE ? -1 : 1; 126 | var s = buffer[offset + i]; 127 | 128 | i += d; 129 | 130 | e = s & ((1 << (-nBits)) - 1); 131 | s >>= (-nBits); 132 | nBits += eLen; 133 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} 134 | 135 | m = e & ((1 << (-nBits)) - 1); 136 | e >>= (-nBits); 137 | nBits += mLen; 138 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} 139 | 140 | if (e === 0) { 141 | e = 1 - eBias; 142 | } else if (e === eMax) { 143 | return m ? NaN : ((s ? -1 : 1) * Infinity) 144 | } else { 145 | m = m + Math.pow(2, mLen); 146 | e = e - eBias; 147 | } 148 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen) 149 | } 150 | 151 | function write (buffer, value, offset, isLE, mLen, nBytes) { 152 | var e, m, c; 153 | var eLen = nBytes * 8 - mLen - 1; 154 | var eMax = (1 << eLen) - 1; 155 | var eBias = eMax >> 1; 156 | var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); 157 | var i = isLE ? 0 : (nBytes - 1); 158 | var d = isLE ? 1 : -1; 159 | var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; 160 | 161 | value = Math.abs(value); 162 | 163 | if (isNaN(value) || value === Infinity) { 164 | m = isNaN(value) ? 1 : 0; 165 | e = eMax; 166 | } else { 167 | e = Math.floor(Math.log(value) / Math.LN2); 168 | if (value * (c = Math.pow(2, -e)) < 1) { 169 | e--; 170 | c *= 2; 171 | } 172 | if (e + eBias >= 1) { 173 | value += rt / c; 174 | } else { 175 | value += rt * Math.pow(2, 1 - eBias); 176 | } 177 | if (value * c >= 2) { 178 | e++; 179 | c /= 2; 180 | } 181 | 182 | if (e + eBias >= eMax) { 183 | m = 0; 184 | e = eMax; 185 | } else if (e + eBias >= 1) { 186 | m = (value * c - 1) * Math.pow(2, mLen); 187 | e = e + eBias; 188 | } else { 189 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); 190 | e = 0; 191 | } 192 | } 193 | 194 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} 195 | 196 | e = (e << mLen) | m; 197 | eLen += mLen; 198 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} 199 | 200 | buffer[offset + i - d] |= s * 128; 201 | } 202 | 203 | var toString = {}.toString; 204 | 205 | var isArray = Array.isArray || function (arr) { 206 | return toString.call(arr) == '[object Array]'; 207 | }; 208 | 209 | var INSPECT_MAX_BYTES = 50; 210 | 211 | /** 212 | * If \`Buffer.TYPED_ARRAY_SUPPORT\`: 213 | * === true Use Uint8Array implementation (fastest) 214 | * === false Use Object implementation (most compatible, even IE6) 215 | * 216 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 217 | * Opera 11.6+, iOS 4.2+. 218 | * 219 | * Due to various browser bugs, sometimes the Object implementation will be used even 220 | * when the browser supports typed arrays. 221 | * 222 | * Note: 223 | * 224 | * - Firefox 4-29 lacks support for adding new properties to \`Uint8Array\` instances, 225 | * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. 226 | * 227 | * - Chrome 9-10 is missing the \`TypedArray.prototype.subarray\` function. 228 | * 229 | * - IE10 has a broken \`TypedArray.prototype.subarray\` function which returns arrays of 230 | * incorrect length in some situations. 231 | 232 | * We detect these buggy browsers and set \`Buffer.TYPED_ARRAY_SUPPORT\` to \`false\` so they 233 | * get the Object implementation, which is slower but behaves correctly. 234 | */ 235 | Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined 236 | ? global$1.TYPED_ARRAY_SUPPORT 237 | : true; 238 | 239 | function kMaxLength () { 240 | return Buffer.TYPED_ARRAY_SUPPORT 241 | ? 0x7fffffff 242 | : 0x3fffffff 243 | } 244 | 245 | function createBuffer (that, length) { 246 | if (kMaxLength() < length) { 247 | throw new RangeError('Invalid typed array length') 248 | } 249 | if (Buffer.TYPED_ARRAY_SUPPORT) { 250 | // Return an augmented \`Uint8Array\` instance, for best performance 251 | that = new Uint8Array(length); 252 | that.__proto__ = Buffer.prototype; 253 | } else { 254 | // Fallback: Return an object instance of the Buffer class 255 | if (that === null) { 256 | that = new Buffer(length); 257 | } 258 | that.length = length; 259 | } 260 | 261 | return that 262 | } 263 | 264 | /** 265 | * The Buffer constructor returns instances of \`Uint8Array\` that have their 266 | * prototype changed to \`Buffer.prototype\`. Furthermore, \`Buffer\` is a subclass of 267 | * \`Uint8Array\`, so the returned instances will have all the node \`Buffer\` methods 268 | * and the \`Uint8Array\` methods. Square bracket notation works as expected -- it 269 | * returns a single octet. 270 | * 271 | * The \`Uint8Array\` prototype remains unmodified. 272 | */ 273 | 274 | function Buffer (arg, encodingOrOffset, length) { 275 | if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { 276 | return new Buffer(arg, encodingOrOffset, length) 277 | } 278 | 279 | // Common case. 280 | if (typeof arg === 'number') { 281 | if (typeof encodingOrOffset === 'string') { 282 | throw new Error( 283 | 'If encoding is specified then the first argument must be a string' 284 | ) 285 | } 286 | return allocUnsafe(this, arg) 287 | } 288 | return from(this, arg, encodingOrOffset, length) 289 | } 290 | 291 | Buffer.poolSize = 8192; // not used by this implementation 292 | 293 | // TODO: Legacy, not needed anymore. Remove in next major version. 294 | Buffer._augment = function (arr) { 295 | arr.__proto__ = Buffer.prototype; 296 | return arr 297 | }; 298 | 299 | function from (that, value, encodingOrOffset, length) { 300 | if (typeof value === 'number') { 301 | throw new TypeError('\\"value\\" argument must not be a number') 302 | } 303 | 304 | if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { 305 | return fromArrayBuffer(that, value, encodingOrOffset, length) 306 | } 307 | 308 | if (typeof value === 'string') { 309 | return fromString(that, value, encodingOrOffset) 310 | } 311 | 312 | return fromObject(that, value) 313 | } 314 | 315 | /** 316 | * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError 317 | * if value is a number. 318 | * Buffer.from(str[, encoding]) 319 | * Buffer.from(array) 320 | * Buffer.from(buffer) 321 | * Buffer.from(arrayBuffer[, byteOffset[, length]]) 322 | **/ 323 | Buffer.from = function (value, encodingOrOffset, length) { 324 | return from(null, value, encodingOrOffset, length) 325 | }; 326 | 327 | if (Buffer.TYPED_ARRAY_SUPPORT) { 328 | Buffer.prototype.__proto__ = Uint8Array.prototype; 329 | Buffer.__proto__ = Uint8Array; 330 | } 331 | 332 | function assertSize (size) { 333 | if (typeof size !== 'number') { 334 | throw new TypeError('\\"size\\" argument must be a number') 335 | } else if (size < 0) { 336 | throw new RangeError('\\"size\\" argument must not be negative') 337 | } 338 | } 339 | 340 | function alloc (that, size, fill, encoding) { 341 | assertSize(size); 342 | if (size <= 0) { 343 | return createBuffer(that, size) 344 | } 345 | if (fill !== undefined) { 346 | // Only pay attention to encoding if it's a string. This 347 | // prevents accidentally sending in a number that would 348 | // be interpretted as a start offset. 349 | return typeof encoding === 'string' 350 | ? createBuffer(that, size).fill(fill, encoding) 351 | : createBuffer(that, size).fill(fill) 352 | } 353 | return createBuffer(that, size) 354 | } 355 | 356 | /** 357 | * Creates a new filled Buffer instance. 358 | * alloc(size[, fill[, encoding]]) 359 | **/ 360 | Buffer.alloc = function (size, fill, encoding) { 361 | return alloc(null, size, fill, encoding) 362 | }; 363 | 364 | function allocUnsafe (that, size) { 365 | assertSize(size); 366 | that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); 367 | if (!Buffer.TYPED_ARRAY_SUPPORT) { 368 | for (var i = 0; i < size; ++i) { 369 | that[i] = 0; 370 | } 371 | } 372 | return that 373 | } 374 | 375 | /** 376 | * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. 377 | * */ 378 | Buffer.allocUnsafe = function (size) { 379 | return allocUnsafe(null, size) 380 | }; 381 | /** 382 | * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. 383 | */ 384 | Buffer.allocUnsafeSlow = function (size) { 385 | return allocUnsafe(null, size) 386 | }; 387 | 388 | function fromString (that, string, encoding) { 389 | if (typeof encoding !== 'string' || encoding === '') { 390 | encoding = 'utf8'; 391 | } 392 | 393 | if (!Buffer.isEncoding(encoding)) { 394 | throw new TypeError('\\"encoding\\" must be a valid string encoding') 395 | } 396 | 397 | var length = byteLength(string, encoding) | 0; 398 | that = createBuffer(that, length); 399 | 400 | var actual = that.write(string, encoding); 401 | 402 | if (actual !== length) { 403 | // Writing a hex string, for example, that contains invalid characters will 404 | // cause everything after the first invalid character to be ignored. (e.g. 405 | // 'abxxcd' will be treated as 'ab') 406 | that = that.slice(0, actual); 407 | } 408 | 409 | return that 410 | } 411 | 412 | function fromArrayLike (that, array) { 413 | var length = array.length < 0 ? 0 : checked(array.length) | 0; 414 | that = createBuffer(that, length); 415 | for (var i = 0; i < length; i += 1) { 416 | that[i] = array[i] & 255; 417 | } 418 | return that 419 | } 420 | 421 | function fromArrayBuffer (that, array, byteOffset, length) { 422 | array.byteLength; // this throws if \`array\` is not a valid ArrayBuffer 423 | 424 | if (byteOffset < 0 || array.byteLength < byteOffset) { 425 | throw new RangeError('\\\\'offset\\\\' is out of bounds') 426 | } 427 | 428 | if (array.byteLength < byteOffset + (length || 0)) { 429 | throw new RangeError('\\\\'length\\\\' is out of bounds') 430 | } 431 | 432 | if (byteOffset === undefined && length === undefined) { 433 | array = new Uint8Array(array); 434 | } else if (length === undefined) { 435 | array = new Uint8Array(array, byteOffset); 436 | } else { 437 | array = new Uint8Array(array, byteOffset, length); 438 | } 439 | 440 | if (Buffer.TYPED_ARRAY_SUPPORT) { 441 | // Return an augmented \`Uint8Array\` instance, for best performance 442 | that = array; 443 | that.__proto__ = Buffer.prototype; 444 | } else { 445 | // Fallback: Return an object instance of the Buffer class 446 | that = fromArrayLike(that, array); 447 | } 448 | return that 449 | } 450 | 451 | function fromObject (that, obj) { 452 | if (internalIsBuffer(obj)) { 453 | var len = checked(obj.length) | 0; 454 | that = createBuffer(that, len); 455 | 456 | if (that.length === 0) { 457 | return that 458 | } 459 | 460 | obj.copy(that, 0, 0, len); 461 | return that 462 | } 463 | 464 | if (obj) { 465 | if ((typeof ArrayBuffer !== 'undefined' && 466 | obj.buffer instanceof ArrayBuffer) || 'length' in obj) { 467 | if (typeof obj.length !== 'number' || isnan(obj.length)) { 468 | return createBuffer(that, 0) 469 | } 470 | return fromArrayLike(that, obj) 471 | } 472 | 473 | if (obj.type === 'Buffer' && isArray(obj.data)) { 474 | return fromArrayLike(that, obj.data) 475 | } 476 | } 477 | 478 | throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') 479 | } 480 | 481 | function checked (length) { 482 | // Note: cannot use \`length < kMaxLength()\` here because that fails when 483 | // length is NaN (which is otherwise coerced to zero.) 484 | if (length >= kMaxLength()) { 485 | throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 486 | 'size: 0x' + kMaxLength().toString(16) + ' bytes') 487 | } 488 | return length | 0 489 | } 490 | Buffer.isBuffer = isBuffer; 491 | function internalIsBuffer (b) { 492 | return !!(b != null && b._isBuffer) 493 | } 494 | 495 | Buffer.compare = function compare (a, b) { 496 | if (!internalIsBuffer(a) || !internalIsBuffer(b)) { 497 | throw new TypeError('Arguments must be Buffers') 498 | } 499 | 500 | if (a === b) return 0 501 | 502 | var x = a.length; 503 | var y = b.length; 504 | 505 | for (var i = 0, len = Math.min(x, y); i < len; ++i) { 506 | if (a[i] !== b[i]) { 507 | x = a[i]; 508 | y = b[i]; 509 | break 510 | } 511 | } 512 | 513 | if (x < y) return -1 514 | if (y < x) return 1 515 | return 0 516 | }; 517 | 518 | Buffer.isEncoding = function isEncoding (encoding) { 519 | switch (String(encoding).toLowerCase()) { 520 | case 'hex': 521 | case 'utf8': 522 | case 'utf-8': 523 | case 'ascii': 524 | case 'latin1': 525 | case 'binary': 526 | case 'base64': 527 | case 'ucs2': 528 | case 'ucs-2': 529 | case 'utf16le': 530 | case 'utf-16le': 531 | return true 532 | default: 533 | return false 534 | } 535 | }; 536 | 537 | Buffer.concat = function concat (list, length) { 538 | if (!isArray(list)) { 539 | throw new TypeError('\\"list\\" argument must be an Array of Buffers') 540 | } 541 | 542 | if (list.length === 0) { 543 | return Buffer.alloc(0) 544 | } 545 | 546 | var i; 547 | if (length === undefined) { 548 | length = 0; 549 | for (i = 0; i < list.length; ++i) { 550 | length += list[i].length; 551 | } 552 | } 553 | 554 | var buffer = Buffer.allocUnsafe(length); 555 | var pos = 0; 556 | for (i = 0; i < list.length; ++i) { 557 | var buf = list[i]; 558 | if (!internalIsBuffer(buf)) { 559 | throw new TypeError('\\"list\\" argument must be an Array of Buffers') 560 | } 561 | buf.copy(buffer, pos); 562 | pos += buf.length; 563 | } 564 | return buffer 565 | }; 566 | 567 | function byteLength (string, encoding) { 568 | if (internalIsBuffer(string)) { 569 | return string.length 570 | } 571 | if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && 572 | (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { 573 | return string.byteLength 574 | } 575 | if (typeof string !== 'string') { 576 | string = '' + string; 577 | } 578 | 579 | var len = string.length; 580 | if (len === 0) return 0 581 | 582 | // Use a for loop to avoid recursion 583 | var loweredCase = false; 584 | for (;;) { 585 | switch (encoding) { 586 | case 'ascii': 587 | case 'latin1': 588 | case 'binary': 589 | return len 590 | case 'utf8': 591 | case 'utf-8': 592 | case undefined: 593 | return utf8ToBytes(string).length 594 | case 'ucs2': 595 | case 'ucs-2': 596 | case 'utf16le': 597 | case 'utf-16le': 598 | return len * 2 599 | case 'hex': 600 | return len >>> 1 601 | case 'base64': 602 | return base64ToBytes(string).length 603 | default: 604 | if (loweredCase) return utf8ToBytes(string).length // assume utf8 605 | encoding = ('' + encoding).toLowerCase(); 606 | loweredCase = true; 607 | } 608 | } 609 | } 610 | Buffer.byteLength = byteLength; 611 | 612 | function slowToString (encoding, start, end) { 613 | var loweredCase = false; 614 | 615 | // No need to verify that \\"this.length <= MAX_UINT32\\" since it's a read-only 616 | // property of a typed array. 617 | 618 | // This behaves neither like String nor Uint8Array in that we set start/end 619 | // to their upper/lower bounds if the value passed is out of range. 620 | // undefined is handled specially as per ECMA-262 6th Edition, 621 | // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. 622 | if (start === undefined || start < 0) { 623 | start = 0; 624 | } 625 | // Return early if start > this.length. Done here to prevent potential uint32 626 | // coercion fail below. 627 | if (start > this.length) { 628 | return '' 629 | } 630 | 631 | if (end === undefined || end > this.length) { 632 | end = this.length; 633 | } 634 | 635 | if (end <= 0) { 636 | return '' 637 | } 638 | 639 | // Force coersion to uint32. This will also coerce falsey/NaN values to 0. 640 | end >>>= 0; 641 | start >>>= 0; 642 | 643 | if (end <= start) { 644 | return '' 645 | } 646 | 647 | if (!encoding) encoding = 'utf8'; 648 | 649 | while (true) { 650 | switch (encoding) { 651 | case 'hex': 652 | return hexSlice(this, start, end) 653 | 654 | case 'utf8': 655 | case 'utf-8': 656 | return utf8Slice(this, start, end) 657 | 658 | case 'ascii': 659 | return asciiSlice(this, start, end) 660 | 661 | case 'latin1': 662 | case 'binary': 663 | return latin1Slice(this, start, end) 664 | 665 | case 'base64': 666 | return base64Slice(this, start, end) 667 | 668 | case 'ucs2': 669 | case 'ucs-2': 670 | case 'utf16le': 671 | case 'utf-16le': 672 | return utf16leSlice(this, start, end) 673 | 674 | default: 675 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 676 | encoding = (encoding + '').toLowerCase(); 677 | loweredCase = true; 678 | } 679 | } 680 | } 681 | 682 | // The property is used by \`Buffer.isBuffer\` and \`is-buffer\` (in Safari 5-7) to detect 683 | // Buffer instances. 684 | Buffer.prototype._isBuffer = true; 685 | 686 | function swap (b, n, m) { 687 | var i = b[n]; 688 | b[n] = b[m]; 689 | b[m] = i; 690 | } 691 | 692 | Buffer.prototype.swap16 = function swap16 () { 693 | var len = this.length; 694 | if (len % 2 !== 0) { 695 | throw new RangeError('Buffer size must be a multiple of 16-bits') 696 | } 697 | for (var i = 0; i < len; i += 2) { 698 | swap(this, i, i + 1); 699 | } 700 | return this 701 | }; 702 | 703 | Buffer.prototype.swap32 = function swap32 () { 704 | var len = this.length; 705 | if (len % 4 !== 0) { 706 | throw new RangeError('Buffer size must be a multiple of 32-bits') 707 | } 708 | for (var i = 0; i < len; i += 4) { 709 | swap(this, i, i + 3); 710 | swap(this, i + 1, i + 2); 711 | } 712 | return this 713 | }; 714 | 715 | Buffer.prototype.swap64 = function swap64 () { 716 | var len = this.length; 717 | if (len % 8 !== 0) { 718 | throw new RangeError('Buffer size must be a multiple of 64-bits') 719 | } 720 | for (var i = 0; i < len; i += 8) { 721 | swap(this, i, i + 7); 722 | swap(this, i + 1, i + 6); 723 | swap(this, i + 2, i + 5); 724 | swap(this, i + 3, i + 4); 725 | } 726 | return this 727 | }; 728 | 729 | Buffer.prototype.toString = function toString () { 730 | var length = this.length | 0; 731 | if (length === 0) return '' 732 | if (arguments.length === 0) return utf8Slice(this, 0, length) 733 | return slowToString.apply(this, arguments) 734 | }; 735 | 736 | Buffer.prototype.equals = function equals (b) { 737 | if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') 738 | if (this === b) return true 739 | return Buffer.compare(this, b) === 0 740 | }; 741 | 742 | Buffer.prototype.inspect = function inspect () { 743 | var str = ''; 744 | var max = INSPECT_MAX_BYTES; 745 | if (this.length > 0) { 746 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); 747 | if (this.length > max) str += ' ... '; 748 | } 749 | return '' 750 | }; 751 | 752 | Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { 753 | if (!internalIsBuffer(target)) { 754 | throw new TypeError('Argument must be a Buffer') 755 | } 756 | 757 | if (start === undefined) { 758 | start = 0; 759 | } 760 | if (end === undefined) { 761 | end = target ? target.length : 0; 762 | } 763 | if (thisStart === undefined) { 764 | thisStart = 0; 765 | } 766 | if (thisEnd === undefined) { 767 | thisEnd = this.length; 768 | } 769 | 770 | if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { 771 | throw new RangeError('out of range index') 772 | } 773 | 774 | if (thisStart >= thisEnd && start >= end) { 775 | return 0 776 | } 777 | if (thisStart >= thisEnd) { 778 | return -1 779 | } 780 | if (start >= end) { 781 | return 1 782 | } 783 | 784 | start >>>= 0; 785 | end >>>= 0; 786 | thisStart >>>= 0; 787 | thisEnd >>>= 0; 788 | 789 | if (this === target) return 0 790 | 791 | var x = thisEnd - thisStart; 792 | var y = end - start; 793 | var len = Math.min(x, y); 794 | 795 | var thisCopy = this.slice(thisStart, thisEnd); 796 | var targetCopy = target.slice(start, end); 797 | 798 | for (var i = 0; i < len; ++i) { 799 | if (thisCopy[i] !== targetCopy[i]) { 800 | x = thisCopy[i]; 801 | y = targetCopy[i]; 802 | break 803 | } 804 | } 805 | 806 | if (x < y) return -1 807 | if (y < x) return 1 808 | return 0 809 | }; 810 | 811 | // Finds either the first index of \`val\` in \`buffer\` at offset >= \`byteOffset\`, 812 | // OR the last index of \`val\` in \`buffer\` at offset <= \`byteOffset\`. 813 | // 814 | // Arguments: 815 | // - buffer - a Buffer to search 816 | // - val - a string, Buffer, or number 817 | // - byteOffset - an index into \`buffer\`; will be clamped to an int32 818 | // - encoding - an optional encoding, relevant is val is a string 819 | // - dir - true for indexOf, false for lastIndexOf 820 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { 821 | // Empty buffer means no match 822 | if (buffer.length === 0) return -1 823 | 824 | // Normalize byteOffset 825 | if (typeof byteOffset === 'string') { 826 | encoding = byteOffset; 827 | byteOffset = 0; 828 | } else if (byteOffset > 0x7fffffff) { 829 | byteOffset = 0x7fffffff; 830 | } else if (byteOffset < -0x80000000) { 831 | byteOffset = -0x80000000; 832 | } 833 | byteOffset = +byteOffset; // Coerce to Number. 834 | if (isNaN(byteOffset)) { 835 | // byteOffset: it it's undefined, null, NaN, \\"foo\\", etc, search whole buffer 836 | byteOffset = dir ? 0 : (buffer.length - 1); 837 | } 838 | 839 | // Normalize byteOffset: negative offsets start from the end of the buffer 840 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset; 841 | if (byteOffset >= buffer.length) { 842 | if (dir) return -1 843 | else byteOffset = buffer.length - 1; 844 | } else if (byteOffset < 0) { 845 | if (dir) byteOffset = 0; 846 | else return -1 847 | } 848 | 849 | // Normalize val 850 | if (typeof val === 'string') { 851 | val = Buffer.from(val, encoding); 852 | } 853 | 854 | // Finally, search either indexOf (if dir is true) or lastIndexOf 855 | if (internalIsBuffer(val)) { 856 | // Special case: looking for empty string/buffer always fails 857 | if (val.length === 0) { 858 | return -1 859 | } 860 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir) 861 | } else if (typeof val === 'number') { 862 | val = val & 0xFF; // Search for a byte value [0-255] 863 | if (Buffer.TYPED_ARRAY_SUPPORT && 864 | typeof Uint8Array.prototype.indexOf === 'function') { 865 | if (dir) { 866 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) 867 | } else { 868 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) 869 | } 870 | } 871 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) 872 | } 873 | 874 | throw new TypeError('val must be string, number or Buffer') 875 | } 876 | 877 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) { 878 | var indexSize = 1; 879 | var arrLength = arr.length; 880 | var valLength = val.length; 881 | 882 | if (encoding !== undefined) { 883 | encoding = String(encoding).toLowerCase(); 884 | if (encoding === 'ucs2' || encoding === 'ucs-2' || 885 | encoding === 'utf16le' || encoding === 'utf-16le') { 886 | if (arr.length < 2 || val.length < 2) { 887 | return -1 888 | } 889 | indexSize = 2; 890 | arrLength /= 2; 891 | valLength /= 2; 892 | byteOffset /= 2; 893 | } 894 | } 895 | 896 | function read$$1 (buf, i) { 897 | if (indexSize === 1) { 898 | return buf[i] 899 | } else { 900 | return buf.readUInt16BE(i * indexSize) 901 | } 902 | } 903 | 904 | var i; 905 | if (dir) { 906 | var foundIndex = -1; 907 | for (i = byteOffset; i < arrLength; i++) { 908 | if (read$$1(arr, i) === read$$1(val, foundIndex === -1 ? 0 : i - foundIndex)) { 909 | if (foundIndex === -1) foundIndex = i; 910 | if (i - foundIndex + 1 === valLength) return foundIndex * indexSize 911 | } else { 912 | if (foundIndex !== -1) i -= i - foundIndex; 913 | foundIndex = -1; 914 | } 915 | } 916 | } else { 917 | if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; 918 | for (i = byteOffset; i >= 0; i--) { 919 | var found = true; 920 | for (var j = 0; j < valLength; j++) { 921 | if (read$$1(arr, i + j) !== read$$1(val, j)) { 922 | found = false; 923 | break 924 | } 925 | } 926 | if (found) return i 927 | } 928 | } 929 | 930 | return -1 931 | } 932 | 933 | Buffer.prototype.includes = function includes (val, byteOffset, encoding) { 934 | return this.indexOf(val, byteOffset, encoding) !== -1 935 | }; 936 | 937 | Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { 938 | return bidirectionalIndexOf(this, val, byteOffset, encoding, true) 939 | }; 940 | 941 | Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { 942 | return bidirectionalIndexOf(this, val, byteOffset, encoding, false) 943 | }; 944 | 945 | function hexWrite (buf, string, offset, length) { 946 | offset = Number(offset) || 0; 947 | var remaining = buf.length - offset; 948 | if (!length) { 949 | length = remaining; 950 | } else { 951 | length = Number(length); 952 | if (length > remaining) { 953 | length = remaining; 954 | } 955 | } 956 | 957 | // must be an even number of digits 958 | var strLen = string.length; 959 | if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') 960 | 961 | if (length > strLen / 2) { 962 | length = strLen / 2; 963 | } 964 | for (var i = 0; i < length; ++i) { 965 | var parsed = parseInt(string.substr(i * 2, 2), 16); 966 | if (isNaN(parsed)) return i 967 | buf[offset + i] = parsed; 968 | } 969 | return i 970 | } 971 | 972 | function utf8Write (buf, string, offset, length) { 973 | return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) 974 | } 975 | 976 | function asciiWrite (buf, string, offset, length) { 977 | return blitBuffer(asciiToBytes(string), buf, offset, length) 978 | } 979 | 980 | function latin1Write (buf, string, offset, length) { 981 | return asciiWrite(buf, string, offset, length) 982 | } 983 | 984 | function base64Write (buf, string, offset, length) { 985 | return blitBuffer(base64ToBytes(string), buf, offset, length) 986 | } 987 | 988 | function ucs2Write (buf, string, offset, length) { 989 | return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) 990 | } 991 | 992 | Buffer.prototype.write = function write$$1 (string, offset, length, encoding) { 993 | // Buffer#write(string) 994 | if (offset === undefined) { 995 | encoding = 'utf8'; 996 | length = this.length; 997 | offset = 0; 998 | // Buffer#write(string, encoding) 999 | } else if (length === undefined && typeof offset === 'string') { 1000 | encoding = offset; 1001 | length = this.length; 1002 | offset = 0; 1003 | // Buffer#write(string, offset[, length][, encoding]) 1004 | } else if (isFinite(offset)) { 1005 | offset = offset | 0; 1006 | if (isFinite(length)) { 1007 | length = length | 0; 1008 | if (encoding === undefined) encoding = 'utf8'; 1009 | } else { 1010 | encoding = length; 1011 | length = undefined; 1012 | } 1013 | // legacy write(string, encoding, offset, length) - remove in v0.13 1014 | } else { 1015 | throw new Error( 1016 | 'Buffer.write(string, encoding, offset[, length]) is no longer supported' 1017 | ) 1018 | } 1019 | 1020 | var remaining = this.length - offset; 1021 | if (length === undefined || length > remaining) length = remaining; 1022 | 1023 | if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { 1024 | throw new RangeError('Attempt to write outside buffer bounds') 1025 | } 1026 | 1027 | if (!encoding) encoding = 'utf8'; 1028 | 1029 | var loweredCase = false; 1030 | for (;;) { 1031 | switch (encoding) { 1032 | case 'hex': 1033 | return hexWrite(this, string, offset, length) 1034 | 1035 | case 'utf8': 1036 | case 'utf-8': 1037 | return utf8Write(this, string, offset, length) 1038 | 1039 | case 'ascii': 1040 | return asciiWrite(this, string, offset, length) 1041 | 1042 | case 'latin1': 1043 | case 'binary': 1044 | return latin1Write(this, string, offset, length) 1045 | 1046 | case 'base64': 1047 | // Warning: maxLength not taken into account in base64Write 1048 | return base64Write(this, string, offset, length) 1049 | 1050 | case 'ucs2': 1051 | case 'ucs-2': 1052 | case 'utf16le': 1053 | case 'utf-16le': 1054 | return ucs2Write(this, string, offset, length) 1055 | 1056 | default: 1057 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 1058 | encoding = ('' + encoding).toLowerCase(); 1059 | loweredCase = true; 1060 | } 1061 | } 1062 | }; 1063 | 1064 | Buffer.prototype.toJSON = function toJSON () { 1065 | return { 1066 | type: 'Buffer', 1067 | data: Array.prototype.slice.call(this._arr || this, 0) 1068 | } 1069 | }; 1070 | 1071 | function base64Slice (buf, start, end) { 1072 | if (start === 0 && end === buf.length) { 1073 | return fromByteArray(buf) 1074 | } else { 1075 | return fromByteArray(buf.slice(start, end)) 1076 | } 1077 | } 1078 | 1079 | function utf8Slice (buf, start, end) { 1080 | end = Math.min(buf.length, end); 1081 | var res = []; 1082 | 1083 | var i = start; 1084 | while (i < end) { 1085 | var firstByte = buf[i]; 1086 | var codePoint = null; 1087 | var bytesPerSequence = (firstByte > 0xEF) ? 4 1088 | : (firstByte > 0xDF) ? 3 1089 | : (firstByte > 0xBF) ? 2 1090 | : 1; 1091 | 1092 | if (i + bytesPerSequence <= end) { 1093 | var secondByte, thirdByte, fourthByte, tempCodePoint; 1094 | 1095 | switch (bytesPerSequence) { 1096 | case 1: 1097 | if (firstByte < 0x80) { 1098 | codePoint = firstByte; 1099 | } 1100 | break 1101 | case 2: 1102 | secondByte = buf[i + 1]; 1103 | if ((secondByte & 0xC0) === 0x80) { 1104 | tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); 1105 | if (tempCodePoint > 0x7F) { 1106 | codePoint = tempCodePoint; 1107 | } 1108 | } 1109 | break 1110 | case 3: 1111 | secondByte = buf[i + 1]; 1112 | thirdByte = buf[i + 2]; 1113 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { 1114 | tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); 1115 | if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { 1116 | codePoint = tempCodePoint; 1117 | } 1118 | } 1119 | break 1120 | case 4: 1121 | secondByte = buf[i + 1]; 1122 | thirdByte = buf[i + 2]; 1123 | fourthByte = buf[i + 3]; 1124 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { 1125 | tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); 1126 | if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { 1127 | codePoint = tempCodePoint; 1128 | } 1129 | } 1130 | } 1131 | } 1132 | 1133 | if (codePoint === null) { 1134 | // we did not generate a valid codePoint so insert a 1135 | // replacement char (U+FFFD) and advance only 1 byte 1136 | codePoint = 0xFFFD; 1137 | bytesPerSequence = 1; 1138 | } else if (codePoint > 0xFFFF) { 1139 | // encode to utf16 (surrogate pair dance) 1140 | codePoint -= 0x10000; 1141 | res.push(codePoint >>> 10 & 0x3FF | 0xD800); 1142 | codePoint = 0xDC00 | codePoint & 0x3FF; 1143 | } 1144 | 1145 | res.push(codePoint); 1146 | i += bytesPerSequence; 1147 | } 1148 | 1149 | return decodeCodePointsArray(res) 1150 | } 1151 | 1152 | // Based on http://stackoverflow.com/a/22747272/680742, the browser with 1153 | // the lowest limit is Chrome, with 0x10000 args. 1154 | // We go 1 magnitude less, for safety 1155 | var MAX_ARGUMENTS_LENGTH = 0x1000; 1156 | 1157 | function decodeCodePointsArray (codePoints) { 1158 | var len = codePoints.length; 1159 | if (len <= MAX_ARGUMENTS_LENGTH) { 1160 | return String.fromCharCode.apply(String, codePoints) // avoid extra slice() 1161 | } 1162 | 1163 | // Decode in chunks to avoid \\"call stack size exceeded\\". 1164 | var res = ''; 1165 | var i = 0; 1166 | while (i < len) { 1167 | res += String.fromCharCode.apply( 1168 | String, 1169 | codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) 1170 | ); 1171 | } 1172 | return res 1173 | } 1174 | 1175 | function asciiSlice (buf, start, end) { 1176 | var ret = ''; 1177 | end = Math.min(buf.length, end); 1178 | 1179 | for (var i = start; i < end; ++i) { 1180 | ret += String.fromCharCode(buf[i] & 0x7F); 1181 | } 1182 | return ret 1183 | } 1184 | 1185 | function latin1Slice (buf, start, end) { 1186 | var ret = ''; 1187 | end = Math.min(buf.length, end); 1188 | 1189 | for (var i = start; i < end; ++i) { 1190 | ret += String.fromCharCode(buf[i]); 1191 | } 1192 | return ret 1193 | } 1194 | 1195 | function hexSlice (buf, start, end) { 1196 | var len = buf.length; 1197 | 1198 | if (!start || start < 0) start = 0; 1199 | if (!end || end < 0 || end > len) end = len; 1200 | 1201 | var out = ''; 1202 | for (var i = start; i < end; ++i) { 1203 | out += toHex(buf[i]); 1204 | } 1205 | return out 1206 | } 1207 | 1208 | function utf16leSlice (buf, start, end) { 1209 | var bytes = buf.slice(start, end); 1210 | var res = ''; 1211 | for (var i = 0; i < bytes.length; i += 2) { 1212 | res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); 1213 | } 1214 | return res 1215 | } 1216 | 1217 | Buffer.prototype.slice = function slice (start, end) { 1218 | var len = this.length; 1219 | start = ~~start; 1220 | end = end === undefined ? len : ~~end; 1221 | 1222 | if (start < 0) { 1223 | start += len; 1224 | if (start < 0) start = 0; 1225 | } else if (start > len) { 1226 | start = len; 1227 | } 1228 | 1229 | if (end < 0) { 1230 | end += len; 1231 | if (end < 0) end = 0; 1232 | } else if (end > len) { 1233 | end = len; 1234 | } 1235 | 1236 | if (end < start) end = start; 1237 | 1238 | var newBuf; 1239 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1240 | newBuf = this.subarray(start, end); 1241 | newBuf.__proto__ = Buffer.prototype; 1242 | } else { 1243 | var sliceLen = end - start; 1244 | newBuf = new Buffer(sliceLen, undefined); 1245 | for (var i = 0; i < sliceLen; ++i) { 1246 | newBuf[i] = this[i + start]; 1247 | } 1248 | } 1249 | 1250 | return newBuf 1251 | }; 1252 | 1253 | /* 1254 | * Need to make sure that buffer isn't trying to write out of bounds. 1255 | */ 1256 | function checkOffset (offset, ext, length) { 1257 | if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') 1258 | if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') 1259 | } 1260 | 1261 | Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { 1262 | offset = offset | 0; 1263 | byteLength = byteLength | 0; 1264 | if (!noAssert) checkOffset(offset, byteLength, this.length); 1265 | 1266 | var val = this[offset]; 1267 | var mul = 1; 1268 | var i = 0; 1269 | while (++i < byteLength && (mul *= 0x100)) { 1270 | val += this[offset + i] * mul; 1271 | } 1272 | 1273 | return val 1274 | }; 1275 | 1276 | Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { 1277 | offset = offset | 0; 1278 | byteLength = byteLength | 0; 1279 | if (!noAssert) { 1280 | checkOffset(offset, byteLength, this.length); 1281 | } 1282 | 1283 | var val = this[offset + --byteLength]; 1284 | var mul = 1; 1285 | while (byteLength > 0 && (mul *= 0x100)) { 1286 | val += this[offset + --byteLength] * mul; 1287 | } 1288 | 1289 | return val 1290 | }; 1291 | 1292 | Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { 1293 | if (!noAssert) checkOffset(offset, 1, this.length); 1294 | return this[offset] 1295 | }; 1296 | 1297 | Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { 1298 | if (!noAssert) checkOffset(offset, 2, this.length); 1299 | return this[offset] | (this[offset + 1] << 8) 1300 | }; 1301 | 1302 | Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { 1303 | if (!noAssert) checkOffset(offset, 2, this.length); 1304 | return (this[offset] << 8) | this[offset + 1] 1305 | }; 1306 | 1307 | Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { 1308 | if (!noAssert) checkOffset(offset, 4, this.length); 1309 | 1310 | return ((this[offset]) | 1311 | (this[offset + 1] << 8) | 1312 | (this[offset + 2] << 16)) + 1313 | (this[offset + 3] * 0x1000000) 1314 | }; 1315 | 1316 | Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { 1317 | if (!noAssert) checkOffset(offset, 4, this.length); 1318 | 1319 | return (this[offset] * 0x1000000) + 1320 | ((this[offset + 1] << 16) | 1321 | (this[offset + 2] << 8) | 1322 | this[offset + 3]) 1323 | }; 1324 | 1325 | Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { 1326 | offset = offset | 0; 1327 | byteLength = byteLength | 0; 1328 | if (!noAssert) checkOffset(offset, byteLength, this.length); 1329 | 1330 | var val = this[offset]; 1331 | var mul = 1; 1332 | var i = 0; 1333 | while (++i < byteLength && (mul *= 0x100)) { 1334 | val += this[offset + i] * mul; 1335 | } 1336 | mul *= 0x80; 1337 | 1338 | if (val >= mul) val -= Math.pow(2, 8 * byteLength); 1339 | 1340 | return val 1341 | }; 1342 | 1343 | Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { 1344 | offset = offset | 0; 1345 | byteLength = byteLength | 0; 1346 | if (!noAssert) checkOffset(offset, byteLength, this.length); 1347 | 1348 | var i = byteLength; 1349 | var mul = 1; 1350 | var val = this[offset + --i]; 1351 | while (i > 0 && (mul *= 0x100)) { 1352 | val += this[offset + --i] * mul; 1353 | } 1354 | mul *= 0x80; 1355 | 1356 | if (val >= mul) val -= Math.pow(2, 8 * byteLength); 1357 | 1358 | return val 1359 | }; 1360 | 1361 | Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { 1362 | if (!noAssert) checkOffset(offset, 1, this.length); 1363 | if (!(this[offset] & 0x80)) return (this[offset]) 1364 | return ((0xff - this[offset] + 1) * -1) 1365 | }; 1366 | 1367 | Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { 1368 | if (!noAssert) checkOffset(offset, 2, this.length); 1369 | var val = this[offset] | (this[offset + 1] << 8); 1370 | return (val & 0x8000) ? val | 0xFFFF0000 : val 1371 | }; 1372 | 1373 | Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { 1374 | if (!noAssert) checkOffset(offset, 2, this.length); 1375 | var val = this[offset + 1] | (this[offset] << 8); 1376 | return (val & 0x8000) ? val | 0xFFFF0000 : val 1377 | }; 1378 | 1379 | Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { 1380 | if (!noAssert) checkOffset(offset, 4, this.length); 1381 | 1382 | return (this[offset]) | 1383 | (this[offset + 1] << 8) | 1384 | (this[offset + 2] << 16) | 1385 | (this[offset + 3] << 24) 1386 | }; 1387 | 1388 | Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { 1389 | if (!noAssert) checkOffset(offset, 4, this.length); 1390 | 1391 | return (this[offset] << 24) | 1392 | (this[offset + 1] << 16) | 1393 | (this[offset + 2] << 8) | 1394 | (this[offset + 3]) 1395 | }; 1396 | 1397 | Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { 1398 | if (!noAssert) checkOffset(offset, 4, this.length); 1399 | return read(this, offset, true, 23, 4) 1400 | }; 1401 | 1402 | Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { 1403 | if (!noAssert) checkOffset(offset, 4, this.length); 1404 | return read(this, offset, false, 23, 4) 1405 | }; 1406 | 1407 | Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { 1408 | if (!noAssert) checkOffset(offset, 8, this.length); 1409 | return read(this, offset, true, 52, 8) 1410 | }; 1411 | 1412 | Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { 1413 | if (!noAssert) checkOffset(offset, 8, this.length); 1414 | return read(this, offset, false, 52, 8) 1415 | }; 1416 | 1417 | function checkInt (buf, value, offset, ext, max, min) { 1418 | if (!internalIsBuffer(buf)) throw new TypeError('\\"buffer\\" argument must be a Buffer instance') 1419 | if (value > max || value < min) throw new RangeError('\\"value\\" argument is out of bounds') 1420 | if (offset + ext > buf.length) throw new RangeError('Index out of range') 1421 | } 1422 | 1423 | Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { 1424 | value = +value; 1425 | offset = offset | 0; 1426 | byteLength = byteLength | 0; 1427 | if (!noAssert) { 1428 | var maxBytes = Math.pow(2, 8 * byteLength) - 1; 1429 | checkInt(this, value, offset, byteLength, maxBytes, 0); 1430 | } 1431 | 1432 | var mul = 1; 1433 | var i = 0; 1434 | this[offset] = value & 0xFF; 1435 | while (++i < byteLength && (mul *= 0x100)) { 1436 | this[offset + i] = (value / mul) & 0xFF; 1437 | } 1438 | 1439 | return offset + byteLength 1440 | }; 1441 | 1442 | Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { 1443 | value = +value; 1444 | offset = offset | 0; 1445 | byteLength = byteLength | 0; 1446 | if (!noAssert) { 1447 | var maxBytes = Math.pow(2, 8 * byteLength) - 1; 1448 | checkInt(this, value, offset, byteLength, maxBytes, 0); 1449 | } 1450 | 1451 | var i = byteLength - 1; 1452 | var mul = 1; 1453 | this[offset + i] = value & 0xFF; 1454 | while (--i >= 0 && (mul *= 0x100)) { 1455 | this[offset + i] = (value / mul) & 0xFF; 1456 | } 1457 | 1458 | return offset + byteLength 1459 | }; 1460 | 1461 | Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { 1462 | value = +value; 1463 | offset = offset | 0; 1464 | if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); 1465 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 1466 | this[offset] = (value & 0xff); 1467 | return offset + 1 1468 | }; 1469 | 1470 | function objectWriteUInt16 (buf, value, offset, littleEndian) { 1471 | if (value < 0) value = 0xffff + value + 1; 1472 | for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { 1473 | buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> 1474 | (littleEndian ? i : 1 - i) * 8; 1475 | } 1476 | } 1477 | 1478 | Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { 1479 | value = +value; 1480 | offset = offset | 0; 1481 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); 1482 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1483 | this[offset] = (value & 0xff); 1484 | this[offset + 1] = (value >>> 8); 1485 | } else { 1486 | objectWriteUInt16(this, value, offset, true); 1487 | } 1488 | return offset + 2 1489 | }; 1490 | 1491 | Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { 1492 | value = +value; 1493 | offset = offset | 0; 1494 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); 1495 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1496 | this[offset] = (value >>> 8); 1497 | this[offset + 1] = (value & 0xff); 1498 | } else { 1499 | objectWriteUInt16(this, value, offset, false); 1500 | } 1501 | return offset + 2 1502 | }; 1503 | 1504 | function objectWriteUInt32 (buf, value, offset, littleEndian) { 1505 | if (value < 0) value = 0xffffffff + value + 1; 1506 | for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { 1507 | buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; 1508 | } 1509 | } 1510 | 1511 | Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { 1512 | value = +value; 1513 | offset = offset | 0; 1514 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); 1515 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1516 | this[offset + 3] = (value >>> 24); 1517 | this[offset + 2] = (value >>> 16); 1518 | this[offset + 1] = (value >>> 8); 1519 | this[offset] = (value & 0xff); 1520 | } else { 1521 | objectWriteUInt32(this, value, offset, true); 1522 | } 1523 | return offset + 4 1524 | }; 1525 | 1526 | Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { 1527 | value = +value; 1528 | offset = offset | 0; 1529 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); 1530 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1531 | this[offset] = (value >>> 24); 1532 | this[offset + 1] = (value >>> 16); 1533 | this[offset + 2] = (value >>> 8); 1534 | this[offset + 3] = (value & 0xff); 1535 | } else { 1536 | objectWriteUInt32(this, value, offset, false); 1537 | } 1538 | return offset + 4 1539 | }; 1540 | 1541 | Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { 1542 | value = +value; 1543 | offset = offset | 0; 1544 | if (!noAssert) { 1545 | var limit = Math.pow(2, 8 * byteLength - 1); 1546 | 1547 | checkInt(this, value, offset, byteLength, limit - 1, -limit); 1548 | } 1549 | 1550 | var i = 0; 1551 | var mul = 1; 1552 | var sub = 0; 1553 | this[offset] = value & 0xFF; 1554 | while (++i < byteLength && (mul *= 0x100)) { 1555 | if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { 1556 | sub = 1; 1557 | } 1558 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 1559 | } 1560 | 1561 | return offset + byteLength 1562 | }; 1563 | 1564 | Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { 1565 | value = +value; 1566 | offset = offset | 0; 1567 | if (!noAssert) { 1568 | var limit = Math.pow(2, 8 * byteLength - 1); 1569 | 1570 | checkInt(this, value, offset, byteLength, limit - 1, -limit); 1571 | } 1572 | 1573 | var i = byteLength - 1; 1574 | var mul = 1; 1575 | var sub = 0; 1576 | this[offset + i] = value & 0xFF; 1577 | while (--i >= 0 && (mul *= 0x100)) { 1578 | if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { 1579 | sub = 1; 1580 | } 1581 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; 1582 | } 1583 | 1584 | return offset + byteLength 1585 | }; 1586 | 1587 | Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { 1588 | value = +value; 1589 | offset = offset | 0; 1590 | if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); 1591 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); 1592 | if (value < 0) value = 0xff + value + 1; 1593 | this[offset] = (value & 0xff); 1594 | return offset + 1 1595 | }; 1596 | 1597 | Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { 1598 | value = +value; 1599 | offset = offset | 0; 1600 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); 1601 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1602 | this[offset] = (value & 0xff); 1603 | this[offset + 1] = (value >>> 8); 1604 | } else { 1605 | objectWriteUInt16(this, value, offset, true); 1606 | } 1607 | return offset + 2 1608 | }; 1609 | 1610 | Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { 1611 | value = +value; 1612 | offset = offset | 0; 1613 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); 1614 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1615 | this[offset] = (value >>> 8); 1616 | this[offset + 1] = (value & 0xff); 1617 | } else { 1618 | objectWriteUInt16(this, value, offset, false); 1619 | } 1620 | return offset + 2 1621 | }; 1622 | 1623 | Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { 1624 | value = +value; 1625 | offset = offset | 0; 1626 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); 1627 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1628 | this[offset] = (value & 0xff); 1629 | this[offset + 1] = (value >>> 8); 1630 | this[offset + 2] = (value >>> 16); 1631 | this[offset + 3] = (value >>> 24); 1632 | } else { 1633 | objectWriteUInt32(this, value, offset, true); 1634 | } 1635 | return offset + 4 1636 | }; 1637 | 1638 | Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { 1639 | value = +value; 1640 | offset = offset | 0; 1641 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); 1642 | if (value < 0) value = 0xffffffff + value + 1; 1643 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1644 | this[offset] = (value >>> 24); 1645 | this[offset + 1] = (value >>> 16); 1646 | this[offset + 2] = (value >>> 8); 1647 | this[offset + 3] = (value & 0xff); 1648 | } else { 1649 | objectWriteUInt32(this, value, offset, false); 1650 | } 1651 | return offset + 4 1652 | }; 1653 | 1654 | function checkIEEE754 (buf, value, offset, ext, max, min) { 1655 | if (offset + ext > buf.length) throw new RangeError('Index out of range') 1656 | if (offset < 0) throw new RangeError('Index out of range') 1657 | } 1658 | 1659 | function writeFloat (buf, value, offset, littleEndian, noAssert) { 1660 | if (!noAssert) { 1661 | checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); 1662 | } 1663 | write(buf, value, offset, littleEndian, 23, 4); 1664 | return offset + 4 1665 | } 1666 | 1667 | Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { 1668 | return writeFloat(this, value, offset, true, noAssert) 1669 | }; 1670 | 1671 | Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { 1672 | return writeFloat(this, value, offset, false, noAssert) 1673 | }; 1674 | 1675 | function writeDouble (buf, value, offset, littleEndian, noAssert) { 1676 | if (!noAssert) { 1677 | checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); 1678 | } 1679 | write(buf, value, offset, littleEndian, 52, 8); 1680 | return offset + 8 1681 | } 1682 | 1683 | Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { 1684 | return writeDouble(this, value, offset, true, noAssert) 1685 | }; 1686 | 1687 | Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { 1688 | return writeDouble(this, value, offset, false, noAssert) 1689 | }; 1690 | 1691 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) 1692 | Buffer.prototype.copy = function copy (target, targetStart, start, end) { 1693 | if (!start) start = 0; 1694 | if (!end && end !== 0) end = this.length; 1695 | if (targetStart >= target.length) targetStart = target.length; 1696 | if (!targetStart) targetStart = 0; 1697 | if (end > 0 && end < start) end = start; 1698 | 1699 | // Copy 0 bytes; we're done 1700 | if (end === start) return 0 1701 | if (target.length === 0 || this.length === 0) return 0 1702 | 1703 | // Fatal error conditions 1704 | if (targetStart < 0) { 1705 | throw new RangeError('targetStart out of bounds') 1706 | } 1707 | if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') 1708 | if (end < 0) throw new RangeError('sourceEnd out of bounds') 1709 | 1710 | // Are we oob? 1711 | if (end > this.length) end = this.length; 1712 | if (target.length - targetStart < end - start) { 1713 | end = target.length - targetStart + start; 1714 | } 1715 | 1716 | var len = end - start; 1717 | var i; 1718 | 1719 | if (this === target && start < targetStart && targetStart < end) { 1720 | // descending copy from end 1721 | for (i = len - 1; i >= 0; --i) { 1722 | target[i + targetStart] = this[i + start]; 1723 | } 1724 | } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { 1725 | // ascending copy from start 1726 | for (i = 0; i < len; ++i) { 1727 | target[i + targetStart] = this[i + start]; 1728 | } 1729 | } else { 1730 | Uint8Array.prototype.set.call( 1731 | target, 1732 | this.subarray(start, start + len), 1733 | targetStart 1734 | ); 1735 | } 1736 | 1737 | return len 1738 | }; 1739 | 1740 | // Usage: 1741 | // buffer.fill(number[, offset[, end]]) 1742 | // buffer.fill(buffer[, offset[, end]]) 1743 | // buffer.fill(string[, offset[, end]][, encoding]) 1744 | Buffer.prototype.fill = function fill (val, start, end, encoding) { 1745 | // Handle string cases: 1746 | if (typeof val === 'string') { 1747 | if (typeof start === 'string') { 1748 | encoding = start; 1749 | start = 0; 1750 | end = this.length; 1751 | } else if (typeof end === 'string') { 1752 | encoding = end; 1753 | end = this.length; 1754 | } 1755 | if (val.length === 1) { 1756 | var code = val.charCodeAt(0); 1757 | if (code < 256) { 1758 | val = code; 1759 | } 1760 | } 1761 | if (encoding !== undefined && typeof encoding !== 'string') { 1762 | throw new TypeError('encoding must be a string') 1763 | } 1764 | if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { 1765 | throw new TypeError('Unknown encoding: ' + encoding) 1766 | } 1767 | } else if (typeof val === 'number') { 1768 | val = val & 255; 1769 | } 1770 | 1771 | // Invalid ranges are not set to a default, so can range check early. 1772 | if (start < 0 || this.length < start || this.length < end) { 1773 | throw new RangeError('Out of range index') 1774 | } 1775 | 1776 | if (end <= start) { 1777 | return this 1778 | } 1779 | 1780 | start = start >>> 0; 1781 | end = end === undefined ? this.length : end >>> 0; 1782 | 1783 | if (!val) val = 0; 1784 | 1785 | var i; 1786 | if (typeof val === 'number') { 1787 | for (i = start; i < end; ++i) { 1788 | this[i] = val; 1789 | } 1790 | } else { 1791 | var bytes = internalIsBuffer(val) 1792 | ? val 1793 | : utf8ToBytes(new Buffer(val, encoding).toString()); 1794 | var len = bytes.length; 1795 | for (i = 0; i < end - start; ++i) { 1796 | this[i + start] = bytes[i % len]; 1797 | } 1798 | } 1799 | 1800 | return this 1801 | }; 1802 | 1803 | // HELPER FUNCTIONS 1804 | // ================ 1805 | 1806 | var INVALID_BASE64_RE = /[^+\\\\/0-9A-Za-z-_]/g; 1807 | 1808 | function base64clean (str) { 1809 | // Node strips out invalid characters like \\\\n and \\\\t from the string, base64-js does not 1810 | str = stringtrim(str).replace(INVALID_BASE64_RE, ''); 1811 | // Node converts strings with length < 2 to '' 1812 | if (str.length < 2) return '' 1813 | // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 1814 | while (str.length % 4 !== 0) { 1815 | str = str + '='; 1816 | } 1817 | return str 1818 | } 1819 | 1820 | function stringtrim (str) { 1821 | if (str.trim) return str.trim() 1822 | return str.replace(/^\\\\s+|\\\\s+$/g, '') 1823 | } 1824 | 1825 | function toHex (n) { 1826 | if (n < 16) return '0' + n.toString(16) 1827 | return n.toString(16) 1828 | } 1829 | 1830 | function utf8ToBytes (string, units) { 1831 | units = units || Infinity; 1832 | var codePoint; 1833 | var length = string.length; 1834 | var leadSurrogate = null; 1835 | var bytes = []; 1836 | 1837 | for (var i = 0; i < length; ++i) { 1838 | codePoint = string.charCodeAt(i); 1839 | 1840 | // is surrogate component 1841 | if (codePoint > 0xD7FF && codePoint < 0xE000) { 1842 | // last char was a lead 1843 | if (!leadSurrogate) { 1844 | // no lead yet 1845 | if (codePoint > 0xDBFF) { 1846 | // unexpected trail 1847 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1848 | continue 1849 | } else if (i + 1 === length) { 1850 | // unpaired lead 1851 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1852 | continue 1853 | } 1854 | 1855 | // valid lead 1856 | leadSurrogate = codePoint; 1857 | 1858 | continue 1859 | } 1860 | 1861 | // 2 leads in a row 1862 | if (codePoint < 0xDC00) { 1863 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1864 | leadSurrogate = codePoint; 1865 | continue 1866 | } 1867 | 1868 | // valid surrogate pair 1869 | codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; 1870 | } else if (leadSurrogate) { 1871 | // valid bmp char, but last char was a lead 1872 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); 1873 | } 1874 | 1875 | leadSurrogate = null; 1876 | 1877 | // encode utf8 1878 | if (codePoint < 0x80) { 1879 | if ((units -= 1) < 0) break 1880 | bytes.push(codePoint); 1881 | } else if (codePoint < 0x800) { 1882 | if ((units -= 2) < 0) break 1883 | bytes.push( 1884 | codePoint >> 0x6 | 0xC0, 1885 | codePoint & 0x3F | 0x80 1886 | ); 1887 | } else if (codePoint < 0x10000) { 1888 | if ((units -= 3) < 0) break 1889 | bytes.push( 1890 | codePoint >> 0xC | 0xE0, 1891 | codePoint >> 0x6 & 0x3F | 0x80, 1892 | codePoint & 0x3F | 0x80 1893 | ); 1894 | } else if (codePoint < 0x110000) { 1895 | if ((units -= 4) < 0) break 1896 | bytes.push( 1897 | codePoint >> 0x12 | 0xF0, 1898 | codePoint >> 0xC & 0x3F | 0x80, 1899 | codePoint >> 0x6 & 0x3F | 0x80, 1900 | codePoint & 0x3F | 0x80 1901 | ); 1902 | } else { 1903 | throw new Error('Invalid code point') 1904 | } 1905 | } 1906 | 1907 | return bytes 1908 | } 1909 | 1910 | function asciiToBytes (str) { 1911 | var byteArray = []; 1912 | for (var i = 0; i < str.length; ++i) { 1913 | // Node's code seems to be doing this and not & 0x7F.. 1914 | byteArray.push(str.charCodeAt(i) & 0xFF); 1915 | } 1916 | return byteArray 1917 | } 1918 | 1919 | function utf16leToBytes (str, units) { 1920 | var c, hi, lo; 1921 | var byteArray = []; 1922 | for (var i = 0; i < str.length; ++i) { 1923 | if ((units -= 2) < 0) break 1924 | 1925 | c = str.charCodeAt(i); 1926 | hi = c >> 8; 1927 | lo = c % 256; 1928 | byteArray.push(lo); 1929 | byteArray.push(hi); 1930 | } 1931 | 1932 | return byteArray 1933 | } 1934 | 1935 | 1936 | function base64ToBytes (str) { 1937 | return toByteArray(base64clean(str)) 1938 | } 1939 | 1940 | function blitBuffer (src, dst, offset, length) { 1941 | for (var i = 0; i < length; ++i) { 1942 | if ((i + offset >= dst.length) || (i >= src.length)) break 1943 | dst[i + offset] = src[i]; 1944 | } 1945 | return i 1946 | } 1947 | 1948 | function isnan (val) { 1949 | return val !== val // eslint-disable-line no-self-compare 1950 | } 1951 | 1952 | 1953 | // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence 1954 | // The _isBuffer check is for Safari 5-7 support, because it's missing 1955 | // Object.prototype.constructor. Remove this eventually 1956 | function isBuffer(obj) { 1957 | return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) 1958 | } 1959 | 1960 | function isFastBuffer (obj) { 1961 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 1962 | } 1963 | 1964 | // For Node v0.10 support. Remove this eventually. 1965 | function isSlowBuffer (obj) { 1966 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) 1967 | } 1968 | 1969 | if (process.env.NODE_ENV !== 'production') { 1970 | throw Error('should be a production'); 1971 | } 1972 | 1973 | if (dirname !== __dirname) { 1974 | throw new Error('invlaid __dirname'); 1975 | } 1976 | if (filename !== __filename) { 1977 | throw new Error('invlaid __filename'); 1978 | } 1979 | 1980 | var timeout; 1981 | if (global.setImmediate) { 1982 | timeout = global.setImmediate; 1983 | } else { 1984 | timeout = global.setTimeout; 1985 | } 1986 | if (typeof timeout !== 'function') { 1987 | throw new Error('no timeout'); 1988 | } 1989 | 1990 | var buf = new Buffer('foo'); 1991 | if (!isBuffer(buf)) { 1992 | throw new Error('not a buffer'); 1993 | } 1994 | if (buf.toString() !== 'foo') { 1995 | throw new Error('wrong thing!'); 1996 | } 1997 | " 1998 | `; 1999 | 2000 | exports[`conditionally polyfills dirname 1`] = ` 2001 | "var __dirname = '/test/fixtures'; 2002 | 2003 | if (process.env.NODE_ENV !== 'production') { 2004 | throw Error('should be a production'); 2005 | } 2006 | 2007 | if (dirname !== __dirname) { 2008 | throw new Error('invlaid __dirname'); 2009 | } 2010 | if (filename !== __filename) { 2011 | throw new Error('invlaid __filename'); 2012 | } 2013 | 2014 | var timeout; 2015 | if (global.setImmediate) { 2016 | timeout = global.setImmediate; 2017 | } else { 2018 | timeout = global.setTimeout; 2019 | } 2020 | if (typeof timeout !== 'function') { 2021 | throw new Error('no timeout'); 2022 | } 2023 | 2024 | var buf = new Buffer('foo'); 2025 | if (!Buffer.isBuffer(buf)) { 2026 | throw new Error('not a buffer'); 2027 | } 2028 | if (buf.toString() !== 'foo') { 2029 | throw new Error('wrong thing!'); 2030 | } 2031 | " 2032 | `; 2033 | 2034 | exports[`conditionally polyfills filename 1`] = ` 2035 | "var __filename = '/test/fixtures/mixed.js'; 2036 | 2037 | if (process.env.NODE_ENV !== 'production') { 2038 | throw Error('should be a production'); 2039 | } 2040 | 2041 | if (dirname !== __dirname) { 2042 | throw new Error('invlaid __dirname'); 2043 | } 2044 | if (filename !== __filename) { 2045 | throw new Error('invlaid __filename'); 2046 | } 2047 | 2048 | var timeout; 2049 | if (global.setImmediate) { 2050 | timeout = global.setImmediate; 2051 | } else { 2052 | timeout = global.setTimeout; 2053 | } 2054 | if (typeof timeout !== 'function') { 2055 | throw new Error('no timeout'); 2056 | } 2057 | 2058 | var buf = new Buffer('foo'); 2059 | if (!Buffer.isBuffer(buf)) { 2060 | throw new Error('not a buffer'); 2061 | } 2062 | if (buf.toString() !== 'foo') { 2063 | throw new Error('wrong thing!'); 2064 | } 2065 | " 2066 | `; 2067 | 2068 | exports[`conditionally polyfills global 1`] = ` 2069 | "var global$1 = (typeof global !== \\"undefined\\" ? global : 2070 | typeof self !== \\"undefined\\" ? self : 2071 | typeof window !== \\"undefined\\" ? window : {}); 2072 | 2073 | if (process.env.NODE_ENV !== 'production') { 2074 | throw Error('should be a production'); 2075 | } 2076 | 2077 | if (dirname !== __dirname) { 2078 | throw new Error('invlaid __dirname'); 2079 | } 2080 | if (filename !== __filename) { 2081 | throw new Error('invlaid __filename'); 2082 | } 2083 | 2084 | var timeout; 2085 | if (global$1.setImmediate) { 2086 | timeout = global$1.setImmediate; 2087 | } else { 2088 | timeout = global$1.setTimeout; 2089 | } 2090 | if (typeof timeout !== 'function') { 2091 | throw new Error('no timeout'); 2092 | } 2093 | 2094 | var buf = new Buffer('foo'); 2095 | if (!Buffer.isBuffer(buf)) { 2096 | throw new Error('not a buffer'); 2097 | } 2098 | if (buf.toString() !== 'foo') { 2099 | throw new Error('wrong thing!'); 2100 | } 2101 | " 2102 | `; 2103 | 2104 | exports[`conditionally polyfills process 1`] = ` 2105 | "var global$1 = (typeof global !== \\"undefined\\" ? global : 2106 | typeof self !== \\"undefined\\" ? self : 2107 | typeof window !== \\"undefined\\" ? window : {}); 2108 | 2109 | // shim for using process in browser 2110 | // based off https://github.com/defunctzombie/node-process/blob/master/browser.js 2111 | 2112 | function defaultSetTimout() { 2113 | throw new Error('setTimeout has not been defined'); 2114 | } 2115 | function defaultClearTimeout () { 2116 | throw new Error('clearTimeout has not been defined'); 2117 | } 2118 | var cachedSetTimeout = defaultSetTimout; 2119 | var cachedClearTimeout = defaultClearTimeout; 2120 | if (typeof global$1.setTimeout === 'function') { 2121 | cachedSetTimeout = setTimeout; 2122 | } 2123 | if (typeof global$1.clearTimeout === 'function') { 2124 | cachedClearTimeout = clearTimeout; 2125 | } 2126 | 2127 | function runTimeout(fun) { 2128 | if (cachedSetTimeout === setTimeout) { 2129 | //normal enviroments in sane situations 2130 | return setTimeout(fun, 0); 2131 | } 2132 | // if setTimeout wasn't available but was latter defined 2133 | if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { 2134 | cachedSetTimeout = setTimeout; 2135 | return setTimeout(fun, 0); 2136 | } 2137 | try { 2138 | // when when somebody has screwed with setTimeout but no I.E. maddness 2139 | return cachedSetTimeout(fun, 0); 2140 | } catch(e){ 2141 | try { 2142 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 2143 | return cachedSetTimeout.call(null, fun, 0); 2144 | } catch(e){ 2145 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error 2146 | return cachedSetTimeout.call(this, fun, 0); 2147 | } 2148 | } 2149 | 2150 | 2151 | } 2152 | function runClearTimeout(marker) { 2153 | if (cachedClearTimeout === clearTimeout) { 2154 | //normal enviroments in sane situations 2155 | return clearTimeout(marker); 2156 | } 2157 | // if clearTimeout wasn't available but was latter defined 2158 | if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { 2159 | cachedClearTimeout = clearTimeout; 2160 | return clearTimeout(marker); 2161 | } 2162 | try { 2163 | // when when somebody has screwed with setTimeout but no I.E. maddness 2164 | return cachedClearTimeout(marker); 2165 | } catch (e){ 2166 | try { 2167 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 2168 | return cachedClearTimeout.call(null, marker); 2169 | } catch (e){ 2170 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. 2171 | // Some versions of I.E. have different rules for clearTimeout vs setTimeout 2172 | return cachedClearTimeout.call(this, marker); 2173 | } 2174 | } 2175 | 2176 | 2177 | 2178 | } 2179 | var queue = []; 2180 | var draining = false; 2181 | var currentQueue; 2182 | var queueIndex = -1; 2183 | 2184 | function cleanUpNextTick() { 2185 | if (!draining || !currentQueue) { 2186 | return; 2187 | } 2188 | draining = false; 2189 | if (currentQueue.length) { 2190 | queue = currentQueue.concat(queue); 2191 | } else { 2192 | queueIndex = -1; 2193 | } 2194 | if (queue.length) { 2195 | drainQueue(); 2196 | } 2197 | } 2198 | 2199 | function drainQueue() { 2200 | if (draining) { 2201 | return; 2202 | } 2203 | var timeout = runTimeout(cleanUpNextTick); 2204 | draining = true; 2205 | 2206 | var len = queue.length; 2207 | while(len) { 2208 | currentQueue = queue; 2209 | queue = []; 2210 | while (++queueIndex < len) { 2211 | if (currentQueue) { 2212 | currentQueue[queueIndex].run(); 2213 | } 2214 | } 2215 | queueIndex = -1; 2216 | len = queue.length; 2217 | } 2218 | currentQueue = null; 2219 | draining = false; 2220 | runClearTimeout(timeout); 2221 | } 2222 | function nextTick(fun) { 2223 | var args = new Array(arguments.length - 1); 2224 | if (arguments.length > 1) { 2225 | for (var i = 1; i < arguments.length; i++) { 2226 | args[i - 1] = arguments[i]; 2227 | } 2228 | } 2229 | queue.push(new Item(fun, args)); 2230 | if (queue.length === 1 && !draining) { 2231 | runTimeout(drainQueue); 2232 | } 2233 | } 2234 | // v8 likes predictible objects 2235 | function Item(fun, array) { 2236 | this.fun = fun; 2237 | this.array = array; 2238 | } 2239 | Item.prototype.run = function () { 2240 | this.fun.apply(null, this.array); 2241 | }; 2242 | var title = 'browser'; 2243 | var platform = 'browser'; 2244 | var browser = true; 2245 | var env = {}; 2246 | var argv = []; 2247 | var version = ''; // empty string to avoid regexp issues 2248 | var versions = {}; 2249 | var release = {}; 2250 | var config = {}; 2251 | 2252 | function noop() {} 2253 | 2254 | var on = noop; 2255 | var addListener = noop; 2256 | var once = noop; 2257 | var off = noop; 2258 | var removeListener = noop; 2259 | var removeAllListeners = noop; 2260 | var emit = noop; 2261 | 2262 | function binding(name) { 2263 | throw new Error('process.binding is not supported'); 2264 | } 2265 | 2266 | function cwd () { return '/' } 2267 | function chdir (dir) { 2268 | throw new Error('process.chdir is not supported'); 2269 | }function umask() { return 0; } 2270 | 2271 | // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js 2272 | var performance = global$1.performance || {}; 2273 | var performanceNow = 2274 | performance.now || 2275 | performance.mozNow || 2276 | performance.msNow || 2277 | performance.oNow || 2278 | performance.webkitNow || 2279 | function(){ return (new Date()).getTime() }; 2280 | 2281 | // generate timestamp or delta 2282 | // see http://nodejs.org/api/process.html#process_process_hrtime 2283 | function hrtime(previousTimestamp){ 2284 | var clocktime = performanceNow.call(performance)*1e-3; 2285 | var seconds = Math.floor(clocktime); 2286 | var nanoseconds = Math.floor((clocktime%1)*1e9); 2287 | if (previousTimestamp) { 2288 | seconds = seconds - previousTimestamp[0]; 2289 | nanoseconds = nanoseconds - previousTimestamp[1]; 2290 | if (nanoseconds<0) { 2291 | seconds--; 2292 | nanoseconds += 1e9; 2293 | } 2294 | } 2295 | return [seconds,nanoseconds] 2296 | } 2297 | 2298 | var startTime = new Date(); 2299 | function uptime() { 2300 | var currentTime = new Date(); 2301 | var dif = currentTime - startTime; 2302 | return dif / 1000; 2303 | } 2304 | 2305 | var process = { 2306 | nextTick: nextTick, 2307 | title: title, 2308 | browser: browser, 2309 | env: env, 2310 | argv: argv, 2311 | version: version, 2312 | versions: versions, 2313 | on: on, 2314 | addListener: addListener, 2315 | once: once, 2316 | off: off, 2317 | removeListener: removeListener, 2318 | removeAllListeners: removeAllListeners, 2319 | emit: emit, 2320 | binding: binding, 2321 | cwd: cwd, 2322 | chdir: chdir, 2323 | umask: umask, 2324 | hrtime: hrtime, 2325 | platform: platform, 2326 | release: release, 2327 | config: config, 2328 | uptime: uptime 2329 | }; 2330 | 2331 | if (process.env.NODE_ENV !== 'production') { 2332 | throw Error('should be a production'); 2333 | } 2334 | 2335 | if (dirname !== __dirname) { 2336 | throw new Error('invlaid __dirname'); 2337 | } 2338 | if (filename !== __filename) { 2339 | throw new Error('invlaid __filename'); 2340 | } 2341 | 2342 | var timeout; 2343 | if (global$1.setImmediate) { 2344 | timeout = global$1.setImmediate; 2345 | } else { 2346 | timeout = global$1.setTimeout; 2347 | } 2348 | if (typeof timeout !== 'function') { 2349 | throw new Error('no timeout'); 2350 | } 2351 | 2352 | var buf = new Buffer('foo'); 2353 | if (!Buffer.isBuffer(buf)) { 2354 | throw new Error('not a buffer'); 2355 | } 2356 | if (buf.toString() !== 'foo') { 2357 | throw new Error('wrong thing!'); 2358 | } 2359 | " 2360 | `; 2361 | -------------------------------------------------------------------------------- /test/conditional.test.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const { rollup } = require('rollup'); 3 | const nodeGlobals = require('../'); 4 | 5 | test.each([ 6 | ['process'], 7 | ['buffer'], 8 | ['dirname'], 9 | ['filename'], 10 | ['global'] 11 | ])('conditionally polyfills %s', async name => { 12 | const options = { 13 | baseDir: process.cwd(), 14 | process: false, 15 | buffer: false, 16 | dirname: false, 17 | filename: false, 18 | global: false, 19 | [name]: true 20 | }; 21 | const bundle = await rollup({ 22 | input: 'test/fixtures/mixed.js', 23 | plugins: [nodeGlobals(options)] 24 | }) 25 | const { code } = await bundle.generate({ format: 'esm' }) 26 | expect(code).toMatchSnapshot(); 27 | }) 28 | 29 | -------------------------------------------------------------------------------- /test/fixtures/buffer-import.js: -------------------------------------------------------------------------------- 1 | import {Buffer} from 'buffer'; 2 | global.buf = {}; 3 | if (Buffer.isBuffer(global.buf)) { 4 | throw new Error('is a buffer'); 5 | } 6 | -------------------------------------------------------------------------------- /test/fixtures/buffer-isBuffer.js: -------------------------------------------------------------------------------- 1 | var buf = {}; 2 | if (Buffer.isBuffer(buf)) { 3 | throw new Error('is a buffer'); 4 | } 5 | -------------------------------------------------------------------------------- /test/fixtures/buffer.js: -------------------------------------------------------------------------------- 1 | var buf = new Buffer('foo'); 2 | if (!Buffer.isBuffer(buf)) { 3 | throw new Error('not a buffer'); 4 | } 5 | if (buf.toString() !== 'foo') { 6 | throw new Error('wrong thing!'); 7 | } 8 | -------------------------------------------------------------------------------- /test/fixtures/dirname.js: -------------------------------------------------------------------------------- 1 | if (dirname !== __dirname) { 2 | throw new Error('invlaid __dirname'); 3 | } 4 | if (filename !== __filename) { 5 | throw new Error('invlaid __filename'); 6 | } 7 | -------------------------------------------------------------------------------- /test/fixtures/global.js: -------------------------------------------------------------------------------- 1 | var timeout; 2 | if (global.setImmediate) { 3 | timeout = global.setImmediate; 4 | } else { 5 | timeout = global.setTimeout; 6 | } 7 | if (typeof timeout !== 'function') { 8 | throw new Error('no timeout'); 9 | } 10 | -------------------------------------------------------------------------------- /test/fixtures/mixed.js: -------------------------------------------------------------------------------- 1 | if (process.env.NODE_ENV !== 'production') { 2 | throw Error('should be a production'); 3 | } 4 | 5 | if (dirname !== __dirname) { 6 | throw new Error('invlaid __dirname'); 7 | } 8 | if (filename !== __filename) { 9 | throw new Error('invlaid __filename'); 10 | } 11 | 12 | var timeout; 13 | if (global.setImmediate) { 14 | timeout = global.setImmediate; 15 | } else { 16 | timeout = global.setTimeout; 17 | } 18 | if (typeof timeout !== 'function') { 19 | throw new Error('no timeout'); 20 | } 21 | 22 | var buf = new Buffer('foo'); 23 | if (!Buffer.isBuffer(buf)) { 24 | throw new Error('not a buffer'); 25 | } 26 | if (buf.toString() !== 'foo') { 27 | throw new Error('wrong thing!'); 28 | } 29 | -------------------------------------------------------------------------------- /test/fixtures/process-browser.js: -------------------------------------------------------------------------------- 1 | // Special case for spread operator 2 | const a = {}; 3 | const b = {...a}; 4 | 5 | if (!process.browser) { 6 | throw Error('must be a browser'); 7 | } 8 | -------------------------------------------------------------------------------- /test/fixtures/process-env.js: -------------------------------------------------------------------------------- 1 | if (process.env.NODE_ENV !== 'production') { 2 | throw Error('should be a production'); 3 | } 4 | -------------------------------------------------------------------------------- /test/fixtures/process-generic.js: -------------------------------------------------------------------------------- 1 | if (process.version !== '') { 2 | throw Error('where is process.version?'); 3 | } 4 | -------------------------------------------------------------------------------- /test/fixtures/process-nexttick.js: -------------------------------------------------------------------------------- 1 | if (typeof process.nextTick !== 'function') { 2 | throw Error('where is process next tick?'); 3 | } 4 | -------------------------------------------------------------------------------- /test/fixtures/process-sneaky.js: -------------------------------------------------------------------------------- 1 | function trickYou(process) { 2 | if (process.browser) { 3 | throw new Error('should not be replaced'); 4 | } 5 | } 6 | trickYou({browser: false}); 7 | -------------------------------------------------------------------------------- /test/form.test.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const { rollup } = require('rollup'); 3 | const nodeGlobals = require('../'); 4 | 5 | test.each([ 6 | 'buffer-import', 7 | 'buffer-isBuffer', 8 | 'buffer', 9 | 'dirname', 10 | 'global', 11 | 'process-browser', 12 | 'process-env', 13 | 'process-generic', 14 | 'process-nexttick', 15 | 'process-sneaky', 16 | ])('polyfills %s', async name => { 17 | const input = `test/fixtures/${name}.js` 18 | const bundle = await rollup({ 19 | input, 20 | plugins: [nodeGlobals({ baseDir: process.cwd() })] 21 | }) 22 | const { code } = await bundle.generate({ format: 'esm' }) 23 | expect(readFileSync(input, 'utf-8')).toMatchSnapshot('input'); 24 | expect(code).toMatchSnapshot('output'); 25 | }) 26 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | 2 | var rollup = require( 'rollup' ); 3 | var nodeResolve = require( 'rollup-plugin-node-resolve' ); 4 | var globals = require( '../dist/rollup-plugin-node-globals.cjs' ); 5 | var path = require('path'); 6 | var vm = require('vm'); 7 | var files = [ 8 | // 'imports.js', 9 | // 'isBuffer.js', 10 | // 'buffer.js', 11 | // 'process-generic.js', 12 | // 'process-nexttick.js', 13 | // 'dirname.js', 14 | 'process-browser.js', 15 | // 'global.js', 16 | // 'sneaky.js' 17 | ]; 18 | describe( 'rollup-plugin-node-globals', function () { 19 | files.forEach(function (file) { 20 | it( 'works with ' + file, function () { 21 | return rollup.rollup({ 22 | input: 'test/fixtures/' + file, 23 | plugins: [ 24 | { 25 | resolveId: function (importee){ 26 | if (importee === 'buffer') { 27 | return require.resolve('buffer-es6'); 28 | } 29 | } 30 | }, 31 | globals() 32 | ] 33 | }).then( async function ( bundle ) { 34 | var generated = await bundle.generate({format: 'es'}); 35 | var code = generated.code; 36 | console.log(code); 37 | var script = new vm.Script(code); 38 | var context = vm.createContext({ 39 | dirname: path.join(__dirname, 'fixtures'), 40 | filename: path.join(__dirname, 'fixtures', 'dirname.js'), 41 | setTimeout: setTimeout, 42 | clearTimeout: clearTimeout, 43 | }); 44 | context.self = context; 45 | script.runInContext(context); 46 | }); 47 | }); 48 | }); 49 | 50 | it( 'works with rollup-plugin-node-resolve', function () { 51 | return rollup.rollup({ 52 | input: 'test/fixtures/dirname.js', 53 | plugins: [ 54 | nodeResolve(), 55 | globals() 56 | ] 57 | }).then( async function ( bundle ) { 58 | var generated = await bundle.generate({format: "es"}); 59 | var code = generated.code; 60 | var script = new vm.Script(code); 61 | var context = vm.createContext({ 62 | dirname: path.join(__dirname, 'fixtures'), 63 | filename: path.join(__dirname, 'fixtures', 'dirname.js'), 64 | setTimeout: setTimeout, 65 | clearTimeout: clearTimeout, 66 | }); 67 | context.self = context; 68 | script.runInContext(context); 69 | }); 70 | }); 71 | }); 72 | --------------------------------------------------------------------------------