Datasets:

name
stringlengths
2
31
dataset
stringclasses
4 values
size
int64
1.66k
14.8k
content
stringlengths
1.66k
14.8k
content_without_annotations
stringlengths
1.66k
14.8k
loc
int64
51
494
functions
int64
3
40
function_signatures
int64
0
0
function_parameters
int64
4
64
variable_declarations
int64
5
54
property_declarations
int64
0
0
function_usages
int64
1
21
trivial_types
int64
0
0
predefined_types
int64
0
0
type_definitions
int64
0
1
dynamism_heuristic
int64
0
34
loc_per_function
float64
5.38
57.8
estimated_tokens
int64
494
3.9k
typechecks
bool
2 classes
ansi-colors
top1k-typed-nodeps
8,320
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var ansiColors = {exports: {}}; var symbols = {exports: {}}; // FILE: symbols.js var hasRequiredSymbols; function requireSymbols () { if (hasRequiredSymbols) return symbols.exports; hasRequiredSymbols = 1; (function (module) { const isHyper = typeof process !== 'undefined' && process.env.TERM_PROGRAM === 'Hyper'; const isWindows = typeof process !== 'undefined' && process.platform === 'win32'; const isLinux = typeof process !== 'undefined' && process.platform === 'linux'; const common = { ballotDisabled: '☒', ballotOff: '☐', ballotOn: '☑', bullet: '•', bulletWhite: '◦', fullBlock: '█', heart: '❤', identicalTo: '≡', line: '─', mark: '※', middot: '·', minus: '-', multiplication: '×', obelus: '÷', pencilDownRight: '✎', pencilRight: '✏', pencilUpRight: '✐', percent: '%', pilcrow2: '❡', pilcrow: '¶', plusMinus: '±', question: '?', section: '§', starsOff: '☆', starsOn: '★', upDownArrow: '↕' }; const windows = Object.assign({}, common, { check: '√', cross: '×', ellipsisLarge: '...', ellipsis: '...', info: 'i', questionSmall: '?', pointer: '>', pointerSmall: '»', radioOff: '( )', radioOn: '(*)', warning: '‼' }); const other = Object.assign({}, common, { ballotCross: '✘', check: '✔', cross: '✖', ellipsisLarge: '⋯', ellipsis: '…', info: 'ℹ', questionFull: '?', questionSmall: '﹖', pointer: isLinux ? '▸' : '❯', pointerSmall: isLinux ? '‣' : '›', radioOff: '◯', radioOn: '◉', warning: '⚠' }); module.exports = (isWindows && !isHyper) ? windows : other; Reflect.defineProperty(module.exports, 'common', { enumerable: false, value: common }); Reflect.defineProperty(module.exports, 'windows', { enumerable: false, value: windows }); Reflect.defineProperty(module.exports, 'other', { enumerable: false, value: other }); } (symbols)); return symbols.exports; } // FILE: index.js const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); /* eslint-disable no-control-regex */ // this is a modified version of https://github.com/chalk/ansi-regex (MIT License) const ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g; const hasColor = () => { if (typeof process !== 'undefined') { return process.env.FORCE_COLOR !== '0'; } return false; }; const create = () => { const colors = { enabled: hasColor(), visible: true, styles: {}, keys: {} }; const ansi = style => { let open = style.open = `\u001b[${style.codes[0]}m`; let close = style.close = `\u001b[${style.codes[1]}m`; let regex = style.regex = new RegExp(`\\u001b\\[${style.codes[1]}m`, 'g'); style.wrap = (input, newline) => { if (input.includes(close)) input = input.replace(regex, close + open); let output = open + input + close; // see https://github.com/chalk/chalk/pull/92, thanks to the // chalk contributors for this fix. However, we've confirmed that // this issue is also present in Windows terminals return newline ? output.replace(/\r*\n/g, `${close}$&${open}`) : output; }; return style; }; const wrap = (style, input, newline) => { return typeof style === 'function' ? style(input) : style.wrap(input, newline); }; const style = (input, stack) => { if (input === '' || input == null) return ''; if (colors.enabled === false) return input; if (colors.visible === false) return ''; let str = '' + input; let nl = str.includes('\n'); let n = stack.length; if (n > 0 && stack.includes('unstyle')) { stack = [...new Set(['unstyle', ...stack])].reverse(); } while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl); return str; }; const define = (name, codes, type) => { colors.styles[name] = ansi({ name, codes }); let keys = colors.keys[type] || (colors.keys[type] = []); keys.push(name); Reflect.defineProperty(colors, name, { configurable: true, enumerable: true, set(value) { colors.alias(name, value); }, get() { let color = input => style(input, color.stack); Reflect.setPrototypeOf(color, colors); color.stack = this.stack ? this.stack.concat(name) : [name]; return color; } }); }; define('reset', [0, 0], 'modifier'); define('bold', [1, 22], 'modifier'); define('dim', [2, 22], 'modifier'); define('italic', [3, 23], 'modifier'); define('underline', [4, 24], 'modifier'); define('inverse', [7, 27], 'modifier'); define('hidden', [8, 28], 'modifier'); define('strikethrough', [9, 29], 'modifier'); define('black', [30, 39], 'color'); define('red', [31, 39], 'color'); define('green', [32, 39], 'color'); define('yellow', [33, 39], 'color'); define('blue', [34, 39], 'color'); define('magenta', [35, 39], 'color'); define('cyan', [36, 39], 'color'); define('white', [37, 39], 'color'); define('gray', [90, 39], 'color'); define('grey', [90, 39], 'color'); define('bgBlack', [40, 49], 'bg'); define('bgRed', [41, 49], 'bg'); define('bgGreen', [42, 49], 'bg'); define('bgYellow', [43, 49], 'bg'); define('bgBlue', [44, 49], 'bg'); define('bgMagenta', [45, 49], 'bg'); define('bgCyan', [46, 49], 'bg'); define('bgWhite', [47, 49], 'bg'); define('blackBright', [90, 39], 'bright'); define('redBright', [91, 39], 'bright'); define('greenBright', [92, 39], 'bright'); define('yellowBright', [93, 39], 'bright'); define('blueBright', [94, 39], 'bright'); define('magentaBright', [95, 39], 'bright'); define('cyanBright', [96, 39], 'bright'); define('whiteBright', [97, 39], 'bright'); define('bgBlackBright', [100, 49], 'bgBright'); define('bgRedBright', [101, 49], 'bgBright'); define('bgGreenBright', [102, 49], 'bgBright'); define('bgYellowBright', [103, 49], 'bgBright'); define('bgBlueBright', [104, 49], 'bgBright'); define('bgMagentaBright', [105, 49], 'bgBright'); define('bgCyanBright', [106, 49], 'bgBright'); define('bgWhiteBright', [107, 49], 'bgBright'); colors.ansiRegex = ANSI_REGEX; colors.hasColor = colors.hasAnsi = str => { colors.ansiRegex.lastIndex = 0; return typeof str === 'string' && str !== '' && colors.ansiRegex.test(str); }; colors.alias = (name, color) => { let fn = typeof color === 'string' ? colors[color] : color; if (typeof fn !== 'function') { throw new TypeError('Expected alias to be the name of an existing color (string) or a function'); } if (!fn.stack) { Reflect.defineProperty(fn, 'name', { value: name }); colors.styles[name] = fn; fn.stack = [name]; } Reflect.defineProperty(colors, name, { configurable: true, enumerable: true, set(value) { colors.alias(name, value); }, get() { let color = input => style(input, color.stack); Reflect.setPrototypeOf(color, colors); color.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack; return color; } }); }; colors.theme = custom => { if (!isObject(custom)) throw new TypeError('Expected theme to be an object'); for (let name of Object.keys(custom)) { colors.alias(name, custom[name]); } return colors; }; colors.alias('unstyle', str => { if (typeof str === 'string' && str !== '') { colors.ansiRegex.lastIndex = 0; return str.replace(colors.ansiRegex, ''); } return ''; }); colors.alias('noop', str => str); colors.none = colors.clear = colors.noop; colors.stripColor = colors.unstyle; colors.symbols = requireSymbols(); colors.define = define; return colors; }; ansiColors.exports = create(); var create_1 = ansiColors.exports.create = create; var ansiColorsExports = ansiColors.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(ansiColorsExports); export { create_1 as create, index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var ansiColors = {exports: {}}; var symbols = {exports: {}}; // FILE: symbols.js var hasRequiredSymbols; function requireSymbols () { if (hasRequiredSymbols) return symbols.exports; hasRequiredSymbols = 1; (function (module) { const isHyper = typeof process !== 'undefined' && process.env.TERM_PROGRAM === 'Hyper'; const isWindows = typeof process !== 'undefined' && process.platform === 'win32'; const isLinux = typeof process !== 'undefined' && process.platform === 'linux'; const common = { ballotDisabled: '☒', ballotOff: '☐', ballotOn: '☑', bullet: '•', bulletWhite: '◦', fullBlock: '█', heart: '❤', identicalTo: '≡', line: '─', mark: '※', middot: '·', minus: '-', multiplication: '×', obelus: '÷', pencilDownRight: '✎', pencilRight: '✏', pencilUpRight: '✐', percent: '%', pilcrow2: '❡', pilcrow: '¶', plusMinus: '±', question: '?', section: '§', starsOff: '☆', starsOn: '★', upDownArrow: '↕' }; const windows = Object.assign({}, common, { check: '√', cross: '×', ellipsisLarge: '...', ellipsis: '...', info: 'i', questionSmall: '?', pointer: '>', pointerSmall: '»', radioOff: '( )', radioOn: '(*)', warning: '‼' }); const other = Object.assign({}, common, { ballotCross: '✘', check: '✔', cross: '✖', ellipsisLarge: '⋯', ellipsis: '…', info: 'ℹ', questionFull: '?', questionSmall: '﹖', pointer: isLinux ? '▸' : '❯', pointerSmall: isLinux ? '‣' : '›', radioOff: '◯', radioOn: '◉', warning: '⚠' }); module.exports = (isWindows && !isHyper) ? windows : other; Reflect.defineProperty(module.exports, 'common', { enumerable: false, value: common }); Reflect.defineProperty(module.exports, 'windows', { enumerable: false, value: windows }); Reflect.defineProperty(module.exports, 'other', { enumerable: false, value: other }); } (symbols)); return symbols.exports; } // FILE: index.js const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); /* eslint-disable no-control-regex */ // this is a modified version of https://github.com/chalk/ansi-regex (MIT License) const ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g; const hasColor = () => { if (typeof process !== 'undefined') { return process.env.FORCE_COLOR !== '0'; } return false; }; const create = () => { const colors = { enabled: hasColor(), visible: true, styles: {}, keys: {} }; const ansi = style => { let open = style.open = `\u001b[${style.codes[0]}m`; let close = style.close = `\u001b[${style.codes[1]}m`; let regex = style.regex = new RegExp(`\\u001b\\[${style.codes[1]}m`, 'g'); style.wrap = (input, newline) => { if (input.includes(close)) input = input.replace(regex, close + open); let output = open + input + close; // see https://github.com/chalk/chalk/pull/92, thanks to the // chalk contributors for this fix. However, we've confirmed that // this issue is also present in Windows terminals return newline ? output.replace(/\r*\n/g, `${close}$&${open}`) : output; }; return style; }; const wrap = (style, input, newline) => { return typeof style === 'function' ? style(input) : style.wrap(input, newline); }; const style = (input, stack) => { if (input === '' || input == null) return ''; if (colors.enabled === false) return input; if (colors.visible === false) return ''; let str = '' + input; let nl = str.includes('\n'); let n = stack.length; if (n > 0 && stack.includes('unstyle')) { stack = [...new Set(['unstyle', ...stack])].reverse(); } while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl); return str; }; const define = (name, codes, type) => { colors.styles[name] = ansi({ name, codes }); let keys = colors.keys[type] || (colors.keys[type] = []); keys.push(name); Reflect.defineProperty(colors, name, { configurable: true, enumerable: true, set(value) { colors.alias(name, value); }, get() { let color = input => style(input, color.stack); Reflect.setPrototypeOf(color, colors); color.stack = this.stack ? this.stack.concat(name) : [name]; return color; } }); }; define('reset', [0, 0], 'modifier'); define('bold', [1, 22], 'modifier'); define('dim', [2, 22], 'modifier'); define('italic', [3, 23], 'modifier'); define('underline', [4, 24], 'modifier'); define('inverse', [7, 27], 'modifier'); define('hidden', [8, 28], 'modifier'); define('strikethrough', [9, 29], 'modifier'); define('black', [30, 39], 'color'); define('red', [31, 39], 'color'); define('green', [32, 39], 'color'); define('yellow', [33, 39], 'color'); define('blue', [34, 39], 'color'); define('magenta', [35, 39], 'color'); define('cyan', [36, 39], 'color'); define('white', [37, 39], 'color'); define('gray', [90, 39], 'color'); define('grey', [90, 39], 'color'); define('bgBlack', [40, 49], 'bg'); define('bgRed', [41, 49], 'bg'); define('bgGreen', [42, 49], 'bg'); define('bgYellow', [43, 49], 'bg'); define('bgBlue', [44, 49], 'bg'); define('bgMagenta', [45, 49], 'bg'); define('bgCyan', [46, 49], 'bg'); define('bgWhite', [47, 49], 'bg'); define('blackBright', [90, 39], 'bright'); define('redBright', [91, 39], 'bright'); define('greenBright', [92, 39], 'bright'); define('yellowBright', [93, 39], 'bright'); define('blueBright', [94, 39], 'bright'); define('magentaBright', [95, 39], 'bright'); define('cyanBright', [96, 39], 'bright'); define('whiteBright', [97, 39], 'bright'); define('bgBlackBright', [100, 49], 'bgBright'); define('bgRedBright', [101, 49], 'bgBright'); define('bgGreenBright', [102, 49], 'bgBright'); define('bgYellowBright', [103, 49], 'bgBright'); define('bgBlueBright', [104, 49], 'bgBright'); define('bgMagentaBright', [105, 49], 'bgBright'); define('bgCyanBright', [106, 49], 'bgBright'); define('bgWhiteBright', [107, 49], 'bgBright'); colors.ansiRegex = ANSI_REGEX; colors.hasColor = colors.hasAnsi = str => { colors.ansiRegex.lastIndex = 0; return typeof str === 'string' && str !== '' && colors.ansiRegex.test(str); }; colors.alias = (name, color) => { let fn = typeof color === 'string' ? colors[color] : color; if (typeof fn !== 'function') { throw new TypeError('Expected alias to be the name of an existing color (string) or a function'); } if (!fn.stack) { Reflect.defineProperty(fn, 'name', { value: name }); colors.styles[name] = fn; fn.stack = [name]; } Reflect.defineProperty(colors, name, { configurable: true, enumerable: true, set(value) { colors.alias(name, value); }, get() { let color = input => style(input, color.stack); Reflect.setPrototypeOf(color, colors); color.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack; return color; } }); }; colors.theme = custom => { if (!isObject(custom)) throw new TypeError('Expected theme to be an object'); for (let name of Object.keys(custom)) { colors.alias(name, custom[name]); } return colors; }; colors.alias('unstyle', str => { if (typeof str === 'string' && str !== '') { colors.ansiRegex.lastIndex = 0; return str.replace(colors.ansiRegex, ''); } return ''; }); colors.alias('noop', str => str); colors.none = colors.clear = colors.noop; colors.stripColor = colors.unstyle; colors.symbols = requireSymbols(); colors.define = define; return colors; }; ansiColors.exports = create(); var create_1 = ansiColors.exports.create = create; var ansiColorsExports = ansiColors.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(ansiColorsExports); export { create_1 as create, index as default };
233
22
0
24
32
0
10
0
0
0
10
16.636364
2,698
false
setimmediate
top1k-typed-nodeps
6,768
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var setImmediate = {}; // FILE: setImmediate.js (function (global, undefined$1) { if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined$1, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof commonjsGlobal === "undefined" ? commonjsGlobal : commonjsGlobal : self)); export { setImmediate as default };
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var setImmediate = {}; // FILE: setImmediate.js (function (global, undefined$1) { if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined$1, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof commonjsGlobal === "undefined" ? commonjsGlobal : commonjsGlobal : self)); export { setImmediate as default };
144
21
0
13
22
0
10
0
0
0
8
12.380952
1,446
false
source-map-url
top1k-untyped-nodeps
1,713
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var sourceMapUrl$1 = {exports: {}}; // FILE: source-map-url.js (function (module, exports) { // Copyright 2014 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) void (function(root, factory) { { module.exports = factory(); } }(commonjsGlobal, function() { var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; var regex = RegExp( "(?:" + "/\\*" + "(?:\\s*\r?\n(?://)?)?" + "(?:" + innerRegex.source + ")" + "\\s*" + "\\*/" + "|" + "//(?:" + innerRegex.source + ")" + ")" + "\\s*" ); return { regex: regex, _innerRegex: innerRegex, getFrom: function(code) { var match = code.match(regex); return (match ? match[1] || match[2] || "" : null) }, existsIn: function(code) { return regex.test(code) }, removeFrom: function(code) { return code.replace(regex, "") }, insertBefore: function(code, string) { var match = code.match(regex); if (match) { return code.slice(0, match.index) + string + code.slice(match.index) } else { return code + string } } } })); } (sourceMapUrl$1)); var sourceMapUrlExports = sourceMapUrl$1.exports; var sourceMapUrl = /*@__PURE__*/getDefaultExportFromCjs(sourceMapUrlExports); export { sourceMapUrl as default };
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var sourceMapUrl$1 = {exports: {}}; // FILE: source-map-url.js (function (module, exports) { // Copyright 2014 Simon Lydell // X11 (“MIT”) Licensed. (See LICENSE.) void (function(root, factory) { { module.exports = factory(); } }(commonjsGlobal, function() { var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; var regex = RegExp( "(?:" + "/\\*" + "(?:\\s*\r?\n(?://)?)?" + "(?:" + innerRegex.source + ")" + "\\s*" + "\\*/" + "|" + "//(?:" + innerRegex.source + ")" + ")" + "\\s*" ); return { regex: regex, _innerRegex: innerRegex, getFrom: function(code) { var match = code.match(regex); return (match ? match[1] || match[2] || "" : null) }, existsIn: function(code) { return regex.test(code) }, removeFrom: function(code) { return code.replace(regex, "") }, insertBefore: function(code, string) { var match = code.match(regex); if (match) { return code.slice(0, match.index) + string + code.slice(match.index) } else { return code + string } } } })); } (sourceMapUrl$1)); var sourceMapUrlExports = sourceMapUrl$1.exports; var sourceMapUrl = /*@__PURE__*/getDefaultExportFromCjs(sourceMapUrlExports); export { sourceMapUrl as default };
51
8
0
10
8
0
1
0
0
0
4
11.25
494
true
which
top1k-typed-with-typed-deps
3,508
import require$$0 from 'path'; import require$$1 from 'isexe'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: which.js const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path = require$$0; const COLON = isWindows ? ';' : ':'; const isexe = require$$1; const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON; // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows ? pathExtExe.split(colon) : ['']; if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }); }); return cb ? step(0).then(res => cb(null, res), cb) : step(0) }; const whichSync = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j]; try { const is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) }; var which_1 = which; which.sync = whichSync; var which$1 = /*@__PURE__*/getDefaultExportFromCjs(which_1); export { which$1 as default };
import require$$0 from 'path'; import require$$1 from 'isexe'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: which.js const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; const path = require$$0; const COLON = isWindows ? ';' : ':'; const isexe = require$$1; const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON; // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ); const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : ''; const pathExt = isWindows ? pathExtExe.split(colon) : ['']; if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } return { pathEnv, pathExt, pathExtExe, } }; const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }); }); return cb ? step(0).then(res => cb(null, res), cb) : step(0) }; const whichSync = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j]; try { const is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) }; var which_1 = which; which.sync = whichSync; var which$1 = /*@__PURE__*/getDefaultExportFromCjs(which_1); export { which$1 as default };
106
11
0
20
33
0
5
0
0
0
1
12.636364
1,135
true
acorn-import-assertions
top1k-untyped-nodeps
7,561
import * as _acorn from 'acorn'; // FILE: src/index.js const leftCurlyBrace = "{".charCodeAt(0); const space = " ".charCodeAt(0); const keyword = "assert"; const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4; function importAssertions(Parser) { // Use supplied version acorn version if present, to avoid // reference mismatches due to different acorn versions. This // allows this plugin to be used with Rollup which supplies // its own internal version of acorn and thereby sidesteps // the package manager. const acorn = Parser.acorn || _acorn; const { tokTypes: tt, TokenType } = acorn; return class extends Parser { constructor(...args) { super(...args); this.assertToken = new TokenType(keyword); } _codeAt(i) { return this.input.charCodeAt(i); } _eat(t) { if (this.type !== t) { this.unexpected(); } this.next(); } readToken(code) { let i = 0; for (; i < keyword.length; i++) { if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) { return super.readToken(code); } } // ensure that the keyword is at the correct location // ie `assert{...` or `assert {...` for (;; i++) { if (this._codeAt(this.pos + i) === leftCurlyBrace) { // Found '{' break; } else if (this._codeAt(this.pos + i) === space) { // white space is allowed between `assert` and `{`, so continue. continue; } else { return super.readToken(code); } } // If we're inside a dynamic import expression we'll parse // the `assert` keyword as a standard object property name // ie `import(""./foo.json", { assert: { type: "json" } })` if (this.type.label === "{") { return super.readToken(code); } this.pos += keyword.length; return this.finishToken(this.assertToken); } parseDynamicImport(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); if (this.eat(tt.comma)) { const obj = this.parseObj(false); node.arguments = [obj]; } this._eat(tt.parenR); return this.finishNode(node, "ImportExpression"); } // ported from acorn/src/statement.js pp.parseExport parseExport(node, exports) { this.next(); // export * from '...' if (this.eat(tt.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseIdent(true); this.checkExport(exports, node.exported.name, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== tt.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(tt._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === tt._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === tt._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== tt.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") } parseImport(node) { this.next(); // import '...' if (this.type === tt.string) { node.specifiers = []; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); } if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); } parseImportAssertions() { this._eat(tt.braceL); const attrs = this.parseAssertEntries(); this._eat(tt.braceR); return attrs; } parseAssertEntries() { const attrs = []; const attrNames = new Set(); do { if (this.type === tt.braceR) { break; } const node = this.startNode(); // parse AssertionKey : IdentifierName, StringLiteral let assertionKeyNode; if (this.type === tt.string) { assertionKeyNode = this.parseLiteral(this.value); } else { assertionKeyNode = this.parseIdent(true); } this.next(); node.key = assertionKeyNode; // check if we already have an entry for an attribute // if a duplicate entry is found, throw an error // for now this logic will come into play only when someone declares `type` twice if (attrNames.has(node.key.name)) { this.raise(this.pos, "Duplicated key in assertions"); } attrNames.add(node.key.name); if (this.type !== tt.string) { this.raise( this.pos, "Only string is supported as an assertion value" ); } node.value = this.parseLiteral(this.value); attrs.push(this.finishNode(node, "ImportAttribute")); } while (this.eat(tt.comma)); return attrs; } }; } export { importAssertions };
import * as _acorn from 'acorn'; // FILE: src/index.js const leftCurlyBrace = "{".charCodeAt(0); const space = " ".charCodeAt(0); const keyword = "assert"; const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4; function importAssertions(Parser) { // Use supplied version acorn version if present, to avoid // reference mismatches due to different acorn versions. This // allows this plugin to be used with Rollup which supplies // its own internal version of acorn and thereby sidesteps // the package manager. const acorn = Parser.acorn || _acorn; const { tokTypes: tt, TokenType } = acorn; return class extends Parser { constructor(...args) { super(...args); this.assertToken = new TokenType(keyword); } _codeAt(i) { return this.input.charCodeAt(i); } _eat(t) { if (this.type !== t) { this.unexpected(); } this.next(); } readToken(code) { let i = 0; for (; i < keyword.length; i++) { if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) { return super.readToken(code); } } // ensure that the keyword is at the correct location // ie `assert{...` or `assert {...` for (;; i++) { if (this._codeAt(this.pos + i) === leftCurlyBrace) { // Found '{' break; } else if (this._codeAt(this.pos + i) === space) { // white space is allowed between `assert` and `{`, so continue. continue; } else { return super.readToken(code); } } // If we're inside a dynamic import expression we'll parse // the `assert` keyword as a standard object property name // ie `import(""./foo.json", { assert: { type: "json" } })` if (this.type.label === "{") { return super.readToken(code); } this.pos += keyword.length; return this.finishToken(this.assertToken); } parseDynamicImport(node) { this.next(); // skip `(` // Parse node.source. node.source = this.parseMaybeAssign(); if (this.eat(tt.comma)) { const obj = this.parseObj(false); node.arguments = [obj]; } this._eat(tt.parenR); return this.finishNode(node, "ImportExpression"); } // ported from acorn/src/statement.js pp.parseExport parseExport(node, exports) { this.next(); // export * from '...' if (this.eat(tt.star)) { if (this.options.ecmaVersion >= 11) { if (this.eatContextual("as")) { node.exported = this.parseIdent(true); this.checkExport(exports, node.exported.name, this.lastTokStart); } else { node.exported = null; } } this.expectContextual("from"); if (this.type !== tt.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(tt._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === tt._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === tt._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== tt.string) { this.unexpected(); } node.source = this.parseExprAtom(); if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this.checkUnreserved(spec.local); // check if export is defined this.checkLocalExport(spec.local); } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") } parseImport(node) { this.next(); // import '...' if (this.type === tt.string) { node.specifiers = []; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); } if (this.type === this.assertToken) { this.next(); const assertions = this.parseImportAssertions(); if (assertions) { node.assertions = assertions; } } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); } parseImportAssertions() { this._eat(tt.braceL); const attrs = this.parseAssertEntries(); this._eat(tt.braceR); return attrs; } parseAssertEntries() { const attrs = []; const attrNames = new Set(); do { if (this.type === tt.braceR) { break; } const node = this.startNode(); // parse AssertionKey : IdentifierName, StringLiteral let assertionKeyNode; if (this.type === tt.string) { assertionKeyNode = this.parseLiteral(this.value); } else { assertionKeyNode = this.parseIdent(true); } this.next(); node.key = assertionKeyNode; // check if we already have an entry for an attribute // if a duplicate entry is found, throw an error // for now this logic will come into play only when someone declares `type` twice if (attrNames.has(node.key.name)) { this.raise(this.pos, "Duplicated key in assertions"); } attrNames.add(node.key.name); if (this.type !== tt.string) { this.raise( this.pos, "Only string is supported as an assertion value" ); } node.value = this.parseLiteral(this.value); attrs.push(this.finishNode(node, "ImportAttribute")); } while (this.eat(tt.comma)); return attrs; } }; } export { importAssertions };
189
10
0
9
23
0
5
0
0
0
0
34
1,898
false
through2
top1k-typed-with-typed-deps
2,318
import require$$0 from 'readable-stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var through2$2 = {exports: {}}; // FILE: through2.js const { Transform } = require$$0; function inherits (fn, sup) { fn.super_ = sup; fn.prototype = Object.create(sup.prototype, { constructor: { value: fn, enumerable: false, writable: true, configurable: true } }); } // create a new export function, used by both the main export and // the .ctor export, contains common logic for dealing with arguments function through2 (construct) { return (options, transform, flush) => { if (typeof options === 'function') { flush = transform; transform = options; options = {}; } if (typeof transform !== 'function') { // noop transform = (chunk, enc, cb) => cb(null, chunk); } if (typeof flush !== 'function') { flush = null; } return construct(options, transform, flush) } } // main export, just make me a transform stream! const make = through2((options, transform, flush) => { const t2 = new Transform(options); t2._transform = transform; if (flush) { t2._flush = flush; } return t2 }); // make me a reusable prototype that I can `new`, or implicitly `new` // with a constructor call const ctor = through2((options, transform, flush) => { function Through2 (override) { if (!(this instanceof Through2)) { return new Through2(override) } this.options = Object.assign({}, options, override); Transform.call(this, this.options); this._transform = transform; if (flush) { this._flush = flush; } } inherits(Through2, Transform); return Through2 }); const obj = through2(function (options, transform, flush) { const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options)); t2._transform = transform; if (flush) { t2._flush = flush; } return t2 }); through2$2.exports = make; var ctor_1 = through2$2.exports.ctor = ctor; var obj_1 = through2$2.exports.obj = obj; var through2Exports = through2$2.exports; var through2$1 = /*@__PURE__*/getDefaultExportFromCjs(through2Exports); export { ctor_1 as ctor, through2$1 as default, obj_1 as obj };
import require$$0 from 'readable-stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var through2$2 = {exports: {}}; // FILE: through2.js const { Transform } = require$$0; function inherits (fn, sup) { fn.super_ = sup; fn.prototype = Object.create(sup.prototype, { constructor: { value: fn, enumerable: false, writable: true, configurable: true } }); } // create a new export function, used by both the main export and // the .ctor export, contains common logic for dealing with arguments function through2 (construct) { return (options, transform, flush) => { if (typeof options === 'function') { flush = transform; transform = options; options = {}; } if (typeof transform !== 'function') { // noop transform = (chunk, enc, cb) => cb(null, chunk); } if (typeof flush !== 'function') { flush = null; } return construct(options, transform, flush) } } // main export, just make me a transform stream! const make = through2((options, transform, flush) => { const t2 = new Transform(options); t2._transform = transform; if (flush) { t2._flush = flush; } return t2 }); // make me a reusable prototype that I can `new`, or implicitly `new` // with a constructor call const ctor = through2((options, transform, flush) => { function Through2 (override) { if (!(this instanceof Through2)) { return new Through2(override) } this.options = Object.assign({}, options, override); Transform.call(this, this.options); this._transform = transform; if (flush) { this._flush = flush; } } inherits(Through2, Transform); return Through2 }); const obj = through2(function (options, transform, flush) { const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options)); t2._transform = transform; if (flush) { t2._flush = flush; } return t2 }); through2$2.exports = make; var ctor_1 = through2$2.exports.ctor = ctor; var obj_1 = through2$2.exports.obj = obj; var through2Exports = through2$2.exports; var through2$1 = /*@__PURE__*/getDefaultExportFromCjs(through2Exports); export { ctor_1 as ctor, through2$1 as default, obj_1 as obj };
65
9
0
20
11
0
3
0
0
0
4
7.333333
662
false
asynckit
top1k-untyped-nodeps
8,630
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/defer.js var defer_1 = defer$1; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer$1(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } // FILE: lib/async.js var defer = defer_1; // API var async_1 = async$2; /** * Runs provided callback asynchronously * even if callback itself is not * * @param {function} callback - callback to invoke * @returns {function} - augmented callback */ function async$2(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } // FILE: lib/abort.js // API var abort_1 = abort$2; /** * Aborts leftover active jobs * * @param {object} state - current state object */ function abort$2(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; } /** * Cleans up leftover job by invoking abort function for the provided job id * * @this state * @param {string|number} key - job id to abort */ function clean(key) { if (typeof this.jobs[key] == 'function') { this.jobs[key](); } } // FILE: lib/iterate.js var async$1 = async_1 , abort$1 = abort_1 ; // API var iterate_1 = iterate$2; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate$2(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort$1(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * Runs iterator over provided job element * * @param {function} iterator - iterator to invoke * @param {string|number} key - key/index of the element in the list of jobs * @param {mixed} item - job description * @param {function} callback - invoked after iterator is done with the job * @returns {function|mixed} - job abort function or something else */ function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async$1(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async$1(callback)); } return aborter; } // FILE: lib/state.js // API var state_1 = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; } // FILE: lib/terminator.js var abort = abort_1 , async = async_1 ; // API var terminator_1 = terminator$2; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator$2(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } // FILE: parallel.js var iterate$1 = iterate_1 , initState$1 = state_1 , terminator$1 = terminator_1 ; // Public API var parallel_1 = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState$1(list); while (state.index < (state['keyedList'] || list).length) { iterate$1(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator$1.bind(state, callback); } var serialOrdered$2 = {exports: {}}; // FILE: serialOrdered.js var iterate = iterate_1 , initState = state_1 , terminator = terminator_1 ; // Public API serialOrdered$2.exports = serialOrdered$1; // sorting helpers serialOrdered$2.exports.ascending = ascending; serialOrdered$2.exports.descending = descending; /** * Runs iterator over provided sorted array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} sortMethod - custom sort function * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serialOrdered$1(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * sort helper to sort array elements in ascending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function ascending(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } var serialOrderedExports = serialOrdered$2.exports; // FILE: serial.js var serialOrdered = serialOrderedExports; // Public API var serial_1 = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } // FILE: index.js var asynckit = { parallel : parallel_1, serial : serial_1, serialOrdered : serialOrderedExports }; var index = /*@__PURE__*/getDefaultExportFromCjs(asynckit); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/defer.js var defer_1 = defer$1; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer$1(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } // FILE: lib/async.js var defer = defer_1; // API var async_1 = async$2; /** * Runs provided callback asynchronously * even if callback itself is not * * @param {function} callback - callback to invoke * @returns {function} - augmented callback */ function async$2(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } // FILE: lib/abort.js // API var abort_1 = abort$2; /** * Aborts leftover active jobs * * @param {object} state - current state object */ function abort$2(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; } /** * Cleans up leftover job by invoking abort function for the provided job id * * @this state * @param {string|number} key - job id to abort */ function clean(key) { if (typeof this.jobs[key] == 'function') { this.jobs[key](); } } // FILE: lib/iterate.js var async$1 = async_1 , abort$1 = abort_1 ; // API var iterate_1 = iterate$2; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate$2(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort$1(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * Runs iterator over provided job element * * @param {function} iterator - iterator to invoke * @param {string|number} key - key/index of the element in the list of jobs * @param {mixed} item - job description * @param {function} callback - invoked after iterator is done with the job * @returns {function|mixed} - job abort function or something else */ function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async$1(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async$1(callback)); } return aborter; } // FILE: lib/state.js // API var state_1 = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; } // FILE: lib/terminator.js var abort = abort_1 , async = async_1 ; // API var terminator_1 = terminator$2; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator$2(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } // FILE: parallel.js var iterate$1 = iterate_1 , initState$1 = state_1 , terminator$1 = terminator_1 ; // Public API var parallel_1 = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState$1(list); while (state.index < (state['keyedList'] || list).length) { iterate$1(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator$1.bind(state, callback); } var serialOrdered$2 = {exports: {}}; // FILE: serialOrdered.js var iterate = iterate_1 , initState = state_1 , terminator = terminator_1 ; // Public API serialOrdered$2.exports = serialOrdered$1; // sorting helpers serialOrdered$2.exports.ascending = ascending; serialOrdered$2.exports.descending = descending; /** * Runs iterator over provided sorted array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} sortMethod - custom sort function * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serialOrdered$1(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * sort helper to sort array elements in ascending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function ascending(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } var serialOrderedExports = serialOrdered$2.exports; // FILE: serial.js var serialOrdered = serialOrderedExports; // Public API var serial_1 = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } // FILE: index.js var asynckit = { parallel : parallel_1, serial : serial_1, serialOrdered : serialOrderedExports }; var index = /*@__PURE__*/getDefaultExportFromCjs(asynckit); export { index as default };
208
21
0
40
32
0
3
0
0
0
4
8.571429
2,474
false
glob-parent
top1k-typed-with-typed-deps
1,932
import require$$0 from 'is-glob'; import require$$1 from 'path'; import require$$2 from 'os'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var isGlob = require$$0; var pathPosixDirname = require$$1.posix.dirname; var isWin32 = require$$2.platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var escaped = /\\([!*?|[\](){}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] */ var globParent = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (isEnclosure(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlobby(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; function isEnclosure(str) { var lastChar = str.slice(-1); var enclosureStart; switch (lastChar) { case '}': enclosureStart = '{'; break; case ']': enclosureStart = '['; break; default: return false; } var foundIndex = str.indexOf(enclosureStart); if (foundIndex < 0) { return false; } return str.slice(foundIndex + 1, -1).includes(slash); } function isGlobby(str) { if (/\([^()]+$/.test(str)) { return true; } if (str[0] === '{' || str[0] === '[') { return true; } if (/[^\\][{[]/.test(str)) { return true; } return isGlob(str); } var index = /*@__PURE__*/getDefaultExportFromCjs(globParent); export { index as default };
import require$$0 from 'is-glob'; import require$$1 from 'path'; import require$$2 from 'os'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var isGlob = require$$0; var pathPosixDirname = require$$1.posix.dirname; var isWin32 = require$$2.platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var escaped = /\\([!*?|[\](){}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] */ var globParent = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (isEnclosure(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlobby(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; function isEnclosure(str) { var lastChar = str.slice(-1); var enclosureStart; switch (lastChar) { case '}': enclosureStart = '{'; break; case ']': enclosureStart = '['; break; default: return false; } var foundIndex = str.indexOf(enclosureStart); if (foundIndex < 0) { return false; } return str.slice(foundIndex + 1, -1).includes(slash); } function isGlobby(str) { if (/\([^()]+$/.test(str)) { return true; } if (str[0] === '{' || str[0] === '[') { return true; } if (/[^\\][{[]/.test(str)) { return true; } return isGlob(str); } var index = /*@__PURE__*/getDefaultExportFromCjs(globParent); export { index as default };
59
4
0
5
12
0
3
0
0
0
0
10
604
true
figgy-pudding
top1k-untyped-nodeps
4,970
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js class FiggyPudding { constructor (specs, opts, providers) { this.__specs = specs || {}; Object.keys(this.__specs).forEach(alias => { if (typeof this.__specs[alias] === 'string') { const key = this.__specs[alias]; const realSpec = this.__specs[key]; if (realSpec) { const aliasArr = realSpec.aliases || []; aliasArr.push(alias, key); realSpec.aliases = [...(new Set(aliasArr))]; this.__specs[alias] = realSpec; } else { throw new Error(`Alias refers to invalid key: ${key} -> ${alias}`) } } }); this.__opts = opts || {}; this.__providers = reverse((providers).filter( x => x != null && typeof x === 'object' )); this.__isFiggyPudding = true; } get (key) { return pudGet(this, key, true) } get [Symbol.toStringTag] () { return 'FiggyPudding' } forEach (fn, thisArg = this) { for (let [key, value] of this.entries()) { fn.call(thisArg, value, key, this); } } toJSON () { const obj = {}; this.forEach((val, key) => { obj[key] = val; }); return obj } * entries (_matcher) { for (let key of Object.keys(this.__specs)) { yield [key, this.get(key)]; } const matcher = _matcher || this.__opts.other; if (matcher) { const seen = new Set(); for (let p of this.__providers) { const iter = p.entries ? p.entries(matcher) : entries(p); for (let [key, val] of iter) { if (matcher(key) && !seen.has(key)) { seen.add(key); yield [key, val]; } } } } } * [Symbol.iterator] () { for (let [key, value] of this.entries()) { yield [key, value]; } } * keys () { for (let [key] of this.entries()) { yield key; } } * values () { for (let [, value] of this.entries()) { yield value; } } concat (...moreConfig) { return new Proxy(new FiggyPudding( this.__specs, this.__opts, reverse(this.__providers).concat(moreConfig) ), proxyHandler) } } try { const util = require('util'); FiggyPudding.prototype[util.inspect.custom] = function (depth, opts) { return ( this[Symbol.toStringTag] + ' ' ) + util.inspect(this.toJSON(), opts) }; } catch (e) {} function BadKeyError (key) { throw Object.assign(new Error( `invalid config key requested: ${key}` ), {code: 'EBADKEY'}) } function pudGet (pud, key, validate) { let spec = pud.__specs[key]; if (validate && !spec && (!pud.__opts.other || !pud.__opts.other(key))) { BadKeyError(key); } else { if (!spec) { spec = {}; } let ret; for (let p of pud.__providers) { ret = tryGet(key, p); if (ret === undefined && spec.aliases && spec.aliases.length) { for (let alias of spec.aliases) { if (alias === key) { continue } ret = tryGet(alias, p); if (ret !== undefined) { break } } } if (ret !== undefined) { break } } if (ret === undefined && spec.default !== undefined) { if (typeof spec.default === 'function') { return spec.default(pud) } else { return spec.default } } else { return ret } } } function tryGet (key, p) { let ret; if (p.__isFiggyPudding) { ret = pudGet(p, key, false); } else if (typeof p.get === 'function') { ret = p.get(key); } else { ret = p[key]; } return ret } const proxyHandler = { has (obj, prop) { return prop in obj.__specs && pudGet(obj, prop, false) !== undefined }, ownKeys (obj) { return Object.keys(obj.__specs) }, get (obj, prop) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' || prop in FiggyPudding.prototype ) { return obj[prop] } return obj.get(prop) }, set (obj, prop, value) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' ) { obj[prop] = value; return true } else { throw new Error('figgyPudding options cannot be modified. Use .concat() instead.') } }, deleteProperty () { throw new Error('figgyPudding options cannot be deleted. Use .concat() and shadow them instead.') } }; var figgyPudding_1 = figgyPudding; function figgyPudding (specs, opts) { function factory (...providers) { return new Proxy(new FiggyPudding( specs, opts, providers ), proxyHandler) } return factory } function reverse (arr) { const ret = []; arr.forEach(x => ret.unshift(x)); return ret } function entries (obj) { return Object.keys(obj).map(k => [k, obj[k]]) } var index = /*@__PURE__*/getDefaultExportFromCjs(figgyPudding_1); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js class FiggyPudding { constructor (specs, opts, providers) { this.__specs = specs || {}; Object.keys(this.__specs).forEach(alias => { if (typeof this.__specs[alias] === 'string') { const key = this.__specs[alias]; const realSpec = this.__specs[key]; if (realSpec) { const aliasArr = realSpec.aliases || []; aliasArr.push(alias, key); realSpec.aliases = [...(new Set(aliasArr))]; this.__specs[alias] = realSpec; } else { throw new Error(`Alias refers to invalid key: ${key} -> ${alias}`) } } }); this.__opts = opts || {}; this.__providers = reverse((providers).filter( x => x != null && typeof x === 'object' )); this.__isFiggyPudding = true; } get (key) { return pudGet(this, key, true) } get [Symbol.toStringTag] () { return 'FiggyPudding' } forEach (fn, thisArg = this) { for (let [key, value] of this.entries()) { fn.call(thisArg, value, key, this); } } toJSON () { const obj = {}; this.forEach((val, key) => { obj[key] = val; }); return obj } * entries (_matcher) { for (let key of Object.keys(this.__specs)) { yield [key, this.get(key)]; } const matcher = _matcher || this.__opts.other; if (matcher) { const seen = new Set(); for (let p of this.__providers) { const iter = p.entries ? p.entries(matcher) : entries(p); for (let [key, val] of iter) { if (matcher(key) && !seen.has(key)) { seen.add(key); yield [key, val]; } } } } } * [Symbol.iterator] () { for (let [key, value] of this.entries()) { yield [key, value]; } } * keys () { for (let [key] of this.entries()) { yield key; } } * values () { for (let [, value] of this.entries()) { yield value; } } concat (...moreConfig) { return new Proxy(new FiggyPudding( this.__specs, this.__opts, reverse(this.__providers).concat(moreConfig) ), proxyHandler) } } try { const util = require('util'); FiggyPudding.prototype[util.inspect.custom] = function (depth, opts) { return ( this[Symbol.toStringTag] + ' ' ) + util.inspect(this.toJSON(), opts) }; } catch (e) {} function BadKeyError (key) { throw Object.assign(new Error( `invalid config key requested: ${key}` ), {code: 'EBADKEY'}) } function pudGet (pud, key, validate) { let spec = pud.__specs[key]; if (validate && !spec && (!pud.__opts.other || !pud.__opts.other(key))) { BadKeyError(key); } else { if (!spec) { spec = {}; } let ret; for (let p of pud.__providers) { ret = tryGet(key, p); if (ret === undefined && spec.aliases && spec.aliases.length) { for (let alias of spec.aliases) { if (alias === key) { continue } ret = tryGet(alias, p); if (ret !== undefined) { break } } } if (ret !== undefined) { break } } if (ret === undefined && spec.default !== undefined) { if (typeof spec.default === 'function') { return spec.default(pud) } else { return spec.default } } else { return ret } } } function tryGet (key, p) { let ret; if (p.__isFiggyPudding) { ret = pudGet(p, key, false); } else if (typeof p.get === 'function') { ret = p.get(key); } else { ret = p[key]; } return ret } const proxyHandler = { has (obj, prop) { return prop in obj.__specs && pudGet(obj, prop, false) !== undefined }, ownKeys (obj) { return Object.keys(obj.__specs) }, get (obj, prop) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' || prop in FiggyPudding.prototype ) { return obj[prop] } return obj.get(prop) }, set (obj, prop, value) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' ) { obj[prop] = value; return true } else { throw new Error('figgyPudding options cannot be modified. Use .concat() instead.') } }, deleteProperty () { throw new Error('figgyPudding options cannot be deleted. Use .concat() and shadow them instead.') } }; var figgyPudding_1 = figgyPudding; function figgyPudding (specs, opts) { function factory (...providers) { return new Proxy(new FiggyPudding( specs, opts, providers ), proxyHandler) } return factory } function reverse (arr) { const ret = []; arr.forEach(x => ret.unshift(x)); return ret } function entries (obj) { return Object.keys(obj).map(k => [k, obj[k]]) } var index = /*@__PURE__*/getDefaultExportFromCjs(figgyPudding_1); export { index as default };
193
29
0
36
15
0
12
0
0
1
6
5.517241
1,477
false
pumpify
top1k-typed-with-typed-deps
2,231
import require$$0 from 'pump'; import require$$1 from 'inherits'; import require$$2 from 'duplexify'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var pumpify = {exports: {}}; // FILE: index.js var pump = require$$0; var inherits = require$$1; var Duplexify = require$$2; var toArray = function(args) { if (!args.length) return [] return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args) }; var define = function(opts) { var Pumpify = function() { var streams = toArray(arguments); if (!(this instanceof Pumpify)) return new Pumpify(streams) Duplexify.call(this, null, null, opts); if (streams.length) this.setPipeline(streams); }; inherits(Pumpify, Duplexify); Pumpify.prototype.setPipeline = function() { var streams = toArray(arguments); var self = this; var ended = false; var w = streams[0]; var r = streams[streams.length-1]; r = r.readable ? r : null; w = w.writable ? w : null; var onclose = function() { streams[0].emit('error', new Error('stream was destroyed')); }; this.on('close', onclose); this.on('prefinish', function() { if (!ended) self.cork(); }); pump(streams, function(err) { self.removeListener('close', onclose); if (err) return self.destroy(err.message === 'premature close' ? null : err) ended = true; // pump ends after the last stream is not writable *but* // pumpify still forwards the readable part so we need to catch errors // still, so reenable autoDestroy in this case if (self._autoDestroy === false) self._autoDestroy = true; self.uncork(); }); if (this.destroyed) return onclose() this.setWritable(w); this.setReadable(r); }; return Pumpify }; pumpify.exports = define({autoDestroy:false, destroy:false}); var obj = pumpify.exports.obj = define({autoDestroy: false, destroy:false, objectMode:true, highWaterMark:16}); var ctor = pumpify.exports.ctor = define; var pumpifyExports = pumpify.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(pumpifyExports); export { ctor, index as default, obj };
import require$$0 from 'pump'; import require$$1 from 'inherits'; import require$$2 from 'duplexify'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var pumpify = {exports: {}}; // FILE: index.js var pump = require$$0; var inherits = require$$1; var Duplexify = require$$2; var toArray = function(args) { if (!args.length) return [] return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args) }; var define = function(opts) { var Pumpify = function() { var streams = toArray(arguments); if (!(this instanceof Pumpify)) return new Pumpify(streams) Duplexify.call(this, null, null, opts); if (streams.length) this.setPipeline(streams); }; inherits(Pumpify, Duplexify); Pumpify.prototype.setPipeline = function() { var streams = toArray(arguments); var self = this; var ended = false; var w = streams[0]; var r = streams[streams.length-1]; r = r.readable ? r : null; w = w.writable ? w : null; var onclose = function() { streams[0].emit('error', new Error('stream was destroyed')); }; this.on('close', onclose); this.on('prefinish', function() { if (!ended) self.cork(); }); pump(streams, function(err) { self.removeListener('close', onclose); if (err) return self.destroy(err.message === 'premature close' ? null : err) ended = true; // pump ends after the last stream is not writable *but* // pumpify still forwards the readable part so we need to catch errors // still, so reenable autoDestroy in this case if (self._autoDestroy === false) self._autoDestroy = true; self.uncork(); }); if (this.destroyed) return onclose() this.setWritable(w); this.setReadable(r); }; return Pumpify }; pumpify.exports = define({autoDestroy:false, destroy:false}); var obj = pumpify.exports.obj = define({autoDestroy: false, destroy:false, objectMode:true, highWaterMark:16}); var ctor = pumpify.exports.ctor = define; var pumpifyExports = pumpify.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(pumpifyExports); export { ctor, index as default, obj };
56
8
0
4
18
0
5
0
0
0
1
9
645
false
pop-iterate
top1k-untyped-nodeps
2,479
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: iteration.js var iteration = Iteration$2; function Iteration$2(value, done, index) { this.value = value; this.done = done; this.index = index; } Iteration$2.prototype.equals = function (other) { return ( typeof other == 'object' && other.value === this.value && other.done === this.done && other.index === this.index ); }; // FILE: array-iterator.js var Iteration$1 = iteration; var arrayIterator = ArrayIterator$2; function ArrayIterator$2(iterable, start, stop, step) { this.array = iterable; this.start = start || 0; this.stop = stop || Infinity; this.step = step || 1; } ArrayIterator$2.prototype.next = function () { var iteration; if (this.start < Math.min(this.array.length, this.stop)) { iteration = new Iteration$1(this.array[this.start], false, this.start); this.start += this.step; } else { iteration = new Iteration$1(undefined, true); } return iteration; }; // FILE: object-iterator.js var Iteration = iteration; var ArrayIterator$1 = arrayIterator; var objectIterator = ObjectIterator$1; function ObjectIterator$1(iterable, start, stop, step) { this.object = iterable; this.keysIterator = new ArrayIterator$1(Object.keys(iterable), start, stop, step); } ObjectIterator$1.prototype.next = function () { var iteration = this.keysIterator.next(); if (iteration.done) { return iteration; } var key = iteration.value; return new Iteration(this.object[key], false, key); }; // FILE: pop-iterate.js var ArrayIterator = arrayIterator; var ObjectIterator = objectIterator; var popIterate = iterate; function iterate(iterable, start, stop, step) { if (!iterable) { return empty; } else if (Array.isArray(iterable)) { return new ArrayIterator(iterable, start, stop, step); } else if (typeof iterable.next === "function") { return iterable; } else if (typeof iterable.iterate === "function") { return iterable.iterate(start, stop, step); } else if (typeof iterable === "object") { return new ObjectIterator(iterable); } else { throw new TypeError("Can't iterate " + iterable); } } var popIterate$1 = /*@__PURE__*/getDefaultExportFromCjs(popIterate); export { popIterate$1 as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: iteration.js var iteration = Iteration$2; function Iteration$2(value, done, index) { this.value = value; this.done = done; this.index = index; } Iteration$2.prototype.equals = function (other) { return ( typeof other == 'object' && other.value === this.value && other.done === this.done && other.index === this.index ); }; // FILE: array-iterator.js var Iteration$1 = iteration; var arrayIterator = ArrayIterator$2; function ArrayIterator$2(iterable, start, stop, step) { this.array = iterable; this.start = start || 0; this.stop = stop || Infinity; this.step = step || 1; } ArrayIterator$2.prototype.next = function () { var iteration; if (this.start < Math.min(this.array.length, this.stop)) { iteration = new Iteration$1(this.array[this.start], false, this.start); this.start += this.step; } else { iteration = new Iteration$1(undefined, true); } return iteration; }; // FILE: object-iterator.js var Iteration = iteration; var ArrayIterator$1 = arrayIterator; var objectIterator = ObjectIterator$1; function ObjectIterator$1(iterable, start, stop, step) { this.object = iterable; this.keysIterator = new ArrayIterator$1(Object.keys(iterable), start, stop, step); } ObjectIterator$1.prototype.next = function () { var iteration = this.keysIterator.next(); if (iteration.done) { return iteration; } var key = iteration.value; return new Iteration(this.object[key], false, key); }; // FILE: pop-iterate.js var ArrayIterator = arrayIterator; var ObjectIterator = objectIterator; var popIterate = iterate; function iterate(iterable, start, stop, step) { if (!iterable) { return empty; } else if (Array.isArray(iterable)) { return new ArrayIterator(iterable, start, stop, step); } else if (typeof iterable.next === "function") { return iterable; } else if (typeof iterable.iterate === "function") { return iterable.iterate(start, stop, step); } else if (typeof iterable === "object") { return new ObjectIterator(iterable); } else { throw new TypeError("Can't iterate " + iterable); } } var popIterate$1 = /*@__PURE__*/getDefaultExportFromCjs(popIterate); export { popIterate$1 as default };
70
8
0
17
13
0
3
0
0
0
4
5.375
684
false
miller-rabin
top1k-untyped-with-typed-deps
2,780
import require$$0 from 'bn.js'; import require$$1 from 'brorand'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/mr.js var bn = require$$0; var brorand = require$$1; function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } var mr = MillerRabin; MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0); return a; }; MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } if (i === s) return false; } return prime; }; MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } return false; }; var mr$1 = /*@__PURE__*/getDefaultExportFromCjs(mr); export { mr$1 as default };
import require$$0 from 'bn.js'; import require$$1 from 'brorand'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/mr.js var bn = require$$0; var brorand = require$$1; function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } var mr = MillerRabin; MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0); return a; }; MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } if (i === s) return false; } return prime; }; MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } return false; }; var mr$1 = /*@__PURE__*/getDefaultExportFromCjs(mr); export { mr$1 as default };
90
7
0
11
30
0
3
0
0
0
0
9.857143
1,078
false
@sinonjs_commons
top1k-typed-with-typed-deps
9,663
import require$$0 from 'type-detect'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/global.js /** * A reference to the global object * * @type {object} globalObject */ var globalObject; /* istanbul ignore else */ if (typeof commonjsGlobal !== "undefined") { // Node globalObject = commonjsGlobal; } else if (typeof window !== "undefined") { // Browser globalObject = window; } else { // WebWorker globalObject = self; } var global$1 = globalObject; // FILE: lib/prototypes/copy-prototype.js var call = Function.call; var copyPrototype$6 = function copyPrototypeMethods(prototype) { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods return Object.getOwnPropertyNames(prototype).reduce(function(result, name) { // ignore size because it throws from Map if ( name !== "size" && name !== "caller" && name !== "callee" && name !== "arguments" && typeof prototype[name] === "function" ) { result[name] = call.bind(prototype[name]); } return result; }, Object.create(null)); }; // FILE: lib/prototypes/array.js var copyPrototype$5 = copyPrototype$6; var array = copyPrototype$5(Array.prototype); // FILE: lib/called-in-order.js var every$1 = array.every; /** * @private */ function hasCallsLeft(callMap, spy) { if (callMap[spy.id] === undefined) { callMap[spy.id] = 0; } return callMap[spy.id] < spy.callCount; } /** * @private */ function checkAdjacentCalls(callMap, spy, index, spies) { var calledBeforeNext = true; if (index !== spies.length - 1) { calledBeforeNext = spy.calledBefore(spies[index + 1]); } if (hasCallsLeft(callMap, spy) && calledBeforeNext) { callMap[spy.id] += 1; return true; } return false; } /** * A Sinon proxy object (fake, spy, stub) * * @typedef {object} SinonProxy * @property {Function} calledBefore - A method that determines if this proxy was called before another one * @property {string} id - Some id * @property {number} callCount - Number of times this proxy has been called */ /** * Returns true when the spies have been called in the order they were supplied in * * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments * @returns {boolean} true when spies are called in order, false otherwise */ function calledInOrder(spies) { var callMap = {}; // eslint-disable-next-line no-underscore-dangle var _spies = arguments.length > 1 ? arguments : spies; return every$1(_spies, checkAdjacentCalls.bind(null, callMap)); } var calledInOrder_1 = calledInOrder; // FILE: lib/function-name.js /** * Returns a display name for a function * * @param {Function} func * @returns {string} */ var functionName$1 = function functionName(func) { if (!func) { return ""; } try { return ( func.displayName || func.name || // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). (String(func).match(/function ([^\s(]+)/) || [])[1] ); } catch (e) { // Stringify may fail and we might get an exception, as a last-last // resort fall back to empty string. return ""; } }; // FILE: lib/class-name.js var functionName = functionName$1; /** * Returns a display name for a value from a constructor * * @param {object} value A value to examine * @returns {(string|null)} A string or null */ function className(value) { return ( (value.constructor && value.constructor.name) || // The next branch is for IE11 support only: // Because the name property is not set on the prototype // of the Function object, we finally try to grab the // name from its definition. This will never be reached // in node, so we are not able to test this properly. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name (typeof value.constructor === "function" && /* istanbul ignore next */ functionName(value.constructor)) || null ); } var className_1 = className; var deprecated = {}; // FILE: lib/deprecated.js /* eslint-disable no-console */ (function (exports) { /** * Returns a function that will invoke the supplied function and print a * deprecation warning to the console each time it is called. * * @param {Function} func * @param {string} msg * @returns {Function} */ exports.wrap = function(func, msg) { var wrapped = function() { exports.printWarning(msg); return func.apply(this, arguments); }; if (func.prototype) { wrapped.prototype = func.prototype; } return wrapped; }; /** * Returns a string which can be supplied to `wrap()` to notify the user that a * particular part of the sinon API has been deprecated. * * @param {string} packageName * @param {string} funcName * @returns {string} */ exports.defaultMsg = function(packageName, funcName) { return ( packageName + "." + funcName + " is deprecated and will be removed from the public API in a future version of " + packageName + "." ); }; /** * Prints a warning on the console, when it exists * * @param {string} msg * @returns {undefined} */ exports.printWarning = function(msg) { /* istanbul ignore next */ if (typeof process === "object" && process.emitWarning) { // Emit Warnings in Node process.emitWarning(msg); } else if (console.info) { console.info(msg); } else { console.log(msg); } }; } (deprecated)); // FILE: lib/every.js /** * Returns true when fn returns true for all members of obj. * This is an every implementation that works for all iterables * * @param {object} obj * @param {Function} fn * @returns {boolean} */ var every = function every(obj, fn) { var pass = true; try { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods obj.forEach(function() { if (!fn.apply(this, arguments)) { // Throwing an error is the only way to break `forEach` throw new Error(); } }); } catch (e) { pass = false; } return pass; }; // FILE: lib/order-by-first-call.js var sort = array.sort; var slice = array.slice; /** * @private */ function comparator(a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = (aCall && aCall.callId) || -1; var bId = (bCall && bCall.callId) || -1; return aId < bId ? -1 : 1; } /** * A Sinon proxy object (fake, spy, stub) * * @typedef {object} SinonProxy * @property {Function} getCall - A method that can return the first call */ /** * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call * * @param {SinonProxy[] | SinonProxy} spies * @returns {SinonProxy[]} */ function orderByFirstCall(spies) { return sort(slice(spies), comparator); } var orderByFirstCall_1 = orderByFirstCall; // FILE: lib/prototypes/function.js var copyPrototype$4 = copyPrototype$6; var _function = copyPrototype$4(Function.prototype); // FILE: lib/prototypes/map.js var copyPrototype$3 = copyPrototype$6; var map = copyPrototype$3(Map.prototype); // FILE: lib/prototypes/object.js var copyPrototype$2 = copyPrototype$6; var object = copyPrototype$2(Object.prototype); // FILE: lib/prototypes/set.js var copyPrototype$1 = copyPrototype$6; var set = copyPrototype$1(Set.prototype); // FILE: lib/prototypes/string.js var copyPrototype = copyPrototype$6; var string = copyPrototype(String.prototype); // FILE: lib/prototypes/index.js var prototypes = { array: array, function: _function, map: map, object: object, set: set, string: string }; // FILE: lib/type-of.js var type = require$$0; /** * Returns the lower-case result of running type from type-detect on the value * * @param {*} value * @returns {string} */ var typeOf = function typeOf(value) { return type(value).toLowerCase(); }; // FILE: lib/value-to-string.js /** * Returns a string representation of the value * * @param {*} value * @returns {string} */ function valueToString(value) { if (value && value.toString) { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods return value.toString(); } return String(value); } var valueToString_1 = valueToString; // FILE: lib/index.js var lib = { global: global$1, calledInOrder: calledInOrder_1, className: className_1, deprecated: deprecated, every: every, functionName: functionName$1, orderByFirstCall: orderByFirstCall_1, prototypes: prototypes, typeOf: typeOf, valueToString: valueToString_1 }; var index = /*@__PURE__*/getDefaultExportFromCjs(lib); export { index as default };
import require$$0 from 'type-detect'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/global.js /** * A reference to the global object * * @type {object} globalObject */ var globalObject; /* istanbul ignore else */ if (typeof commonjsGlobal !== "undefined") { // Node globalObject = commonjsGlobal; } else if (typeof window !== "undefined") { // Browser globalObject = window; } else { // WebWorker globalObject = self; } var global$1 = globalObject; // FILE: lib/prototypes/copy-prototype.js var call = Function.call; var copyPrototype$6 = function copyPrototypeMethods(prototype) { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods return Object.getOwnPropertyNames(prototype).reduce(function(result, name) { // ignore size because it throws from Map if ( name !== "size" && name !== "caller" && name !== "callee" && name !== "arguments" && typeof prototype[name] === "function" ) { result[name] = call.bind(prototype[name]); } return result; }, Object.create(null)); }; // FILE: lib/prototypes/array.js var copyPrototype$5 = copyPrototype$6; var array = copyPrototype$5(Array.prototype); // FILE: lib/called-in-order.js var every$1 = array.every; /** * @private */ function hasCallsLeft(callMap, spy) { if (callMap[spy.id] === undefined) { callMap[spy.id] = 0; } return callMap[spy.id] < spy.callCount; } /** * @private */ function checkAdjacentCalls(callMap, spy, index, spies) { var calledBeforeNext = true; if (index !== spies.length - 1) { calledBeforeNext = spy.calledBefore(spies[index + 1]); } if (hasCallsLeft(callMap, spy) && calledBeforeNext) { callMap[spy.id] += 1; return true; } return false; } /** * A Sinon proxy object (fake, spy, stub) * * @typedef {object} SinonProxy * @property {Function} calledBefore - A method that determines if this proxy was called before another one * @property {string} id - Some id * @property {number} callCount - Number of times this proxy has been called */ /** * Returns true when the spies have been called in the order they were supplied in * * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments * @returns {boolean} true when spies are called in order, false otherwise */ function calledInOrder(spies) { var callMap = {}; // eslint-disable-next-line no-underscore-dangle var _spies = arguments.length > 1 ? arguments : spies; return every$1(_spies, checkAdjacentCalls.bind(null, callMap)); } var calledInOrder_1 = calledInOrder; // FILE: lib/function-name.js /** * Returns a display name for a function * * @param {Function} func * @returns {string} */ var functionName$1 = function functionName(func) { if (!func) { return ""; } try { return ( func.displayName || func.name || // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). (String(func).match(/function ([^\s(]+)/) || [])[1] ); } catch (e) { // Stringify may fail and we might get an exception, as a last-last // resort fall back to empty string. return ""; } }; // FILE: lib/class-name.js var functionName = functionName$1; /** * Returns a display name for a value from a constructor * * @param {object} value A value to examine * @returns {(string|null)} A string or null */ function className(value) { return ( (value.constructor && value.constructor.name) || // The next branch is for IE11 support only: // Because the name property is not set on the prototype // of the Function object, we finally try to grab the // name from its definition. This will never be reached // in node, so we are not able to test this properly. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name (typeof value.constructor === "function" && /* istanbul ignore next */ functionName(value.constructor)) || null ); } var className_1 = className; var deprecated = {}; // FILE: lib/deprecated.js /* eslint-disable no-console */ (function (exports) { /** * Returns a function that will invoke the supplied function and print a * deprecation warning to the console each time it is called. * * @param {Function} func * @param {string} msg * @returns {Function} */ exports.wrap = function(func, msg) { var wrapped = function() { exports.printWarning(msg); return func.apply(this, arguments); }; if (func.prototype) { wrapped.prototype = func.prototype; } return wrapped; }; /** * Returns a string which can be supplied to `wrap()` to notify the user that a * particular part of the sinon API has been deprecated. * * @param {string} packageName * @param {string} funcName * @returns {string} */ exports.defaultMsg = function(packageName, funcName) { return ( packageName + "." + funcName + " is deprecated and will be removed from the public API in a future version of " + packageName + "." ); }; /** * Prints a warning on the console, when it exists * * @param {string} msg * @returns {undefined} */ exports.printWarning = function(msg) { /* istanbul ignore next */ if (typeof process === "object" && process.emitWarning) { // Emit Warnings in Node process.emitWarning(msg); } else if (console.info) { console.info(msg); } else { console.log(msg); } }; } (deprecated)); // FILE: lib/every.js /** * Returns true when fn returns true for all members of obj. * This is an every implementation that works for all iterables * * @param {object} obj * @param {Function} fn * @returns {boolean} */ var every = function every(obj, fn) { var pass = true; try { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods obj.forEach(function() { if (!fn.apply(this, arguments)) { // Throwing an error is the only way to break `forEach` throw new Error(); } }); } catch (e) { pass = false; } return pass; }; // FILE: lib/order-by-first-call.js var sort = array.sort; var slice = array.slice; /** * @private */ function comparator(a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = (aCall && aCall.callId) || -1; var bId = (bCall && bCall.callId) || -1; return aId < bId ? -1 : 1; } /** * A Sinon proxy object (fake, spy, stub) * * @typedef {object} SinonProxy * @property {Function} getCall - A method that can return the first call */ /** * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call * * @param {SinonProxy[] | SinonProxy} spies * @returns {SinonProxy[]} */ function orderByFirstCall(spies) { return sort(slice(spies), comparator); } var orderByFirstCall_1 = orderByFirstCall; // FILE: lib/prototypes/function.js var copyPrototype$4 = copyPrototype$6; var _function = copyPrototype$4(Function.prototype); // FILE: lib/prototypes/map.js var copyPrototype$3 = copyPrototype$6; var map = copyPrototype$3(Map.prototype); // FILE: lib/prototypes/object.js var copyPrototype$2 = copyPrototype$6; var object = copyPrototype$2(Object.prototype); // FILE: lib/prototypes/set.js var copyPrototype$1 = copyPrototype$6; var set = copyPrototype$1(Set.prototype); // FILE: lib/prototypes/string.js var copyPrototype = copyPrototype$6; var string = copyPrototype(String.prototype); // FILE: lib/prototypes/index.js var prototypes = { array: array, function: _function, map: map, object: object, set: set, string: string }; // FILE: lib/type-of.js var type = require$$0; /** * Returns the lower-case result of running type from type-detect on the value * * @param {*} value * @returns {string} */ var typeOf = function typeOf(value) { return type(value).toLowerCase(); }; // FILE: lib/value-to-string.js /** * Returns a string representation of the value * * @param {*} value * @returns {string} */ function valueToString(value) { if (value && value.toString) { // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods return value.toString(); } return String(value); } var valueToString_1 = valueToString; // FILE: lib/index.js var lib = { global: global$1, calledInOrder: calledInOrder_1, className: className_1, deprecated: deprecated, every: every, functionName: functionName$1, orderByFirstCall: orderByFirstCall_1, prototypes: prototypes, typeOf: typeOf, valueToString: valueToString_1 }; var index = /*@__PURE__*/getDefaultExportFromCjs(lib); export { index as default };
180
19
0
26
42
0
4
0
0
0
9
7.157895
2,685
false
etag
top1k-typed-nodeps
2,774
import require$$0 from 'crypto'; import require$$1 from 'fs'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /*! * etag * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed */ /** * Module exports. * @public */ var etag_1 = etag; /** * Module dependencies. * @private */ var crypto = require$$0; var Stats = require$$1.Stats; /** * Module variables. * @private */ var toString = Object.prototype.toString; /** * Generate an entity tag. * * @param {Buffer|string} entity * @return {string} * @private */ function entitytag (entity) { if (entity.length === 0) { // fast-path empty return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' } // compute hash of entity var hash = crypto .createHash('sha1') .update(entity, 'utf8') .digest('base64') .substring(0, 27); // compute length of entity var len = typeof entity === 'string' ? Buffer.byteLength(entity, 'utf8') : entity.length; return '"' + len.toString(16) + '-' + hash + '"' } /** * Create a simple ETag. * * @param {string|Buffer|Stats} entity * @param {object} [options] * @param {boolean} [options.weak] * @return {String} * @public */ function etag (entity, options) { if (entity == null) { throw new TypeError('argument entity is required') } // support fs.Stats object var isStats = isstats(entity); var weak = options && typeof options.weak === 'boolean' ? options.weak : isStats; // validate argument if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } // generate entity tag var tag = isStats ? stattag(entity) : entitytag(entity); return weak ? 'W/' + tag : tag } /** * Determine if object is a Stats object. * * @param {object} obj * @return {boolean} * @api private */ function isstats (obj) { // genuine fs.Stats if (typeof Stats === 'function' && obj instanceof Stats) { return true } // quack quack return obj && typeof obj === 'object' && 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && 'ino' in obj && typeof obj.ino === 'number' && 'size' in obj && typeof obj.size === 'number' } /** * Generate a tag for a stat. * * @param {object} stat * @return {string} * @private */ function stattag (stat) { var mtime = stat.mtime.getTime().toString(16); var size = stat.size.toString(16); return '"' + size + '-' + mtime + '"' } var index = /*@__PURE__*/getDefaultExportFromCjs(etag_1); export { index as default };
import require$$0 from 'crypto'; import require$$1 from 'fs'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /*! * etag * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed */ /** * Module exports. * @public */ var etag_1 = etag; /** * Module dependencies. * @private */ var crypto = require$$0; var Stats = require$$1.Stats; /** * Module variables. * @private */ var toString = Object.prototype.toString; /** * Generate an entity tag. * * @param {Buffer|string} entity * @return {string} * @private */ function entitytag (entity) { if (entity.length === 0) { // fast-path empty return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' } // compute hash of entity var hash = crypto .createHash('sha1') .update(entity, 'utf8') .digest('base64') .substring(0, 27); // compute length of entity var len = typeof entity === 'string' ? Buffer.byteLength(entity, 'utf8') : entity.length; return '"' + len.toString(16) + '-' + hash + '"' } /** * Create a simple ETag. * * @param {string|Buffer|Stats} entity * @param {object} [options] * @param {boolean} [options.weak] * @return {String} * @public */ function etag (entity, options) { if (entity == null) { throw new TypeError('argument entity is required') } // support fs.Stats object var isStats = isstats(entity); var weak = options && typeof options.weak === 'boolean' ? options.weak : isStats; // validate argument if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } // generate entity tag var tag = isStats ? stattag(entity) : entitytag(entity); return weak ? 'W/' + tag : tag } /** * Determine if object is a Stats object. * * @param {object} obj * @return {boolean} * @api private */ function isstats (obj) { // genuine fs.Stats if (typeof Stats === 'function' && obj instanceof Stats) { return true } // quack quack return obj && typeof obj === 'object' && 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && 'ino' in obj && typeof obj.ino === 'number' && 'size' in obj && typeof obj.size === 'number' } /** * Generate a tag for a stat. * * @param {object} stat * @return {string} * @private */ function stattag (stat) { var mtime = stat.mtime.getTime().toString(16); var size = stat.size.toString(16); return '"' + size + '-' + mtime + '"' } var index = /*@__PURE__*/getDefaultExportFromCjs(etag_1); export { index as default };
58
5
0
6
12
0
4
0
0
0
8
8
871
true
quick-lru
top1k-typed-nodeps
5,901
// FILE: index.js class QuickLRU extends Map { constructor(options = {}) { super(); if (!(options.maxSize && options.maxSize > 0)) { throw new TypeError('`maxSize` must be a number greater than 0'); } if (typeof options.maxAge === 'number' && options.maxAge === 0) { throw new TypeError('`maxAge` must be a number greater than 0'); } // TODO: Use private class fields when ESLint supports them. this.maxSize = options.maxSize; this.maxAge = options.maxAge || Number.POSITIVE_INFINITY; this.onEviction = options.onEviction; this.cache = new Map(); this.oldCache = new Map(); this._size = 0; } // TODO: Use private class methods when targeting Node.js 16. _emitEvictions(cache) { if (typeof this.onEviction !== 'function') { return; } for (const [key, item] of cache) { this.onEviction(key, item.value); } } _deleteIfExpired(key, item) { if (typeof item.expiry === 'number' && item.expiry <= Date.now()) { if (typeof this.onEviction === 'function') { this.onEviction(key, item.value); } return this.delete(key); } return false; } _getOrDeleteIfExpired(key, item) { const deleted = this._deleteIfExpired(key, item); if (deleted === false) { return item.value; } } _getItemValue(key, item) { return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value; } _peek(key, cache) { const item = cache.get(key); return this._getItemValue(key, item); } _set(key, value) { this.cache.set(key, value); this._size++; if (this._size >= this.maxSize) { this._size = 0; this._emitEvictions(this.oldCache); this.oldCache = this.cache; this.cache = new Map(); } } _moveToRecent(key, item) { this.oldCache.delete(key); this._set(key, item); } * _entriesAscending() { for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } get(key) { if (this.cache.has(key)) { const item = this.cache.get(key); return this._getItemValue(key, item); } if (this.oldCache.has(key)) { const item = this.oldCache.get(key); if (this._deleteIfExpired(key, item) === false) { this._moveToRecent(key, item); return item.value; } } } set(key, value, {maxAge = this.maxAge} = {}) { const expiry = typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ? Date.now() + maxAge : undefined; if (this.cache.has(key)) { this.cache.set(key, { value, expiry }); } else { this._set(key, {value, expiry}); } } has(key) { if (this.cache.has(key)) { return !this._deleteIfExpired(key, this.cache.get(key)); } if (this.oldCache.has(key)) { return !this._deleteIfExpired(key, this.oldCache.get(key)); } return false; } peek(key) { if (this.cache.has(key)) { return this._peek(key, this.cache); } if (this.oldCache.has(key)) { return this._peek(key, this.oldCache); } } delete(key) { const deleted = this.cache.delete(key); if (deleted) { this._size--; } return this.oldCache.delete(key) || deleted; } clear() { this.cache.clear(); this.oldCache.clear(); this._size = 0; } resize(newSize) { if (!(newSize && newSize > 0)) { throw new TypeError('`maxSize` must be a number greater than 0'); } const items = [...this._entriesAscending()]; const removeCount = items.length - newSize; if (removeCount < 0) { this.cache = new Map(items); this.oldCache = new Map(); this._size = items.length; } else { if (removeCount > 0) { this._emitEvictions(items.slice(0, removeCount)); } this.oldCache = new Map(items.slice(removeCount)); this.cache = new Map(); this._size = 0; } this.maxSize = newSize; } * keys() { for (const [key] of this) { yield key; } } * values() { for (const [, value] of this) { yield value; } } * [Symbol.iterator]() { for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } * entriesDescending() { let items = [...this.cache]; for (let i = items.length - 1; i >= 0; --i) { const item = items[i]; const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } items = [...this.oldCache]; for (let i = items.length - 1; i >= 0; --i) { const item = items[i]; const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } * entriesAscending() { for (const [key, value] of this._entriesAscending()) { yield [key, value.value]; } } get size() { if (!this._size) { return this.oldCache.size; } let oldCacheSize = 0; for (const key of this.oldCache.keys()) { if (!this.cache.has(key)) { oldCacheSize++; } } return Math.min(this._size + oldCacheSize, this.maxSize); } entries() { return this.entriesAscending(); } forEach(callbackFunction, thisArgument = this) { for (const [key, value] of this.entriesAscending()) { callbackFunction.call(thisArgument, value, key, this); } } get [Symbol.toStringTag]() { return JSON.stringify([...this.entriesAscending()]); } } export { QuickLRU as default };
// FILE: index.js class QuickLRU extends Map { constructor(options = {}) { super(); if (!(options.maxSize && options.maxSize > 0)) { throw new TypeError('`maxSize` must be a number greater than 0'); } if (typeof options.maxAge === 'number' && options.maxAge === 0) { throw new TypeError('`maxAge` must be a number greater than 0'); } // TODO: Use private class fields when ESLint supports them. this.maxSize = options.maxSize; this.maxAge = options.maxAge || Number.POSITIVE_INFINITY; this.onEviction = options.onEviction; this.cache = new Map(); this.oldCache = new Map(); this._size = 0; } // TODO: Use private class methods when targeting Node.js 16. _emitEvictions(cache) { if (typeof this.onEviction !== 'function') { return; } for (const [key, item] of cache) { this.onEviction(key, item.value); } } _deleteIfExpired(key, item) { if (typeof item.expiry === 'number' && item.expiry <= Date.now()) { if (typeof this.onEviction === 'function') { this.onEviction(key, item.value); } return this.delete(key); } return false; } _getOrDeleteIfExpired(key, item) { const deleted = this._deleteIfExpired(key, item); if (deleted === false) { return item.value; } } _getItemValue(key, item) { return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value; } _peek(key, cache) { const item = cache.get(key); return this._getItemValue(key, item); } _set(key, value) { this.cache.set(key, value); this._size++; if (this._size >= this.maxSize) { this._size = 0; this._emitEvictions(this.oldCache); this.oldCache = this.cache; this.cache = new Map(); } } _moveToRecent(key, item) { this.oldCache.delete(key); this._set(key, item); } * _entriesAscending() { for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } get(key) { if (this.cache.has(key)) { const item = this.cache.get(key); return this._getItemValue(key, item); } if (this.oldCache.has(key)) { const item = this.oldCache.get(key); if (this._deleteIfExpired(key, item) === false) { this._moveToRecent(key, item); return item.value; } } } set(key, value, {maxAge = this.maxAge} = {}) { const expiry = typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ? Date.now() + maxAge : undefined; if (this.cache.has(key)) { this.cache.set(key, { value, expiry }); } else { this._set(key, {value, expiry}); } } has(key) { if (this.cache.has(key)) { return !this._deleteIfExpired(key, this.cache.get(key)); } if (this.oldCache.has(key)) { return !this._deleteIfExpired(key, this.oldCache.get(key)); } return false; } peek(key) { if (this.cache.has(key)) { return this._peek(key, this.cache); } if (this.oldCache.has(key)) { return this._peek(key, this.oldCache); } } delete(key) { const deleted = this.cache.delete(key); if (deleted) { this._size--; } return this.oldCache.delete(key) || deleted; } clear() { this.cache.clear(); this.oldCache.clear(); this._size = 0; } resize(newSize) { if (!(newSize && newSize > 0)) { throw new TypeError('`maxSize` must be a number greater than 0'); } const items = [...this._entriesAscending()]; const removeCount = items.length - newSize; if (removeCount < 0) { this.cache = new Map(items); this.oldCache = new Map(); this._size = items.length; } else { if (removeCount > 0) { this._emitEvictions(items.slice(0, removeCount)); } this.oldCache = new Map(items.slice(removeCount)); this.cache = new Map(); this._size = 0; } this.maxSize = newSize; } * keys() { for (const [key] of this) { yield key; } } * values() { for (const [, value] of this) { yield value; } } * [Symbol.iterator]() { for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } * entriesDescending() { let items = [...this.cache]; for (let i = items.length - 1; i >= 0; --i) { const item = items[i]; const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } items = [...this.oldCache]; for (let i = items.length - 1; i >= 0; --i) { const item = items[i]; const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } * entriesAscending() { for (const [key, value] of this._entriesAscending()) { yield [key, value.value]; } } get size() { if (!this._size) { return this.oldCache.size; } let oldCacheSize = 0; for (const key of this.oldCache.keys()) { if (!this.cache.has(key)) { oldCacheSize++; } } return Math.min(this._size + oldCacheSize, this.maxSize); } entries() { return this.entriesAscending(); } forEach(callbackFunction, thisArgument = this) { for (const [key, value] of this.entriesAscending()) { callbackFunction.call(thisArgument, value, key, this); } } get [Symbol.toStringTag]() { return JSON.stringify([...this.entriesAscending()]); } } export { QuickLRU as default };
234
25
0
24
26
0
15
0
0
1
5
7.24
2,093
false
@humanwhocodes_object-schema
top1k-untyped-nodeps
12,889
var src = {}; var objectSchema = {}; var mergeStrategy = {}; // FILE: src/merge-strategy.js /** * @filedescription Merge Strategy */ //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Container class for several different merge strategies. */ let MergeStrategy$2 = class MergeStrategy { /** * Merges two keys by overwriting the first with the second. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} The second value. */ static overwrite(value1, value2) { return value2; } /** * Merges two keys by replacing the first with the second only if the * second is defined. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} The second value if it is defined. */ static replace(value1, value2) { if (typeof value2 !== "undefined") { return value2; } return value1; } /** * Merges two properties by assigning properties from the second to the first. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} A new object containing properties from both value1 and * value2. */ static assign(value1, value2) { return Object.assign({}, value1, value2); } }; mergeStrategy.MergeStrategy = MergeStrategy$2; var validationStrategy = {}; // FILE: src/validation-strategy.js /** * @filedescription Validation Strategy */ //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Container class for several different validation strategies. */ let ValidationStrategy$2 = class ValidationStrategy { /** * Validates that a value is an array. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static array(value) { if (!Array.isArray(value)) { throw new TypeError("Expected an array."); } } /** * Validates that a value is a boolean. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static boolean(value) { if (typeof value !== "boolean") { throw new TypeError("Expected a Boolean."); } } /** * Validates that a value is a number. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static number(value) { if (typeof value !== "number") { throw new TypeError("Expected a number."); } } /** * Validates that a value is a object. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static object(value) { if (!value || typeof value !== "object") { throw new TypeError("Expected an object."); } } /** * Validates that a value is a object or null. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static "object?"(value) { if (typeof value !== "object") { throw new TypeError("Expected an object or null."); } } /** * Validates that a value is a string. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static string(value) { if (typeof value !== "string") { throw new TypeError("Expected a string."); } } /** * Validates that a value is a non-empty string. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static "string!"(value) { if (typeof value !== "string" || value.length === 0) { throw new TypeError("Expected a non-empty string."); } } }; validationStrategy.ValidationStrategy = ValidationStrategy$2; // FILE: src/object-schema.js /** * @filedescription Object Schema */ //----------------------------------------------------------------------------- // Requirements //----------------------------------------------------------------------------- const { MergeStrategy: MergeStrategy$1 } = mergeStrategy; const { ValidationStrategy: ValidationStrategy$1 } = validationStrategy; //----------------------------------------------------------------------------- // Private //----------------------------------------------------------------------------- const strategies = Symbol("strategies"); const requiredKeys = Symbol("requiredKeys"); /** * Validates a schema strategy. * @param {string} name The name of the key this strategy is for. * @param {Object} strategy The strategy for the object key. * @param {boolean} [strategy.required=true] Whether the key is required. * @param {string[]} [strategy.requires] Other keys that are required when * this key is present. * @param {Function} strategy.merge A method to call when merging two objects * with the same key. * @param {Function} strategy.validate A method to call when validating an * object with the key. * @returns {void} * @throws {Error} When the strategy is missing a name. * @throws {Error} When the strategy is missing a merge() method. * @throws {Error} When the strategy is missing a validate() method. */ function validateDefinition(name, strategy) { let hasSchema = false; if (strategy.schema) { if (typeof strategy.schema === "object") { hasSchema = true; } else { throw new TypeError("Schema must be an object."); } } if (typeof strategy.merge === "string") { if (!(strategy.merge in MergeStrategy$1)) { throw new TypeError(`Definition for key "${name}" missing valid merge strategy.`); } } else if (!hasSchema && typeof strategy.merge !== "function") { throw new TypeError(`Definition for key "${name}" must have a merge property.`); } if (typeof strategy.validate === "string") { if (!(strategy.validate in ValidationStrategy$1)) { throw new TypeError(`Definition for key "${name}" missing valid validation strategy.`); } } else if (!hasSchema && typeof strategy.validate !== "function") { throw new TypeError(`Definition for key "${name}" must have a validate() method.`); } } //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Represents an object validation/merging schema. */ let ObjectSchema$1 = class ObjectSchema { /** * Creates a new instance. */ constructor(definitions) { if (!definitions) { throw new Error("Schema definitions missing."); } /** * Track all strategies in the schema by key. * @type {Map} * @property strategies */ this[strategies] = new Map(); /** * Separately track any keys that are required for faster validation. * @type {Map} * @property requiredKeys */ this[requiredKeys] = new Map(); // add in all strategies for (const key of Object.keys(definitions)) { validateDefinition(key, definitions[key]); // normalize merge and validate methods if subschema is present if (typeof definitions[key].schema === "object") { const schema = new ObjectSchema(definitions[key].schema); definitions[key] = { ...definitions[key], merge(first = {}, second = {}) { return schema.merge(first, second); }, validate(value) { ValidationStrategy$1.object(value); schema.validate(value); } }; } // normalize the merge method in case there's a string if (typeof definitions[key].merge === "string") { definitions[key] = { ...definitions[key], merge: MergeStrategy$1[definitions[key].merge] }; } // normalize the validate method in case there's a string if (typeof definitions[key].validate === "string") { definitions[key] = { ...definitions[key], validate: ValidationStrategy$1[definitions[key].validate] }; } this[strategies].set(key, definitions[key]); if (definitions[key].required) { this[requiredKeys].set(key, definitions[key]); } } } /** * Determines if a strategy has been registered for the given object key. * @param {string} key The object key to find a strategy for. * @returns {boolean} True if the key has a strategy registered, false if not. */ hasKey(key) { return this[strategies].has(key); } /** * Merges objects together to create a new object comprised of the keys * of the all objects. Keys are merged based on the each key's merge * strategy. * @param {...Object} objects The objects to merge. * @returns {Object} A new object with a mix of all objects' keys. * @throws {Error} If any object is invalid. */ merge(...objects) { // double check arguments if (objects.length < 2) { throw new Error("merge() requires at least two arguments."); } if (objects.some(object => (object == null || typeof object !== "object"))) { throw new Error("All arguments must be objects."); } return objects.reduce((result, object) => { this.validate(object); for (const [key, strategy] of this[strategies]) { try { if (key in result || key in object) { const value = strategy.merge.call(this, result[key], object[key]); if (value !== undefined) { result[key] = value; } } } catch (ex) { ex.message = `Key "${key}": ` + ex.message; throw ex; } } return result; }, {}); } /** * Validates an object's keys based on the validate strategy for each key. * @param {Object} object The object to validate. * @returns {void} * @throws {Error} When the object is invalid. */ validate(object) { // check existing keys first for (const key of Object.keys(object)) { // check to see if the key is defined if (!this.hasKey(key)) { throw new Error(`Unexpected key "${key}" found.`); } // validate existing keys const strategy = this[strategies].get(key); // first check to see if any other keys are required if (Array.isArray(strategy.requires)) { if (!strategy.requires.every(otherKey => otherKey in object)) { throw new Error(`Key "${key}" requires keys "${strategy.requires.join("\", \"")}".`); } } // now apply remaining validation strategy try { strategy.validate.call(strategy, object[key]); } catch (ex) { ex.message = `Key "${key}": ` + ex.message; throw ex; } } // ensure required keys aren't missing for (const [key] of this[requiredKeys]) { if (!(key in object)) { throw new Error(`Missing required key "${key}".`); } } } }; objectSchema.ObjectSchema = ObjectSchema$1; // FILE: src/index.js /** * @filedescription Object Schema Package */ var ObjectSchema = src.ObjectSchema = objectSchema.ObjectSchema; var MergeStrategy = src.MergeStrategy = mergeStrategy.MergeStrategy; var ValidationStrategy = src.ValidationStrategy = validationStrategy.ValidationStrategy; export { MergeStrategy, ObjectSchema, ValidationStrategy, src as default };
var src = {}; var objectSchema = {}; var mergeStrategy = {}; // FILE: src/merge-strategy.js /** * @filedescription Merge Strategy */ //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Container class for several different merge strategies. */ let MergeStrategy$2 = class MergeStrategy { /** * Merges two keys by overwriting the first with the second. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} The second value. */ static overwrite(value1, value2) { return value2; } /** * Merges two keys by replacing the first with the second only if the * second is defined. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} The second value if it is defined. */ static replace(value1, value2) { if (typeof value2 !== "undefined") { return value2; } return value1; } /** * Merges two properties by assigning properties from the second to the first. * @param {*} value1 The value from the first object key. * @param {*} value2 The value from the second object key. * @returns {*} A new object containing properties from both value1 and * value2. */ static assign(value1, value2) { return Object.assign({}, value1, value2); } }; mergeStrategy.MergeStrategy = MergeStrategy$2; var validationStrategy = {}; // FILE: src/validation-strategy.js /** * @filedescription Validation Strategy */ //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Container class for several different validation strategies. */ let ValidationStrategy$2 = class ValidationStrategy { /** * Validates that a value is an array. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static array(value) { if (!Array.isArray(value)) { throw new TypeError("Expected an array."); } } /** * Validates that a value is a boolean. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static boolean(value) { if (typeof value !== "boolean") { throw new TypeError("Expected a Boolean."); } } /** * Validates that a value is a number. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static number(value) { if (typeof value !== "number") { throw new TypeError("Expected a number."); } } /** * Validates that a value is a object. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static object(value) { if (!value || typeof value !== "object") { throw new TypeError("Expected an object."); } } /** * Validates that a value is a object or null. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static "object?"(value) { if (typeof value !== "object") { throw new TypeError("Expected an object or null."); } } /** * Validates that a value is a string. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static string(value) { if (typeof value !== "string") { throw new TypeError("Expected a string."); } } /** * Validates that a value is a non-empty string. * @param {*} value The value to validate. * @returns {void} * @throws {TypeError} If the value is invalid. */ static "string!"(value) { if (typeof value !== "string" || value.length === 0) { throw new TypeError("Expected a non-empty string."); } } }; validationStrategy.ValidationStrategy = ValidationStrategy$2; // FILE: src/object-schema.js /** * @filedescription Object Schema */ //----------------------------------------------------------------------------- // Requirements //----------------------------------------------------------------------------- const { MergeStrategy: MergeStrategy$1 } = mergeStrategy; const { ValidationStrategy: ValidationStrategy$1 } = validationStrategy; //----------------------------------------------------------------------------- // Private //----------------------------------------------------------------------------- const strategies = Symbol("strategies"); const requiredKeys = Symbol("requiredKeys"); /** * Validates a schema strategy. * @param {string} name The name of the key this strategy is for. * @param {Object} strategy The strategy for the object key. * @param {boolean} [strategy.required=true] Whether the key is required. * @param {string[]} [strategy.requires] Other keys that are required when * this key is present. * @param {Function} strategy.merge A method to call when merging two objects * with the same key. * @param {Function} strategy.validate A method to call when validating an * object with the key. * @returns {void} * @throws {Error} When the strategy is missing a name. * @throws {Error} When the strategy is missing a merge() method. * @throws {Error} When the strategy is missing a validate() method. */ function validateDefinition(name, strategy) { let hasSchema = false; if (strategy.schema) { if (typeof strategy.schema === "object") { hasSchema = true; } else { throw new TypeError("Schema must be an object."); } } if (typeof strategy.merge === "string") { if (!(strategy.merge in MergeStrategy$1)) { throw new TypeError(`Definition for key "${name}" missing valid merge strategy.`); } } else if (!hasSchema && typeof strategy.merge !== "function") { throw new TypeError(`Definition for key "${name}" must have a merge property.`); } if (typeof strategy.validate === "string") { if (!(strategy.validate in ValidationStrategy$1)) { throw new TypeError(`Definition for key "${name}" missing valid validation strategy.`); } } else if (!hasSchema && typeof strategy.validate !== "function") { throw new TypeError(`Definition for key "${name}" must have a validate() method.`); } } //----------------------------------------------------------------------------- // Class //----------------------------------------------------------------------------- /** * Represents an object validation/merging schema. */ let ObjectSchema$1 = class ObjectSchema { /** * Creates a new instance. */ constructor(definitions) { if (!definitions) { throw new Error("Schema definitions missing."); } /** * Track all strategies in the schema by key. * @type {Map} * @property strategies */ this[strategies] = new Map(); /** * Separately track any keys that are required for faster validation. * @type {Map} * @property requiredKeys */ this[requiredKeys] = new Map(); // add in all strategies for (const key of Object.keys(definitions)) { validateDefinition(key, definitions[key]); // normalize merge and validate methods if subschema is present if (typeof definitions[key].schema === "object") { const schema = new ObjectSchema(definitions[key].schema); definitions[key] = { ...definitions[key], merge(first = {}, second = {}) { return schema.merge(first, second); }, validate(value) { ValidationStrategy$1.object(value); schema.validate(value); } }; } // normalize the merge method in case there's a string if (typeof definitions[key].merge === "string") { definitions[key] = { ...definitions[key], merge: MergeStrategy$1[definitions[key].merge] }; } // normalize the validate method in case there's a string if (typeof definitions[key].validate === "string") { definitions[key] = { ...definitions[key], validate: ValidationStrategy$1[definitions[key].validate] }; } this[strategies].set(key, definitions[key]); if (definitions[key].required) { this[requiredKeys].set(key, definitions[key]); } } } /** * Determines if a strategy has been registered for the given object key. * @param {string} key The object key to find a strategy for. * @returns {boolean} True if the key has a strategy registered, false if not. */ hasKey(key) { return this[strategies].has(key); } /** * Merges objects together to create a new object comprised of the keys * of the all objects. Keys are merged based on the each key's merge * strategy. * @param {...Object} objects The objects to merge. * @returns {Object} A new object with a mix of all objects' keys. * @throws {Error} If any object is invalid. */ merge(...objects) { // double check arguments if (objects.length < 2) { throw new Error("merge() requires at least two arguments."); } if (objects.some(object => (object == null || typeof object !== "object"))) { throw new Error("All arguments must be objects."); } return objects.reduce((result, object) => { this.validate(object); for (const [key, strategy] of this[strategies]) { try { if (key in result || key in object) { const value = strategy.merge.call(this, result[key], object[key]); if (value !== undefined) { result[key] = value; } } } catch (ex) { ex.message = `Key "${key}": ` + ex.message; throw ex; } } return result; }, {}); } /** * Validates an object's keys based on the validate strategy for each key. * @param {Object} object The object to validate. * @returns {void} * @throws {Error} When the object is invalid. */ validate(object) { // check existing keys first for (const key of Object.keys(object)) { // check to see if the key is defined if (!this.hasKey(key)) { throw new Error(`Unexpected key "${key}" found.`); } // validate existing keys const strategy = this[strategies].get(key); // first check to see if any other keys are required if (Array.isArray(strategy.requires)) { if (!strategy.requires.every(otherKey => otherKey in object)) { throw new Error(`Key "${key}" requires keys "${strategy.requires.join("\", \"")}".`); } } // now apply remaining validation strategy try { strategy.validate.call(strategy, object[key]); } catch (ex) { ex.message = `Key "${key}": ` + ex.message; throw ex; } } // ensure required keys aren't missing for (const [key] of this[requiredKeys]) { if (!(key in object)) { throw new Error(`Missing required key "${key}".`); } } } }; objectSchema.ObjectSchema = ObjectSchema$1; // FILE: src/index.js /** * @filedescription Object Schema Package */ var ObjectSchema = src.ObjectSchema = objectSchema.ObjectSchema; var MergeStrategy = src.MergeStrategy = mergeStrategy.MergeStrategy; var ValidationStrategy = src.ValidationStrategy = validationStrategy.ValidationStrategy; export { MergeStrategy, ObjectSchema, ValidationStrategy, src as default };
183
20
0
26
18
0
6
0
0
0
16
7.6
2,720
false
makeerror
top1k-untyped-with-typed-deps
2,772
import require$$0 from 'tmpl'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/makeerror.js var tmpl = require$$0; var makeerror = makeError; function BaseError() {} BaseError.prototype = new Error(); BaseError.prototype.toString = function() { return this.message }; /** * Makes an Error function with the signature: * * function(message, data) * * You'll typically do something like: * * var UnknownFileTypeError = makeError( * 'UnknownFileTypeError', * 'The specified type is not known.' * ) * var er = UnknownFileTypeError() * * `er` will have a prototype chain that ensures: * * er instanceof Error * er instanceof UnknownFileTypeError * * You can also do `var er = new UnknownFileTypeError()` if you really like the * `new` keyword. * * @param String The name of the error. * @param String The default message string. * @param Object The default data object, merged with per instance data. */ function makeError(name, defaultMessage, defaultData) { defaultMessage = tmpl(defaultMessage || ''); defaultData = defaultData || {}; if (defaultData.proto && !(defaultData.proto instanceof BaseError)) throw new Error('The custom "proto" must be an Error created via makeError') var CustomError = function(message, data) { if (!(this instanceof CustomError)) return new CustomError(message, data) if (typeof message !== 'string' && !data) { data = message; message = null; } this.name = name; this.data = data || defaultData; if (typeof message === 'string') { this.message = tmpl(message, this.data); } else { this.message = defaultMessage(this.data); } var er = new Error(); this.stack = er.stack; if (this.stack) { // remove TWO stack level: if (typeof Components !== 'undefined') { // Mozilla: this.stack = this.stack.substring(this.stack.indexOf('\n') + 2); } else if (typeof chrome !== 'undefined' || typeof process !== 'undefined') { // Google Chrome/Node.js: this.stack = this.stack.replace(/\n[^\n]*/, ''); this.stack = this.stack.replace(/\n[^\n]*/, ''); this.stack = ( this.name + (this.message ? (': ' + this.message) : '') + this.stack.substring(5) ); } } if ('fileName' in er) this.fileName = er.fileName; if ('lineNumber' in er) this.lineNumber = er.lineNumber; }; CustomError.prototype = defaultData.proto || new BaseError(); delete defaultData.proto; return CustomError } var makeerror$1 = /*@__PURE__*/getDefaultExportFromCjs(makeerror); export { makeerror$1 as default };
import require$$0 from 'tmpl'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/makeerror.js var tmpl = require$$0; var makeerror = makeError; function BaseError() {} BaseError.prototype = new Error(); BaseError.prototype.toString = function() { return this.message }; /** * Makes an Error function with the signature: * * function(message, data) * * You'll typically do something like: * * var UnknownFileTypeError = makeError( * 'UnknownFileTypeError', * 'The specified type is not known.' * ) * var er = UnknownFileTypeError() * * `er` will have a prototype chain that ensures: * * er instanceof Error * er instanceof UnknownFileTypeError * * You can also do `var er = new UnknownFileTypeError()` if you really like the * `new` keyword. * * @param String The name of the error. * @param String The default message string. * @param Object The default data object, merged with per instance data. */ function makeError(name, defaultMessage, defaultData) { defaultMessage = tmpl(defaultMessage || ''); defaultData = defaultData || {}; if (defaultData.proto && !(defaultData.proto instanceof BaseError)) throw new Error('The custom "proto" must be an Error created via makeError') var CustomError = function(message, data) { if (!(this instanceof CustomError)) return new CustomError(message, data) if (typeof message !== 'string' && !data) { data = message; message = null; } this.name = name; this.data = data || defaultData; if (typeof message === 'string') { this.message = tmpl(message, this.data); } else { this.message = defaultMessage(this.data); } var er = new Error(); this.stack = er.stack; if (this.stack) { // remove TWO stack level: if (typeof Components !== 'undefined') { // Mozilla: this.stack = this.stack.substring(this.stack.indexOf('\n') + 2); } else if (typeof chrome !== 'undefined' || typeof process !== 'undefined') { // Google Chrome/Node.js: this.stack = this.stack.replace(/\n[^\n]*/, ''); this.stack = this.stack.replace(/\n[^\n]*/, ''); this.stack = ( this.name + (this.message ? (': ' + this.message) : '') + this.stack.substring(5) ); } } if ('fileName' in er) this.fileName = er.fileName; if ('lineNumber' in er) this.lineNumber = er.lineNumber; }; CustomError.prototype = defaultData.proto || new BaseError(); delete defaultData.proto; return CustomError } var makeerror$1 = /*@__PURE__*/getDefaultExportFromCjs(makeerror); export { makeerror$1 as default };
53
5
0
6
5
0
1
0
0
0
7
13.8
749
false
side-channel
top1k-untyped-with-typed-deps
3,665
import require$$0 from 'get-intrinsic'; import require$$1 from 'call-bind/callBound'; import require$$2 from 'object-inspect'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var GetIntrinsic = require$$0; var callBound = require$$1; var inspect = require$$2; var $TypeError = GetIntrinsic('%TypeError%'); var $WeakMap = GetIntrinsic('%WeakMap%', true); var $Map = GetIntrinsic('%Map%', true); var $weakMapGet = callBound('WeakMap.prototype.get', true); var $weakMapSet = callBound('WeakMap.prototype.set', true); var $weakMapHas = callBound('WeakMap.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSet = callBound('Map.prototype.set', true); var $mapHas = callBound('Map.prototype.has', true); /* * This function traverses the list returning the node corresponding to the given key. * * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly. */ var listGetNode = function (list, key) { // eslint-disable-line consistent-return for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { if (curr.key === key) { prev.next = curr.next; curr.next = list.next; list.next = curr; // eslint-disable-line no-param-reassign return curr; } } }; var listGet = function (objects, key) { var node = listGetNode(objects, key); return node && node.value; }; var listSet = function (objects, key, value) { var node = listGetNode(objects, key); if (node) { node.value = value; } else { // Prepend the new node to the beginning of the list objects.next = { // eslint-disable-line no-param-reassign key: key, next: objects.next, value: value }; } }; var listHas = function (objects, key) { return !!listGetNode(objects, key); }; var sideChannel = function getSideChannel() { var $wm; var $m; var $o; var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, get: function (key) { // eslint-disable-line consistent-return if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } else if ($Map) { if ($m) { return $mapGet($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listGet($o, key); } } }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } else if ($Map) { if ($m) { return $mapHas($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listHas($o, key); } } return false; }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if ($Map) { if (!$m) { $m = new $Map(); } $mapSet($m, key, value); } else { if (!$o) { // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head $o = { key: {}, next: null }; } listSet($o, key, value); } } }; return channel; }; var index = /*@__PURE__*/getDefaultExportFromCjs(sideChannel); export { index as default };
import require$$0 from 'get-intrinsic'; import require$$1 from 'call-bind/callBound'; import require$$2 from 'object-inspect'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var GetIntrinsic = require$$0; var callBound = require$$1; var inspect = require$$2; var $TypeError = GetIntrinsic('%TypeError%'); var $WeakMap = GetIntrinsic('%WeakMap%', true); var $Map = GetIntrinsic('%Map%', true); var $weakMapGet = callBound('WeakMap.prototype.get', true); var $weakMapSet = callBound('WeakMap.prototype.set', true); var $weakMapHas = callBound('WeakMap.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSet = callBound('Map.prototype.set', true); var $mapHas = callBound('Map.prototype.has', true); /* * This function traverses the list returning the node corresponding to the given key. * * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly. */ var listGetNode = function (list, key) { // eslint-disable-line consistent-return for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { if (curr.key === key) { prev.next = curr.next; curr.next = list.next; list.next = curr; // eslint-disable-line no-param-reassign return curr; } } }; var listGet = function (objects, key) { var node = listGetNode(objects, key); return node && node.value; }; var listSet = function (objects, key, value) { var node = listGetNode(objects, key); if (node) { node.value = value; } else { // Prepend the new node to the beginning of the list objects.next = { // eslint-disable-line no-param-reassign key: key, next: objects.next, value: value }; } }; var listHas = function (objects, key) { return !!listGetNode(objects, key); }; var sideChannel = function getSideChannel() { var $wm; var $m; var $o; var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, get: function (key) { // eslint-disable-line consistent-return if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } else if ($Map) { if ($m) { return $mapGet($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listGet($o, key); } } }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } else if ($Map) { if ($m) { return $mapHas($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listHas($o, key); } } return false; }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if ($Map) { if (!$m) { $m = new $Map(); } $mapSet($m, key, value); } else { if (!$o) { // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head $o = { key: {}, next: null }; } listSet($o, key, value); } } }; return channel; }; var index = /*@__PURE__*/getDefaultExportFromCjs(sideChannel); export { index as default };
111
10
0
15
26
0
5
0
0
0
6
12.8
1,206
true
color-string
top1k-typed-with-typed-deps
6,116
import require$$0 from 'color-name'; import require$$1 from 'simple-swizzle'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var colorString = {exports: {}}; // FILE: index.js /* MIT license */ var colorNames = require$$0; var swizzle = require$$1; var hasOwnProperty = Object.hasOwnProperty; var reverseNames = Object.create(null); // create a list of reverse color names for (var name in colorNames) { if (hasOwnProperty.call(colorNames, name)) { reverseNames[colorNames[name]] = name; } } var cs = colorString.exports = { to: {}, get: {} }; cs.get = function (string) { var prefix = string.substring(0, 3).toLowerCase(); var val; var model; switch (prefix) { case 'hsl': val = cs.get.hsl(string); model = 'hsl'; break; case 'hwb': val = cs.get.hwb(string); model = 'hwb'; break; default: val = cs.get.rgb(string); model = 'rgb'; break; } if (!val) { return null; } return {model: model, value: val}; }; cs.get.rgb = function (string) { if (!string) { return null; } var abbr = /^#([a-f0-9]{3,4})$/i; var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; var keyword = /^(\w+)$/; var rgb = [0, 0, 0, 1]; var match; var i; var hexAlpha; if (match = string.match(hex)) { hexAlpha = match[2]; match = match[1]; for (i = 0; i < 3; i++) { // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 var i2 = i * 2; rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); } if (hexAlpha) { rgb[3] = parseInt(hexAlpha, 16) / 255; } } else if (match = string.match(abbr)) { match = match[1]; hexAlpha = match[3]; for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i] + match[i], 16); } if (hexAlpha) { rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; } } else if (match = string.match(rgba)) { for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i + 1], 0); } if (match[4]) { if (match[5]) { rgb[3] = parseFloat(match[4]) * 0.01; } else { rgb[3] = parseFloat(match[4]); } } } else if (match = string.match(per)) { for (i = 0; i < 3; i++) { rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); } if (match[4]) { if (match[5]) { rgb[3] = parseFloat(match[4]) * 0.01; } else { rgb[3] = parseFloat(match[4]); } } } else if (match = string.match(keyword)) { if (match[1] === 'transparent') { return [0, 0, 0, 0]; } if (!hasOwnProperty.call(colorNames, match[1])) { return null; } rgb = colorNames[match[1]]; rgb[3] = 1; return rgb; } else { return null; } for (i = 0; i < 3; i++) { rgb[i] = clamp(rgb[i], 0, 255); } rgb[3] = clamp(rgb[3], 0, 1); return rgb; }; cs.get.hsl = function (string) { if (!string) { return null; } var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; var match = string.match(hsl); if (match) { var alpha = parseFloat(match[4]); var h = ((parseFloat(match[1]) % 360) + 360) % 360; var s = clamp(parseFloat(match[2]), 0, 100); var l = clamp(parseFloat(match[3]), 0, 100); var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, s, l, a]; } return null; }; cs.get.hwb = function (string) { if (!string) { return null; } var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; var match = string.match(hwb); if (match) { var alpha = parseFloat(match[4]); var h = ((parseFloat(match[1]) % 360) + 360) % 360; var w = clamp(parseFloat(match[2]), 0, 100); var b = clamp(parseFloat(match[3]), 0, 100); var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, w, b, a]; } return null; }; cs.to.hex = function () { var rgba = swizzle(arguments); return ( '#' + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? (hexDouble(Math.round(rgba[3] * 255))) : '') ); }; cs.to.rgb = function () { var rgba = swizzle(arguments); return rgba.length < 4 || rgba[3] === 1 ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; }; cs.to.rgb.percent = function () { var rgba = swizzle(arguments); var r = Math.round(rgba[0] / 255 * 100); var g = Math.round(rgba[1] / 255 * 100); var b = Math.round(rgba[2] / 255 * 100); return rgba.length < 4 || rgba[3] === 1 ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; }; cs.to.hsl = function () { var hsla = swizzle(arguments); return hsla.length < 4 || hsla[3] === 1 ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; }; // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax // (hwb have alpha optional & 1 is default value) cs.to.hwb = function () { var hwba = swizzle(arguments); var a = ''; if (hwba.length >= 4 && hwba[3] !== 1) { a = ', ' + hwba[3]; } return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; }; cs.to.keyword = function (rgb) { return reverseNames[rgb.slice(0, 3)]; }; // helpers function clamp(num, min, max) { return Math.min(Math.max(min, num), max); } function hexDouble(num) { var str = Math.round(num).toString(16).toUpperCase(); return (str.length < 2) ? '0' + str : str; } var colorStringExports = colorString.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(colorStringExports); export { index as default };
import require$$0 from 'color-name'; import require$$1 from 'simple-swizzle'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var colorString = {exports: {}}; // FILE: index.js /* MIT license */ var colorNames = require$$0; var swizzle = require$$1; var hasOwnProperty = Object.hasOwnProperty; var reverseNames = Object.create(null); // create a list of reverse color names for (var name in colorNames) { if (hasOwnProperty.call(colorNames, name)) { reverseNames[colorNames[name]] = name; } } var cs = colorString.exports = { to: {}, get: {} }; cs.get = function (string) { var prefix = string.substring(0, 3).toLowerCase(); var val; var model; switch (prefix) { case 'hsl': val = cs.get.hsl(string); model = 'hsl'; break; case 'hwb': val = cs.get.hwb(string); model = 'hwb'; break; default: val = cs.get.rgb(string); model = 'rgb'; break; } if (!val) { return null; } return {model: model, value: val}; }; cs.get.rgb = function (string) { if (!string) { return null; } var abbr = /^#([a-f0-9]{3,4})$/i; var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; var keyword = /^(\w+)$/; var rgb = [0, 0, 0, 1]; var match; var i; var hexAlpha; if (match = string.match(hex)) { hexAlpha = match[2]; match = match[1]; for (i = 0; i < 3; i++) { // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 var i2 = i * 2; rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); } if (hexAlpha) { rgb[3] = parseInt(hexAlpha, 16) / 255; } } else if (match = string.match(abbr)) { match = match[1]; hexAlpha = match[3]; for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i] + match[i], 16); } if (hexAlpha) { rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; } } else if (match = string.match(rgba)) { for (i = 0; i < 3; i++) { rgb[i] = parseInt(match[i + 1], 0); } if (match[4]) { if (match[5]) { rgb[3] = parseFloat(match[4]) * 0.01; } else { rgb[3] = parseFloat(match[4]); } } } else if (match = string.match(per)) { for (i = 0; i < 3; i++) { rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); } if (match[4]) { if (match[5]) { rgb[3] = parseFloat(match[4]) * 0.01; } else { rgb[3] = parseFloat(match[4]); } } } else if (match = string.match(keyword)) { if (match[1] === 'transparent') { return [0, 0, 0, 0]; } if (!hasOwnProperty.call(colorNames, match[1])) { return null; } rgb = colorNames[match[1]]; rgb[3] = 1; return rgb; } else { return null; } for (i = 0; i < 3; i++) { rgb[i] = clamp(rgb[i], 0, 255); } rgb[3] = clamp(rgb[3], 0, 1); return rgb; }; cs.get.hsl = function (string) { if (!string) { return null; } var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; var match = string.match(hsl); if (match) { var alpha = parseFloat(match[4]); var h = ((parseFloat(match[1]) % 360) + 360) % 360; var s = clamp(parseFloat(match[2]), 0, 100); var l = clamp(parseFloat(match[3]), 0, 100); var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, s, l, a]; } return null; }; cs.get.hwb = function (string) { if (!string) { return null; } var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; var match = string.match(hwb); if (match) { var alpha = parseFloat(match[4]); var h = ((parseFloat(match[1]) % 360) + 360) % 360; var w = clamp(parseFloat(match[2]), 0, 100); var b = clamp(parseFloat(match[3]), 0, 100); var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); return [h, w, b, a]; } return null; }; cs.to.hex = function () { var rgba = swizzle(arguments); return ( '#' + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? (hexDouble(Math.round(rgba[3] * 255))) : '') ); }; cs.to.rgb = function () { var rgba = swizzle(arguments); return rgba.length < 4 || rgba[3] === 1 ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; }; cs.to.rgb.percent = function () { var rgba = swizzle(arguments); var r = Math.round(rgba[0] / 255 * 100); var g = Math.round(rgba[1] / 255 * 100); var b = Math.round(rgba[2] / 255 * 100); return rgba.length < 4 || rgba[3] === 1 ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; }; cs.to.hsl = function () { var hsla = swizzle(arguments); return hsla.length < 4 || hsla[3] === 1 ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; }; // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax // (hwb have alpha optional & 1 is default value) cs.to.hwb = function () { var hwba = swizzle(arguments); var a = ''; if (hwba.length >= 4 && hwba[3] !== 1) { a = ', ' + hwba[3]; } return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; }; cs.to.keyword = function (rgb) { return reverseNames[rgb.slice(0, 3)]; }; // helpers function clamp(num, min, max) { return Math.min(Math.max(min, num), max); } function hexDouble(num) { var str = Math.round(num).toString(16).toUpperCase(); return (str.length < 2) ? '0' + str : str; } var colorStringExports = colorString.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(colorStringExports); export { index as default };
201
13
0
10
45
0
6
0
0
0
0
12
2,699
false
postcss-modules-extract-imports
top1k-typed-nodeps
7,277
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var src = {exports: {}}; // FILE: src/topologicalSort.js const PERMANENT_MARKER = 2; const TEMPORARY_MARKER = 1; function createError(node, graph) { const er = new Error("Nondeterministic import's order"); const related = graph[node]; const relatedNode = related.find( (relatedNode) => graph[relatedNode].indexOf(node) > -1 ); er.nodes = [node, relatedNode]; return er; } function walkGraph(node, graph, state, result, strict) { if (state[node] === PERMANENT_MARKER) { return; } if (state[node] === TEMPORARY_MARKER) { if (strict) { return createError(node, graph); } return; } state[node] = TEMPORARY_MARKER; const children = graph[node]; const length = children.length; for (let i = 0; i < length; ++i) { const error = walkGraph(children[i], graph, state, result, strict); if (error instanceof Error) { return error; } } state[node] = PERMANENT_MARKER; result.push(node); } function topologicalSort$1(graph, strict) { const result = []; const state = {}; const nodes = Object.keys(graph); const length = nodes.length; for (let i = 0; i < length; ++i) { const er = walkGraph(nodes[i], graph, state, result, strict); if (er instanceof Error) { return er; } } return result; } var topologicalSort_1 = topologicalSort$1; // FILE: src/index.js const topologicalSort = topologicalSort_1; const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/; const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/; const VISITED_MARKER = 1; /** * :import('G') {} * * Rule * composes: ... from 'A' * composes: ... from 'B' * Rule * composes: ... from 'A' * composes: ... from 'A' * composes: ... from 'C' * * Results in: * * graph: { * G: [], * A: [], * B: ['A'], * C: ['A'], * } */ function addImportToGraph(importId, parentId, graph, visited) { const siblingsId = parentId + "_" + "siblings"; const visitedId = parentId + "_" + importId; if (visited[visitedId] !== VISITED_MARKER) { if (!Array.isArray(visited[siblingsId])) { visited[siblingsId] = []; } const siblings = visited[siblingsId]; if (Array.isArray(graph[importId])) { graph[importId] = graph[importId].concat(siblings); } else { graph[importId] = siblings.slice(); } visited[visitedId] = VISITED_MARKER; siblings.push(importId); } } src.exports = (options = {}) => { let importIndex = 0; const createImportedName = typeof options.createImportedName !== "function" ? (importName /*, path*/) => `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}` : options.createImportedName; const failOnWrongOrder = options.failOnWrongOrder; return { postcssPlugin: "postcss-modules-extract-imports", prepare() { const graph = {}; const visited = {}; const existingImports = {}; const importDecls = {}; const imports = {}; return { Once(root, postcss) { // Check the existing imports order and save refs root.walkRules((rule) => { const matches = icssImport.exec(rule.selector); if (matches) { const [, /*match*/ doubleQuotePath, singleQuotePath] = matches; const importPath = doubleQuotePath || singleQuotePath; addImportToGraph(importPath, "root", graph, visited); existingImports[importPath] = rule; } }); root.walkDecls(/^composes$/, (declaration) => { const matches = declaration.value.match(matchImports); if (!matches) { return; } let tmpSymbols; let [ , /*match*/ symbols, doubleQuotePath, singleQuotePath, global, ] = matches; if (global) { // Composing globals simply means changing these classes to wrap them in global(name) tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`); } else { const importPath = doubleQuotePath || singleQuotePath; let parent = declaration.parent; let parentIndexes = ""; while (parent.type !== "root") { parentIndexes = parent.parent.index(parent) + "_" + parentIndexes; parent = parent.parent; } const { selector } = declaration.parent; const parentRule = `_${parentIndexes}${selector}`; addImportToGraph(importPath, parentRule, graph, visited); importDecls[importPath] = declaration; imports[importPath] = imports[importPath] || {}; tmpSymbols = symbols.split(/\s+/).map((s) => { if (!imports[importPath][s]) { imports[importPath][s] = createImportedName(s, importPath); } return imports[importPath][s]; }); } declaration.value = tmpSymbols.join(" "); }); const importsOrder = topologicalSort(graph, failOnWrongOrder); if (importsOrder instanceof Error) { const importPath = importsOrder.nodes.find((importPath) => // eslint-disable-next-line no-prototype-builtins importDecls.hasOwnProperty(importPath) ); const decl = importDecls[importPath]; throw decl.error( "Failed to resolve order of composed modules " + importsOrder.nodes .map((importPath) => "`" + importPath + "`") .join(", ") + ".", { plugin: "postcss-modules-extract-imports", word: "composes", } ); } let lastImportRule; importsOrder.forEach((path) => { const importedSymbols = imports[path]; let rule = existingImports[path]; if (!rule && importedSymbols) { rule = postcss.rule({ selector: `:import("${path}")`, raws: { after: "\n" }, }); if (lastImportRule) { root.insertAfter(lastImportRule, rule); } else { root.prepend(rule); } } lastImportRule = rule; if (!importedSymbols) { return; } Object.keys(importedSymbols).forEach((importedSymbol) => { rule.append( postcss.decl({ value: importedSymbol, prop: importedSymbols[importedSymbol], raws: { before: "\n " }, }) ); }); }); }, }; }, }; }; var postcss = src.exports.postcss = true; var srcExports = src.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(srcExports); export { index as default, postcss };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var src = {exports: {}}; // FILE: src/topologicalSort.js const PERMANENT_MARKER = 2; const TEMPORARY_MARKER = 1; function createError(node, graph) { const er = new Error("Nondeterministic import's order"); const related = graph[node]; const relatedNode = related.find( (relatedNode) => graph[relatedNode].indexOf(node) > -1 ); er.nodes = [node, relatedNode]; return er; } function walkGraph(node, graph, state, result, strict) { if (state[node] === PERMANENT_MARKER) { return; } if (state[node] === TEMPORARY_MARKER) { if (strict) { return createError(node, graph); } return; } state[node] = TEMPORARY_MARKER; const children = graph[node]; const length = children.length; for (let i = 0; i < length; ++i) { const error = walkGraph(children[i], graph, state, result, strict); if (error instanceof Error) { return error; } } state[node] = PERMANENT_MARKER; result.push(node); } function topologicalSort$1(graph, strict) { const result = []; const state = {}; const nodes = Object.keys(graph); const length = nodes.length; for (let i = 0; i < length; ++i) { const er = walkGraph(nodes[i], graph, state, result, strict); if (er instanceof Error) { return er; } } return result; } var topologicalSort_1 = topologicalSort$1; // FILE: src/index.js const topologicalSort = topologicalSort_1; const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/; const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/; const VISITED_MARKER = 1; /** * :import('G') {} * * Rule * composes: ... from 'A' * composes: ... from 'B' * Rule * composes: ... from 'A' * composes: ... from 'A' * composes: ... from 'C' * * Results in: * * graph: { * G: [], * A: [], * B: ['A'], * C: ['A'], * } */ function addImportToGraph(importId, parentId, graph, visited) { const siblingsId = parentId + "_" + "siblings"; const visitedId = parentId + "_" + importId; if (visited[visitedId] !== VISITED_MARKER) { if (!Array.isArray(visited[siblingsId])) { visited[siblingsId] = []; } const siblings = visited[siblingsId]; if (Array.isArray(graph[importId])) { graph[importId] = graph[importId].concat(siblings); } else { graph[importId] = siblings.slice(); } visited[visitedId] = VISITED_MARKER; siblings.push(importId); } } src.exports = (options = {}) => { let importIndex = 0; const createImportedName = typeof options.createImportedName !== "function" ? (importName /*, path*/) => `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}` : options.createImportedName; const failOnWrongOrder = options.failOnWrongOrder; return { postcssPlugin: "postcss-modules-extract-imports", prepare() { const graph = {}; const visited = {}; const existingImports = {}; const importDecls = {}; const imports = {}; return { Once(root, postcss) { // Check the existing imports order and save refs root.walkRules((rule) => { const matches = icssImport.exec(rule.selector); if (matches) { const [, /*match*/ doubleQuotePath, singleQuotePath] = matches; const importPath = doubleQuotePath || singleQuotePath; addImportToGraph(importPath, "root", graph, visited); existingImports[importPath] = rule; } }); root.walkDecls(/^composes$/, (declaration) => { const matches = declaration.value.match(matchImports); if (!matches) { return; } let tmpSymbols; let [ , /*match*/ symbols, doubleQuotePath, singleQuotePath, global, ] = matches; if (global) { // Composing globals simply means changing these classes to wrap them in global(name) tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`); } else { const importPath = doubleQuotePath || singleQuotePath; let parent = declaration.parent; let parentIndexes = ""; while (parent.type !== "root") { parentIndexes = parent.parent.index(parent) + "_" + parentIndexes; parent = parent.parent; } const { selector } = declaration.parent; const parentRule = `_${parentIndexes}${selector}`; addImportToGraph(importPath, parentRule, graph, visited); importDecls[importPath] = declaration; imports[importPath] = imports[importPath] || {}; tmpSymbols = symbols.split(/\s+/).map((s) => { if (!imports[importPath][s]) { imports[importPath][s] = createImportedName(s, importPath); } return imports[importPath][s]; }); } declaration.value = tmpSymbols.join(" "); }); const importsOrder = topologicalSort(graph, failOnWrongOrder); if (importsOrder instanceof Error) { const importPath = importsOrder.nodes.find((importPath) => // eslint-disable-next-line no-prototype-builtins importDecls.hasOwnProperty(importPath) ); const decl = importDecls[importPath]; throw decl.error( "Failed to resolve order of composed modules " + importsOrder.nodes .map((importPath) => "`" + importPath + "`") .join(", ") + ".", { plugin: "postcss-modules-extract-imports", word: "composes", } ); } let lastImportRule; importsOrder.forEach((path) => { const importedSymbols = imports[path]; let rule = existingImports[path]; if (!rule && importedSymbols) { rule = postcss.rule({ selector: `:import("${path}")`, raws: { after: "\n" }, }); if (lastImportRule) { root.insertAfter(lastImportRule, rule); } else { root.prepend(rule); } } lastImportRule = rule; if (!importedSymbols) { return; } Object.keys(importedSymbols).forEach((importedSymbol) => { rule.append( postcss.decl({ value: importedSymbol, prop: importedSymbols[importedSymbol], raws: { before: "\n " }, }) ); }); }); }, }; }, }; }; var postcss = src.exports.postcss = true; var srcExports = src.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(srcExports); export { index as default, postcss };
193
18
0
27
52
0
4
0
0
0
4
25.055556
1,798
false
events
top1k-typed-nodeps
14,106
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var events$1 = {exports: {}}; // FILE: events.js var R = typeof Reflect === 'object' ? Reflect : null; var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } events$1.exports = EventEmitter; var once_1 = events$1.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); } eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } var eventsExports = events$1.exports; var events = /*@__PURE__*/getDefaultExportFromCjs(eventsExports); export { events as default, once_1 as once };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var events$1 = {exports: {}}; // FILE: events.js var R = typeof Reflect === 'object' ? Reflect : null; var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } events$1.exports = EventEmitter; var once_1 = events$1.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); } eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } var eventsExports = events$1.exports; var events = /*@__PURE__*/getDefaultExportFromCjs(eventsExports); export { events as default, once_1 as once };
378
40
0
57
43
0
21
0
0
0
20
7.5
3,626
false
split-string
top1k-typed-nodeps
4,021
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var splitString = (input, options = {}, fn) => { if (typeof input !== 'string') throw new TypeError('expected a string'); if (typeof options === 'function') { fn = options; options = {}; } let separator = options.separator || '.'; let ast = { type: 'root', nodes: [], stash: [''] }; let stack = [ast]; let state = { input, separator, stack }; let string = input; let value, node; let i = -1; state.bos = () => i === 0; state.eos = () => i === string.length; state.prev = () => string[i - 1]; state.next = () => string[i + 1]; let quotes = options.quotes || []; let openers = options.brackets || {}; if (options.brackets === true) { openers = { '[': ']', '(': ')', '{': '}', '<': '>' }; } if (options.quotes === true) { quotes = ['"', '\'', '`']; } let closers = invert(openers); let keep = options.keep || (value => value !== '\\'); const block = () => (state.block = stack[stack.length - 1]); const peek = () => string[i + 1]; const next = () => string[++i]; const append = value => { state.value = value; if (value && keep(value, state) !== false) { state.block.stash[state.block.stash.length - 1] += value; } }; const closeIndex = (value, startIdx) => { let idx = string.indexOf(value, startIdx); if (idx > -1 && string[idx - 1] === '\\') { idx = closeIndex(value, idx + 1); } return idx; }; for (; i < string.length - 1;) { state.value = value = next(); state.index = i; block(); // handle escaped characters if (value === '\\') { if (peek() === '\\') { append(value + next()); } else { // if the next char is not '\\', allow the "append" function // to determine if the backslashes should be added append(value); append(next()); } continue; } // handle quoted strings if (quotes.includes(value)) { let pos = i + 1; let idx = closeIndex(value, pos); if (idx > -1) { append(value); // append opening quote append(string.slice(pos, idx)); // append quoted string append(string[idx]); // append closing quote i = idx; continue; } append(value); continue; } // handle opening brackets, if not disabled if (options.brackets !== false && openers[value]) { node = { type: 'bracket', nodes: [] }; node.stash = keep(value) !== false ? [value] : ['']; node.parent = state.block; state.block.nodes.push(node); stack.push(node); continue; } // handle closing brackets, if not disabled if (options.brackets !== false && closers[value]) { if (stack.length === 1) { append(value); continue; } append(value); node = stack.pop(); block(); append(node.stash.join('')); continue; } // push separator onto stash if (value === separator && state.block.type === 'root') { if (typeof fn === 'function' && fn(state) === false) { append(value); continue; } state.block.stash.push(''); continue; } // append value onto the last string on the stash append(value); } node = stack.pop(); while (node !== ast) { if (options.strict === true) { let column = i - node.stash.length + 1; throw new SyntaxError(`Unmatched: "${node.stash[0]}", at column ${column}`); } value = (node.parent.stash.pop() + node.stash.join('.')); node.parent.stash = node.parent.stash.concat(value.split('.')); node = stack.pop(); } return node.stash; }; function invert(obj) { let inverted = {}; for (const key of Object.keys(obj)) inverted[obj[key]] = key; return inverted; } var index = /*@__PURE__*/getDefaultExportFromCjs(splitString); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var splitString = (input, options = {}, fn) => { if (typeof input !== 'string') throw new TypeError('expected a string'); if (typeof options === 'function') { fn = options; options = {}; } let separator = options.separator || '.'; let ast = { type: 'root', nodes: [], stash: [''] }; let stack = [ast]; let state = { input, separator, stack }; let string = input; let value, node; let i = -1; state.bos = () => i === 0; state.eos = () => i === string.length; state.prev = () => string[i - 1]; state.next = () => string[i + 1]; let quotes = options.quotes || []; let openers = options.brackets || {}; if (options.brackets === true) { openers = { '[': ']', '(': ')', '{': '}', '<': '>' }; } if (options.quotes === true) { quotes = ['"', '\'', '`']; } let closers = invert(openers); let keep = options.keep || (value => value !== '\\'); const block = () => (state.block = stack[stack.length - 1]); const peek = () => string[i + 1]; const next = () => string[++i]; const append = value => { state.value = value; if (value && keep(value, state) !== false) { state.block.stash[state.block.stash.length - 1] += value; } }; const closeIndex = (value, startIdx) => { let idx = string.indexOf(value, startIdx); if (idx > -1 && string[idx - 1] === '\\') { idx = closeIndex(value, idx + 1); } return idx; }; for (; i < string.length - 1;) { state.value = value = next(); state.index = i; block(); // handle escaped characters if (value === '\\') { if (peek() === '\\') { append(value + next()); } else { // if the next char is not '\\', allow the "append" function // to determine if the backslashes should be added append(value); append(next()); } continue; } // handle quoted strings if (quotes.includes(value)) { let pos = i + 1; let idx = closeIndex(value, pos); if (idx > -1) { append(value); // append opening quote append(string.slice(pos, idx)); // append quoted string append(string[idx]); // append closing quote i = idx; continue; } append(value); continue; } // handle opening brackets, if not disabled if (options.brackets !== false && openers[value]) { node = { type: 'bracket', nodes: [] }; node.stash = keep(value) !== false ? [value] : ['']; node.parent = state.block; state.block.nodes.push(node); stack.push(node); continue; } // handle closing brackets, if not disabled if (options.brackets !== false && closers[value]) { if (stack.length === 1) { append(value); continue; } append(value); node = stack.pop(); block(); append(node.stash.join('')); continue; } // push separator onto stash if (value === separator && state.block.type === 'root') { if (typeof fn === 'function' && fn(state) === false) { append(value); continue; } state.block.stash.push(''); continue; } // append value onto the last string on the stash append(value); } node = stack.pop(); while (node !== ast) { if (options.strict === true) { let column = i - node.stash.length + 1; throw new SyntaxError(`Unmatched: "${node.stash[0]}", at column ${column}`); } value = (node.parent.stash.pop() + node.stash.join('.')); node.parent.stash = node.parent.stash.concat(value.split('.')); node = stack.pop(); } return node.stash; }; function invert(obj) { let inverted = {}; for (const key of Object.keys(obj)) inverted[obj[key]] = key; return inverted; } var index = /*@__PURE__*/getDefaultExportFromCjs(splitString); export { index as default };
120
13
0
9
24
0
7
0
0
0
3
9.923077
1,127
false
component-emitter
top1k-typed-nodeps
3,808
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var componentEmitter = {exports: {}}; // FILE: index.js (function (module) { /** * Expose `Emitter`. */ { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); } /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } // Remove event specific arrays for event types that no // one is subscribed for to avoid memory leak. if (callbacks.length === 0) { delete this._callbacks['$' + event]; } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = new Array(arguments.length - 1) , callbacks = this._callbacks['$' + event]; for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; } (componentEmitter)); var componentEmitterExports = componentEmitter.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(componentEmitterExports); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var componentEmitter = {exports: {}}; // FILE: index.js (function (module) { /** * Expose `Emitter`. */ { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); } /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } // Remove event specific arrays for event types that no // one is subscribed for to avoid memory leak. if (callbacks.length === 0) { delete this._callbacks['$' + event]; } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = new Array(arguments.length - 1) , callbacks = this._callbacks['$' + event]; for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; } (componentEmitter)); var componentEmitterExports = componentEmitter.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(componentEmitterExports); export { index as default };
87
11
0
13
11
0
4
0
0
0
0
12.363636
1,113
true
@sellside_emitter
top1k-untyped-nodeps
5,976
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /** * Initialize a new `Emitter`. * * ```js * const Emitter = require('emitter'); * // as an `Emitter` instance * const emitter = new Emitter; * emitter.emit('something'); * // or inherit * class MyEmitter extends Emitter {} * ``` * @name Emitter * @api public */ class Emitter { /** * Return the array of registered listeners for `event`. * * ```js * // all listeners for event "status" * console.log(emitter.listeners('status')); * // all listeners * console.log(emitter.listeners()); * ``` * @name .listeners * @param {String} `event` * @return {Array} * @api public */ listeners(event) { if (!this._listeners) define(this, '_listeners', {}); if (!this._only) define(this, '_only', {}); if (!event) return this._listeners; return this._listeners['$' + event] || (this._listeners['$' + event] = []); } /** * Listen on the given `event` with `fn`. * * ```js * emitter.on('foo', () => 'do stuff'); * ``` * @name .on * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ on(event, fn) { if (this._only && this._only[event]) { return this.only(event, fn); } this.listeners(event).push(fn); return this; } /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * ```js * emitter.only('once', () => 'do stuff'); * ``` * @name .once * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ once(event, fn) { const on = function() { this.off(event, on); fn.apply(this, arguments); }; on.fn = fn; this.on(event, on); return this; } /** * Ensures that listeners for `event` are only **_registered_** once * and are disabled correctly when specified. This is different from * `.once`, which only **emits** once. * * ```js * emitter.only('foo', () => 'do stuff'); * ``` * @name .only * @param {String} `event` * @param {Object} `options` * @param {Function} `fn` * @return {Emitter} * @api public */ only(event, options, fn) { this.listeners(); if (typeof options === 'function') { fn = options; options = null; } if (options && options.first === true) { define(this, '_first', true); } if (!fn || !event || !this._only[event]) { this.off(event); if (!fn) return this; } const existing = this._only[event]; if (existing) { if (this._first === true) return this; this.off(event, existing); } this._only[event] = fn; this.listeners(event).push(fn); return this; } /** * Remove the given listener for `event`, or remove all * registered listeners if `event` is undefined. * * ```js * emitter.off(); * emitter.off('foo'); * emitter.off('foo', fn); * ``` * @name .off * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ off(event, fn) { this.listeners(); // remove all listeners if (!event) { this._listeners = {}; this._only = {}; return this; } // remove all listeners for "event" if (!fn) { this._listeners['$' + event] = []; this._only['$' + event] = []; return this; } // remove all instances of "fn" from "event" removeListeners(fn, this.listeners(event)); return this; } /** * Emit `event` with the given args. * * ```js * emitter.emit('foo', 'bar'); * ``` * @name .emit * @param {String} `event` * @param {Mixed} ... * @return {Emitter} */ emit(event) { const listeners = this.listeners(event).slice(); const args = [].slice.call(arguments, 1); for (const fn of listeners) { fn.apply(this, args); } return this; } /** * Returns true if the emitter has registered listeners for `event`. * * ```js * emitter.on('foo', 'do stuff'); * console.log(emitter.has('foo')); // true * console.log(emitter.has('bar')); // false * ``` * @name .has * @param {String} `event` * @return {Boolean} * @api public */ has(event) { return this.listeners(event).length > 0; } } /** * Expose common aliases for `.has`, `.on` and `.off` */ Emitter.prototype.hasListeners = Emitter.prototype.has; Emitter.prototype.addListener = Emitter.prototype.addEventListener = Emitter.prototype.on; Emitter.prototype.removeListener = Emitter.prototype.removeListeners = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = Emitter.prototype.off; /** * Remove all instances of the given `fn` from listeners. */ function removeListeners(fn, listeners) { for (let i = 0; i < listeners.length; i++) { const listener = listeners[i]; if (listener === fn || listener.fn === fn) { listeners.splice(i, 1); return removeListeners(fn, listeners); } } } /** * Mixin emitter properties. */ function mixin(target) { if (!target) target = {}; const emitter = new Emitter(); copy(target, emitter, Object.getOwnPropertyNames(Emitter.prototype)); copy(target, emitter, Object.keys(emitter)); return target; } function copy(target, provider, keys) { for (const key of keys) { if (typeof provider[key] === 'function') { define(target, key, provider[key].bind(provider)); } else { define(target, key, provider[key]); } } } function define(obj, key, val) { Reflect.defineProperty(obj, key, { configurable: true, writable: true, value: val }); } /** * Expose `Emitter` */ var _sellside_emitter = mixin; var index = /*@__PURE__*/getDefaultExportFromCjs(_sellside_emitter); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /** * Initialize a new `Emitter`. * * ```js * const Emitter = require('emitter'); * // as an `Emitter` instance * const emitter = new Emitter; * emitter.emit('something'); * // or inherit * class MyEmitter extends Emitter {} * ``` * @name Emitter * @api public */ class Emitter { /** * Return the array of registered listeners for `event`. * * ```js * // all listeners for event "status" * console.log(emitter.listeners('status')); * // all listeners * console.log(emitter.listeners()); * ``` * @name .listeners * @param {String} `event` * @return {Array} * @api public */ listeners(event) { if (!this._listeners) define(this, '_listeners', {}); if (!this._only) define(this, '_only', {}); if (!event) return this._listeners; return this._listeners['$' + event] || (this._listeners['$' + event] = []); } /** * Listen on the given `event` with `fn`. * * ```js * emitter.on('foo', () => 'do stuff'); * ``` * @name .on * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ on(event, fn) { if (this._only && this._only[event]) { return this.only(event, fn); } this.listeners(event).push(fn); return this; } /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * ```js * emitter.only('once', () => 'do stuff'); * ``` * @name .once * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ once(event, fn) { const on = function() { this.off(event, on); fn.apply(this, arguments); }; on.fn = fn; this.on(event, on); return this; } /** * Ensures that listeners for `event` are only **_registered_** once * and are disabled correctly when specified. This is different from * `.once`, which only **emits** once. * * ```js * emitter.only('foo', () => 'do stuff'); * ``` * @name .only * @param {String} `event` * @param {Object} `options` * @param {Function} `fn` * @return {Emitter} * @api public */ only(event, options, fn) { this.listeners(); if (typeof options === 'function') { fn = options; options = null; } if (options && options.first === true) { define(this, '_first', true); } if (!fn || !event || !this._only[event]) { this.off(event); if (!fn) return this; } const existing = this._only[event]; if (existing) { if (this._first === true) return this; this.off(event, existing); } this._only[event] = fn; this.listeners(event).push(fn); return this; } /** * Remove the given listener for `event`, or remove all * registered listeners if `event` is undefined. * * ```js * emitter.off(); * emitter.off('foo'); * emitter.off('foo', fn); * ``` * @name .off * @param {String} `event` * @param {Function} `fn` * @return {Emitter} * @api public */ off(event, fn) { this.listeners(); // remove all listeners if (!event) { this._listeners = {}; this._only = {}; return this; } // remove all listeners for "event" if (!fn) { this._listeners['$' + event] = []; this._only['$' + event] = []; return this; } // remove all instances of "fn" from "event" removeListeners(fn, this.listeners(event)); return this; } /** * Emit `event` with the given args. * * ```js * emitter.emit('foo', 'bar'); * ``` * @name .emit * @param {String} `event` * @param {Mixed} ... * @return {Emitter} */ emit(event) { const listeners = this.listeners(event).slice(); const args = [].slice.call(arguments, 1); for (const fn of listeners) { fn.apply(this, args); } return this; } /** * Returns true if the emitter has registered listeners for `event`. * * ```js * emitter.on('foo', 'do stuff'); * console.log(emitter.has('foo')); // true * console.log(emitter.has('bar')); // false * ``` * @name .has * @param {String} `event` * @return {Boolean} * @api public */ has(event) { return this.listeners(event).length > 0; } } /** * Expose common aliases for `.has`, `.on` and `.off` */ Emitter.prototype.hasListeners = Emitter.prototype.has; Emitter.prototype.addListener = Emitter.prototype.addEventListener = Emitter.prototype.on; Emitter.prototype.removeListener = Emitter.prototype.removeListeners = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = Emitter.prototype.off; /** * Remove all instances of the given `fn` from listeners. */ function removeListeners(fn, listeners) { for (let i = 0; i < listeners.length; i++) { const listener = listeners[i]; if (listener === fn || listener.fn === fn) { listeners.splice(i, 1); return removeListeners(fn, listeners); } } } /** * Mixin emitter properties. */ function mixin(target) { if (!target) target = {}; const emitter = new Emitter(); copy(target, emitter, Object.getOwnPropertyNames(Emitter.prototype)); copy(target, emitter, Object.keys(emitter)); return target; } function copy(target, provider, keys) { for (const key of keys) { if (typeof provider[key] === 'function') { define(target, key, provider[key].bind(provider)); } else { define(target, key, provider[key]); } } } function define(obj, key, val) { Reflect.defineProperty(obj, key, { configurable: true, writable: true, value: val }); } /** * Expose `Emitter` */ var _sellside_emitter = mixin; var index = /*@__PURE__*/getDefaultExportFromCjs(_sellside_emitter); export { index as default };
120
13
0
22
9
0
8
0
0
1
2
6.384615
1,733
false
json-parse-even-better-errors
top1k-untyped-nodeps
4,202
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js const hexify = char => { const h = char.charCodeAt(0).toString(16).toUpperCase(); return '0x' + (h.length % 2 ? '0' : '') + h }; const parseError = (e, txt, context) => { if (!txt) { return { message: e.message + ' while parsing empty string', position: 0, } } const badToken = e.message.match(/^Unexpected token (.) .*position\s+(\d+)/i); const errIdx = badToken ? +badToken[2] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null; const msg = badToken ? e.message.replace(/^Unexpected token ./, `Unexpected token ${ JSON.stringify(badToken[1]) } (${hexify(badToken[1])})`) : e.message; if (errIdx !== null && errIdx !== undefined) { const start = errIdx <= context ? 0 : errIdx - context; const end = errIdx + context >= txt.length ? txt.length : errIdx + context; const slice = (start === 0 ? '' : '...') + txt.slice(start, end) + (end === txt.length ? '' : '...'); const near = txt === slice ? '' : 'near '; return { message: msg + ` while parsing ${near}${JSON.stringify(slice)}`, position: errIdx, } } else { return { message: msg + ` while parsing '${txt.slice(0, context * 2)}'`, position: 0, } } }; class JSONParseError extends SyntaxError { constructor (er, txt, context, caller) { context = context || 20; const metadata = parseError(er, txt, context); super(metadata.message); Object.assign(this, metadata); this.code = 'EJSONPARSE'; this.systemError = er; Error.captureStackTrace(this, caller || this.constructor); } get name () { return this.constructor.name } set name (n) {} get [Symbol.toStringTag] () { return this.constructor.name } } const kIndent = Symbol.for('indent'); const kNewline = Symbol.for('newline'); // only respect indentation if we got a line break, otherwise squash it // things other than objects and arrays aren't indented, so ignore those // Important: in both of these regexps, the $1 capture group is the newline // or undefined, and the $2 capture group is the indent, or undefined. const formatRE = /^\s*[{\[]((?:\r?\n)+)([\s\t]*)/; const emptyRE = /^(?:\{\}|\[\])((?:\r?\n)+)?$/; const parseJson = (txt, reviver, context) => { const parseText = stripBOM(txt); context = context || 20; try { // get the indentation so that we can save it back nicely // if the file starts with {" then we have an indent of '', ie, none // otherwise, pick the indentation of the next line after the first \n // If the pattern doesn't match, then it means no indentation. // JSON.stringify ignores symbols, so this is reasonably safe. // if the string is '{}' or '[]', then use the default 2-space indent. const [, newline = '\n', indent = ' '] = parseText.match(emptyRE) || parseText.match(formatRE) || [, '', '']; const result = JSON.parse(parseText, reviver); if (result && typeof result === 'object') { result[kNewline] = newline; result[kIndent] = indent; } return result } catch (e) { if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) { const isEmptyArray = Array.isArray(txt) && txt.length === 0; throw Object.assign(new TypeError( `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}` ), { code: 'EJSONPARSE', systemError: e, }) } throw new JSONParseError(e, parseText, context, parseJson) } }; // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. const stripBOM = txt => String(txt).replace(/^\uFEFF/, ''); var jsonParseEvenBetterErrors = parseJson; parseJson.JSONParseError = JSONParseError; parseJson.noExceptions = (txt, reviver) => { try { return JSON.parse(stripBOM(txt), reviver) } catch (e) {} }; var index = /*@__PURE__*/getDefaultExportFromCjs(jsonParseEvenBetterErrors); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js const hexify = char => { const h = char.charCodeAt(0).toString(16).toUpperCase(); return '0x' + (h.length % 2 ? '0' : '') + h }; const parseError = (e, txt, context) => { if (!txt) { return { message: e.message + ' while parsing empty string', position: 0, } } const badToken = e.message.match(/^Unexpected token (.) .*position\s+(\d+)/i); const errIdx = badToken ? +badToken[2] : e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 : null; const msg = badToken ? e.message.replace(/^Unexpected token ./, `Unexpected token ${ JSON.stringify(badToken[1]) } (${hexify(badToken[1])})`) : e.message; if (errIdx !== null && errIdx !== undefined) { const start = errIdx <= context ? 0 : errIdx - context; const end = errIdx + context >= txt.length ? txt.length : errIdx + context; const slice = (start === 0 ? '' : '...') + txt.slice(start, end) + (end === txt.length ? '' : '...'); const near = txt === slice ? '' : 'near '; return { message: msg + ` while parsing ${near}${JSON.stringify(slice)}`, position: errIdx, } } else { return { message: msg + ` while parsing '${txt.slice(0, context * 2)}'`, position: 0, } } }; class JSONParseError extends SyntaxError { constructor (er, txt, context, caller) { context = context || 20; const metadata = parseError(er, txt, context); super(metadata.message); Object.assign(this, metadata); this.code = 'EJSONPARSE'; this.systemError = er; Error.captureStackTrace(this, caller || this.constructor); } get name () { return this.constructor.name } set name (n) {} get [Symbol.toStringTag] () { return this.constructor.name } } const kIndent = Symbol.for('indent'); const kNewline = Symbol.for('newline'); // only respect indentation if we got a line break, otherwise squash it // things other than objects and arrays aren't indented, so ignore those // Important: in both of these regexps, the $1 capture group is the newline // or undefined, and the $2 capture group is the indent, or undefined. const formatRE = /^\s*[{\[]((?:\r?\n)+)([\s\t]*)/; const emptyRE = /^(?:\{\}|\[\])((?:\r?\n)+)?$/; const parseJson = (txt, reviver, context) => { const parseText = stripBOM(txt); context = context || 20; try { // get the indentation so that we can save it back nicely // if the file starts with {" then we have an indent of '', ie, none // otherwise, pick the indentation of the next line after the first \n // If the pattern doesn't match, then it means no indentation. // JSON.stringify ignores symbols, so this is reasonably safe. // if the string is '{}' or '[]', then use the default 2-space indent. const [, newline = '\n', indent = ' '] = parseText.match(emptyRE) || parseText.match(formatRE) || [, '', '']; const result = JSON.parse(parseText, reviver); if (result && typeof result === 'object') { result[kNewline] = newline; result[kIndent] = indent; } return result } catch (e) { if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) { const isEmptyArray = Array.isArray(txt) && txt.length === 0; throw Object.assign(new TypeError( `Cannot parse ${isEmptyArray ? 'an empty array' : String(txt)}` ), { code: 'EJSONPARSE', systemError: e, }) } throw new JSONParseError(e, parseText, context, parseJson) } }; // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. const stripBOM = txt => String(txt).replace(/^\uFEFF/, ''); var jsonParseEvenBetterErrors = parseJson; parseJson.JSONParseError = JSONParseError; parseJson.noExceptions = (txt, reviver) => { try { return JSON.parse(stripBOM(txt), reviver) } catch (e) {} }; var index = /*@__PURE__*/getDefaultExportFromCjs(jsonParseEvenBetterErrors); export { index as default };
96
10
0
16
23
0
4
0
0
1
2
7.3
1,215
false
@npmcli_move-file
top1k-untyped-with-typed-deps
5,477
import require$$0 from 'path'; import require$$1 from 'rimraf'; import require$$2 from 'util'; import require$$3 from 'fs'; import require$$4 from 'mkdirp'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var lib = {exports: {}}; // FILE: lib/index.js const { dirname, join, resolve, relative, isAbsolute } = require$$0; const rimraf_ = require$$1; const { promisify } = require$$2; const { access: access_, accessSync, copyFile: copyFile_, copyFileSync, readdir: readdir_, readdirSync, rename: rename_, renameSync, stat: stat_, statSync, lstat: lstat_, lstatSync, symlink: symlink_, symlinkSync, readlink: readlink_, readlinkSync, } = require$$3; const access = promisify(access_); const copyFile = promisify(copyFile_); const readdir = promisify(readdir_); const rename = promisify(rename_); const stat = promisify(stat_); const lstat = promisify(lstat_); const symlink = promisify(symlink_); const readlink = promisify(readlink_); const rimraf = promisify(rimraf_); const rimrafSync = rimraf_.sync; const mkdirp = require$$4; const pathExists = async path => { try { await access(path); return true } catch (er) { return er.code !== 'ENOENT' } }; const pathExistsSync = path => { try { accessSync(path); return true } catch (er) { return er.code !== 'ENOENT' } }; const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, }; if (!options.overwrite && await pathExists(destination)) { throw new Error(`The destination file exists: ${destination}`) } await mkdirp(dirname(destination)); try { await rename(source, destination); } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = await lstat(source); if (sourceStat.isDirectory()) { const files = await readdir(source); await Promise.all(files.map((file) => moveFile(join(source, file), join(destination, file), options, false, symlinks) )); } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }); } else { await copyFile(source, destination); } } else { throw error } } if (root) { await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { let target = await readlink(symSource); // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)); } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file'; try { targetStat = await stat(resolve(dirname(symSource), target)); if (targetStat.isDirectory()) { targetStat = 'junction'; } } catch { // targetStat remains 'file' } await symlink( target, symDestination, targetStat ); })); await rimraf(source); } }; const moveFileSync = (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, }; if (!options.overwrite && pathExistsSync(destination)) { throw new Error(`The destination file exists: ${destination}`) } mkdirp.sync(dirname(destination)); try { renameSync(source, destination); } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = lstatSync(source); if (sourceStat.isDirectory()) { const files = readdirSync(source); for (const file of files) { moveFileSync(join(source, file), join(destination, file), options, false, symlinks); } } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }); } else { copyFileSync(source, destination); } } else { throw error } } if (root) { for (const { source: symSource, destination: symDestination } of symlinks) { let target = readlinkSync(symSource); // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)); } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file'; try { targetStat = statSync(resolve(dirname(symSource), target)); if (targetStat.isDirectory()) { targetStat = 'junction'; } } catch { // targetStat remains 'file' } symlinkSync( target, symDestination, targetStat ); } rimrafSync(source); } }; lib.exports = moveFile; var sync = lib.exports.sync = moveFileSync; var libExports = lib.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(libExports); export { index as default, sync };
import require$$0 from 'path'; import require$$1 from 'rimraf'; import require$$2 from 'util'; import require$$3 from 'fs'; import require$$4 from 'mkdirp'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var lib = {exports: {}}; // FILE: lib/index.js const { dirname, join, resolve, relative, isAbsolute } = require$$0; const rimraf_ = require$$1; const { promisify } = require$$2; const { access: access_, accessSync, copyFile: copyFile_, copyFileSync, readdir: readdir_, readdirSync, rename: rename_, renameSync, stat: stat_, statSync, lstat: lstat_, lstatSync, symlink: symlink_, symlinkSync, readlink: readlink_, readlinkSync, } = require$$3; const access = promisify(access_); const copyFile = promisify(copyFile_); const readdir = promisify(readdir_); const rename = promisify(rename_); const stat = promisify(stat_); const lstat = promisify(lstat_); const symlink = promisify(symlink_); const readlink = promisify(readlink_); const rimraf = promisify(rimraf_); const rimrafSync = rimraf_.sync; const mkdirp = require$$4; const pathExists = async path => { try { await access(path); return true } catch (er) { return er.code !== 'ENOENT' } }; const pathExistsSync = path => { try { accessSync(path); return true } catch (er) { return er.code !== 'ENOENT' } }; const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, }; if (!options.overwrite && await pathExists(destination)) { throw new Error(`The destination file exists: ${destination}`) } await mkdirp(dirname(destination)); try { await rename(source, destination); } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = await lstat(source); if (sourceStat.isDirectory()) { const files = await readdir(source); await Promise.all(files.map((file) => moveFile(join(source, file), join(destination, file), options, false, symlinks) )); } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }); } else { await copyFile(source, destination); } } else { throw error } } if (root) { await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { let target = await readlink(symSource); // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)); } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file'; try { targetStat = await stat(resolve(dirname(symSource), target)); if (targetStat.isDirectory()) { targetStat = 'junction'; } } catch { // targetStat remains 'file' } await symlink( target, symDestination, targetStat ); })); await rimraf(source); } }; const moveFileSync = (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, }; if (!options.overwrite && pathExistsSync(destination)) { throw new Error(`The destination file exists: ${destination}`) } mkdirp.sync(dirname(destination)); try { renameSync(source, destination); } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = lstatSync(source); if (sourceStat.isDirectory()) { const files = readdirSync(source); for (const file of files) { moveFileSync(join(source, file), join(destination, file), options, false, symlinks); } } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }); } else { copyFileSync(source, destination); } } else { throw error } } if (root) { for (const { source: symSource, destination: symDestination } of symlinks) { let target = readlinkSync(symSource); // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)); } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file'; try { targetStat = statSync(resolve(dirname(symSource), target)); if (targetStat.isDirectory()) { targetStat = 'junction'; } } catch { // targetStat remains 'file' } symlinkSync( target, symDestination, targetStat ); } rimrafSync(source); } }; lib.exports = moveFile; var sync = lib.exports.sync = moveFileSync; var libExports = lib.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(libExports); export { index as default, sync };
170
7
0
15
31
0
5
0
0
0
0
19.285714
1,417
false
chownr
top1k-typed-nodeps
4,616
import require$$0 from 'fs'; import require$$1 from 'path'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: chownr.js const fs = require$$0; const path = require$$1; /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown'; /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'; /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } }; /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } }; /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er); else fs.chown(path, uid, gid, cb); } : (_, __, ___, cb) => cb; /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid); } } : (path, uid, gid) => lchownSync(path, uid, gid); // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version; let readdir = (path, options, cb) => fs.readdir(path, options, cb); let readdirSync = (path, options) => fs.readdirSync(path, options); /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb); const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null); })); }; const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child; chownrKid(p, stats, uid, gid, cb); }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); }); } else { const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); } }; const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length; let errState = null; const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) }; children.forEach(child => chownrKid(p, child, uid, gid, then)); }); }; const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)); stats.name = child; child = stats; } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid); handleEISDirSync(path.resolve(p, child.name), uid, gid); }; const chownrSync = (p, uid, gid) => { let children; try { children = readdirSync(p, { withFileTypes: true }); } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)); return handleEISDirSync(p, uid, gid) }; var chownr_1 = chownr; chownr.sync = chownrSync; var chownr$1 = /*@__PURE__*/getDefaultExportFromCjs(chownr_1); export { chownr$1 as default };
import require$$0 from 'fs'; import require$$1 from 'path'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: chownr.js const fs = require$$0; const path = require$$1; /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown'; /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'; /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/); const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } }; /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } }; /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er); else fs.chown(path, uid, gid, cb); } : (_, __, ___, cb) => cb; /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid); } } : (path, uid, gid) => lchownSync(path, uid, gid); // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version; let readdir = (path, options, cb) => fs.readdir(path, options, cb); let readdirSync = (path, options) => fs.readdirSync(path, options); /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb); const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null); })); }; const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child; chownrKid(p, stats, uid, gid, cb); }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); }); } else { const cpath = path.resolve(p, child.name); chown(cpath, uid, gid, cb); } }; const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length; let errState = null; const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) }; children.forEach(child => chownrKid(p, child, uid, gid, then)); }); }; const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)); stats.name = child; child = stats; } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid); handleEISDirSync(path.resolve(p, child.name), uid, gid); }; const chownrSync = (p, uid, gid) => { let children; try { children = readdirSync(p, { withFileTypes: true }); } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)); return handleEISDirSync(p, uid, gid) }; var chownr_1 = chownr; chownr.sync = chownrSync; var chownr$1 = /*@__PURE__*/getDefaultExportFromCjs(chownr_1); export { chownr$1 as default };
137
23
0
59
26
0
10
0
0
0
2
6.130435
1,550
false
source-map-resolve
top1k-untyped-with-typed-deps
10,226
import require$$0 from 'atob'; import require$$1 from 'url'; import require$$2 from 'path'; import require$$3 from 'decode-uri-component'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var atob = require$$0; var urlLib = require$$1; var pathLib = require$$2; var decodeUriComponentLib = require$$3; function resolveUrl(/* ...urls */) { return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { return urlLib.resolve(resolved, nextUrl) }) } function convertWindowsPath(aPath) { return pathLib.sep === "\\" ? aPath.replace(/\\/g, "/").replace(/^[a-z]:\/?/i, "/") : aPath } function customDecodeUriComponent(string) { // `decodeUriComponentLib` turns `+` into ` `, but that's not wanted. return decodeUriComponentLib(string.replace(/\+/g, "%2B")) } function callbackAsync(callback, error, result) { setImmediate(function() { callback(error, result); }); } function parseMapToJSON(string, data) { try { return JSON.parse(string.replace(/^\)\]\}'/, "")) } catch (error) { error.sourceMapData = data; throw error } } function readSync(read, url, data) { var readUrl = customDecodeUriComponent(url); try { return String(read(readUrl)) } catch (error) { error.sourceMapData = data; throw error } } var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; var sourceMappingURLRegex = RegExp( "(?:" + "/\\*" + "(?:\\s*\r?\n(?://)?)?" + "(?:" + innerRegex.source + ")" + "\\s*" + "\\*/" + "|" + "//(?:" + innerRegex.source + ")" + ")" + "\\s*" ); function getSourceMappingUrl(code) { var match = code.match(sourceMappingURLRegex); return match ? match[1] || match[2] || "" : null } function resolveSourceMap(code, codeUrl, read, callback) { var mapData; try { mapData = resolveSourceMapHelper(code, codeUrl); } catch (error) { return callbackAsync(callback, error) } if (!mapData || mapData.map) { return callbackAsync(callback, null, mapData) } var readUrl = customDecodeUriComponent(mapData.url); read(readUrl, function(error, result) { if (error) { error.sourceMapData = mapData; return callback(error) } mapData.map = String(result); try { mapData.map = parseMapToJSON(mapData.map, mapData); } catch (error) { return callback(error) } callback(null, mapData); }); } function resolveSourceMapSync(code, codeUrl, read) { var mapData = resolveSourceMapHelper(code, codeUrl); if (!mapData || mapData.map) { return mapData } mapData.map = readSync(read, mapData.url, mapData); mapData.map = parseMapToJSON(mapData.map, mapData); return mapData } var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/; /** * The media type for JSON text is application/json. * * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations } * * `text/json` is non-standard media type */ var jsonMimeTypeRegex = /^(?:application|text)\/json$/; /** * JSON text exchanged between systems that are not part of a closed ecosystem * MUST be encoded using UTF-8. * * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding} */ var jsonCharacterEncoding = "utf-8"; function base64ToBuf(b64) { var binStr = atob(b64); var len = binStr.length; var arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } return arr } function decodeBase64String(b64) { if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { return atob(b64) } var buf = base64ToBuf(b64); // Note: `decoder.decode` method will throw a `DOMException` with the // `"EncodingError"` value when an coding error is found. var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true}); return decoder.decode(buf); } function resolveSourceMapHelper(code, codeUrl) { codeUrl = convertWindowsPath(codeUrl); var url = getSourceMappingUrl(code); if (!url) { return null } var dataUri = url.match(dataUriRegex); if (dataUri) { var mimeType = dataUri[1] || "text/plain"; var lastParameter = dataUri[2] || ""; var encoded = dataUri[3] || ""; var data = { sourceMappingURL: url, url: null, sourcesRelativeTo: codeUrl, map: encoded }; if (!jsonMimeTypeRegex.test(mimeType)) { var error = new Error("Unuseful data uri mime type: " + mimeType); error.sourceMapData = data; throw error } try { data.map = parseMapToJSON( lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), data ); } catch (error) { error.sourceMapData = data; throw error } return data } var mapUrl = resolveUrl(codeUrl, url); return { sourceMappingURL: url, url: mapUrl, sourcesRelativeTo: mapUrl, map: null } } function resolveSources(map, mapUrl, read, options, callback) { if (typeof options === "function") { callback = options; options = {}; } var pending = map.sources ? map.sources.length : 0; var result = { sourcesResolved: [], sourcesContent: [] }; if (pending === 0) { callbackAsync(callback, null, result); return } var done = function() { pending--; if (pending === 0) { callback(null, result); } }; resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { result.sourcesResolved[index] = fullUrl; if (typeof sourceContent === "string") { result.sourcesContent[index] = sourceContent; callbackAsync(done, null); } else { var readUrl = customDecodeUriComponent(fullUrl); read(readUrl, function(error, source) { result.sourcesContent[index] = error ? error : String(source); done(); }); } }); } function resolveSourcesSync(map, mapUrl, read, options) { var result = { sourcesResolved: [], sourcesContent: [] }; if (!map.sources || map.sources.length === 0) { return result } resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { result.sourcesResolved[index] = fullUrl; if (read !== null) { if (typeof sourceContent === "string") { result.sourcesContent[index] = sourceContent; } else { var readUrl = customDecodeUriComponent(fullUrl); try { result.sourcesContent[index] = String(read(readUrl)); } catch (error) { result.sourcesContent[index] = error; } } } }); return result } var endingSlash = /\/?$/; function resolveSourcesHelper(map, mapUrl, options, fn) { options = options || {}; mapUrl = convertWindowsPath(mapUrl); var fullUrl; var sourceContent; var sourceRoot; for (var index = 0, len = map.sources.length; index < len; index++) { sourceRoot = null; if (typeof options.sourceRoot === "string") { sourceRoot = options.sourceRoot; } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { sourceRoot = map.sourceRoot; } // If the sourceRoot is the empty string, it is equivalent to not setting // the property at all. if (sourceRoot === null || sourceRoot === '') { fullUrl = resolveUrl(mapUrl, map.sources[index]); } else { // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes // `/scripts/subdir/<source>`, not `/scripts/<source>`. Pointing to a file as source root // does not make sense. fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]); } sourceContent = (map.sourcesContent || [])[index]; fn(fullUrl, sourceContent, index); } } function resolve(code, codeUrl, read, options, callback) { if (typeof options === "function") { callback = options; options = {}; } if (code === null) { var mapUrl = codeUrl; var data = { sourceMappingURL: null, url: mapUrl, sourcesRelativeTo: mapUrl, map: null }; var readUrl = customDecodeUriComponent(mapUrl); read(readUrl, function(error, result) { if (error) { error.sourceMapData = data; return callback(error) } data.map = String(result); try { data.map = parseMapToJSON(data.map, data); } catch (error) { return callback(error) } _resolveSources(data); }); } else { resolveSourceMap(code, codeUrl, read, function(error, mapData) { if (error) { return callback(error) } if (!mapData) { return callback(null, null) } _resolveSources(mapData); }); } function _resolveSources(mapData) { resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { if (error) { return callback(error) } mapData.sourcesResolved = result.sourcesResolved; mapData.sourcesContent = result.sourcesContent; callback(null, mapData); }); } } function resolveSync(code, codeUrl, read, options) { var mapData; if (code === null) { var mapUrl = codeUrl; mapData = { sourceMappingURL: null, url: mapUrl, sourcesRelativeTo: mapUrl, map: null }; mapData.map = readSync(read, mapUrl, mapData); mapData.map = parseMapToJSON(mapData.map, mapData); } else { mapData = resolveSourceMapSync(code, codeUrl, read); if (!mapData) { return null } } var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options); mapData.sourcesResolved = result.sourcesResolved; mapData.sourcesContent = result.sourcesContent; return mapData } var sourceMapResolve = { resolveSourceMap: resolveSourceMap, resolveSourceMapSync: resolveSourceMapSync, resolveSources: resolveSources, resolveSourcesSync: resolveSourcesSync, resolve: resolve, resolveSync: resolveSync, parseMapToJSON: parseMapToJSON }; var index = /*@__PURE__*/getDefaultExportFromCjs(sourceMapResolve); export { index as default };
import require$$0 from 'atob'; import require$$1 from 'url'; import require$$2 from 'path'; import require$$3 from 'decode-uri-component'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var atob = require$$0; var urlLib = require$$1; var pathLib = require$$2; var decodeUriComponentLib = require$$3; function resolveUrl(/* ...urls */) { return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { return urlLib.resolve(resolved, nextUrl) }) } function convertWindowsPath(aPath) { return pathLib.sep === "\\" ? aPath.replace(/\\/g, "/").replace(/^[a-z]:\/?/i, "/") : aPath } function customDecodeUriComponent(string) { // `decodeUriComponentLib` turns `+` into ` `, but that's not wanted. return decodeUriComponentLib(string.replace(/\+/g, "%2B")) } function callbackAsync(callback, error, result) { setImmediate(function() { callback(error, result); }); } function parseMapToJSON(string, data) { try { return JSON.parse(string.replace(/^\)\]\}'/, "")) } catch (error) { error.sourceMapData = data; throw error } } function readSync(read, url, data) { var readUrl = customDecodeUriComponent(url); try { return String(read(readUrl)) } catch (error) { error.sourceMapData = data; throw error } } var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/; var sourceMappingURLRegex = RegExp( "(?:" + "/\\*" + "(?:\\s*\r?\n(?://)?)?" + "(?:" + innerRegex.source + ")" + "\\s*" + "\\*/" + "|" + "//(?:" + innerRegex.source + ")" + ")" + "\\s*" ); function getSourceMappingUrl(code) { var match = code.match(sourceMappingURLRegex); return match ? match[1] || match[2] || "" : null } function resolveSourceMap(code, codeUrl, read, callback) { var mapData; try { mapData = resolveSourceMapHelper(code, codeUrl); } catch (error) { return callbackAsync(callback, error) } if (!mapData || mapData.map) { return callbackAsync(callback, null, mapData) } var readUrl = customDecodeUriComponent(mapData.url); read(readUrl, function(error, result) { if (error) { error.sourceMapData = mapData; return callback(error) } mapData.map = String(result); try { mapData.map = parseMapToJSON(mapData.map, mapData); } catch (error) { return callback(error) } callback(null, mapData); }); } function resolveSourceMapSync(code, codeUrl, read) { var mapData = resolveSourceMapHelper(code, codeUrl); if (!mapData || mapData.map) { return mapData } mapData.map = readSync(read, mapData.url, mapData); mapData.map = parseMapToJSON(mapData.map, mapData); return mapData } var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/; /** * The media type for JSON text is application/json. * * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations } * * `text/json` is non-standard media type */ var jsonMimeTypeRegex = /^(?:application|text)\/json$/; /** * JSON text exchanged between systems that are not part of a closed ecosystem * MUST be encoded using UTF-8. * * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding} */ var jsonCharacterEncoding = "utf-8"; function base64ToBuf(b64) { var binStr = atob(b64); var len = binStr.length; var arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } return arr } function decodeBase64String(b64) { if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { return atob(b64) } var buf = base64ToBuf(b64); // Note: `decoder.decode` method will throw a `DOMException` with the // `"EncodingError"` value when an coding error is found. var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true}); return decoder.decode(buf); } function resolveSourceMapHelper(code, codeUrl) { codeUrl = convertWindowsPath(codeUrl); var url = getSourceMappingUrl(code); if (!url) { return null } var dataUri = url.match(dataUriRegex); if (dataUri) { var mimeType = dataUri[1] || "text/plain"; var lastParameter = dataUri[2] || ""; var encoded = dataUri[3] || ""; var data = { sourceMappingURL: url, url: null, sourcesRelativeTo: codeUrl, map: encoded }; if (!jsonMimeTypeRegex.test(mimeType)) { var error = new Error("Unuseful data uri mime type: " + mimeType); error.sourceMapData = data; throw error } try { data.map = parseMapToJSON( lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), data ); } catch (error) { error.sourceMapData = data; throw error } return data } var mapUrl = resolveUrl(codeUrl, url); return { sourceMappingURL: url, url: mapUrl, sourcesRelativeTo: mapUrl, map: null } } function resolveSources(map, mapUrl, read, options, callback) { if (typeof options === "function") { callback = options; options = {}; } var pending = map.sources ? map.sources.length : 0; var result = { sourcesResolved: [], sourcesContent: [] }; if (pending === 0) { callbackAsync(callback, null, result); return } var done = function() { pending--; if (pending === 0) { callback(null, result); } }; resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { result.sourcesResolved[index] = fullUrl; if (typeof sourceContent === "string") { result.sourcesContent[index] = sourceContent; callbackAsync(done, null); } else { var readUrl = customDecodeUriComponent(fullUrl); read(readUrl, function(error, source) { result.sourcesContent[index] = error ? error : String(source); done(); }); } }); } function resolveSourcesSync(map, mapUrl, read, options) { var result = { sourcesResolved: [], sourcesContent: [] }; if (!map.sources || map.sources.length === 0) { return result } resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { result.sourcesResolved[index] = fullUrl; if (read !== null) { if (typeof sourceContent === "string") { result.sourcesContent[index] = sourceContent; } else { var readUrl = customDecodeUriComponent(fullUrl); try { result.sourcesContent[index] = String(read(readUrl)); } catch (error) { result.sourcesContent[index] = error; } } } }); return result } var endingSlash = /\/?$/; function resolveSourcesHelper(map, mapUrl, options, fn) { options = options || {}; mapUrl = convertWindowsPath(mapUrl); var fullUrl; var sourceContent; var sourceRoot; for (var index = 0, len = map.sources.length; index < len; index++) { sourceRoot = null; if (typeof options.sourceRoot === "string") { sourceRoot = options.sourceRoot; } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { sourceRoot = map.sourceRoot; } // If the sourceRoot is the empty string, it is equivalent to not setting // the property at all. if (sourceRoot === null || sourceRoot === '') { fullUrl = resolveUrl(mapUrl, map.sources[index]); } else { // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes // `/scripts/subdir/<source>`, not `/scripts/<source>`. Pointing to a file as source root // does not make sense. fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]); } sourceContent = (map.sourcesContent || [])[index]; fn(fullUrl, sourceContent, index); } } function resolve(code, codeUrl, read, options, callback) { if (typeof options === "function") { callback = options; options = {}; } if (code === null) { var mapUrl = codeUrl; var data = { sourceMappingURL: null, url: mapUrl, sourcesRelativeTo: mapUrl, map: null }; var readUrl = customDecodeUriComponent(mapUrl); read(readUrl, function(error, result) { if (error) { error.sourceMapData = data; return callback(error) } data.map = String(result); try { data.map = parseMapToJSON(data.map, data); } catch (error) { return callback(error) } _resolveSources(data); }); } else { resolveSourceMap(code, codeUrl, read, function(error, mapData) { if (error) { return callback(error) } if (!mapData) { return callback(null, null) } _resolveSources(mapData); }); } function _resolveSources(mapData) { resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { if (error) { return callback(error) } mapData.sourcesResolved = result.sourcesResolved; mapData.sourcesContent = result.sourcesContent; callback(null, mapData); }); } } function resolveSync(code, codeUrl, read, options) { var mapData; if (code === null) { var mapUrl = codeUrl; mapData = { sourceMappingURL: null, url: mapUrl, sourcesRelativeTo: mapUrl, map: null }; mapData.map = readSync(read, mapUrl, mapData); mapData.map = parseMapToJSON(mapData.map, mapData); } else { mapData = resolveSourceMapSync(code, codeUrl, read); if (!mapData) { return null } } var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options); mapData.sourcesResolved = result.sourcesResolved; mapData.sourcesContent = result.sourcesContent; return mapData } var sourceMapResolve = { resolveSourceMap: resolveSourceMap, resolveSourceMapSync: resolveSourceMapSync, resolveSources: resolveSources, resolveSourcesSync: resolveSourcesSync, resolve: resolve, resolveSync: resolveSync, parseMapToJSON: parseMapToJSON }; var index = /*@__PURE__*/getDefaultExportFromCjs(sourceMapResolve); export { index as default };
319
29
0
64
48
0
19
0
0
0
8
11.103448
2,881
false
next-tick
top1k-typed-nodeps
2,328
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var ensureCallable = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; var byObserver = function (Observer) { var node = document.createTextNode(''), queue, currentQueue, bit = 0, i = 0; new Observer(function () { var callback; if (!queue) { if (!currentQueue) return; queue = currentQueue; } else if (currentQueue) { queue = currentQueue.slice(i).concat(queue); } currentQueue = queue; queue = null; i = 0; if (typeof currentQueue === 'function') { callback = currentQueue; currentQueue = null; callback(); return; } node.data = (bit = ++bit % 2); // Invoke other batch, to handle leftover callbacks in case of crash while (i < currentQueue.length) { callback = currentQueue[i]; i++; if (i === currentQueue.length) currentQueue = null; callback(); } }).observe(node, { characterData: true }); return function (fn) { ensureCallable(fn); if (queue) { if (typeof queue === 'function') queue = [queue, fn]; else queue.push(fn); return; } queue = fn; node.data = (bit = ++bit % 2); }; }; var nextTick = (function () { // Node.js if ((typeof process === 'object') && process && (typeof process.nextTick === 'function')) { return process.nextTick; } // queueMicrotask if (typeof queueMicrotask === "function") { return function (cb) { queueMicrotask(ensureCallable(cb)); }; } // MutationObserver if ((typeof document === 'object') && document) { if (typeof MutationObserver === 'function') return byObserver(MutationObserver); if (typeof WebKitMutationObserver === 'function') return byObserver(WebKitMutationObserver); } // W3C Draft // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html if (typeof setImmediate === 'function') { return function (cb) { setImmediate(ensureCallable(cb)); }; } // Wide available standard if ((typeof setTimeout === 'function') || (typeof setTimeout === 'object')) { return function (cb) { setTimeout(ensureCallable(cb), 0); }; } return null; }()); var index = /*@__PURE__*/getDefaultExportFromCjs(nextTick); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js var ensureCallable = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; var byObserver = function (Observer) { var node = document.createTextNode(''), queue, currentQueue, bit = 0, i = 0; new Observer(function () { var callback; if (!queue) { if (!currentQueue) return; queue = currentQueue; } else if (currentQueue) { queue = currentQueue.slice(i).concat(queue); } currentQueue = queue; queue = null; i = 0; if (typeof currentQueue === 'function') { callback = currentQueue; currentQueue = null; callback(); return; } node.data = (bit = ++bit % 2); // Invoke other batch, to handle leftover callbacks in case of crash while (i < currentQueue.length) { callback = currentQueue[i]; i++; if (i === currentQueue.length) currentQueue = null; callback(); } }).observe(node, { characterData: true }); return function (fn) { ensureCallable(fn); if (queue) { if (typeof queue === 'function') queue = [queue, fn]; else queue.push(fn); return; } queue = fn; node.data = (bit = ++bit % 2); }; }; var nextTick = (function () { // Node.js if ((typeof process === 'object') && process && (typeof process.nextTick === 'function')) { return process.nextTick; } // queueMicrotask if (typeof queueMicrotask === "function") { return function (cb) { queueMicrotask(ensureCallable(cb)); }; } // MutationObserver if ((typeof document === 'object') && document) { if (typeof MutationObserver === 'function') return byObserver(MutationObserver); if (typeof WebKitMutationObserver === 'function') return byObserver(WebKitMutationObserver); } // W3C Draft // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html if (typeof setImmediate === 'function') { return function (cb) { setImmediate(ensureCallable(cb)); }; } // Wide available standard if ((typeof setTimeout === 'function') || (typeof setTimeout === 'object')) { return function (cb) { setTimeout(ensureCallable(cb), 0); }; } return null; }()); var index = /*@__PURE__*/getDefaultExportFromCjs(nextTick); export { index as default };
66
9
0
7
10
0
3
0
0
0
12
10
720
false
json-schema
top1k-typed-nodeps
11,374
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var validate$1 = {exports: {}}; // FILE: lib/validate.js /** * JSONSchema Validator - Validates JavaScript objects using JSON Schemas * (http://www.json.com/json-schema-proposal/) * Licensed under AFL-2.1 OR BSD-3-Clause To use the validator call the validate function with an instance object and an optional schema object. If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), that schema will be used to validate and the schema parameter is not necessary (if both exist, both validations will occur). The validate method will return an array of validation errors. If there are no errors, then an empty list will be returned. A validation error will have two properties: "property" which indicates which property had the error "message" which indicates what the error was */ (function (module) { (function (root, factory) { if (module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals root.jsonSchema = factory(); } }(commonjsGlobal, function () {// setup primitive classes to be JSON Schema types var exports = validate; exports.Integer = {type:"integer"}; var primitiveConstructors = { String: String, Boolean: Boolean, Number: Number, Object: Object, Array: Array, Date: Date }; exports.validate = validate; function validate(/*Any*/instance,/*Object*/schema) { // Summary: // To use the validator call JSONSchema.validate with an instance object and an optional schema object. // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), // that schema will be used to validate and the schema parameter is not necessary (if both exist, // both validations will occur). // The validate method will return an object with two properties: // valid: A boolean indicating if the instance is valid by the schema // errors: An array of validation errors. If there are no errors, then an // empty list will be returned. A validation error will have two properties: // property: which indicates which property had the error // message: which indicates what the error was // return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); } exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { // Summary: // The checkPropertyChange method will check to see if an value can legally be in property with the given schema // This is slightly different than the validate method in that it will fail if the schema is readonly and it will // not check for self-validation, it is assumed that the passed in value is already internally valid. // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for // information. // return validate(value, schema, {changing: property || "property"}); }; var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { if (!options) options = {}; var _changing = options.changing; function getType(schema){ return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); } var errors = []; // validate a value against a property definition function checkProp(value, schema, path,i){ var l; path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; function addError(message){ errors.push({property:path,message:message}); } if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ if(typeof schema == 'function'){ if(!(value instanceof schema)){ addError("is not an instance of the class/constructor " + schema.name); } }else if(schema){ addError("Invalid schema/property definition " + schema); } return null; } if(_changing && schema.readonly){ addError("is a readonly field, it can not be changed"); } if(schema['extends']){ // if it extends another schema, it must pass that schema as well checkProp(value,schema['extends'],path,i); } // validate a value against a type definition function checkType(type,value){ if(type){ if(typeof type == 'string' && type != 'any' && (type == 'null' ? value !== null : typeof value != type) && !(value instanceof Array && type == 'array') && !(value instanceof Date && type == 'date') && !(type == 'integer' && value%1===0)){ return [{property:path,message:value + " - " + (typeof value) + " value found, but a " + type + " is required"}]; } if(type instanceof Array){ var unionErrors=[]; for(var j = 0; j < type.length; j++){ // a union type if(!(unionErrors=checkType(type[j],value)).length){ break; } } if(unionErrors.length){ return unionErrors; } }else if(typeof type == 'object'){ var priorErrors = errors; errors = []; checkProp(value,type,path); var theseErrors = errors; errors = priorErrors; return theseErrors; } } return []; } if(value === undefined){ if(schema.required){ addError("is missing and it is required"); } }else { errors = errors.concat(checkType(getType(schema),value)); if(schema.disallow && !checkType(schema.disallow,value).length){ addError(" disallowed value was matched"); } if(value !== null){ if(value instanceof Array){ if(schema.items){ var itemsIsArray = schema.items instanceof Array; var propDef = schema.items; for (i = 0, l = value.length; i < l; i += 1) { if (itemsIsArray) propDef = schema.items[i]; if (options.coerce) value[i] = options.coerce(value[i], propDef); errors.concat(checkProp(value[i],propDef,path,i)); } } if(schema.minItems && value.length < schema.minItems){ addError("There must be a minimum of " + schema.minItems + " in the array"); } if(schema.maxItems && value.length > schema.maxItems){ addError("There must be a maximum of " + schema.maxItems + " in the array"); } }else if(schema.properties || schema.additionalProperties){ errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); } if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ addError("does not match the regex pattern " + schema.pattern); } if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ addError("may only be " + schema.maxLength + " characters long"); } if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ addError("must be at least " + schema.minLength + " characters long"); } if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && schema.minimum > value){ addError("must have a minimum value of " + schema.minimum); } if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && schema.maximum < value){ addError("must have a maximum value of " + schema.maximum); } if(schema['enum']){ var enumer = schema['enum']; l = enumer.length; var found; for(var j = 0; j < l; j++){ if(enumer[j]===value){ found=1; break; } } if(!found){ addError("does not have a value in the enumeration " + enumer.join(", ")); } } if(typeof schema.maxDecimal == 'number' && (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ addError("may only have " + schema.maxDecimal + " digits of decimal places"); } } } return null; } // validate an object against a schema function checkObj(instance,objTypeDef,path,additionalProp){ if(typeof objTypeDef =='object'){ if(typeof instance != 'object' || instance instanceof Array){ errors.push({property:path,message:"an object is required"}); } for(var i in objTypeDef){ if(Object.prototype.hasOwnProperty.call(objTypeDef, i) && i != '__proto__' && i != 'constructor'){ var value = Object.prototype.hasOwnProperty.call(instance, i) ? instance[i] : undefined; // skip _not_ specified properties if (value === undefined && options.existingOnly) continue; var propDef = objTypeDef[i]; // set default if(value === undefined && propDef["default"]){ value = instance[i] = propDef["default"]; } if(options.coerce && i in instance){ value = instance[i] = options.coerce(value, propDef); } checkProp(value,propDef,path,i); } } } for(i in instance){ if(Object.prototype.hasOwnProperty.call(instance, i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ if (options.filter) { delete instance[i]; continue; } else { errors.push({property:path,message:"The property " + i + " is not defined in the schema and the schema does not allow additional properties"}); } } var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; if(requires && !(requires in instance)){ errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); } value = instance[i]; if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ if(options.coerce){ value = instance[i] = options.coerce(value, additionalProp); } checkProp(value,additionalProp,path,i); } if(!_changing && value && value.$schema){ errors = errors.concat(checkProp(value,value.$schema,path,i)); } } return errors; } if(schema){ checkProp(instance,schema,'',_changing || ''); } if(!_changing && instance && instance.$schema){ checkProp(instance,instance.$schema,'',''); } return {valid:!errors.length,errors:errors}; }; exports.mustBeValid = function(result){ // summary: // This checks to ensure that the result is valid and will throw an appropriate error message if it is not // result: the result returned from checkPropertyChange or validate if(!result.valid){ throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); } }; return exports; })); } (validate$1)); var validateExports = validate$1.exports; var validate = /*@__PURE__*/getDefaultExportFromCjs(validateExports); export { validate as default };
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var validate$1 = {exports: {}}; // FILE: lib/validate.js /** * JSONSchema Validator - Validates JavaScript objects using JSON Schemas * (http://www.json.com/json-schema-proposal/) * Licensed under AFL-2.1 OR BSD-3-Clause To use the validator call the validate function with an instance object and an optional schema object. If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), that schema will be used to validate and the schema parameter is not necessary (if both exist, both validations will occur). The validate method will return an array of validation errors. If there are no errors, then an empty list will be returned. A validation error will have two properties: "property" which indicates which property had the error "message" which indicates what the error was */ (function (module) { (function (root, factory) { if (module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals root.jsonSchema = factory(); } }(commonjsGlobal, function () {// setup primitive classes to be JSON Schema types var exports = validate; exports.Integer = {type:"integer"}; var primitiveConstructors = { String: String, Boolean: Boolean, Number: Number, Object: Object, Array: Array, Date: Date }; exports.validate = validate; function validate(/*Any*/instance,/*Object*/schema) { // Summary: // To use the validator call JSONSchema.validate with an instance object and an optional schema object. // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), // that schema will be used to validate and the schema parameter is not necessary (if both exist, // both validations will occur). // The validate method will return an object with two properties: // valid: A boolean indicating if the instance is valid by the schema // errors: An array of validation errors. If there are no errors, then an // empty list will be returned. A validation error will have two properties: // property: which indicates which property had the error // message: which indicates what the error was // return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); } exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { // Summary: // The checkPropertyChange method will check to see if an value can legally be in property with the given schema // This is slightly different than the validate method in that it will fail if the schema is readonly and it will // not check for self-validation, it is assumed that the passed in value is already internally valid. // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for // information. // return validate(value, schema, {changing: property || "property"}); }; var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { if (!options) options = {}; var _changing = options.changing; function getType(schema){ return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); } var errors = []; // validate a value against a property definition function checkProp(value, schema, path,i){ var l; path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; function addError(message){ errors.push({property:path,message:message}); } if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ if(typeof schema == 'function'){ if(!(value instanceof schema)){ addError("is not an instance of the class/constructor " + schema.name); } }else if(schema){ addError("Invalid schema/property definition " + schema); } return null; } if(_changing && schema.readonly){ addError("is a readonly field, it can not be changed"); } if(schema['extends']){ // if it extends another schema, it must pass that schema as well checkProp(value,schema['extends'],path,i); } // validate a value against a type definition function checkType(type,value){ if(type){ if(typeof type == 'string' && type != 'any' && (type == 'null' ? value !== null : typeof value != type) && !(value instanceof Array && type == 'array') && !(value instanceof Date && type == 'date') && !(type == 'integer' && value%1===0)){ return [{property:path,message:value + " - " + (typeof value) + " value found, but a " + type + " is required"}]; } if(type instanceof Array){ var unionErrors=[]; for(var j = 0; j < type.length; j++){ // a union type if(!(unionErrors=checkType(type[j],value)).length){ break; } } if(unionErrors.length){ return unionErrors; } }else if(typeof type == 'object'){ var priorErrors = errors; errors = []; checkProp(value,type,path); var theseErrors = errors; errors = priorErrors; return theseErrors; } } return []; } if(value === undefined){ if(schema.required){ addError("is missing and it is required"); } }else { errors = errors.concat(checkType(getType(schema),value)); if(schema.disallow && !checkType(schema.disallow,value).length){ addError(" disallowed value was matched"); } if(value !== null){ if(value instanceof Array){ if(schema.items){ var itemsIsArray = schema.items instanceof Array; var propDef = schema.items; for (i = 0, l = value.length; i < l; i += 1) { if (itemsIsArray) propDef = schema.items[i]; if (options.coerce) value[i] = options.coerce(value[i], propDef); errors.concat(checkProp(value[i],propDef,path,i)); } } if(schema.minItems && value.length < schema.minItems){ addError("There must be a minimum of " + schema.minItems + " in the array"); } if(schema.maxItems && value.length > schema.maxItems){ addError("There must be a maximum of " + schema.maxItems + " in the array"); } }else if(schema.properties || schema.additionalProperties){ errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); } if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ addError("does not match the regex pattern " + schema.pattern); } if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ addError("may only be " + schema.maxLength + " characters long"); } if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ addError("must be at least " + schema.minLength + " characters long"); } if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && schema.minimum > value){ addError("must have a minimum value of " + schema.minimum); } if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && schema.maximum < value){ addError("must have a maximum value of " + schema.maximum); } if(schema['enum']){ var enumer = schema['enum']; l = enumer.length; var found; for(var j = 0; j < l; j++){ if(enumer[j]===value){ found=1; break; } } if(!found){ addError("does not have a value in the enumeration " + enumer.join(", ")); } } if(typeof schema.maxDecimal == 'number' && (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ addError("may only have " + schema.maxDecimal + " digits of decimal places"); } } } return null; } // validate an object against a schema function checkObj(instance,objTypeDef,path,additionalProp){ if(typeof objTypeDef =='object'){ if(typeof instance != 'object' || instance instanceof Array){ errors.push({property:path,message:"an object is required"}); } for(var i in objTypeDef){ if(Object.prototype.hasOwnProperty.call(objTypeDef, i) && i != '__proto__' && i != 'constructor'){ var value = Object.prototype.hasOwnProperty.call(instance, i) ? instance[i] : undefined; // skip _not_ specified properties if (value === undefined && options.existingOnly) continue; var propDef = objTypeDef[i]; // set default if(value === undefined && propDef["default"]){ value = instance[i] = propDef["default"]; } if(options.coerce && i in instance){ value = instance[i] = options.coerce(value, propDef); } checkProp(value,propDef,path,i); } } } for(i in instance){ if(Object.prototype.hasOwnProperty.call(instance, i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ if (options.filter) { delete instance[i]; continue; } else { errors.push({property:path,message:"The property " + i + " is not defined in the schema and the schema does not allow additional properties"}); } } var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; if(requires && !(requires in instance)){ errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); } value = instance[i]; if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ if(options.coerce){ value = instance[i] = options.coerce(value, additionalProp); } checkProp(value,additionalProp,path,i); } if(!_changing && value && value.$schema){ errors = errors.concat(checkProp(value,value.$schema,path,i)); } } return errors; } if(schema){ checkProp(instance,schema,'',_changing || ''); } if(!_changing && instance && instance.$schema){ checkProp(instance,instance.$schema,'',''); } return {valid:!errors.length,errors:errors}; }; exports.mustBeValid = function(result){ // summary: // This checks to ensure that the result is valid and will throw an appropriate error message if it is not // result: the result returned from checkPropertyChange or validate if(!result.valid){ throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); } }; return exports; })); } (validate$1)); var validateExports = validate$1.exports; var validate = /*@__PURE__*/getDefaultExportFromCjs(validateExports); export { validate as default };
224
14
0
26
22
0
7
0
0
0
34
57.785714
3,104
false
eventemitter3
top1k-typed-nodeps
9,771
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var eventemitter3 = {exports: {}}; // FILE: index.js (function (module) { var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // { module.exports = EventEmitter; } } (eventemitter3)); var eventemitter3Exports = eventemitter3.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var eventemitter3 = {exports: {}}; // FILE: index.js (function (module) { var has = Object.prototype.hasOwnProperty , prefix = '~'; /** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @private */ function Events() {} // // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if (Object.create) { Events.prototype = Object.create(null); // // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if (!new Events().__proto__) prefix = false; } /** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @private */ function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } /** * Add a listener for a given event. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} context The context to invoke the listener with. * @param {Boolean} once Specify if the listener is a one-time listener. * @returns {EventEmitter} * @private */ function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } /** * Clear event by name. * * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. * @param {(String|Symbol)} evt The Event name. * @private */ function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } /** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @public */ function EventEmitter() { this._events = new Events(); this._eventsCount = 0; } /** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @public */ EventEmitter.prototype.eventNames = function eventNames() { var names = [] , events , name; if (this._eventsCount === 0) return names; for (name in (events = this._events)) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; /** * Return the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Array} The registered listeners. * @public */ EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event , handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; /** * Return the number of listeners listening to a given event. * * @param {(String|Symbol)} event The event name. * @returns {Number} The number of listeners. * @public */ EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event , listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; /** * Calls each of the listeners registered for a given event. * * @param {(String|Symbol)} event The event name. * @returns {Boolean} `true` if the event had listeners, else `false`. * @public */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt] , len = arguments.length , args , i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; /** * Add a listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; /** * Add a one-time listener for a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; /** * Remove the listeners of a given event. * * @param {(String|Symbol)} event The event name. * @param {Function} fn Only remove the listeners that match this function. * @param {*} context Only remove the listeners that have this context. * @param {Boolean} once Only remove one-time listeners. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if ( listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context) ) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if ( listeners[i].fn !== fn || (once && !listeners[i].once) || (context && listeners[i].context !== context) ) { events.push(listeners[i]); } } // // Reset the array, or remove it completely if we have no more listeners. // if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; /** * Remove all listeners, or those of the specified event. * * @param {(String|Symbol)} [event] The event name. * @returns {EventEmitter} `this`. * @public */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; // // Expose the prefix. // EventEmitter.prefixed = prefix; // // Allow `EventEmitter` to be imported as module namespace. // EventEmitter.EventEmitter = EventEmitter; // // Expose the module. // { module.exports = EventEmitter; } } (eventemitter3)); var eventemitter3Exports = eventemitter3.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports); export { index as default };
166
15
0
31
30
0
4
0
0
0
1
18.466667
2,750
false
parseurl
top1k-typed-nodeps
3,232
import require$$0 from 'url'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var parseurl$1 = {exports: {}}; // FILE: index.js /*! * parseurl * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var url = require$$0; var parse = url.parse; // eslint-disable-line var Url = url.Url; /** * Module exports. * @public */ parseurl$1.exports = parseurl; var original = parseurl$1.exports.original = originalurl; /** * Parse the `req` url with memoization. * * @param {ServerRequest} req * @return {Object} * @public */ function parseurl (req) { var url = req.url; if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url); parsed._raw = url; return (req._parsedUrl = parsed) } /** * Parse the `req` original url with fallback and memoization. * * @param {ServerRequest} req * @return {Object} * @public */ function originalurl (req) { var url = req.originalUrl; if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url); parsed._raw = url; return (req._parsedOriginalUrl = parsed) } /** * Parse the `str` url with fast-path short-cut. * * @param {string} str * @return {Object} * @private */ function fastparse (str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str) } var pathname = str; var query = null; var search = null; // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (var i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f: /* ? */ if (search === null) { pathname = str.substring(0, i); query = str.substring(i + 1); search = str.substring(i); } break case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str) } } var url = Url !== undefined ? new Url() : {}; url.path = str; url.href = str; url.pathname = pathname; if (search !== null) { url.query = query; url.search = search; } return url } /** * Determine if parsed is still fresh for url. * * @param {string} url * @param {object} parsedUrl * @return {boolean} * @private */ function fresh (url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url } var parseurlExports = parseurl$1.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(parseurlExports); export { index as default, original };
import require$$0 from 'url'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var parseurl$1 = {exports: {}}; // FILE: index.js /*! * parseurl * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var url = require$$0; var parse = url.parse; // eslint-disable-line var Url = url.Url; /** * Module exports. * @public */ parseurl$1.exports = parseurl; var original = parseurl$1.exports.original = originalurl; /** * Parse the `req` url with memoization. * * @param {ServerRequest} req * @return {Object} * @public */ function parseurl (req) { var url = req.url; if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url); parsed._raw = url; return (req._parsedUrl = parsed) } /** * Parse the `req` original url with fallback and memoization. * * @param {ServerRequest} req * @return {Object} * @public */ function originalurl (req) { var url = req.originalUrl; if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url); parsed._raw = url; return (req._parsedOriginalUrl = parsed) } /** * Parse the `str` url with fast-path short-cut. * * @param {string} str * @return {Object} * @private */ function fastparse (str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str) } var pathname = str; var query = null; var search = null; // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (var i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f: /* ? */ if (search === null) { pathname = str.substring(0, i); query = str.substring(i + 1); search = str.substring(i); } break case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str) } } var url = Url !== undefined ? new Url() : {}; url.path = str; url.href = str; url.pathname = pathname; if (search !== null) { url.query = query; url.search = search; } return url } /** * Determine if parsed is still fresh for url. * * @param {string} url * @param {object} parsedUrl * @return {boolean} * @private */ function fresh (url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url } var parseurlExports = parseurl$1.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(parseurlExports); export { index as default, original };
84
5
0
6
16
0
4
0
0
0
4
12.8
1,031
false
rimraf
top1k-typed-with-typed-deps
9,325
import require$$0 from 'assert'; import require$$1 from 'path'; import require$$2 from 'fs'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: rimraf.js const assert = require$$0; const path = require$$1; const fs = require$$2; let glob = undefined; try { glob = require("glob"); } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true }; // for EMFILE handling let timeout = 0; const isWindows = (process.platform === "win32"); const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ]; methods.forEach(m => { options[m] = options[m] || fs[m]; m = m + 'Sync'; options[m] = options[m] || fs[m]; }); options.maxBusyTries = options.maxBusyTries || 3; options.emfileWait = options.emfileWait || 1000; if (options.glob === false) { options.disableGlob = true; } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false; options.glob = options.glob || defaultGlobOpts; }; const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options; options = {}; } assert(p, 'rimraf: missing path'); assert.equal(typeof p, 'string', 'rimraf: path should be a string'); assert.equal(typeof cb, 'function', 'rimraf: callback function required'); assert(options, 'rimraf: invalid options argument provided'); assert.equal(typeof options, 'object', 'rimraf: options should be object'); defaults(options); let busyTries = 0; let errState = null; let n = 0; const next = (er) => { errState = errState || er; if (--n === 0) cb(errState); }; const afterGlob = (er, results) => { if (er) return cb(er) n = results.length; if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++; // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null; } timeout = 0; next(er); }; rimraf_(p, options, CB); }); }; if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob); }); }; // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb); if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }); }); }; const fixWinEPERM = (p, options, er, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er); else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er); else if (stats.isDirectory()) rmdir(p, options, er, cb); else options.unlink(p, cb); }); }); }; const fixWinEPERMSync = (p, options, er) => { assert(p); assert(options); try { options.chmodSync(p, 0o666); } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats; try { stats = options.statSync(p); } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er); else options.unlinkSync(p); }; const rmdir = (p, options, originalEr, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb); else if (er && er.code === "ENOTDIR") cb(originalEr); else cb(er); }); }; const rmkids = (p, options, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length; if (n === 0) return options.rmdir(p, cb) let errState; files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb); }); }); }); }; // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {}; defaults(options); assert(p, 'rimraf: missing path'); assert.equal(typeof p, 'string', 'rimraf: path should be a string'); assert(options, 'rimraf: missing options'); assert.equal(typeof options, 'object', 'rimraf: options should be object'); let results; if (options.disableGlob || !glob.hasMagic(p)) { results = [p]; } else { try { options.lstatSync(p); results = [p]; } catch (er) { results = glob.sync(p, options.glob); } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i]; let st; try { st = options.lstatSync(p); } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er); } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null); else options.unlinkSync(p); } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er); } } }; const rmdirSync = (p, options, originalEr) => { assert(p); assert(options); try { options.rmdirSync(p); } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options); } }; const rmkidsSync = (p, options) => { assert(p); assert(options); options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)); // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1; let i = 0; do { let threw = true; try { const ret = options.rmdirSync(p, options); threw = false; return ret } finally { if (++i < retries && threw) continue } } while (true) }; var rimraf_1 = rimraf; rimraf.sync = rimrafSync; var rimraf$1 = /*@__PURE__*/getDefaultExportFromCjs(rimraf_1); export { rimraf$1 as default };
import require$$0 from 'assert'; import require$$1 from 'path'; import require$$2 from 'fs'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: rimraf.js const assert = require$$0; const path = require$$1; const fs = require$$2; let glob = undefined; try { glob = require("glob"); } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true }; // for EMFILE handling let timeout = 0; const isWindows = (process.platform === "win32"); const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ]; methods.forEach(m => { options[m] = options[m] || fs[m]; m = m + 'Sync'; options[m] = options[m] || fs[m]; }); options.maxBusyTries = options.maxBusyTries || 3; options.emfileWait = options.emfileWait || 1000; if (options.glob === false) { options.disableGlob = true; } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false; options.glob = options.glob || defaultGlobOpts; }; const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options; options = {}; } assert(p, 'rimraf: missing path'); assert.equal(typeof p, 'string', 'rimraf: path should be a string'); assert.equal(typeof cb, 'function', 'rimraf: callback function required'); assert(options, 'rimraf: invalid options argument provided'); assert.equal(typeof options, 'object', 'rimraf: options should be object'); defaults(options); let busyTries = 0; let errState = null; let n = 0; const next = (er) => { errState = errState || er; if (--n === 0) cb(errState); }; const afterGlob = (er, results) => { if (er) return cb(er) n = results.length; if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++; // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null; } timeout = 0; next(er); }; rimraf_(p, options, CB); }); }; if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob); }); }; // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb); if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }); }); }; const fixWinEPERM = (p, options, er, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er); else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er); else if (stats.isDirectory()) rmdir(p, options, er, cb); else options.unlink(p, cb); }); }); }; const fixWinEPERMSync = (p, options, er) => { assert(p); assert(options); try { options.chmodSync(p, 0o666); } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats; try { stats = options.statSync(p); } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er); else options.unlinkSync(p); }; const rmdir = (p, options, originalEr, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb); else if (er && er.code === "ENOTDIR") cb(originalEr); else cb(er); }); }; const rmkids = (p, options, cb) => { assert(p); assert(options); assert(typeof cb === 'function'); options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length; if (n === 0) return options.rmdir(p, cb) let errState; files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb); }); }); }); }; // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {}; defaults(options); assert(p, 'rimraf: missing path'); assert.equal(typeof p, 'string', 'rimraf: path should be a string'); assert(options, 'rimraf: missing options'); assert.equal(typeof options, 'object', 'rimraf: options should be object'); let results; if (options.disableGlob || !glob.hasMagic(p)) { results = [p]; } else { try { options.lstatSync(p); results = [p]; } catch (er) { results = glob.sync(p, options.glob); } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i]; let st; try { st = options.lstatSync(p); } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er); } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null); else options.unlinkSync(p); } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er); } } }; const rmdirSync = (p, options, originalEr) => { assert(p); assert(options); try { options.rmdirSync(p); } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options); } }; const rmkidsSync = (p, options) => { assert(p); assert(options); options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)); // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1; let i = 0; do { let threw = true; try { const ret = options.rmdirSync(p, options); threw = false; return ret } finally { if (++i < retries && threw) continue } } while (true) }; var rimraf_1 = rimraf; rimraf.sync = rimrafSync; var rimraf$1 = /*@__PURE__*/getDefaultExportFromCjs(rimraf_1); export { rimraf$1 as default };
285
28
0
49
37
0
13
0
0
0
10
13.892857
2,872
false
querystring
top1k-typed-nodeps
2,536
var querystring = {}; // FILE: decode.js // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var decode$1 = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; // FILE: encode.js var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).filter(Boolean).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; // FILE: index.js var stringify; var parse; var decode = querystring.decode = parse = querystring.parse = decode$1; var encode = querystring.encode = stringify = querystring.stringify = encode$1; export { decode, querystring as default, encode, parse, stringify };
var querystring = {}; // FILE: decode.js // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var decode$1 = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; // FILE: encode.js var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).filter(Boolean).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; // FILE: index.js var stringify; var parse; var decode = querystring.decode = parse = querystring.parse = decode$1; var encode = querystring.encode = stringify = querystring.stringify = encode$1; export { decode, querystring as default, encode, parse, stringify };
83
6
0
13
20
0
2
0
0
0
4
13
767
false
ip
top1k-typed-nodeps
10,951
import require$$0 from 'buffer'; import require$$1 from 'os'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var ip$1 = {}; // FILE: lib/ip.js (function (exports) { const ip = exports; const { Buffer } = require$$0; const os = require$$1; ip.toBuffer = function (ip, buff, offset) { offset = ~~offset; let result; if (this.isV4Format(ip)) { result = buff || Buffer.alloc(offset + 4); ip.split(/\./g).map((byte) => { result[offset++] = parseInt(byte, 10) & 0xff; }); } else if (this.isV6Format(ip)) { const sections = ip.split(':', 8); let i; for (i = 0; i < sections.length; i++) { const isv4 = this.isV4Format(sections[i]); let v4Buffer; if (isv4) { v4Buffer = this.toBuffer(sections[i]); sections[i] = v4Buffer.slice(0, 2).toString('hex'); } if (v4Buffer && ++i < 8) { sections.splice(i, 0, v4Buffer.slice(2, 4).toString('hex')); } } if (sections[0] === '') { while (sections.length < 8) sections.unshift('0'); } else if (sections[sections.length - 1] === '') { while (sections.length < 8) sections.push('0'); } else if (sections.length < 8) { for (i = 0; i < sections.length && sections[i] !== ''; i++); const argv = [i, 1]; for (i = 9 - sections.length; i > 0; i--) { argv.push('0'); } sections.splice(...argv); } result = buff || Buffer.alloc(offset + 16); for (i = 0; i < sections.length; i++) { const word = parseInt(sections[i], 16); result[offset++] = (word >> 8) & 0xff; result[offset++] = word & 0xff; } } if (!result) { throw Error(`Invalid ip address: ${ip}`); } return result; }; ip.toString = function (buff, offset, length) { offset = ~~offset; length = length || (buff.length - offset); let result = []; if (length === 4) { // IPv4 for (let i = 0; i < length; i++) { result.push(buff[offset + i]); } result = result.join('.'); } else if (length === 16) { // IPv6 for (let i = 0; i < length; i += 2) { result.push(buff.readUInt16BE(offset + i).toString(16)); } result = result.join(':'); result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3'); result = result.replace(/:{3,4}/, '::'); } return result; }; const ipv4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/; const ipv6Regex = /^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i; ip.isV4Format = function (ip) { return ipv4Regex.test(ip); }; ip.isV6Format = function (ip) { return ipv6Regex.test(ip); }; function _normalizeFamily(family) { if (family === 4) { return 'ipv4'; } if (family === 6) { return 'ipv6'; } return family ? family.toLowerCase() : 'ipv4'; } ip.fromPrefixLen = function (prefixlen, family) { if (prefixlen > 32) { family = 'ipv6'; } else { family = _normalizeFamily(family); } let len = 4; if (family === 'ipv6') { len = 16; } const buff = Buffer.alloc(len); for (let i = 0, n = buff.length; i < n; ++i) { let bits = 8; if (prefixlen < 8) { bits = prefixlen; } prefixlen -= bits; buff[i] = ~(0xff >> bits) & 0xff; } return ip.toString(buff); }; ip.mask = function (addr, mask) { addr = ip.toBuffer(addr); mask = ip.toBuffer(mask); const result = Buffer.alloc(Math.max(addr.length, mask.length)); // Same protocol - do bitwise and let i; if (addr.length === mask.length) { for (i = 0; i < addr.length; i++) { result[i] = addr[i] & mask[i]; } } else if (mask.length === 4) { // IPv6 address and IPv4 mask // (Mask low bits) for (i = 0; i < mask.length; i++) { result[i] = addr[addr.length - 4 + i] & mask[i]; } } else { // IPv6 mask and IPv4 addr for (i = 0; i < result.length - 6; i++) { result[i] = 0; } // ::ffff:ipv4 result[10] = 0xff; result[11] = 0xff; for (i = 0; i < addr.length; i++) { result[i + 12] = addr[i] & mask[i + 12]; } i += 12; } for (; i < result.length; i++) { result[i] = 0; } return ip.toString(result); }; ip.cidr = function (cidrString) { const cidrParts = cidrString.split('/'); const addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.mask(addr, mask); }; ip.subnet = function (addr, mask) { const networkAddress = ip.toLong(ip.mask(addr, mask)); // Calculate the mask's length. const maskBuffer = ip.toBuffer(mask); let maskLength = 0; for (let i = 0; i < maskBuffer.length; i++) { if (maskBuffer[i] === 0xff) { maskLength += 8; } else { let octet = maskBuffer[i] & 0xff; while (octet) { octet = (octet << 1) & 0xff; maskLength++; } } } const numberOfAddresses = 2 ** (32 - maskLength); return { networkAddress: ip.fromLong(networkAddress), firstAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress) : ip.fromLong(networkAddress + 1), lastAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress + numberOfAddresses - 1) : ip.fromLong(networkAddress + numberOfAddresses - 2), broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1), subnetMask: mask, subnetMaskLength: maskLength, numHosts: numberOfAddresses <= 2 ? numberOfAddresses : numberOfAddresses - 2, length: numberOfAddresses, contains(other) { return networkAddress === ip.toLong(ip.mask(other, mask)); }, }; }; ip.cidrSubnet = function (cidrString) { const cidrParts = cidrString.split('/'); const addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.subnet(addr, mask); }; ip.not = function (addr) { const buff = ip.toBuffer(addr); for (let i = 0; i < buff.length; i++) { buff[i] = 0xff ^ buff[i]; } return ip.toString(buff); }; ip.or = function (a, b) { a = ip.toBuffer(a); b = ip.toBuffer(b); // same protocol if (a.length === b.length) { for (let i = 0; i < a.length; ++i) { a[i] |= b[i]; } return ip.toString(a); // mixed protocols } let buff = a; let other = b; if (b.length > a.length) { buff = b; other = a; } const offset = buff.length - other.length; for (let i = offset; i < buff.length; ++i) { buff[i] |= other[i - offset]; } return ip.toString(buff); }; ip.isEqual = function (a, b) { a = ip.toBuffer(a); b = ip.toBuffer(b); // Same protocol if (a.length === b.length) { for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } // Swap if (b.length === 4) { const t = b; b = a; a = t; } // a - IPv4, b - IPv6 for (let i = 0; i < 10; i++) { if (b[i] !== 0) return false; } const word = b.readUInt16BE(10); if (word !== 0 && word !== 0xffff) return false; for (let i = 0; i < 4; i++) { if (a[i] !== b[i + 12]) return false; } return true; }; ip.isPrivate = function (addr) { return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^f[cd][0-9a-f]{2}:/i.test(addr) || /^fe80:/i.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.isPublic = function (addr) { return !ip.isPrivate(addr); }; ip.isLoopback = function (addr) { return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/ .test(addr) || /^fe80::1$/.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.loopback = function (family) { // // Default to `ipv4` // family = _normalizeFamily(family); if (family !== 'ipv4' && family !== 'ipv6') { throw new Error('family must be ipv4 or ipv6'); } return family === 'ipv4' ? '127.0.0.1' : 'fe80::1'; }; // // ### function address (name, family) // #### @name {string|'public'|'private'} **Optional** Name or security // of the network interface. // #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults // to ipv4). // // Returns the address for the network interface on the current system with // the specified `name`: // * String: First `family` address of the interface. // If not found see `undefined`. // * 'public': the first public ip address of family. // * 'private': the first private ip address of family. // * undefined: First address with `ipv4` or loopback address `127.0.0.1`. // ip.address = function (name, family) { const interfaces = os.networkInterfaces(); // // Default to `ipv4` // family = _normalizeFamily(family); // // If a specific network interface has been named, // return the address. // if (name && name !== 'private' && name !== 'public') { const res = interfaces[name].filter((details) => { const itemFamily = _normalizeFamily(details.family); return itemFamily === family; }); if (res.length === 0) { return undefined; } return res[0].address; } const all = Object.keys(interfaces).map((nic) => { // // Note: name will only be `public` or `private` // when this is called. // const addresses = interfaces[nic].filter((details) => { details.family = _normalizeFamily(details.family); if (details.family !== family || ip.isLoopback(details.address)) { return false; } if (!name) { return true; } return name === 'public' ? ip.isPrivate(details.address) : ip.isPublic(details.address); }); return addresses.length ? addresses[0].address : undefined; }).filter(Boolean); return !all.length ? ip.loopback(family) : all[0]; }; ip.toLong = function (ip) { let ipl = 0; ip.split('.').forEach((octet) => { ipl <<= 8; ipl += parseInt(octet); }); return (ipl >>> 0); }; ip.fromLong = function (ipl) { return (`${ipl >>> 24}.${ ipl >> 16 & 255}.${ ipl >> 8 & 255}.${ ipl & 255}`); }; } (ip$1)); var ip = /*@__PURE__*/getDefaultExportFromCjs(ip$1); export { ip as default };
import require$$0 from 'buffer'; import require$$1 from 'os'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var ip$1 = {}; // FILE: lib/ip.js (function (exports) { const ip = exports; const { Buffer } = require$$0; const os = require$$1; ip.toBuffer = function (ip, buff, offset) { offset = ~~offset; let result; if (this.isV4Format(ip)) { result = buff || Buffer.alloc(offset + 4); ip.split(/\./g).map((byte) => { result[offset++] = parseInt(byte, 10) & 0xff; }); } else if (this.isV6Format(ip)) { const sections = ip.split(':', 8); let i; for (i = 0; i < sections.length; i++) { const isv4 = this.isV4Format(sections[i]); let v4Buffer; if (isv4) { v4Buffer = this.toBuffer(sections[i]); sections[i] = v4Buffer.slice(0, 2).toString('hex'); } if (v4Buffer && ++i < 8) { sections.splice(i, 0, v4Buffer.slice(2, 4).toString('hex')); } } if (sections[0] === '') { while (sections.length < 8) sections.unshift('0'); } else if (sections[sections.length - 1] === '') { while (sections.length < 8) sections.push('0'); } else if (sections.length < 8) { for (i = 0; i < sections.length && sections[i] !== ''; i++); const argv = [i, 1]; for (i = 9 - sections.length; i > 0; i--) { argv.push('0'); } sections.splice(...argv); } result = buff || Buffer.alloc(offset + 16); for (i = 0; i < sections.length; i++) { const word = parseInt(sections[i], 16); result[offset++] = (word >> 8) & 0xff; result[offset++] = word & 0xff; } } if (!result) { throw Error(`Invalid ip address: ${ip}`); } return result; }; ip.toString = function (buff, offset, length) { offset = ~~offset; length = length || (buff.length - offset); let result = []; if (length === 4) { // IPv4 for (let i = 0; i < length; i++) { result.push(buff[offset + i]); } result = result.join('.'); } else if (length === 16) { // IPv6 for (let i = 0; i < length; i += 2) { result.push(buff.readUInt16BE(offset + i).toString(16)); } result = result.join(':'); result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3'); result = result.replace(/:{3,4}/, '::'); } return result; }; const ipv4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/; const ipv6Regex = /^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i; ip.isV4Format = function (ip) { return ipv4Regex.test(ip); }; ip.isV6Format = function (ip) { return ipv6Regex.test(ip); }; function _normalizeFamily(family) { if (family === 4) { return 'ipv4'; } if (family === 6) { return 'ipv6'; } return family ? family.toLowerCase() : 'ipv4'; } ip.fromPrefixLen = function (prefixlen, family) { if (prefixlen > 32) { family = 'ipv6'; } else { family = _normalizeFamily(family); } let len = 4; if (family === 'ipv6') { len = 16; } const buff = Buffer.alloc(len); for (let i = 0, n = buff.length; i < n; ++i) { let bits = 8; if (prefixlen < 8) { bits = prefixlen; } prefixlen -= bits; buff[i] = ~(0xff >> bits) & 0xff; } return ip.toString(buff); }; ip.mask = function (addr, mask) { addr = ip.toBuffer(addr); mask = ip.toBuffer(mask); const result = Buffer.alloc(Math.max(addr.length, mask.length)); // Same protocol - do bitwise and let i; if (addr.length === mask.length) { for (i = 0; i < addr.length; i++) { result[i] = addr[i] & mask[i]; } } else if (mask.length === 4) { // IPv6 address and IPv4 mask // (Mask low bits) for (i = 0; i < mask.length; i++) { result[i] = addr[addr.length - 4 + i] & mask[i]; } } else { // IPv6 mask and IPv4 addr for (i = 0; i < result.length - 6; i++) { result[i] = 0; } // ::ffff:ipv4 result[10] = 0xff; result[11] = 0xff; for (i = 0; i < addr.length; i++) { result[i + 12] = addr[i] & mask[i + 12]; } i += 12; } for (; i < result.length; i++) { result[i] = 0; } return ip.toString(result); }; ip.cidr = function (cidrString) { const cidrParts = cidrString.split('/'); const addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.mask(addr, mask); }; ip.subnet = function (addr, mask) { const networkAddress = ip.toLong(ip.mask(addr, mask)); // Calculate the mask's length. const maskBuffer = ip.toBuffer(mask); let maskLength = 0; for (let i = 0; i < maskBuffer.length; i++) { if (maskBuffer[i] === 0xff) { maskLength += 8; } else { let octet = maskBuffer[i] & 0xff; while (octet) { octet = (octet << 1) & 0xff; maskLength++; } } } const numberOfAddresses = 2 ** (32 - maskLength); return { networkAddress: ip.fromLong(networkAddress), firstAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress) : ip.fromLong(networkAddress + 1), lastAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress + numberOfAddresses - 1) : ip.fromLong(networkAddress + numberOfAddresses - 2), broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1), subnetMask: mask, subnetMaskLength: maskLength, numHosts: numberOfAddresses <= 2 ? numberOfAddresses : numberOfAddresses - 2, length: numberOfAddresses, contains(other) { return networkAddress === ip.toLong(ip.mask(other, mask)); }, }; }; ip.cidrSubnet = function (cidrString) { const cidrParts = cidrString.split('/'); const addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } const mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.subnet(addr, mask); }; ip.not = function (addr) { const buff = ip.toBuffer(addr); for (let i = 0; i < buff.length; i++) { buff[i] = 0xff ^ buff[i]; } return ip.toString(buff); }; ip.or = function (a, b) { a = ip.toBuffer(a); b = ip.toBuffer(b); // same protocol if (a.length === b.length) { for (let i = 0; i < a.length; ++i) { a[i] |= b[i]; } return ip.toString(a); // mixed protocols } let buff = a; let other = b; if (b.length > a.length) { buff = b; other = a; } const offset = buff.length - other.length; for (let i = offset; i < buff.length; ++i) { buff[i] |= other[i - offset]; } return ip.toString(buff); }; ip.isEqual = function (a, b) { a = ip.toBuffer(a); b = ip.toBuffer(b); // Same protocol if (a.length === b.length) { for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } // Swap if (b.length === 4) { const t = b; b = a; a = t; } // a - IPv4, b - IPv6 for (let i = 0; i < 10; i++) { if (b[i] !== 0) return false; } const word = b.readUInt16BE(10); if (word !== 0 && word !== 0xffff) return false; for (let i = 0; i < 4; i++) { if (a[i] !== b[i + 12]) return false; } return true; }; ip.isPrivate = function (addr) { return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^f[cd][0-9a-f]{2}:/i.test(addr) || /^fe80:/i.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.isPublic = function (addr) { return !ip.isPrivate(addr); }; ip.isLoopback = function (addr) { return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/ .test(addr) || /^fe80::1$/.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.loopback = function (family) { // // Default to `ipv4` // family = _normalizeFamily(family); if (family !== 'ipv4' && family !== 'ipv6') { throw new Error('family must be ipv4 or ipv6'); } return family === 'ipv4' ? '127.0.0.1' : 'fe80::1'; }; // // ### function address (name, family) // #### @name {string|'public'|'private'} **Optional** Name or security // of the network interface. // #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults // to ipv4). // // Returns the address for the network interface on the current system with // the specified `name`: // * String: First `family` address of the interface. // If not found see `undefined`. // * 'public': the first public ip address of family. // * 'private': the first private ip address of family. // * undefined: First address with `ipv4` or loopback address `127.0.0.1`. // ip.address = function (name, family) { const interfaces = os.networkInterfaces(); // // Default to `ipv4` // family = _normalizeFamily(family); // // If a specific network interface has been named, // return the address. // if (name && name !== 'private' && name !== 'public') { const res = interfaces[name].filter((details) => { const itemFamily = _normalizeFamily(details.family); return itemFamily === family; }); if (res.length === 0) { return undefined; } return res[0].address; } const all = Object.keys(interfaces).map((nic) => { // // Note: name will only be `public` or `private` // when this is called. // const addresses = interfaces[nic].filter((details) => { details.family = _normalizeFamily(details.family); if (details.family !== family || ip.isLoopback(details.address)) { return false; } if (!name) { return true; } return name === 'public' ? ip.isPrivate(details.address) : ip.isPublic(details.address); }); return addresses.length ? addresses[0].address : undefined; }).filter(Boolean); return !all.length ? ip.loopback(family) : all[0]; }; ip.toLong = function (ip) { let ipl = 0; ip.split('.').forEach((octet) => { ipl <<= 8; ipl += parseInt(octet); }); return (ipl >>> 0); }; ip.fromLong = function (ipl) { return (`${ipl >>> 24}.${ ipl >> 16 & 255}.${ ipl >> 8 & 255}.${ ipl & 255}`); }; } (ip$1)); var ip = /*@__PURE__*/getDefaultExportFromCjs(ip$1); export { ip as default };
322
28
0
38
54
0
15
0
0
0
0
21.607143
3,749
false
through
top1k-typed-nodeps
3,141
import require$$0 from 'stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var through = {exports: {}}; // FILE: index.js (function (module, exports) { var Stream = require$$0; // through // // a stream that does nothing but re-emit the input. // useful for aggregating a series of changing but not ending streams into one stream) module.exports = through; through.through = through; //create a readable writable stream. function through (write, end, opts) { write = write || function (data) { this.queue(data); }; end = end || function () { this.queue(null); }; var ended = false, destroyed = false, buffer = [], _ended = false; var stream = new Stream(); stream.readable = stream.writable = true; stream.paused = false; // stream.autoPause = !(opts && opts.autoPause === false) stream.autoDestroy = !(opts && opts.autoDestroy === false); stream.write = function (data) { write.call(this, data); return !stream.paused }; function drain() { while(buffer.length && !stream.paused) { var data = buffer.shift(); if(null === data) return stream.emit('end') else stream.emit('data', data); } } stream.queue = stream.push = function (data) { // console.error(ended) if(_ended) return stream if(data === null) _ended = true; buffer.push(data); drain(); return stream }; //this will be registered as the first 'end' listener //must call destroy next tick, to make sure we're after any //stream piped from here. //this is only a problem if end is not emitted synchronously. //a nicer way to do this is to make sure this is the last listener for 'end' stream.on('end', function () { stream.readable = false; if(!stream.writable && stream.autoDestroy) process.nextTick(function () { stream.destroy(); }); }); function _end () { stream.writable = false; end.call(stream); if(!stream.readable && stream.autoDestroy) stream.destroy(); } stream.end = function (data) { if(ended) return ended = true; if(arguments.length) stream.write(data); _end(); // will emit or queue return stream }; stream.destroy = function () { if(destroyed) return destroyed = true; ended = true; buffer.length = 0; stream.writable = stream.readable = false; stream.emit('close'); return stream }; stream.pause = function () { if(stream.paused) return stream.paused = true; return stream }; stream.resume = function () { if(stream.paused) { stream.paused = false; stream.emit('resume'); } drain(); //may have become paused again, //as drain emits 'data'. if(!stream.paused) stream.emit('drain'); return stream }; return stream } } (through)); var throughExports = through.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(throughExports); export { index as default };
import require$$0 from 'stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var through = {exports: {}}; // FILE: index.js (function (module, exports) { var Stream = require$$0; // through // // a stream that does nothing but re-emit the input. // useful for aggregating a series of changing but not ending streams into one stream) module.exports = through; through.through = through; //create a readable writable stream. function through (write, end, opts) { write = write || function (data) { this.queue(data); }; end = end || function () { this.queue(null); }; var ended = false, destroyed = false, buffer = [], _ended = false; var stream = new Stream(); stream.readable = stream.writable = true; stream.paused = false; // stream.autoPause = !(opts && opts.autoPause === false) stream.autoDestroy = !(opts && opts.autoDestroy === false); stream.write = function (data) { write.call(this, data); return !stream.paused }; function drain() { while(buffer.length && !stream.paused) { var data = buffer.shift(); if(null === data) return stream.emit('end') else stream.emit('data', data); } } stream.queue = stream.push = function (data) { // console.error(ended) if(_ended) return stream if(data === null) _ended = true; buffer.push(data); drain(); return stream }; //this will be registered as the first 'end' listener //must call destroy next tick, to make sure we're after any //stream piped from here. //this is only a problem if end is not emitted synchronously. //a nicer way to do this is to make sure this is the last listener for 'end' stream.on('end', function () { stream.readable = false; if(!stream.writable && stream.autoDestroy) process.nextTick(function () { stream.destroy(); }); }); function _end () { stream.writable = false; end.call(stream); if(!stream.readable && stream.autoDestroy) stream.destroy(); } stream.end = function (data) { if(ended) return ended = true; if(arguments.length) stream.write(data); _end(); // will emit or queue return stream }; stream.destroy = function () { if(destroyed) return destroyed = true; ended = true; buffer.length = 0; stream.writable = stream.readable = false; stream.emit('close'); return stream }; stream.pause = function () { if(stream.paused) return stream.paused = true; return stream }; stream.resume = function () { if(stream.paused) { stream.paused = false; stream.emit('resume'); } drain(); //may have become paused again, //as drain emits 'data'. if(!stream.paused) stream.emit('drain'); return stream }; return stream } } (through)); var throughExports = through.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(throughExports); export { index as default };
87
15
0
10
10
0
6
0
0
0
0
13.266667
829
false
imurmurhash
top1k-typed-nodeps
4,834
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var imurmurhash$1 = {exports: {}}; // FILE: imurmurhash.js /** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a> * @see http://github.com/homebrewing/brauhaus-diff * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ */ (function (module) { (function(){ var cache; // Call this function without `new` to use the cached object (good for // single-threaded environments), or with `new` to create a new object. // // @param {string} key A UTF-16 or ASCII string // @param {number} seed An optional positive integer // @return {object} A MurmurHash3 object for incremental hashing function MurmurHash3(key, seed) { var m = this instanceof MurmurHash3 ? this : cache; m.reset(seed); if (typeof key === 'string' && key.length > 0) { m.hash(key); } if (m !== this) { return m; } } // Incrementally add a string to this hash // // @param {string} key A UTF-16 or ASCII string // @return {object} this MurmurHash3.prototype.hash = function(key) { var h1, k1, i, top, len; len = key.length; this.len += len; k1 = this.k1; i = 0; switch (this.rem) { case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; case 3: k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; } this.rem = (len + this.rem) & 3; // & 3 is same as % 4 len -= this.rem; if (len > 0) { h1 = this.h1; while (1) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; if (i >= len) { break; } k1 = ((key.charCodeAt(i++) & 0xffff)) ^ ((key.charCodeAt(i++) & 0xffff) << 8) ^ ((key.charCodeAt(i++) & 0xffff) << 16); top = key.charCodeAt(i++); k1 ^= ((top & 0xff) << 24) ^ ((top & 0xff00) >> 8); } k1 = 0; switch (this.rem) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xffff); } this.h1 = h1; } this.k1 = k1; return this; }; // Get the result of this hash // // @return {number} The 32-bit hash MurmurHash3.prototype.result = function() { var k1, h1; k1 = this.k1; h1 = this.h1; if (k1 > 0) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; } h1 ^= this.len; h1 ^= h1 >>> 16; h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; h1 ^= h1 >>> 13; h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }; // Reset the hash object for reuse // // @param {number} seed An optional positive integer MurmurHash3.prototype.reset = function(seed) { this.h1 = typeof seed === 'number' ? seed : 0; this.rem = this.k1 = this.len = 0; return this; }; // A cached object to use. This can be safely used if you're in a single- // threaded environment, otherwise you need to create new hashes to use. cache = new MurmurHash3(); { module.exports = MurmurHash3; } }()); } (imurmurhash$1)); var imurmurhashExports = imurmurhash$1.exports; var imurmurhash = /*@__PURE__*/getDefaultExportFromCjs(imurmurhashExports); export { imurmurhash as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var imurmurhash$1 = {exports: {}}; // FILE: imurmurhash.js /** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author <a href="mailto:jensyt@gmail.com">Jens Taylor</a> * @see http://github.com/homebrewing/brauhaus-diff * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ */ (function (module) { (function(){ var cache; // Call this function without `new` to use the cached object (good for // single-threaded environments), or with `new` to create a new object. // // @param {string} key A UTF-16 or ASCII string // @param {number} seed An optional positive integer // @return {object} A MurmurHash3 object for incremental hashing function MurmurHash3(key, seed) { var m = this instanceof MurmurHash3 ? this : cache; m.reset(seed); if (typeof key === 'string' && key.length > 0) { m.hash(key); } if (m !== this) { return m; } } // Incrementally add a string to this hash // // @param {string} key A UTF-16 or ASCII string // @return {object} this MurmurHash3.prototype.hash = function(key) { var h1, k1, i, top, len; len = key.length; this.len += len; k1 = this.k1; i = 0; switch (this.rem) { case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; case 3: k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; } this.rem = (len + this.rem) & 3; // & 3 is same as % 4 len -= this.rem; if (len > 0) { h1 = this.h1; while (1) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; if (i >= len) { break; } k1 = ((key.charCodeAt(i++) & 0xffff)) ^ ((key.charCodeAt(i++) & 0xffff) << 8) ^ ((key.charCodeAt(i++) & 0xffff) << 16); top = key.charCodeAt(i++); k1 ^= ((top & 0xff) << 24) ^ ((top & 0xff00) >> 8); } k1 = 0; switch (this.rem) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xffff); } this.h1 = h1; } this.k1 = k1; return this; }; // Get the result of this hash // // @return {number} The 32-bit hash MurmurHash3.prototype.result = function() { var k1, h1; k1 = this.k1; h1 = this.h1; if (k1 > 0) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; } h1 ^= this.len; h1 ^= h1 >>> 16; h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; h1 ^= h1 >>> 13; h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }; // Reset the hash object for reuse // // @param {number} seed An optional positive integer MurmurHash3.prototype.reset = function(seed) { this.h1 = typeof seed === 'number' ? seed : 0; this.rem = this.k1 = this.len = 0; return this; }; // A cached object to use. This can be safely used if you're in a single- // threaded environment, otherwise you need to create new hashes to use. cache = new MurmurHash3(); { module.exports = MurmurHash3; } }()); } (imurmurhash$1)); var imurmurhashExports = imurmurhash$1.exports; var imurmurhash = /*@__PURE__*/getDefaultExportFromCjs(imurmurhashExports); export { imurmurhash as default };
95
7
0
6
12
0
3
0
0
0
3
34.571429
1,637
false
filesize
top1k-typed-nodeps
4,656
// FILE: src/constants.js const ARRAY = "array"; const BIT = "bit"; const BITS = "bits"; const BYTE = "byte"; const BYTES = "bytes"; const EMPTY = ""; const EXPONENT = "exponent"; const FUNCTION = "function"; const IEC = "iec"; const INVALID_NUMBER = "Invalid number"; const INVALID_ROUND = "Invalid rounding method"; const JEDEC = "jedec"; const OBJECT = "object"; const PERIOD = "."; const ROUND = "round"; const S = "s"; const SI_KBIT = "kbit"; const SI_KBYTE = "kB"; const SPACE = " "; const STRING = "string"; const ZERO = "0"; // FILE: src/strings.js const strings = { symbol: { iec: { bits: ["bit", "Kibit", "Mibit", "Gibit", "Tibit", "Pibit", "Eibit", "Zibit", "Yibit"], bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] }, jedec: { bits: ["bit", "Kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit", "Zbit", "Ybit"], bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] } }, fullform: { iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"], jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"] } }; // FILE: src/filesize.js /** * filesize * * @method filesize * @param {Mixed} arg String, Int or Float to transform * @param {Object} descriptor [Optional] Flags * @return {String} Readable file size String */ function filesize (arg, { bits = false, pad = false, base = -1, round = 2, locale = EMPTY, localeOptions = {}, separator = EMPTY, spacer = SPACE, symbols = {}, standard = EMPTY, output = STRING, fullform = false, fullforms = [], exponent = -1, roundingMethod = ROUND, precision = 0 } = {}) { let e = exponent, num = Number(arg), result = [], val = 0, u = EMPTY; // Sync base & standard if (base === -1 && standard.length === 0) { base = 10; standard = JEDEC; } else if (base === -1 && standard.length > 0) { standard = standard === IEC ? IEC : JEDEC; base = standard === IEC ? 2 : 10; } else { base = base === 2 ? 2 : 10; standard = base === 10 ? JEDEC : standard === JEDEC ? JEDEC : IEC; } const ceil = base === 10 ? 1000 : 1024, full = fullform === true, neg = num < 0, roundingFunc = Math[roundingMethod]; if (isNaN(arg)) { throw new TypeError(INVALID_NUMBER); } if (typeof roundingFunc !== FUNCTION) { throw new TypeError(INVALID_ROUND); } // Flipping a negative number to determine the size if (neg) { num = -num; } // Determining the exponent if (e === -1 || isNaN(e)) { e = Math.floor(Math.log(num) / Math.log(ceil)); if (e < 0) { e = 0; } } // Exceeding supported length, time to reduce & multiply if (e > 8) { if (precision > 0) { precision += 8 - e; } e = 8; } if (output === EXPONENT) { return e; } // Zero is now a special case because bytes divide by 1 if (num === 0) { result[0] = 0; u = result[1] = strings.symbol[standard][bits ? BITS : BYTES][e]; } else { val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e)); if (bits) { val = val * 8; if (val >= ceil && e < 8) { val = val / ceil; e++; } } const p = Math.pow(10, e > 0 ? round : 0); result[0] = roundingFunc(val * p) / p; if (result[0] === ceil && e < 8 && exponent === -1) { result[0] = 1; e++; } u = result[1] = base === 10 && e === 1 ? bits ? SI_KBIT : SI_KBYTE : strings.symbol[standard][bits ? BITS : BYTES][e]; } // Decorating a 'diff' if (neg) { result[0] = -result[0]; } // Setting optional precision if (precision > 0) { result[0] = result[0].toPrecision(precision); } // Applying custom symbol result[1] = symbols[result[1]] || result[1]; if (locale === true) { result[0] = result[0].toLocaleString(); } else if (locale.length > 0) { result[0] = result[0].toLocaleString(locale, localeOptions); } else if (separator.length > 0) { result[0] = result[0].toString().replace(PERIOD, separator); } if (pad && Number.isInteger(result[0]) === false && round > 0) { const x = separator || PERIOD, tmp = result[0].toString().split(x), s = tmp[1] || EMPTY, l = s.length, n = round - l; result[0] = `${tmp[0]}${x}${s.padEnd(l + n, ZERO)}`; } if (full) { result[1] = fullforms[e] ? fullforms[e] : strings.fullform[standard][e] + (bits ? BIT : BYTE) + (result[0] === 1 ? EMPTY : S); } // Returning Array, Object, or String (default) return output === ARRAY ? result : output === OBJECT ? { value: result[0], symbol: result[1], exponent: e, unit: u } : result.join(spacer); } // Partial application for functional programming filesize.partial = opt => arg => filesize(arg, opt); export { filesize as default };
// FILE: src/constants.js const ARRAY = "array"; const BIT = "bit"; const BITS = "bits"; const BYTE = "byte"; const BYTES = "bytes"; const EMPTY = ""; const EXPONENT = "exponent"; const FUNCTION = "function"; const IEC = "iec"; const INVALID_NUMBER = "Invalid number"; const INVALID_ROUND = "Invalid rounding method"; const JEDEC = "jedec"; const OBJECT = "object"; const PERIOD = "."; const ROUND = "round"; const S = "s"; const SI_KBIT = "kbit"; const SI_KBYTE = "kB"; const SPACE = " "; const STRING = "string"; const ZERO = "0"; // FILE: src/strings.js const strings = { symbol: { iec: { bits: ["bit", "Kibit", "Mibit", "Gibit", "Tibit", "Pibit", "Eibit", "Zibit", "Yibit"], bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] }, jedec: { bits: ["bit", "Kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit", "Zbit", "Ybit"], bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] } }, fullform: { iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"], jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"] } }; // FILE: src/filesize.js /** * filesize * * @method filesize * @param {Mixed} arg String, Int or Float to transform * @param {Object} descriptor [Optional] Flags * @return {String} Readable file size String */ function filesize (arg, { bits = false, pad = false, base = -1, round = 2, locale = EMPTY, localeOptions = {}, separator = EMPTY, spacer = SPACE, symbols = {}, standard = EMPTY, output = STRING, fullform = false, fullforms = [], exponent = -1, roundingMethod = ROUND, precision = 0 } = {}) { let e = exponent, num = Number(arg), result = [], val = 0, u = EMPTY; // Sync base & standard if (base === -1 && standard.length === 0) { base = 10; standard = JEDEC; } else if (base === -1 && standard.length > 0) { standard = standard === IEC ? IEC : JEDEC; base = standard === IEC ? 2 : 10; } else { base = base === 2 ? 2 : 10; standard = base === 10 ? JEDEC : standard === JEDEC ? JEDEC : IEC; } const ceil = base === 10 ? 1000 : 1024, full = fullform === true, neg = num < 0, roundingFunc = Math[roundingMethod]; if (isNaN(arg)) { throw new TypeError(INVALID_NUMBER); } if (typeof roundingFunc !== FUNCTION) { throw new TypeError(INVALID_ROUND); } // Flipping a negative number to determine the size if (neg) { num = -num; } // Determining the exponent if (e === -1 || isNaN(e)) { e = Math.floor(Math.log(num) / Math.log(ceil)); if (e < 0) { e = 0; } } // Exceeding supported length, time to reduce & multiply if (e > 8) { if (precision > 0) { precision += 8 - e; } e = 8; } if (output === EXPONENT) { return e; } // Zero is now a special case because bytes divide by 1 if (num === 0) { result[0] = 0; u = result[1] = strings.symbol[standard][bits ? BITS : BYTES][e]; } else { val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e)); if (bits) { val = val * 8; if (val >= ceil && e < 8) { val = val / ceil; e++; } } const p = Math.pow(10, e > 0 ? round : 0); result[0] = roundingFunc(val * p) / p; if (result[0] === ceil && e < 8 && exponent === -1) { result[0] = 1; e++; } u = result[1] = base === 10 && e === 1 ? bits ? SI_KBIT : SI_KBYTE : strings.symbol[standard][bits ? BITS : BYTES][e]; } // Decorating a 'diff' if (neg) { result[0] = -result[0]; } // Setting optional precision if (precision > 0) { result[0] = result[0].toPrecision(precision); } // Applying custom symbol result[1] = symbols[result[1]] || result[1]; if (locale === true) { result[0] = result[0].toLocaleString(); } else if (locale.length > 0) { result[0] = result[0].toLocaleString(locale, localeOptions); } else if (separator.length > 0) { result[0] = result[0].toString().replace(PERIOD, separator); } if (pad && Number.isInteger(result[0]) === false && round > 0) { const x = separator || PERIOD, tmp = result[0].toString().split(x), s = tmp[1] || EMPTY, l = s.length, n = round - l; result[0] = `${tmp[0]}${x}${s.padEnd(l + n, ZERO)}`; } if (full) { result[1] = fullforms[e] ? fullforms[e] : strings.fullform[standard][e] + (bits ? BIT : BYTE) + (result[0] === 1 ? EMPTY : S); } // Returning Array, Object, or String (default) return output === ARRAY ? result : output === OBJECT ? { value: result[0], symbol: result[1], exponent: e, unit: u } : result.join(spacer); } // Partial application for functional programming filesize.partial = opt => arg => filesize(arg, opt); export { filesize as default };
152
3
0
4
37
0
1
0
0
0
1
32
1,815
false
request-promise-core
top1k-untyped-with-typed-deps
7,836
import require$$1 from 'lodash/isFunction'; import require$$2 from 'lodash/isObjectLike'; import require$$3 from 'lodash/isString'; import require$$4 from 'lodash/isUndefined'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/errors.js function RequestError(cause, options, response) { this.name = 'RequestError'; this.message = String(cause); this.cause = cause; this.error = cause; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } RequestError.prototype = Object.create(Error.prototype); RequestError.prototype.constructor = RequestError; function StatusCodeError(statusCode, body, options, response) { this.name = 'StatusCodeError'; this.statusCode = statusCode; this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body); this.error = body; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } StatusCodeError.prototype = Object.create(Error.prototype); StatusCodeError.prototype.constructor = StatusCodeError; function TransformError(cause, options, response) { this.name = 'TransformError'; this.message = String(cause); this.cause = cause; this.error = cause; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } TransformError.prototype = Object.create(Error.prototype); TransformError.prototype.constructor = TransformError; var errors$1 = { RequestError: RequestError, StatusCodeError: StatusCodeError, TransformError: TransformError }; // FILE: lib/plumbing.js var errors = errors$1, isFunction = require$$1, isObjectLike = require$$2, isString = require$$3, isUndefined = require$$4; var plumbing = function (options) { var errorText = 'Please verify options'; // For better minification because this string is repeating if (!isObjectLike(options)) { throw new TypeError(errorText); } if (!isFunction(options.PromiseImpl)) { throw new TypeError(errorText + '.PromiseImpl'); } if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) { throw new TypeError(errorText + '.PromiseImpl'); } var PromiseImpl = options.PromiseImpl; var constructorMixin = options.constructorMixin; var plumbing = {}; plumbing.init = function (requestOptions) { var self = this; self._rp_promise = new PromiseImpl(function (resolve, reject) { self._rp_resolve = resolve; self._rp_reject = reject; if (constructorMixin) { constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters } }); self._rp_callbackOrig = requestOptions.callback; requestOptions.callback = self.callback = function RP$callback(err, response, body) { plumbing.callback.call(self, err, response, body); }; if (isString(requestOptions.method)) { requestOptions.method = requestOptions.method.toUpperCase(); } requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method]; self._rp_options = requestOptions; self._rp_options.simple = requestOptions.simple !== false; self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true; self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true; }; plumbing.defaultTransformations = { HEAD: function (body, response, resolveWithFullResponse) { return resolveWithFullResponse ? response : response.headers; } }; plumbing.callback = function (err, response, body) { var self = this; var origCallbackThrewException = false, thrownException = null; if (isFunction(self._rp_callbackOrig)) { try { self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next? } catch (e) { origCallbackThrewException = true; thrownException = e; } } var is2xx = !err && /^2/.test('' + response.statusCode); if (err) { self._rp_reject(new errors.RequestError(err, self._rp_options, response)); } else if (self._rp_options.simple && !is2xx) { if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) { (new PromiseImpl(function (resolve) { resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise })) .then(function (transformedResponse) { self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse)); }) .catch(function (transformErr) { self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response)); }); } else { self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response)); } } else { if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) { (new PromiseImpl(function (resolve) { resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise })) .then(function (transformedResponse) { self._rp_resolve(transformedResponse); }) .catch(function (transformErr) { self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response)); }); } else if (self._rp_options.resolveWithFullResponse) { self._rp_resolve(response); } else { self._rp_resolve(body); } } if (origCallbackThrewException) { throw thrownException; } }; plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) { exposeAs = exposeAs || methodToExpose; if (exposeAs in exposeTo) { throw new Error('Unable to expose method "' + exposeAs + '"'); } exposeTo[exposeAs] = function RP$exposed() { var self = bindTo || this; return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments); }; }; plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) { exposeAs = exposeAs || 'promise'; if (exposeAs in exposeTo) { throw new Error('Unable to expose method "' + exposeAs + '"'); } exposeTo[exposeAs] = function RP$promise() { var self = bindTo || this; return self[promisePropertyKey]; }; }; return plumbing; }; var plumbing$1 = /*@__PURE__*/getDefaultExportFromCjs(plumbing); export { plumbing$1 as default };
import require$$1 from 'lodash/isFunction'; import require$$2 from 'lodash/isObjectLike'; import require$$3 from 'lodash/isString'; import require$$4 from 'lodash/isUndefined'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: lib/errors.js function RequestError(cause, options, response) { this.name = 'RequestError'; this.message = String(cause); this.cause = cause; this.error = cause; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } RequestError.prototype = Object.create(Error.prototype); RequestError.prototype.constructor = RequestError; function StatusCodeError(statusCode, body, options, response) { this.name = 'StatusCodeError'; this.statusCode = statusCode; this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body); this.error = body; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } StatusCodeError.prototype = Object.create(Error.prototype); StatusCodeError.prototype.constructor = StatusCodeError; function TransformError(cause, options, response) { this.name = 'TransformError'; this.message = String(cause); this.cause = cause; this.error = cause; // legacy attribute this.options = options; this.response = response; if (Error.captureStackTrace) { // required for non-V8 environments Error.captureStackTrace(this); } } TransformError.prototype = Object.create(Error.prototype); TransformError.prototype.constructor = TransformError; var errors$1 = { RequestError: RequestError, StatusCodeError: StatusCodeError, TransformError: TransformError }; // FILE: lib/plumbing.js var errors = errors$1, isFunction = require$$1, isObjectLike = require$$2, isString = require$$3, isUndefined = require$$4; var plumbing = function (options) { var errorText = 'Please verify options'; // For better minification because this string is repeating if (!isObjectLike(options)) { throw new TypeError(errorText); } if (!isFunction(options.PromiseImpl)) { throw new TypeError(errorText + '.PromiseImpl'); } if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) { throw new TypeError(errorText + '.PromiseImpl'); } var PromiseImpl = options.PromiseImpl; var constructorMixin = options.constructorMixin; var plumbing = {}; plumbing.init = function (requestOptions) { var self = this; self._rp_promise = new PromiseImpl(function (resolve, reject) { self._rp_resolve = resolve; self._rp_reject = reject; if (constructorMixin) { constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters } }); self._rp_callbackOrig = requestOptions.callback; requestOptions.callback = self.callback = function RP$callback(err, response, body) { plumbing.callback.call(self, err, response, body); }; if (isString(requestOptions.method)) { requestOptions.method = requestOptions.method.toUpperCase(); } requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method]; self._rp_options = requestOptions; self._rp_options.simple = requestOptions.simple !== false; self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true; self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true; }; plumbing.defaultTransformations = { HEAD: function (body, response, resolveWithFullResponse) { return resolveWithFullResponse ? response : response.headers; } }; plumbing.callback = function (err, response, body) { var self = this; var origCallbackThrewException = false, thrownException = null; if (isFunction(self._rp_callbackOrig)) { try { self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next? } catch (e) { origCallbackThrewException = true; thrownException = e; } } var is2xx = !err && /^2/.test('' + response.statusCode); if (err) { self._rp_reject(new errors.RequestError(err, self._rp_options, response)); } else if (self._rp_options.simple && !is2xx) { if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) { (new PromiseImpl(function (resolve) { resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise })) .then(function (transformedResponse) { self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse)); }) .catch(function (transformErr) { self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response)); }); } else { self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response)); } } else { if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) { (new PromiseImpl(function (resolve) { resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise })) .then(function (transformedResponse) { self._rp_resolve(transformedResponse); }) .catch(function (transformErr) { self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response)); }); } else if (self._rp_options.resolveWithFullResponse) { self._rp_resolve(response); } else { self._rp_resolve(body); } } if (origCallbackThrewException) { throw thrownException; } }; plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) { exposeAs = exposeAs || methodToExpose; if (exposeAs in exposeTo) { throw new Error('Unable to expose method "' + exposeAs + '"'); } exposeTo[exposeAs] = function RP$exposed() { var self = bindTo || this; return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments); }; }; plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) { exposeAs = exposeAs || 'promise'; if (exposeAs in exposeTo) { throw new Error('Unable to expose method "' + exposeAs + '"'); } exposeTo[exposeAs] = function RP$promise() { var self = bindTo || this; return self[promisePropertyKey]; }; }; return plumbing; }; var plumbing$1 = /*@__PURE__*/getDefaultExportFromCjs(plumbing); export { plumbing$1 as default };
170
20
0
39
19
0
1
0
0
0
0
11.9
1,815
false
merge2
top1k-typed-nodeps
3,551
import require$$0 from 'stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0; const PassThrough = Stream.PassThrough; const slice = Array.prototype.slice; var merge2_1 = merge2; function merge2 () { const streamsQueue = []; const args = slice.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } var index = /*@__PURE__*/getDefaultExportFromCjs(merge2_1); export { index as default };
import require$$0 from 'stream'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0; const PassThrough = Stream.PassThrough; const slice = Array.prototype.slice; var merge2_1 = merge2; function merge2 () { const streamsQueue = []; const args = slice.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } var index = /*@__PURE__*/getDefaultExportFromCjs(merge2_1); export { index as default };
118
11
0
6
19
0
5
0
0
0
0
17.818182
989
false
assert-plus
top1k-typed-nodeps
5,768
import require$$0 from 'assert'; import require$$1 from 'stream'; import require$$2 from 'util'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: assert.js /* * Copyright (c) 2018, Joyent, Inc. and assert-plus authors */ var assert = require$$0; var Stream = require$$1.Stream; var util = require$$2; ///--- Globals /* JSSTYLED */ var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal function _capitalize(str) { return (str.charAt(0).toUpperCase() + str.slice(1)); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format('%s (%s) is required', name, expected), actual: (actual === undefined) ? typeof (arg) : actual(arg), expected: expected, operator: oper || '===', stackStartFunction: _toss.caller }); } function _getClass(arg) { return (Object.prototype.toString.call(arg).slice(8, -1)); } function noop() { // Why even bother with asserts? } ///--- Exports var types = { bool: { check: function (arg) { return typeof (arg) === 'boolean'; } }, func: { check: function (arg) { return typeof (arg) === 'function'; } }, string: { check: function (arg) { return typeof (arg) === 'string'; } }, object: { check: function (arg) { return typeof (arg) === 'object' && arg !== null; } }, number: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg); } }, finite: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function (arg) { return Buffer.isBuffer(arg); }, operator: 'Buffer.isBuffer' }, array: { check: function (arg) { return Array.isArray(arg); }, operator: 'Array.isArray' }, stream: { check: function (arg) { return arg instanceof Stream; }, operator: 'instanceof', actual: _getClass }, date: { check: function (arg) { return arg instanceof Date; }, operator: 'instanceof', actual: _getClass }, regexp: { check: function (arg) { return arg instanceof RegExp; }, operator: 'instanceof', actual: _getClass }, uuid: { check: function (arg) { return typeof (arg) === 'string' && UUID_REGEXP.test(arg); }, operator: 'isUUID' } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; /* re-export standard assert */ if (process.env.NODE_NDEBUG) { out = noop; } else { out = function (arg, msg) { if (!arg) { _toss(msg, 'true', arg); } }; } /* standard checks */ keys.forEach(function (k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function (arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* optional checks */ keys.forEach(function (k) { var name = 'optional' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* arrayOf checks */ keys.forEach(function (k) { var name = 'arrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* optionalArrayOf checks */ keys.forEach(function (k) { var name = 'optionalArrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* re-export built-in assertions */ Object.keys(assert).forEach(function (k) { if (k === 'AssertionError') { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); /* export ourselves (for unit tests _only_) */ out._setExports = _setExports; return out; } var assert_1 = _setExports(process.env.NODE_NDEBUG); var assert$1 = /*@__PURE__*/getDefaultExportFromCjs(assert_1); export { assert$1 as default };
import require$$0 from 'assert'; import require$$1 from 'stream'; import require$$2 from 'util'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: assert.js /* * Copyright (c) 2018, Joyent, Inc. and assert-plus authors */ var assert = require$$0; var Stream = require$$1.Stream; var util = require$$2; ///--- Globals /* JSSTYLED */ var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal function _capitalize(str) { return (str.charAt(0).toUpperCase() + str.slice(1)); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format('%s (%s) is required', name, expected), actual: (actual === undefined) ? typeof (arg) : actual(arg), expected: expected, operator: oper || '===', stackStartFunction: _toss.caller }); } function _getClass(arg) { return (Object.prototype.toString.call(arg).slice(8, -1)); } function noop() { // Why even bother with asserts? } ///--- Exports var types = { bool: { check: function (arg) { return typeof (arg) === 'boolean'; } }, func: { check: function (arg) { return typeof (arg) === 'function'; } }, string: { check: function (arg) { return typeof (arg) === 'string'; } }, object: { check: function (arg) { return typeof (arg) === 'object' && arg !== null; } }, number: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg); } }, finite: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function (arg) { return Buffer.isBuffer(arg); }, operator: 'Buffer.isBuffer' }, array: { check: function (arg) { return Array.isArray(arg); }, operator: 'Array.isArray' }, stream: { check: function (arg) { return arg instanceof Stream; }, operator: 'instanceof', actual: _getClass }, date: { check: function (arg) { return arg instanceof Date; }, operator: 'instanceof', actual: _getClass }, regexp: { check: function (arg) { return arg instanceof RegExp; }, operator: 'instanceof', actual: _getClass }, uuid: { check: function (arg) { return typeof (arg) === 'string' && UUID_REGEXP.test(arg); }, operator: 'isUUID' } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; /* re-export standard assert */ if (process.env.NODE_NDEBUG) { out = noop; } else { out = function (arg, msg) { if (!arg) { _toss(msg, 'true', arg); } }; } /* standard checks */ keys.forEach(function (k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function (arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* optional checks */ keys.forEach(function (k) { var name = 'optional' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* arrayOf checks */ keys.forEach(function (k) { var name = 'arrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* optionalArrayOf checks */ keys.forEach(function (k) { var name = 'optionalArrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* re-export built-in assertions */ Object.keys(assert).forEach(function (k) { if (k === 'AssertionError') { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); /* export ourselves (for unit tests _only_) */ out._setExports = _setExports; return out; } var assert_1 = _setExports(process.env.NODE_NDEBUG); var assert$1 = /*@__PURE__*/getDefaultExportFromCjs(assert_1); export { assert$1 as default };
182
28
0
36
20
0
4
0
0
0
11
7.928571
1,585
false
buffer-from
top1k-typed-nodeps
1,940
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* eslint-disable node/no-deprecated-api */ var toString = Object.prototype.toString; var isModern = ( typeof Buffer !== 'undefined' && typeof Buffer.alloc === 'function' && typeof Buffer.allocUnsafe === 'function' && typeof Buffer.from === 'function' ); function isArrayBuffer (input) { return toString.call(input).slice(8, -1) === 'ArrayBuffer' } function fromArrayBuffer (obj, byteOffset, length) { byteOffset >>>= 0; var maxLength = obj.byteLength - byteOffset; if (maxLength < 0) { throw new RangeError("'offset' is out of bounds") } if (length === undefined) { length = maxLength; } else { length >>>= 0; if (length > maxLength) { throw new RangeError("'length' is out of bounds") } } return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding) } function bufferFrom (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return isModern ? Buffer.from(value) : new Buffer(value) } var bufferFrom_1 = bufferFrom; var index = /*@__PURE__*/getDefaultExportFromCjs(bufferFrom_1); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* eslint-disable node/no-deprecated-api */ var toString = Object.prototype.toString; var isModern = ( typeof Buffer !== 'undefined' && typeof Buffer.alloc === 'function' && typeof Buffer.allocUnsafe === 'function' && typeof Buffer.from === 'function' ); function isArrayBuffer (input) { return toString.call(input).slice(8, -1) === 'ArrayBuffer' } function fromArrayBuffer (obj, byteOffset, length) { byteOffset >>>= 0; var maxLength = obj.byteLength - byteOffset; if (maxLength < 0) { throw new RangeError("'offset' is out of bounds") } if (length === undefined) { length = maxLength; } else { length >>>= 0; if (length > maxLength) { throw new RangeError("'length' is out of bounds") } } return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding) } function bufferFrom (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return isModern ? Buffer.from(value) : new Buffer(value) } var bufferFrom_1 = bufferFrom; var index = /*@__PURE__*/getDefaultExportFromCjs(bufferFrom_1); export { index as default };
59
5
0
10
5
0
4
0
0
0
7
7.8
528
true
querystringify
top1k-typed-nodeps
2,701
var querystringify$1 = {}; // FILE: index.js var has = Object.prototype.hasOwnProperty , undef; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String|Null} The decoded string. * @api private */ function decode(input) { try { return decodeURIComponent(input.replace(/\+/g, ' ')); } catch (e) { return null; } } /** * Attempts to encode a given input. * * @param {String} input The string that needs to be encoded. * @returns {String|Null} The encoded string. * @api private */ function encode(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } /** * Simple query string parser. * * @param {String} query The query string that needs to be parsed. * @returns {Object} * @api public */ function querystring(query) { var parser = /([^=?#&]+)=?([^&]*)/g , result = {} , part; while (part = parser.exec(query)) { var key = decode(part[1]) , value = decode(part[2]); // // Prevent overriding of existing properties. This ensures that build-in // methods like `toString` or __proto__ are not overriden by malicious // querystrings. // // In the case if failed decoding, we want to omit the key/value pairs // from the result. // if (key === null || value === null || key in result) continue; result[key] = value; } return result; } /** * Transform a query string to an object. * * @param {Object} obj Object that should be transformed. * @param {String} prefix Optional prefix. * @returns {String} * @api public */ function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encode(key); value = encode(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key +'='+ value); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // var stringify = querystringify$1.stringify = querystringify; var parse = querystringify$1.parse = querystring; export { querystringify$1 as default, parse, stringify };
var querystringify$1 = {}; // FILE: index.js var has = Object.prototype.hasOwnProperty , undef; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String|Null} The decoded string. * @api private */ function decode(input) { try { return decodeURIComponent(input.replace(/\+/g, ' ')); } catch (e) { return null; } } /** * Attempts to encode a given input. * * @param {String} input The string that needs to be encoded. * @returns {String|Null} The encoded string. * @api private */ function encode(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } /** * Simple query string parser. * * @param {String} query The query string that needs to be parsed. * @returns {Object} * @api public */ function querystring(query) { var parser = /([^=?#&]+)=?([^&]*)/g , result = {} , part; while (part = parser.exec(query)) { var key = decode(part[1]) , value = decode(part[2]); // // Prevent overriding of existing properties. This ensures that build-in // methods like `toString` or __proto__ are not overriden by malicious // querystrings. // // In the case if failed decoding, we want to omit the key/value pairs // from the result. // if (key === null || value === null || key in result) continue; result[key] = value; } return result; } /** * Transform a query string to an object. * * @param {Object} obj Object that should be transformed. * @param {String} prefix Optional prefix. * @returns {String} * @api public */ function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [] , value , key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encode(key); value = encode(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key +'='+ value); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // var stringify = querystringify$1.stringify = querystringify; var parse = querystringify$1.parse = querystring; export { querystringify$1 as default, parse, stringify };
52
4
0
5
13
0
2
0
0
0
1
9.5
740
false
domain-browser
top1k-untyped-nodeps
1,657
import require$$0 from 'events'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: source/index.js var source = function() { // Import Events var events = require$$0; // Export Domain var domain = {}; domain.createDomain = domain.create = function() { var d = new events.EventEmitter(); function emitError(e) { d.emit("error", e); } d.add = function(emitter) { emitter.on("error", emitError); }; d.remove = function(emitter) { emitter.removeListener("error", emitError); }; d.bind = function(fn) { return function() { var args = Array.prototype.slice.call(arguments); try { fn.apply(null, args); } catch (err) { emitError(err); } }; }; d.intercept = function(fn) { return function(err) { if (err) { emitError(err); } else { var args = Array.prototype.slice.call(arguments, 1); try { fn.apply(null, args); } catch (err) { emitError(err); } } }; }; d.run = function(fn) { try { fn(); } catch (err) { emitError(err); } return this; }; d.dispose = function() { this.removeAllListeners(); return this; }; d.enter = d.exit = function() { return this; }; return d; }; return domain; }.call(commonjsGlobal); var index = /*@__PURE__*/getDefaultExportFromCjs(source); export { index as default };
import require$$0 from 'events'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: source/index.js var source = function() { // Import Events var events = require$$0; // Export Domain var domain = {}; domain.createDomain = domain.create = function() { var d = new events.EventEmitter(); function emitError(e) { d.emit("error", e); } d.add = function(emitter) { emitter.on("error", emitError); }; d.remove = function(emitter) { emitter.removeListener("error", emitError); }; d.bind = function(fn) { return function() { var args = Array.prototype.slice.call(arguments); try { fn.apply(null, args); } catch (err) { emitError(err); } }; }; d.intercept = function(fn) { return function(err) { if (err) { emitError(err); } else { var args = Array.prototype.slice.call(arguments, 1); try { fn.apply(null, args); } catch (err) { emitError(err); } } }; }; d.run = function(fn) { try { fn(); } catch (err) { emitError(err); } return this; }; d.dispose = function() { this.removeAllListeners(); return this; }; d.enter = d.exit = function() { return this; }; return d; }; return domain; }.call(commonjsGlobal); var index = /*@__PURE__*/getDefaultExportFromCjs(source); export { index as default };
64
13
0
8
8
0
2
0
0
0
4
11.846154
540
false
ansi-styles
top1k-typed-nodeps
5,138
// FILE: index.js const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value: (red, green, blue) => { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value: hex => { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value: code => { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export { ansiStyles as default };
// FILE: index.js const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value: (red, green, blue) => { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value: hex => { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value: code => { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export { ansiStyles as default };
174
14
0
19
16
0
4
0
0
0
0
16.571429
2,167
false
run-async
top1k-untyped-nodeps
3,163
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var runAsync$1 = {exports: {}}; // FILE: index.js function isPromise(obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; } /** * Return a function that will run a function asynchronously or synchronously * * example: * runAsync(wrappedFunction, callback)(...args); * * @param {Function} func Function to run * @param {Function} cb Callback function passed the `func` returned value * @return {Function(arguments)} Arguments to pass to `func`. This function will in turn * return a Promise (Node >= 0.12) or call the callbacks. */ var runAsync = runAsync$1.exports = function (func, cb) { cb = cb || function () {}; return function () { var args = arguments; var promise = new Promise(function (resolve, reject) { var resolved = false; const wrappedResolve = function (value) { if (resolved) { console.warn('Run-async promise already resolved.'); } resolved = true; resolve(value); }; var rejected = false; const wrappedReject = function (value) { if (rejected) { console.warn('Run-async promise already rejected.'); } rejected = true; reject(value); }; var usingCallback = false; var callbackConflict = false; var contextEnded = false; var answer = func.apply({ async: function () { if (contextEnded) { console.warn('Run-async async() called outside a valid run-async context, callback will be ignored.'); return function() {}; } if (callbackConflict) { console.warn('Run-async wrapped function (async) returned a promise.\nCalls to async() callback can have unexpected results.'); } usingCallback = true; return function (err, value) { if (err) { wrappedReject(err); } else { wrappedResolve(value); } }; } }, Array.prototype.slice.call(args)); if (usingCallback) { if (isPromise(answer)) { console.warn('Run-async wrapped function (sync) returned a promise but async() callback must be executed to resolve.'); } } else { if (isPromise(answer)) { callbackConflict = true; answer.then(wrappedResolve, wrappedReject); } else { wrappedResolve(answer); } } contextEnded = true; }); promise.then(cb.bind(null, null), cb); return promise; } }; runAsync.cb = function (func, cb) { return runAsync(function () { var args = Array.prototype.slice.call(arguments); if (args.length === func.length - 1) { args.push(this.async()); } return func.apply(this, args); }, cb); }; var runAsyncExports = runAsync$1.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(runAsyncExports); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var runAsync$1 = {exports: {}}; // FILE: index.js function isPromise(obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; } /** * Return a function that will run a function asynchronously or synchronously * * example: * runAsync(wrappedFunction, callback)(...args); * * @param {Function} func Function to run * @param {Function} cb Callback function passed the `func` returned value * @return {Function(arguments)} Arguments to pass to `func`. This function will in turn * return a Promise (Node >= 0.12) or call the callbacks. */ var runAsync = runAsync$1.exports = function (func, cb) { cb = cb || function () {}; return function () { var args = arguments; var promise = new Promise(function (resolve, reject) { var resolved = false; const wrappedResolve = function (value) { if (resolved) { console.warn('Run-async promise already resolved.'); } resolved = true; resolve(value); }; var rejected = false; const wrappedReject = function (value) { if (rejected) { console.warn('Run-async promise already rejected.'); } rejected = true; reject(value); }; var usingCallback = false; var callbackConflict = false; var contextEnded = false; var answer = func.apply({ async: function () { if (contextEnded) { console.warn('Run-async async() called outside a valid run-async context, callback will be ignored.'); return function() {}; } if (callbackConflict) { console.warn('Run-async wrapped function (async) returned a promise.\nCalls to async() callback can have unexpected results.'); } usingCallback = true; return function (err, value) { if (err) { wrappedReject(err); } else { wrappedResolve(value); } }; } }, Array.prototype.slice.call(args)); if (usingCallback) { if (isPromise(answer)) { console.warn('Run-async wrapped function (sync) returned a promise but async() callback must be executed to resolve.'); } } else { if (isPromise(answer)) { callbackConflict = true; answer.then(wrappedResolve, wrappedReject); } else { wrappedResolve(answer); } } contextEnded = true; }); promise.then(cb.bind(null, null), cb); return promise; } }; runAsync.cb = function (func, cb) { return runAsync(function () { var args = Array.prototype.slice.call(arguments); if (args.length === func.length - 1) { args.push(this.async()); } return func.apply(this, args); }, cb); }; var runAsyncExports = runAsync$1.exports; var index = /*@__PURE__*/getDefaultExportFromCjs(runAsyncExports); export { index as default };
80
13
0
12
15
0
4
0
0
0
3
16.153846
769
false
w3c-xmlserializer
top1k-typed-with-typed-deps
14,825
import require$$0 from 'xml-name-validator'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var attributes = {}; var constants = {}; // FILE: lib/constants.js constants.NAMESPACES = { HTML: "http://www.w3.org/1999/xhtml", XML: "http://www.w3.org/XML/1998/namespace", XMLNS: "http://www.w3.org/2000/xmlns/" }; constants.NODE_TYPES = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, // historical TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, // historical ENTITY_NODE: 6, // historical PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12 // historical }; constants.VOID_ELEMENTS = new Set([ "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr" ]); // FILE: lib/attributes.js const xnv$1 = require$$0; const { NAMESPACES: NAMESPACES$1 } = constants; function generatePrefix(map, newNamespace, prefixIndex) { const generatedPrefix = `ns${prefixIndex}`; map[newNamespace] = [generatedPrefix]; return generatedPrefix; } function preferredPrefixString(map, ns, preferredPrefix) { const candidateList = map[ns]; if (!candidateList) { return null; } if (candidateList.includes(preferredPrefix)) { return preferredPrefix; } return candidateList[candidateList.length - 1]; } function serializeAttributeValue(value/* , requireWellFormed*/) { if (value === null) { return ""; } // TODO: Check well-formedness return value .replace(/&/ug, "&amp;") .replace(/"/ug, "&quot;") .replace(/</ug, "&lt;") .replace(/>/ug, "&gt;") .replace(/\t/ug, "&#x9;") .replace(/\n/ug, "&#xA;") .replace(/\r/ug, "&#xD;"); } function serializeAttributes( element, map, localPrefixes, ignoreNamespaceDefAttr, requireWellFormed, refs ) { let result = ""; const namespaceLocalnames = Object.create(null); for (const attr of element.attributes) { if ( requireWellFormed && namespaceLocalnames[attr.namespaceURI] && namespaceLocalnames[attr.namespaceURI].has(attr.localName) ) { throw new Error("Found duplicated attribute"); } if (!namespaceLocalnames[attr.namespaceURI]) { namespaceLocalnames[attr.namespaceURI] = new Set(); } namespaceLocalnames[attr.namespaceURI].add(attr.localName); const attributeNamespace = attr.namespaceURI; let candidatePrefix = null; if (attributeNamespace !== null) { candidatePrefix = preferredPrefixString( map, attributeNamespace, attr.prefix ); if (attributeNamespace === NAMESPACES$1.XMLNS) { if ( attr.value === NAMESPACES$1.XML || (attr.prefix === null && ignoreNamespaceDefAttr) || (attr.prefix !== null && localPrefixes[attr.localName] !== attr.value && map[attr.value].includes(attr.localName)) ) { continue; } if (requireWellFormed && attr.value === NAMESPACES$1.XMLNS) { throw new Error( "The XMLNS namespace is reserved and cannot be applied as an element's namespace via XML parsing" ); } if (requireWellFormed && attr.value === "") { throw new Error( "Namespace prefix declarations cannot be used to undeclare a namespace" ); } if (attr.prefix === "xmlns") { candidatePrefix = "xmlns"; } } else if (candidatePrefix === null) { candidatePrefix = generatePrefix( map, attributeNamespace, refs.prefixIndex++ ); result += ` xmlns:${candidatePrefix}="${serializeAttributeValue( attributeNamespace)}"`; } } result += " "; if (candidatePrefix !== null) { result += `${candidatePrefix}:`; } if ( requireWellFormed && (attr.localName.includes(":") || !xnv$1.name(attr.localName) || (attr.localName === "xmlns" && attributeNamespace === null)) ) { throw new Error("Invalid attribute localName value"); } result += `${attr.localName}="${serializeAttributeValue(attr.value)}"`; } return result; } attributes.preferredPrefixString = preferredPrefixString; attributes.generatePrefix = generatePrefix; attributes.serializeAttributeValue = serializeAttributeValue; attributes.serializeAttributes = serializeAttributes; // FILE: lib/serialize.js const xnv = require$$0; const attributeUtils = attributes; const { NAMESPACES, VOID_ELEMENTS, NODE_TYPES } = constants; const XML_CHAR = /^(\x09|\x0A|\x0D|[\x20-\uD7FF]|[\uE000-\uFFFD]|(?:[\uD800-\uDBFF][\uDC00-\uDFFF]))*$/u; const PUBID_CHAR = /^(\x20|\x0D|\x0A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/u; function asciiCaseInsensitiveMatch(a, b) { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; ++i) { if ((a.charCodeAt(i) | 32) !== (b.charCodeAt(i) | 32)) { return false; } } return true; } function recordNamespaceInformation(element, map, prefixMap) { let defaultNamespaceAttrValue = null; for (let i = 0; i < element.attributes.length; ++i) { const attr = element.attributes[i]; if (attr.namespaceURI === NAMESPACES.XMLNS) { if (attr.prefix === null) { defaultNamespaceAttrValue = attr.value; continue; } let namespaceDefinition = attr.value; if (namespaceDefinition === NAMESPACES.XML) { continue; } // This is exactly the other way than the spec says, but that's intended. // All the maps coalesce null to the empty string (explained in the // spec), so instead of doing that every time, just do it once here. if (namespaceDefinition === null) { namespaceDefinition = ""; } if ( namespaceDefinition in map && map[namespaceDefinition].includes(attr.localName) ) { continue; } if (!(namespaceDefinition in map)) { map[namespaceDefinition] = []; } map[namespaceDefinition].push(attr.localName); prefixMap[attr.localName] = namespaceDefinition; } } return defaultNamespaceAttrValue; } function serializeDocumentType(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !PUBID_CHAR.test(node.publicId)) { throw new Error("Failed to serialize XML: document type node publicId is not well-formed."); } if ( requireWellFormed && (!XML_CHAR.test(node.systemId) || (node.systemId.includes('"') && node.systemId.includes("'"))) ) { throw new Error("Failed to serialize XML: document type node systemId is not well-formed."); } let markup = `<!DOCTYPE ${node.name}`; if (node.publicId !== "") { markup += ` PUBLIC "${node.publicId}"`; } else if (node.systemId !== "") { markup += " SYSTEM"; } if (node.systemId !== "") { markup += ` "${node.systemId}"`; } return `${markup}>`; } function serializeProcessingInstruction( node, namespace, prefixMap, requireWellFormed ) { if ( requireWellFormed && (node.target.includes(":") || asciiCaseInsensitiveMatch(node.target, "xml")) ) { throw new Error("Failed to serialize XML: processing instruction node target is not well-formed."); } if ( requireWellFormed && (!XML_CHAR.test(node.data) || node.data.includes("?>")) ) { throw new Error("Failed to serialize XML: processing instruction node data is not well-formed."); } return `<?${node.target} ${node.data}?>`; } function serializeDocument( node, namespace, prefixMap, requireWellFormed, refs ) { if (requireWellFormed && node.documentElement === null) { throw new Error("Failed to serialize XML: document does not have a document element."); } let serializedDocument = ""; for (const child of node.childNodes) { serializedDocument += xmlSerialization( child, namespace, prefixMap, requireWellFormed, refs ); } return serializedDocument; } function serializeDocumentFragment( node, namespace, prefixMap, requireWellFormed, refs ) { let markup = ""; for (const child of node.childNodes) { markup += xmlSerialization( child, namespace, prefixMap, requireWellFormed, refs ); } return markup; } function serializeText(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !XML_CHAR.test(node.data)) { throw new Error("Failed to serialize XML: text node data is not well-formed."); } return node.data .replace(/&/ug, "&amp;") .replace(/</ug, "&lt;") .replace(/>/ug, "&gt;"); } function serializeComment(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !XML_CHAR.test(node.data)) { throw new Error("Failed to serialize XML: comment node data is not well-formed."); } if ( requireWellFormed && (node.data.includes("--") || node.data.endsWith("-")) ) { throw new Error("Failed to serialize XML: found hyphens in illegal places in comment node data."); } return `<!--${node.data}-->`; } function serializeElement(node, namespace, prefixMap, requireWellFormed, refs) { if ( requireWellFormed && (node.localName.includes(":") || !xnv.name(node.localName)) ) { throw new Error("Failed to serialize XML: element node localName is not a valid XML name."); } let markup = "<"; let qualifiedName = ""; let skipEndTag = false; let ignoreNamespaceDefinitionAttr = false; const map = { ...prefixMap }; const localPrefixesMap = Object.create(null); const localDefaultNamespace = recordNamespaceInformation( node, map, localPrefixesMap ); let inheritedNs = namespace; const ns = node.namespaceURI; if (inheritedNs === ns) { if (localDefaultNamespace !== null) { ignoreNamespaceDefinitionAttr = true; } if (ns === NAMESPACES.XML) { qualifiedName = `xml:${node.localName}`; } else { qualifiedName = node.localName; } markup += qualifiedName; } else { let { prefix } = node; let candidatePrefix = attributeUtils.preferredPrefixString(map, ns, prefix); if (prefix === "xmlns") { if (requireWellFormed) { throw new Error("Failed to serialize XML: element nodes can't have a prefix of \"xmlns\"."); } candidatePrefix = "xmlns"; } if (candidatePrefix !== null) { qualifiedName = `${candidatePrefix}:${node.localName}`; if ( localDefaultNamespace !== null && localDefaultNamespace !== NAMESPACES.XML ) { inheritedNs = localDefaultNamespace === "" ? null : localDefaultNamespace; } markup += qualifiedName; } else if (prefix !== null) { if (prefix in localPrefixesMap) { prefix = attributeUtils.generatePrefix(map, ns, refs.prefixIndex++); } if (map[ns]) { map[ns].push(prefix); } else { map[ns] = [prefix]; } qualifiedName = `${prefix}:${node.localName}`; markup += `${qualifiedName} xmlns:${prefix}="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`; if (localDefaultNamespace !== null) { inheritedNs = localDefaultNamespace === "" ? null : localDefaultNamespace; } } else if (localDefaultNamespace === null || localDefaultNamespace !== ns) { ignoreNamespaceDefinitionAttr = true; qualifiedName = node.localName; inheritedNs = ns; markup += `${qualifiedName} xmlns="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`; } else { qualifiedName = node.localName; inheritedNs = ns; markup += qualifiedName; } } markup += attributeUtils.serializeAttributes( node, map, localPrefixesMap, ignoreNamespaceDefinitionAttr, requireWellFormed, refs ); if ( ns === NAMESPACES.HTML && node.childNodes.length === 0 && VOID_ELEMENTS.has(node.localName) ) { markup += " /"; skipEndTag = true; } else if (ns !== NAMESPACES.HTML && node.childNodes.length === 0) { markup += "/"; skipEndTag = true; } markup += ">"; if (skipEndTag) { return markup; } if (ns === NAMESPACES.HTML && node.localName === "template") { markup += xmlSerialization( node.content, inheritedNs, map, requireWellFormed, refs ); } else { for (const child of node.childNodes) { markup += xmlSerialization( child, inheritedNs, map, requireWellFormed, refs ); } } markup += `</${qualifiedName}>`; return markup; } function serializeCDATASection(node) { return `<![CDATA[${node.data}]]>`; } /** * @param {{prefixIndex: number}} refs */ function xmlSerialization(node, namespace, prefixMap, requireWellFormed, refs) { switch (node.nodeType) { case NODE_TYPES.ELEMENT_NODE: return serializeElement( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.DOCUMENT_NODE: return serializeDocument( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.COMMENT_NODE: return serializeComment(node, namespace, prefixMap, requireWellFormed); case NODE_TYPES.TEXT_NODE: return serializeText(node, namespace, prefixMap, requireWellFormed); case NODE_TYPES.DOCUMENT_FRAGMENT_NODE: return serializeDocumentFragment( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.DOCUMENT_TYPE_NODE: return serializeDocumentType( node, namespace, prefixMap, requireWellFormed ); case NODE_TYPES.PROCESSING_INSTRUCTION_NODE: return serializeProcessingInstruction( node, namespace, prefixMap, requireWellFormed ); case NODE_TYPES.ATTRIBUTE_NODE: return ""; case NODE_TYPES.CDATA_SECTION_NODE: return serializeCDATASection(node); default: throw new TypeError("Failed to serialize XML: only Nodes can be serialized."); } } var serialize = (root, { requireWellFormed = false } = {}) => { const namespacePrefixMap = Object.create(null); namespacePrefixMap["http://www.w3.org/XML/1998/namespace"] = ["xml"]; return xmlSerialization(root, null, namespacePrefixMap, requireWellFormed, { prefixIndex: 1 }); }; var serialize$1 = /*@__PURE__*/getDefaultExportFromCjs(serialize); export { serialize$1 as default };
import require$$0 from 'xml-name-validator'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var attributes = {}; var constants = {}; // FILE: lib/constants.js constants.NAMESPACES = { HTML: "http://www.w3.org/1999/xhtml", XML: "http://www.w3.org/XML/1998/namespace", XMLNS: "http://www.w3.org/2000/xmlns/" }; constants.NODE_TYPES = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, // historical TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5, // historical ENTITY_NODE: 6, // historical PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12 // historical }; constants.VOID_ELEMENTS = new Set([ "area", "base", "basefont", "bgsound", "br", "col", "embed", "frame", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr" ]); // FILE: lib/attributes.js const xnv$1 = require$$0; const { NAMESPACES: NAMESPACES$1 } = constants; function generatePrefix(map, newNamespace, prefixIndex) { const generatedPrefix = `ns${prefixIndex}`; map[newNamespace] = [generatedPrefix]; return generatedPrefix; } function preferredPrefixString(map, ns, preferredPrefix) { const candidateList = map[ns]; if (!candidateList) { return null; } if (candidateList.includes(preferredPrefix)) { return preferredPrefix; } return candidateList[candidateList.length - 1]; } function serializeAttributeValue(value/* , requireWellFormed*/) { if (value === null) { return ""; } // TODO: Check well-formedness return value .replace(/&/ug, "&amp;") .replace(/"/ug, "&quot;") .replace(/</ug, "&lt;") .replace(/>/ug, "&gt;") .replace(/\t/ug, "&#x9;") .replace(/\n/ug, "&#xA;") .replace(/\r/ug, "&#xD;"); } function serializeAttributes( element, map, localPrefixes, ignoreNamespaceDefAttr, requireWellFormed, refs ) { let result = ""; const namespaceLocalnames = Object.create(null); for (const attr of element.attributes) { if ( requireWellFormed && namespaceLocalnames[attr.namespaceURI] && namespaceLocalnames[attr.namespaceURI].has(attr.localName) ) { throw new Error("Found duplicated attribute"); } if (!namespaceLocalnames[attr.namespaceURI]) { namespaceLocalnames[attr.namespaceURI] = new Set(); } namespaceLocalnames[attr.namespaceURI].add(attr.localName); const attributeNamespace = attr.namespaceURI; let candidatePrefix = null; if (attributeNamespace !== null) { candidatePrefix = preferredPrefixString( map, attributeNamespace, attr.prefix ); if (attributeNamespace === NAMESPACES$1.XMLNS) { if ( attr.value === NAMESPACES$1.XML || (attr.prefix === null && ignoreNamespaceDefAttr) || (attr.prefix !== null && localPrefixes[attr.localName] !== attr.value && map[attr.value].includes(attr.localName)) ) { continue; } if (requireWellFormed && attr.value === NAMESPACES$1.XMLNS) { throw new Error( "The XMLNS namespace is reserved and cannot be applied as an element's namespace via XML parsing" ); } if (requireWellFormed && attr.value === "") { throw new Error( "Namespace prefix declarations cannot be used to undeclare a namespace" ); } if (attr.prefix === "xmlns") { candidatePrefix = "xmlns"; } } else if (candidatePrefix === null) { candidatePrefix = generatePrefix( map, attributeNamespace, refs.prefixIndex++ ); result += ` xmlns:${candidatePrefix}="${serializeAttributeValue( attributeNamespace)}"`; } } result += " "; if (candidatePrefix !== null) { result += `${candidatePrefix}:`; } if ( requireWellFormed && (attr.localName.includes(":") || !xnv$1.name(attr.localName) || (attr.localName === "xmlns" && attributeNamespace === null)) ) { throw new Error("Invalid attribute localName value"); } result += `${attr.localName}="${serializeAttributeValue(attr.value)}"`; } return result; } attributes.preferredPrefixString = preferredPrefixString; attributes.generatePrefix = generatePrefix; attributes.serializeAttributeValue = serializeAttributeValue; attributes.serializeAttributes = serializeAttributes; // FILE: lib/serialize.js const xnv = require$$0; const attributeUtils = attributes; const { NAMESPACES, VOID_ELEMENTS, NODE_TYPES } = constants; const XML_CHAR = /^(\x09|\x0A|\x0D|[\x20-\uD7FF]|[\uE000-\uFFFD]|(?:[\uD800-\uDBFF][\uDC00-\uDFFF]))*$/u; const PUBID_CHAR = /^(\x20|\x0D|\x0A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/u; function asciiCaseInsensitiveMatch(a, b) { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; ++i) { if ((a.charCodeAt(i) | 32) !== (b.charCodeAt(i) | 32)) { return false; } } return true; } function recordNamespaceInformation(element, map, prefixMap) { let defaultNamespaceAttrValue = null; for (let i = 0; i < element.attributes.length; ++i) { const attr = element.attributes[i]; if (attr.namespaceURI === NAMESPACES.XMLNS) { if (attr.prefix === null) { defaultNamespaceAttrValue = attr.value; continue; } let namespaceDefinition = attr.value; if (namespaceDefinition === NAMESPACES.XML) { continue; } // This is exactly the other way than the spec says, but that's intended. // All the maps coalesce null to the empty string (explained in the // spec), so instead of doing that every time, just do it once here. if (namespaceDefinition === null) { namespaceDefinition = ""; } if ( namespaceDefinition in map && map[namespaceDefinition].includes(attr.localName) ) { continue; } if (!(namespaceDefinition in map)) { map[namespaceDefinition] = []; } map[namespaceDefinition].push(attr.localName); prefixMap[attr.localName] = namespaceDefinition; } } return defaultNamespaceAttrValue; } function serializeDocumentType(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !PUBID_CHAR.test(node.publicId)) { throw new Error("Failed to serialize XML: document type node publicId is not well-formed."); } if ( requireWellFormed && (!XML_CHAR.test(node.systemId) || (node.systemId.includes('"') && node.systemId.includes("'"))) ) { throw new Error("Failed to serialize XML: document type node systemId is not well-formed."); } let markup = `<!DOCTYPE ${node.name}`; if (node.publicId !== "") { markup += ` PUBLIC "${node.publicId}"`; } else if (node.systemId !== "") { markup += " SYSTEM"; } if (node.systemId !== "") { markup += ` "${node.systemId}"`; } return `${markup}>`; } function serializeProcessingInstruction( node, namespace, prefixMap, requireWellFormed ) { if ( requireWellFormed && (node.target.includes(":") || asciiCaseInsensitiveMatch(node.target, "xml")) ) { throw new Error("Failed to serialize XML: processing instruction node target is not well-formed."); } if ( requireWellFormed && (!XML_CHAR.test(node.data) || node.data.includes("?>")) ) { throw new Error("Failed to serialize XML: processing instruction node data is not well-formed."); } return `<?${node.target} ${node.data}?>`; } function serializeDocument( node, namespace, prefixMap, requireWellFormed, refs ) { if (requireWellFormed && node.documentElement === null) { throw new Error("Failed to serialize XML: document does not have a document element."); } let serializedDocument = ""; for (const child of node.childNodes) { serializedDocument += xmlSerialization( child, namespace, prefixMap, requireWellFormed, refs ); } return serializedDocument; } function serializeDocumentFragment( node, namespace, prefixMap, requireWellFormed, refs ) { let markup = ""; for (const child of node.childNodes) { markup += xmlSerialization( child, namespace, prefixMap, requireWellFormed, refs ); } return markup; } function serializeText(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !XML_CHAR.test(node.data)) { throw new Error("Failed to serialize XML: text node data is not well-formed."); } return node.data .replace(/&/ug, "&amp;") .replace(/</ug, "&lt;") .replace(/>/ug, "&gt;"); } function serializeComment(node, namespace, prefixMap, requireWellFormed) { if (requireWellFormed && !XML_CHAR.test(node.data)) { throw new Error("Failed to serialize XML: comment node data is not well-formed."); } if ( requireWellFormed && (node.data.includes("--") || node.data.endsWith("-")) ) { throw new Error("Failed to serialize XML: found hyphens in illegal places in comment node data."); } return `<!--${node.data}-->`; } function serializeElement(node, namespace, prefixMap, requireWellFormed, refs) { if ( requireWellFormed && (node.localName.includes(":") || !xnv.name(node.localName)) ) { throw new Error("Failed to serialize XML: element node localName is not a valid XML name."); } let markup = "<"; let qualifiedName = ""; let skipEndTag = false; let ignoreNamespaceDefinitionAttr = false; const map = { ...prefixMap }; const localPrefixesMap = Object.create(null); const localDefaultNamespace = recordNamespaceInformation( node, map, localPrefixesMap ); let inheritedNs = namespace; const ns = node.namespaceURI; if (inheritedNs === ns) { if (localDefaultNamespace !== null) { ignoreNamespaceDefinitionAttr = true; } if (ns === NAMESPACES.XML) { qualifiedName = `xml:${node.localName}`; } else { qualifiedName = node.localName; } markup += qualifiedName; } else { let { prefix } = node; let candidatePrefix = attributeUtils.preferredPrefixString(map, ns, prefix); if (prefix === "xmlns") { if (requireWellFormed) { throw new Error("Failed to serialize XML: element nodes can't have a prefix of \"xmlns\"."); } candidatePrefix = "xmlns"; } if (candidatePrefix !== null) { qualifiedName = `${candidatePrefix}:${node.localName}`; if ( localDefaultNamespace !== null && localDefaultNamespace !== NAMESPACES.XML ) { inheritedNs = localDefaultNamespace === "" ? null : localDefaultNamespace; } markup += qualifiedName; } else if (prefix !== null) { if (prefix in localPrefixesMap) { prefix = attributeUtils.generatePrefix(map, ns, refs.prefixIndex++); } if (map[ns]) { map[ns].push(prefix); } else { map[ns] = [prefix]; } qualifiedName = `${prefix}:${node.localName}`; markup += `${qualifiedName} xmlns:${prefix}="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`; if (localDefaultNamespace !== null) { inheritedNs = localDefaultNamespace === "" ? null : localDefaultNamespace; } } else if (localDefaultNamespace === null || localDefaultNamespace !== ns) { ignoreNamespaceDefinitionAttr = true; qualifiedName = node.localName; inheritedNs = ns; markup += `${qualifiedName} xmlns="${attributeUtils.serializeAttributeValue(ns, requireWellFormed)}"`; } else { qualifiedName = node.localName; inheritedNs = ns; markup += qualifiedName; } } markup += attributeUtils.serializeAttributes( node, map, localPrefixesMap, ignoreNamespaceDefinitionAttr, requireWellFormed, refs ); if ( ns === NAMESPACES.HTML && node.childNodes.length === 0 && VOID_ELEMENTS.has(node.localName) ) { markup += " /"; skipEndTag = true; } else if (ns !== NAMESPACES.HTML && node.childNodes.length === 0) { markup += "/"; skipEndTag = true; } markup += ">"; if (skipEndTag) { return markup; } if (ns === NAMESPACES.HTML && node.localName === "template") { markup += xmlSerialization( node.content, inheritedNs, map, requireWellFormed, refs ); } else { for (const child of node.childNodes) { markup += xmlSerialization( child, inheritedNs, map, requireWellFormed, refs ); } } markup += `</${qualifiedName}>`; return markup; } function serializeCDATASection(node) { return `<![CDATA[${node.data}]]>`; } /** * @param {{prefixIndex: number}} refs */ function xmlSerialization(node, namespace, prefixMap, requireWellFormed, refs) { switch (node.nodeType) { case NODE_TYPES.ELEMENT_NODE: return serializeElement( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.DOCUMENT_NODE: return serializeDocument( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.COMMENT_NODE: return serializeComment(node, namespace, prefixMap, requireWellFormed); case NODE_TYPES.TEXT_NODE: return serializeText(node, namespace, prefixMap, requireWellFormed); case NODE_TYPES.DOCUMENT_FRAGMENT_NODE: return serializeDocumentFragment( node, namespace, prefixMap, requireWellFormed, refs ); case NODE_TYPES.DOCUMENT_TYPE_NODE: return serializeDocumentType( node, namespace, prefixMap, requireWellFormed ); case NODE_TYPES.PROCESSING_INSTRUCTION_NODE: return serializeProcessingInstruction( node, namespace, prefixMap, requireWellFormed ); case NODE_TYPES.ATTRIBUTE_NODE: return ""; case NODE_TYPES.CDATA_SECTION_NODE: return serializeCDATASection(node); default: throw new TypeError("Failed to serialize XML: only Nodes can be serialized."); } } var serialize = (root, { requireWellFormed = false } = {}) => { const namespacePrefixMap = Object.create(null); namespacePrefixMap["http://www.w3.org/XML/1998/namespace"] = ["xml"]; return xmlSerialization(root, null, namespacePrefixMap, requireWellFormed, { prefixIndex: 1 }); }; var serialize$1 = /*@__PURE__*/getDefaultExportFromCjs(serialize); export { serialize$1 as default };
494
17
0
58
37
0
16
0
0
0
0
22.352941
3,896
false
to-regex-range
top1k-typed-with-typed-deps
6,712
import require$$0 from 'is-number'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /*! * to-regex-range <https://github.com/micromatch/to-regex-range> * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber = require$$0; const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange; var index = /*@__PURE__*/getDefaultExportFromCjs(toRegexRange_1); export { index as default };
import require$$0 from 'is-number'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /*! * to-regex-range <https://github.com/micromatch/to-regex-range> * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber = require$$0; const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange; var index = /*@__PURE__*/getDefaultExportFromCjs(toRegexRange_1); export { index as default };
210
18
0
41
47
0
14
0
0
0
1
9.611111
2,152
false
regjsgen
top1k-untyped-nodeps
12,086
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var regjsgen$1 = {exports: {}}; // FILE: regjsgen.js /*! * regjsgen 0.5.2 * Copyright 2014-2020 Benjamin Tan <https://ofcr.se/> * Available under the MIT license <https://github.com/bnjmnt4n/regjsgen/blob/master/LICENSE-MIT.txt> */ regjsgen$1.exports; (function (module, exports) { (function() { // Used to determine if values are of the language type `Object`. var objectTypes = { 'function': true, 'object': true }; // Used as a reference to the global object. var root = (objectTypes[typeof window] && window) || this; // Detect free variable `exports`. var freeExports = exports && !exports.nodeType && exports; // Detect free variable `module`. var hasFreeModule = module && !module.nodeType; // Detect free variable `global` from Node.js or Browserified code and use it as `root`. var freeGlobal = freeExports && hasFreeModule && typeof commonjsGlobal == 'object' && commonjsGlobal; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { root = freeGlobal; } // Used to check objects for own properties. var hasOwnProperty = Object.prototype.hasOwnProperty; /*--------------------------------------------------------------------------*/ // Generates a string based on the given code point. // Based on https://mths.be/fromcodepoint by @mathias. function fromCodePoint() { var codePoint = Number(arguments[0]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point Math.floor(codePoint) != codePoint // not an integer ) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { // BMP code point return String.fromCharCode(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; var highSurrogate = (codePoint >> 10) + 0xD800; var lowSurrogate = (codePoint % 0x400) + 0xDC00; return String.fromCharCode(highSurrogate, lowSurrogate); } } /*--------------------------------------------------------------------------*/ // Ensures that nodes have the correct types. var assertTypeRegexMap = {}; function assertType(type, expected) { if (expected.indexOf('|') == -1) { if (type == expected) { return; } throw Error('Invalid node type: ' + type + '; expected type: ' + expected); } expected = hasOwnProperty.call(assertTypeRegexMap, expected) ? assertTypeRegexMap[expected] : (assertTypeRegexMap[expected] = RegExp('^(?:' + expected + ')$')); if (expected.test(type)) { return; } throw Error('Invalid node type: ' + type + '; expected types: ' + expected); } /*--------------------------------------------------------------------------*/ // Generates a regular expression string based on an AST. function generate(node) { var type = node.type; if (hasOwnProperty.call(generators, type)) { return generators[type](node); } throw Error('Invalid node type: ' + type); } // Constructs a string by concatentating the output of each term. function generateSequence(generator, terms, /* optional */ separator) { var i = -1, length = terms.length, result = '', term; while (++i < length) { term = terms[i]; if (separator && i > 0) result += separator; // Ensure that `\0` null escapes followed by number symbols are not // treated as backreferences. if ( i + 1 < length && terms[i].type == 'value' && terms[i].kind == 'null' && terms[i + 1].type == 'value' && terms[i + 1].kind == 'symbol' && terms[i + 1].codePoint >= 48 && terms[i + 1].codePoint <= 57 ) { result += '\\000'; continue; } result += generator(term); } return result; } /*--------------------------------------------------------------------------*/ function generateAlternative(node) { assertType(node.type, 'alternative'); return generateSequence(generateTerm, node.body); } function generateAnchor(node) { assertType(node.type, 'anchor'); switch (node.kind) { case 'start': return '^'; case 'end': return '$'; case 'boundary': return '\\b'; case 'not-boundary': return '\\B'; default: throw Error('Invalid assertion'); } } var atomType = 'anchor|characterClass|characterClassEscape|dot|group|reference|unicodePropertyEscape|value'; function generateAtom(node) { assertType(node.type, atomType); return generate(node); } function generateCharacterClass(node) { assertType(node.type, 'characterClass'); var kind = node.kind; var separator = kind === 'intersection' ? '&&' : kind === 'subtraction' ? '--' : ''; return '[' + (node.negative ? '^' : '') + generateSequence(generateClassAtom, node.body, separator) + ']'; } function generateCharacterClassEscape(node) { assertType(node.type, 'characterClassEscape'); return '\\' + node.value; } function generateCharacterClassRange(node) { assertType(node.type, 'characterClassRange'); var min = node.min, max = node.max; if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { throw Error('Invalid character class range'); } return generateClassAtom(min) + '-' + generateClassAtom(max); } function generateClassAtom(node) { assertType(node.type, 'anchor|characterClass|characterClassEscape|characterClassRange|dot|value|unicodePropertyEscape|classStrings'); return generate(node); } function generateClassStrings(node) { assertType(node.type, 'classStrings'); return '\\q{' + generateSequence(generateClassString, node.strings, '|') + '}'; } function generateClassString(node) { assertType(node.type, 'classString'); return generateSequence(generate, node.characters); } function generateDisjunction(node) { assertType(node.type, 'disjunction'); return generateSequence(generate, node.body, '|'); } function generateDot(node) { assertType(node.type, 'dot'); return '.'; } function generateGroup(node) { assertType(node.type, 'group'); var result = ''; switch (node.behavior) { case 'normal': if (node.name) { result += '?<' + generateIdentifier(node.name) + '>'; } break; case 'ignore': result += '?:'; break; case 'lookahead': result += '?='; break; case 'negativeLookahead': result += '?!'; break; case 'lookbehind': result += '?<='; break; case 'negativeLookbehind': result += '?<!'; break; default: throw Error('Invalid behaviour: ' + node.behaviour); } result += generateSequence(generate, node.body); return '(' + result + ')'; } function generateIdentifier(node) { assertType(node.type, 'identifier'); return node.value; } function generateQuantifier(node) { assertType(node.type, 'quantifier'); var quantifier = '', min = node.min, max = node.max; if (max == null) { if (min == 0) { quantifier = '*'; } else if (min == 1) { quantifier = '+'; } else { quantifier = '{' + min + ',}'; } } else if (min == max) { quantifier = '{' + min + '}'; } else if (min == 0 && max == 1) { quantifier = '?'; } else { quantifier = '{' + min + ',' + max + '}'; } if (!node.greedy) { quantifier += '?'; } return generateAtom(node.body[0]) + quantifier; } function generateReference(node) { assertType(node.type, 'reference'); if (node.matchIndex) { return '\\' + node.matchIndex; } if (node.name) { return '\\k<' + generateIdentifier(node.name) + '>'; } throw new Error('Unknown reference type'); } function generateTerm(node) { assertType(node.type, atomType + '|empty|quantifier'); return generate(node); } function generateUnicodePropertyEscape(node) { assertType(node.type, 'unicodePropertyEscape'); return '\\' + (node.negative ? 'P' : 'p') + '{' + node.value + '}'; } function generateValue(node) { assertType(node.type, 'value'); var kind = node.kind, codePoint = node.codePoint; if (typeof codePoint != 'number') { throw new Error('Invalid code point: ' + codePoint); } switch (kind) { case 'controlLetter': return '\\c' + fromCodePoint(codePoint + 64); case 'hexadecimalEscape': return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); case 'identifier': return '\\' + fromCodePoint(codePoint); case 'null': return '\\' + codePoint; case 'octal': return '\\' + ('000' + codePoint.toString(8)).slice(-3); case 'singleEscape': switch (codePoint) { case 0x0008: return '\\b'; case 0x0009: return '\\t'; case 0x000A: return '\\n'; case 0x000B: return '\\v'; case 0x000C: return '\\f'; case 0x000D: return '\\r'; case 0x002D: return '\\-'; default: throw Error('Invalid code point: ' + codePoint); } case 'symbol': return fromCodePoint(codePoint); case 'unicodeEscape': return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); case 'unicodeCodePointEscape': return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; default: throw Error('Unsupported node kind: ' + kind); } } /*--------------------------------------------------------------------------*/ // Used to generate strings for each node type. var generators = { 'alternative': generateAlternative, 'anchor': generateAnchor, 'characterClass': generateCharacterClass, 'characterClassEscape': generateCharacterClassEscape, 'characterClassRange': generateCharacterClassRange, 'classStrings': generateClassStrings, 'disjunction': generateDisjunction, 'dot': generateDot, 'group': generateGroup, 'quantifier': generateQuantifier, 'reference': generateReference, 'unicodePropertyEscape': generateUnicodePropertyEscape, 'value': generateValue }; /*--------------------------------------------------------------------------*/ // Export regjsgen. var regjsgen = { 'generate': generate }; // Some AMD build optimizers, like r.js, check for condition patterns like the following: if (freeExports && hasFreeModule) { // Export for CommonJS support. freeExports.generate = generate; } else { // Export to the global object. root.regjsgen = regjsgen; } }.call(commonjsGlobal)); } (regjsgen$1, regjsgen$1.exports)); var regjsgenExports = regjsgen$1.exports; var regjsgen = /*@__PURE__*/getDefaultExportFromCjs(regjsgenExports); export { regjsgen as default };
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var regjsgen$1 = {exports: {}}; // FILE: regjsgen.js /*! * regjsgen 0.5.2 * Copyright 2014-2020 Benjamin Tan <https://ofcr.se/> * Available under the MIT license <https://github.com/bnjmnt4n/regjsgen/blob/master/LICENSE-MIT.txt> */ regjsgen$1.exports; (function (module, exports) { (function() { // Used to determine if values are of the language type `Object`. var objectTypes = { 'function': true, 'object': true }; // Used as a reference to the global object. var root = (objectTypes[typeof window] && window) || this; // Detect free variable `exports`. var freeExports = exports && !exports.nodeType && exports; // Detect free variable `module`. var hasFreeModule = module && !module.nodeType; // Detect free variable `global` from Node.js or Browserified code and use it as `root`. var freeGlobal = freeExports && hasFreeModule && typeof commonjsGlobal == 'object' && commonjsGlobal; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { root = freeGlobal; } // Used to check objects for own properties. var hasOwnProperty = Object.prototype.hasOwnProperty; /*--------------------------------------------------------------------------*/ // Generates a string based on the given code point. // Based on https://mths.be/fromcodepoint by @mathias. function fromCodePoint() { var codePoint = Number(arguments[0]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point Math.floor(codePoint) != codePoint // not an integer ) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { // BMP code point return String.fromCharCode(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; var highSurrogate = (codePoint >> 10) + 0xD800; var lowSurrogate = (codePoint % 0x400) + 0xDC00; return String.fromCharCode(highSurrogate, lowSurrogate); } } /*--------------------------------------------------------------------------*/ // Ensures that nodes have the correct types. var assertTypeRegexMap = {}; function assertType(type, expected) { if (expected.indexOf('|') == -1) { if (type == expected) { return; } throw Error('Invalid node type: ' + type + '; expected type: ' + expected); } expected = hasOwnProperty.call(assertTypeRegexMap, expected) ? assertTypeRegexMap[expected] : (assertTypeRegexMap[expected] = RegExp('^(?:' + expected + ')$')); if (expected.test(type)) { return; } throw Error('Invalid node type: ' + type + '; expected types: ' + expected); } /*--------------------------------------------------------------------------*/ // Generates a regular expression string based on an AST. function generate(node) { var type = node.type; if (hasOwnProperty.call(generators, type)) { return generators[type](node); } throw Error('Invalid node type: ' + type); } // Constructs a string by concatentating the output of each term. function generateSequence(generator, terms, /* optional */ separator) { var i = -1, length = terms.length, result = '', term; while (++i < length) { term = terms[i]; if (separator && i > 0) result += separator; // Ensure that `\0` null escapes followed by number symbols are not // treated as backreferences. if ( i + 1 < length && terms[i].type == 'value' && terms[i].kind == 'null' && terms[i + 1].type == 'value' && terms[i + 1].kind == 'symbol' && terms[i + 1].codePoint >= 48 && terms[i + 1].codePoint <= 57 ) { result += '\\000'; continue; } result += generator(term); } return result; } /*--------------------------------------------------------------------------*/ function generateAlternative(node) { assertType(node.type, 'alternative'); return generateSequence(generateTerm, node.body); } function generateAnchor(node) { assertType(node.type, 'anchor'); switch (node.kind) { case 'start': return '^'; case 'end': return '$'; case 'boundary': return '\\b'; case 'not-boundary': return '\\B'; default: throw Error('Invalid assertion'); } } var atomType = 'anchor|characterClass|characterClassEscape|dot|group|reference|unicodePropertyEscape|value'; function generateAtom(node) { assertType(node.type, atomType); return generate(node); } function generateCharacterClass(node) { assertType(node.type, 'characterClass'); var kind = node.kind; var separator = kind === 'intersection' ? '&&' : kind === 'subtraction' ? '--' : ''; return '[' + (node.negative ? '^' : '') + generateSequence(generateClassAtom, node.body, separator) + ']'; } function generateCharacterClassEscape(node) { assertType(node.type, 'characterClassEscape'); return '\\' + node.value; } function generateCharacterClassRange(node) { assertType(node.type, 'characterClassRange'); var min = node.min, max = node.max; if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { throw Error('Invalid character class range'); } return generateClassAtom(min) + '-' + generateClassAtom(max); } function generateClassAtom(node) { assertType(node.type, 'anchor|characterClass|characterClassEscape|characterClassRange|dot|value|unicodePropertyEscape|classStrings'); return generate(node); } function generateClassStrings(node) { assertType(node.type, 'classStrings'); return '\\q{' + generateSequence(generateClassString, node.strings, '|') + '}'; } function generateClassString(node) { assertType(node.type, 'classString'); return generateSequence(generate, node.characters); } function generateDisjunction(node) { assertType(node.type, 'disjunction'); return generateSequence(generate, node.body, '|'); } function generateDot(node) { assertType(node.type, 'dot'); return '.'; } function generateGroup(node) { assertType(node.type, 'group'); var result = ''; switch (node.behavior) { case 'normal': if (node.name) { result += '?<' + generateIdentifier(node.name) + '>'; } break; case 'ignore': result += '?:'; break; case 'lookahead': result += '?='; break; case 'negativeLookahead': result += '?!'; break; case 'lookbehind': result += '?<='; break; case 'negativeLookbehind': result += '?<!'; break; default: throw Error('Invalid behaviour: ' + node.behaviour); } result += generateSequence(generate, node.body); return '(' + result + ')'; } function generateIdentifier(node) { assertType(node.type, 'identifier'); return node.value; } function generateQuantifier(node) { assertType(node.type, 'quantifier'); var quantifier = '', min = node.min, max = node.max; if (max == null) { if (min == 0) { quantifier = '*'; } else if (min == 1) { quantifier = '+'; } else { quantifier = '{' + min + ',}'; } } else if (min == max) { quantifier = '{' + min + '}'; } else if (min == 0 && max == 1) { quantifier = '?'; } else { quantifier = '{' + min + ',' + max + '}'; } if (!node.greedy) { quantifier += '?'; } return generateAtom(node.body[0]) + quantifier; } function generateReference(node) { assertType(node.type, 'reference'); if (node.matchIndex) { return '\\' + node.matchIndex; } if (node.name) { return '\\k<' + generateIdentifier(node.name) + '>'; } throw new Error('Unknown reference type'); } function generateTerm(node) { assertType(node.type, atomType + '|empty|quantifier'); return generate(node); } function generateUnicodePropertyEscape(node) { assertType(node.type, 'unicodePropertyEscape'); return '\\' + (node.negative ? 'P' : 'p') + '{' + node.value + '}'; } function generateValue(node) { assertType(node.type, 'value'); var kind = node.kind, codePoint = node.codePoint; if (typeof codePoint != 'number') { throw new Error('Invalid code point: ' + codePoint); } switch (kind) { case 'controlLetter': return '\\c' + fromCodePoint(codePoint + 64); case 'hexadecimalEscape': return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); case 'identifier': return '\\' + fromCodePoint(codePoint); case 'null': return '\\' + codePoint; case 'octal': return '\\' + ('000' + codePoint.toString(8)).slice(-3); case 'singleEscape': switch (codePoint) { case 0x0008: return '\\b'; case 0x0009: return '\\t'; case 0x000A: return '\\n'; case 0x000B: return '\\v'; case 0x000C: return '\\f'; case 0x000D: return '\\r'; case 0x002D: return '\\-'; default: throw Error('Invalid code point: ' + codePoint); } case 'symbol': return fromCodePoint(codePoint); case 'unicodeEscape': return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); case 'unicodeCodePointEscape': return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; default: throw Error('Unsupported node kind: ' + kind); } } /*--------------------------------------------------------------------------*/ // Used to generate strings for each node type. var generators = { 'alternative': generateAlternative, 'anchor': generateAnchor, 'characterClass': generateCharacterClass, 'characterClassEscape': generateCharacterClassEscape, 'characterClassRange': generateCharacterClassRange, 'classStrings': generateClassStrings, 'disjunction': generateDisjunction, 'dot': generateDot, 'group': generateGroup, 'quantifier': generateQuantifier, 'reference': generateReference, 'unicodePropertyEscape': generateUnicodePropertyEscape, 'value': generateValue }; /*--------------------------------------------------------------------------*/ // Export regjsgen. var regjsgen = { 'generate': generate }; // Some AMD build optimizers, like r.js, check for condition patterns like the following: if (freeExports && hasFreeModule) { // Export for CommonJS support. freeExports.generate = generate; } else { // Export to the global object. root.regjsgen = regjsgen; } }.call(commonjsGlobal)); } (regjsgen$1, regjsgen$1.exports)); var regjsgenExports = regjsgen$1.exports; var regjsgen = /*@__PURE__*/getDefaultExportFromCjs(regjsgenExports); export { regjsgen as default };
305
25
0
27
32
0
8
0
0
0
7
31.88
3,005
false
object-assign
top1k-typed-nodeps
2,350
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; var index = /*@__PURE__*/getDefaultExportFromCjs(objectAssign); export { index as default };
function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } // FILE: index.js /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; var index = /*@__PURE__*/getDefaultExportFromCjs(objectAssign); export { index as default };
69
6
0
6
15
0
3
0
0
0
0
9.666667
789
false