language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function carFactory(input) {
const cars = {};
const children = {};
const printQueue = [];
const factory = {
create: (name) => {
cars[name] = {};
},
set: (name, key, value) => {
cars[name][key] = value;
},
print: (name) => {
console.log(
Object.keys(cars[name]).map((key) => `${key}:${cars[name][key]}`).join(',')
)
}
}
for (const entry of input) {
const [operation, name, ...args] = entry.split(' ');
if (operation == 'print') {
printQueue.push(name);
continue;
}
if (args[0] == 'inherit') {
children[name] = args[1];
}
factory[operation](name, args[0], args[1]);
}
for (const child of Object.keys(children)) {
const parent = children[child];
Object.assign(cars[child], cars[parent]);
}
for (const printName of printQueue) {
factory.print(printName);
}
} | function carFactory(input) {
const cars = {};
const children = {};
const printQueue = [];
const factory = {
create: (name) => {
cars[name] = {};
},
set: (name, key, value) => {
cars[name][key] = value;
},
print: (name) => {
console.log(
Object.keys(cars[name]).map((key) => `${key}:${cars[name][key]}`).join(',')
)
}
}
for (const entry of input) {
const [operation, name, ...args] = entry.split(' ');
if (operation == 'print') {
printQueue.push(name);
continue;
}
if (args[0] == 'inherit') {
children[name] = args[1];
}
factory[operation](name, args[0], args[1]);
}
for (const child of Object.keys(children)) {
const parent = children[child];
Object.assign(cars[child], cars[parent]);
}
for (const printName of printQueue) {
factory.print(printName);
}
} |
JavaScript | function maybeBind ( model, value, shouldBind ) {
if ( shouldBind && isFunction( value ) && model.parent && model.parent.isRoot ) {
if ( !model.boundValue ) {
model.boundValue = bind$1( value._r_unbound || value, model.parent.ractive );
}
return model.boundValue;
}
return value;
} | function maybeBind ( model, value, shouldBind ) {
if ( shouldBind && isFunction( value ) && model.parent && model.parent.isRoot ) {
if ( !model.boundValue ) {
model.boundValue = bind$1( value._r_unbound || value, model.parent.ractive );
}
return model.boundValue;
}
return value;
} |
JavaScript | function rebindMatch ( template, next, previous, fragment ) {
var keypath = template.r || template;
// no valid keypath, go with next
if ( !keypath || !isString( keypath ) ) { return next; }
// completely contextual ref, go with next
if ( keypath === '.' || keypath[0] === '@' || ( next || previous ).isKey || ( next || previous ).isKeypath ) { return next; }
var parts = keypath.split( '/' );
var keys = splitKeypath( parts[ parts.length - 1 ] );
var last = keys[ keys.length - 1 ];
// check the keypath against the model keypath to see if it matches
var model = next || previous;
// check to see if this was an alias
if ( model && keys.length === 1 && last !== model.key && fragment ) {
keys = findAlias( last, fragment ) || keys;
}
var i = keys.length;
var match = true;
var shuffling = false;
while ( model && i-- ) {
if ( model.shuffling ) { shuffling = true; }
// non-strict comparison to account for indices in keypaths
if ( keys[i] != model.key ) { match = false; }
model = model.parent;
}
// next is undefined, but keypath is shuffling and previous matches
if ( !next && match && shuffling ) { return previous; }
// next is defined, but doesn't match the keypath
else if ( next && !match && shuffling ) { return previous; }
else { return next; }
} | function rebindMatch ( template, next, previous, fragment ) {
var keypath = template.r || template;
// no valid keypath, go with next
if ( !keypath || !isString( keypath ) ) { return next; }
// completely contextual ref, go with next
if ( keypath === '.' || keypath[0] === '@' || ( next || previous ).isKey || ( next || previous ).isKeypath ) { return next; }
var parts = keypath.split( '/' );
var keys = splitKeypath( parts[ parts.length - 1 ] );
var last = keys[ keys.length - 1 ];
// check the keypath against the model keypath to see if it matches
var model = next || previous;
// check to see if this was an alias
if ( model && keys.length === 1 && last !== model.key && fragment ) {
keys = findAlias( last, fragment ) || keys;
}
var i = keys.length;
var match = true;
var shuffling = false;
while ( model && i-- ) {
if ( model.shuffling ) { shuffling = true; }
// non-strict comparison to account for indices in keypaths
if ( keys[i] != model.key ) { match = false; }
model = model.parent;
}
// next is undefined, but keypath is shuffling and previous matches
if ( !next && match && shuffling ) { return previous; }
// next is defined, but doesn't match the keypath
else if ( next && !match && shuffling ) { return previous; }
else { return next; }
} |
JavaScript | function readKey ( parser ) {
var token;
if ( token = readStringLiteral( parser ) ) {
return identifier.test( token.v ) ? token.v : '"' + token.v.replace( /"/g, '\\"' ) + '"';
}
if ( token = readNumberLiteral( parser ) ) {
return token.v;
}
if ( token = parser.matchPattern( name ) ) {
return token;
}
return null;
} | function readKey ( parser ) {
var token;
if ( token = readStringLiteral( parser ) ) {
return identifier.test( token.v ) ? token.v : '"' + token.v.replace( /"/g, '\\"' ) + '"';
}
if ( token = readNumberLiteral( parser ) ) {
return token.v;
}
if ( token = parser.matchPattern( name ) ) {
return token;
}
return null;
} |
JavaScript | function isUsCounty(wofData) {
return 'US' === wofData.properties['iso:country'] &&
'county' === wofData.properties['wof:placetype'] &&
!_.isUndefined(wofData.properties['qs:a2_alt']);
} | function isUsCounty(wofData) {
return 'US' === wofData.properties['iso:country'] &&
'county' === wofData.properties['wof:placetype'] &&
!_.isUndefined(wofData.properties['qs:a2_alt']);
} |
JavaScript | function LocalPipService(datapath, layers) {
const self = this;
createPipService(datapath, _.defaultTo(layers, []), false, (err, service) => {
if (err) {
throw err;
}
self.pipService = service;
});
} | function LocalPipService(datapath, layers) {
const self = this;
createPipService(datapath, _.defaultTo(layers, []), false, (err, service) => {
if (err) {
throw err;
}
self.pipService = service;
});
} |
JavaScript | function readData(datapath, layer, localizedAdminNames, callback) {
const features = [];
readSqliteRecords(datapath,layer)
.pipe(whosonfirst.recordHasIdAndProperties())
.pipe(whosonfirst.isActiveRecord())
.pipe(filterOutPointRecords.create())
.pipe(filterOutHierarchylessNeighbourhoods.create())
.pipe(filterOutCitylessNeighbourhoods.create())
.pipe(extractFields.create(localizedAdminNames))
.pipe(simplifyGeometry.create())
.pipe(sink.obj((feature) => {
features.push(feature);
}))
.on('finish', function() {
callback(features);
});
} | function readData(datapath, layer, localizedAdminNames, callback) {
const features = [];
readSqliteRecords(datapath,layer)
.pipe(whosonfirst.recordHasIdAndProperties())
.pipe(whosonfirst.isActiveRecord())
.pipe(filterOutPointRecords.create())
.pipe(filterOutHierarchylessNeighbourhoods.create())
.pipe(filterOutCitylessNeighbourhoods.create())
.pipe(extractFields.create(localizedAdminNames))
.pipe(simplifyGeometry.create())
.pipe(sink.obj((feature) => {
features.push(feature);
}))
.on('finish', function() {
callback(features);
});
} |
JavaScript | function calculateLayers(inputLayers) {
const allowedLayers = [ 'neighbourhood', 'borough', 'locality', 'localadmin', 'county',
'macrocounty', 'region', 'macroregion', 'dependency', 'country' ];
// if no input layers are specified, return all of the allowed layers
if (!inputLayers) {
inputLayers = allowedLayers;
}
return _.intersection(allowedLayers, inputLayers);
} | function calculateLayers(inputLayers) {
const allowedLayers = [ 'neighbourhood', 'borough', 'locality', 'localadmin', 'county',
'macrocounty', 'region', 'macroregion', 'dependency', 'country' ];
// if no input layers are specified, return all of the allowed layers
if (!inputLayers) {
inputLayers = allowedLayers;
}
return _.intersection(allowedLayers, inputLayers);
} |
JavaScript | function q1(){
var favorite_passtime;
var favorite_passtime_correct_answer = 'y';
favorite_passtime = prompt('Do you think that rob obsessivly plays video games? Y or N');
console.log(favorite_passtime + ' y or n');
if(favorite_passtime === favorite_passtime_correct_answer){
alert('How could he not come on now');}
else{
alert('Well your wrong because gaming is life!');
}
} | function q1(){
var favorite_passtime;
var favorite_passtime_correct_answer = 'y';
favorite_passtime = prompt('Do you think that rob obsessivly plays video games? Y or N');
console.log(favorite_passtime + ' y or n');
if(favorite_passtime === favorite_passtime_correct_answer){
alert('How could he not come on now');}
else{
alert('Well your wrong because gaming is life!');
}
} |
JavaScript | _onNobleStateChange(state) {
Logger.debug(`Noble state changed to ${state}`);
if (state === 'poweredOn') {
Logger.info('Searching for drones...');
this.noble.startScanning();
}
} | _onNobleStateChange(state) {
Logger.debug(`Noble state changed to ${state}`);
if (state === 'poweredOn') {
Logger.info('Searching for drones...');
this.noble.startScanning();
}
} |
JavaScript | _onPeripheralDiscovery(peripheral) {
if (!this._validatePeripheral(peripheral)) {
return;
}
Logger.info(`Peripheral found ${peripheral.advertisement.localName}`);
this.noble.stopScanning();
peripheral.connect(error => {
if (error) {
throw error;
}
this._peripheral = peripheral;
this._setupPeripheral();
});
} | _onPeripheralDiscovery(peripheral) {
if (!this._validatePeripheral(peripheral)) {
return;
}
Logger.info(`Peripheral found ${peripheral.advertisement.localName}`);
this.noble.stopScanning();
peripheral.connect(error => {
if (error) {
throw error;
}
this._peripheral = peripheral;
this._setupPeripheral();
});
} |
JavaScript | _validatePeripheral(peripheral) {
if (!peripheral) {
return false;
}
const localName = peripheral.advertisement.localName;
const manufacturer = peripheral.advertisement.manufacturerData;
const matchesFilter = !this.droneFilter || localName === this.droneFilter;
const localNameMatch =
matchesFilter ||
DRONE_PREFIXES.some(
prefix => localName && localName.indexOf(prefix) >= 0
);
const manufacturerMatch =
manufacturer && MANUFACTURER_SERIALS.indexOf(manufacturer) >= 0;
// Is TRUE according to droneFilter or if empty, for EITHER an "RS_" name OR manufacturer code.
return localNameMatch || manufacturerMatch;
} | _validatePeripheral(peripheral) {
if (!peripheral) {
return false;
}
const localName = peripheral.advertisement.localName;
const manufacturer = peripheral.advertisement.manufacturerData;
const matchesFilter = !this.droneFilter || localName === this.droneFilter;
const localNameMatch =
matchesFilter ||
DRONE_PREFIXES.some(
prefix => localName && localName.indexOf(prefix) >= 0
);
const manufacturerMatch =
manufacturer && MANUFACTURER_SERIALS.indexOf(manufacturer) >= 0;
// Is TRUE according to droneFilter or if empty, for EITHER an "RS_" name OR manufacturer code.
return localNameMatch || manufacturerMatch;
} |
JavaScript | _setupPeripheral() {
this.peripheral.discoverAllServicesAndCharacteristics(
(err, services, characteristics) => {
if (err) {
throw err;
}
// @todo
// Parse characteristics and only store the ones needed
// also validate that they're also present
this.characteristics = characteristics;
Logger.debug('Preforming handshake');
for (const uuid of handshakeUuids) {
const target = this.getCharacteristic(uuid);
target.subscribe();
}
Logger.debug('Adding listeners');
for (const uuid of characteristicReceiveUuids.values()) {
const target = this.getCharacteristic(`fb${uuid}`);
target.subscribe();
target.on('data', data => this._handleIncoming(uuid, data));
}
Logger.info(
`Device connected ${this.peripheral.advertisement.localName}`
);
// Register some event handlers
/**
* Drone disconnected event
* Fired when the bluetooth connection has been disconnected
*
* @event DroneCommand#disconnected
*/
this.noble.on('disconnect', () => this.emit('disconnected'));
setTimeout(() => {
/**
* Drone connected event
* You can control the drone once this event has been triggered.
*
* @event DroneCommand#connected
*/
this.emit('connected');
}, 200);
}
);
} | _setupPeripheral() {
this.peripheral.discoverAllServicesAndCharacteristics(
(err, services, characteristics) => {
if (err) {
throw err;
}
// @todo
// Parse characteristics and only store the ones needed
// also validate that they're also present
this.characteristics = characteristics;
Logger.debug('Preforming handshake');
for (const uuid of handshakeUuids) {
const target = this.getCharacteristic(uuid);
target.subscribe();
}
Logger.debug('Adding listeners');
for (const uuid of characteristicReceiveUuids.values()) {
const target = this.getCharacteristic(`fb${uuid}`);
target.subscribe();
target.on('data', data => this._handleIncoming(uuid, data));
}
Logger.info(
`Device connected ${this.peripheral.advertisement.localName}`
);
// Register some event handlers
/**
* Drone disconnected event
* Fired when the bluetooth connection has been disconnected
*
* @event DroneCommand#disconnected
*/
this.noble.on('disconnect', () => this.emit('disconnected'));
setTimeout(() => {
/**
* Drone connected event
* You can control the drone once this event has been triggered.
*
* @event DroneCommand#connected
*/
this.emit('connected');
}, 200);
}
);
} |
JavaScript | runCommand(command) {
Logger.debug('SEND: ', command.toString());
const buffer = command.toBuffer();
const messageId = this._getStep(command.bufferType);
buffer.writeIntLE(messageId, 1);
// console.log(command.bufferType, 'type');
this.getCharacteristic(command.sendCharacteristicUuid).write(buffer, true);
} | runCommand(command) {
Logger.debug('SEND: ', command.toString());
const buffer = command.toBuffer();
const messageId = this._getStep(command.bufferType);
buffer.writeIntLE(messageId, 1);
// console.log(command.bufferType, 'type');
this.getCharacteristic(command.sendCharacteristicUuid).write(buffer, true);
} |
JavaScript | get sendCharacteristicUuid() {
const t = bufferCharTranslationMap[this.bufferType] || 'SEND_WITH_ACK';
return `fa${characteristicSendUuids[t]}`;
} | get sendCharacteristicUuid() {
const t = bufferCharTranslationMap[this.bufferType] || 'SEND_WITH_ACK';
return `fa${characteristicSendUuids[t]}`;
} |
JavaScript | toBuffer() {
const bufferLength =
6 + this.arguments.reduce((acc, val) => val.getValueSize() + acc, 0);
const buffer = new Buffer(bufferLength);
buffer.fill(0);
buffer.writeUInt16LE(this.bufferFlag, 0);
// Skip command counter (offset 1) because it's set in DroneConnection::runCommand
buffer.writeUInt16LE(this.projectId, 2);
buffer.writeUInt16LE(this.classId, 3);
buffer.writeUInt16LE(this.commandId, 4); // two bytes
let bufferOffset = 6;
for (const arg of this.arguments) {
const valueSize = arg.getValueSize();
switch (arg.type) {
case 'u8':
case 'u16':
case 'u32':
case 'u64':
buffer.writeUIntLE(Math.floor(arg.value), bufferOffset, valueSize);
break;
case 'i8':
case 'i16':
case 'i32':
case 'i64':
case 'enum':
buffer.writeIntLE(Math.floor(arg.value), bufferOffset, valueSize);
break;
case 'string':
buffer.write(arg.value, bufferOffset, valueSize, 'ascii');
break;
case 'float':
buffer.writeFloatLE(arg.value, bufferOffset);
break;
case 'double':
buffer.writeDoubleLE(arg.value, bufferOffset);
break;
default:
throw new TypeError(
`Can't encode buffer: unknown data type "${
arg.type
}" for argument "${arg.name}" in ${this.getToken()}`
);
}
bufferOffset += valueSize;
}
return buffer;
} | toBuffer() {
const bufferLength =
6 + this.arguments.reduce((acc, val) => val.getValueSize() + acc, 0);
const buffer = new Buffer(bufferLength);
buffer.fill(0);
buffer.writeUInt16LE(this.bufferFlag, 0);
// Skip command counter (offset 1) because it's set in DroneConnection::runCommand
buffer.writeUInt16LE(this.projectId, 2);
buffer.writeUInt16LE(this.classId, 3);
buffer.writeUInt16LE(this.commandId, 4); // two bytes
let bufferOffset = 6;
for (const arg of this.arguments) {
const valueSize = arg.getValueSize();
switch (arg.type) {
case 'u8':
case 'u16':
case 'u32':
case 'u64':
buffer.writeUIntLE(Math.floor(arg.value), bufferOffset, valueSize);
break;
case 'i8':
case 'i16':
case 'i32':
case 'i64':
case 'enum':
buffer.writeIntLE(Math.floor(arg.value), bufferOffset, valueSize);
break;
case 'string':
buffer.write(arg.value, bufferOffset, valueSize, 'ascii');
break;
case 'float':
buffer.writeFloatLE(arg.value, bufferOffset);
break;
case 'double':
buffer.writeDoubleLE(arg.value, bufferOffset);
break;
default:
throw new TypeError(
`Can't encode buffer: unknown data type "${
arg.type
}" for argument "${arg.name}" in ${this.getToken()}`
);
}
bufferOffset += valueSize;
}
return buffer;
} |
JavaScript | static async load(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
// It is important to await on _importDynamic to catch the error code.
return isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
}
catch (error) {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {
throw new module_load_error_1.ModuleLoadError(`${isESM ? 'import()' : 'require'} failed to load ${filePath || modulePath}`);
}
throw error;
}
} | static async load(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
// It is important to await on _importDynamic to catch the error code.
return isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
}
catch (error) {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {
throw new module_load_error_1.ModuleLoadError(`${isESM ? 'import()' : 'require'} failed to load ${filePath || modulePath}`);
}
throw error;
}
} |
JavaScript | static async loadWithData(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
const module = isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
return { isESM, module, filePath };
}
catch (error) {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {
throw new module_load_error_1.ModuleLoadError(`${isESM ? 'import()' : 'require'} failed to load ${filePath || modulePath}`);
}
throw error;
}
} | static async loadWithData(config, modulePath) {
let filePath;
let isESM;
try {
({ isESM, filePath } = ModuleLoader.resolvePath(config, modulePath));
const module = isESM ? await _importDynamic(url.pathToFileURL(filePath)) : require(filePath);
return { isESM, module, filePath };
}
catch (error) {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {
throw new module_load_error_1.ModuleLoadError(`${isESM ? 'import()' : 'require'} failed to load ${filePath || modulePath}`);
}
throw error;
}
} |
JavaScript | static resolvePath(config, modulePath) {
let isESM;
let filePath;
try {
filePath = require.resolve(modulePath);
isESM = ModuleLoader.isPathModule(filePath);
}
catch (error) {
filePath = ts_node_1.tsPath(config.root, modulePath);
// Try all supported extensions.
if (!fs.existsSync(filePath)) {
for (const extension of s_EXTENSIONS) {
const testPath = `${filePath}${extension}`;
if (fs.existsSync(testPath)) {
filePath = testPath;
break;
}
}
}
isESM = ModuleLoader.isPathModule(filePath);
}
return { isESM, filePath };
} | static resolvePath(config, modulePath) {
let isESM;
let filePath;
try {
filePath = require.resolve(modulePath);
isESM = ModuleLoader.isPathModule(filePath);
}
catch (error) {
filePath = ts_node_1.tsPath(config.root, modulePath);
// Try all supported extensions.
if (!fs.existsSync(filePath)) {
for (const extension of s_EXTENSIONS) {
const testPath = `${filePath}${extension}`;
if (fs.existsSync(testPath)) {
filePath = testPath;
break;
}
}
}
isESM = ModuleLoader.isPathModule(filePath);
}
return { isESM, filePath };
} |
JavaScript | function compose(...fns) {
return (...args) => {
return fns.reduceRight((leftFn, rightFn) => {
return leftFn instanceof Promise
? Promise.resolve(leftFn).then(rightFn)
: rightFn(leftFn);
}, args[0]);
};
} | function compose(...fns) {
return (...args) => {
return fns.reduceRight((leftFn, rightFn) => {
return leftFn instanceof Promise
? Promise.resolve(leftFn).then(rightFn)
: rightFn(leftFn);
}, args[0]);
};
} |
JavaScript | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
// because that method is always synchronous.
lib.until(() => predicatePromise).then(() => {
window.XMLHttpRequest.prototype.send = originalXhrSend;
this.send(...args);
});
};
// Defer any `fetch` requests until the Service Worker is ready.
const originalFetch = window.fetch;
window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
yield lib.until(() => predicatePromise);
window.fetch = originalFetch;
return window.fetch(...args);
});
} | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
// because that method is always synchronous.
lib.until(() => predicatePromise).then(() => {
window.XMLHttpRequest.prototype.send = originalXhrSend;
this.send(...args);
});
};
// Defer any `fetch` requests until the Service Worker is ready.
const originalFetch = window.fetch;
window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
yield lib.until(() => predicatePromise);
window.fetch = originalFetch;
return window.fetch(...args);
});
} |
JavaScript | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker: this browser does not support Service Workers (see https://caniuse.com/serviceworkers), or your application is running on an insecure host (consider using HTTPS for custom hostnames).`);
return null;
}
// Remove all previously existing event listeners.
// This way none of the listeners persists between Fast refresh
// of the application's code.
context.events.removeAllListeners();
context.events.addListener(navigator.serviceWorker, 'message', handleRequestWith(context, resolvedOptions));
const [, instance] = yield lib.until(() => getWorkerInstance(resolvedOptions.serviceWorker.url, resolvedOptions.serviceWorker.options, resolvedOptions.findWorker));
if (!instance) {
return null;
}
const [worker, registration] = instance;
if (!worker) {
if (options === null || options === void 0 ? void 0 : options.findWorker) {
console.error(`\
[MSW] Failed to locate the Service Worker registration using a custom "findWorker" predicate.
Please ensure that the custom predicate properly locates the Service Worker registration at "${resolvedOptions.serviceWorker.url}".
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
`);
}
else {
console.error(`\
[MSW] Failed to locate the Service Worker registration.
This most likely means that the worker script URL "${resolvedOptions.serviceWorker.url}" cannot resolve against the actual public hostname (${location.host}). This may happen if your application runs behind a proxy, or has a dynamic hostname.
Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`);
}
return null;
}
context.worker = worker;
context.registration = registration;
context.events.addListener(window, 'beforeunload', () => {
if (worker.state !== 'redundant') {
// Notify the Service Worker that this client has closed.
// Internally, it's similar to disabling the mocking, only
// client close event has a handler that self-terminates
// the Service Worker when there are no open clients.
worker.postMessage('CLIENT_CLOSED');
}
// Make sure we're always clearing the interval - there are reports that not doing this can
// cause memory leaks in headless browser environments.
window.clearInterval(context.keepAliveInterval);
});
// Check if the active Service Worker is the latest published one
const [integrityError] = yield lib.until(() => requestIntegrityCheck(context, worker));
if (integrityError) {
console.error(`\
[MSW] Detected outdated Service Worker: ${integrityError.message}
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
$ npx msw init <PUBLIC_DIR>
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
`);
}
// Signal the Service Worker to enable requests interception
const [activationError] = yield lib.until(() => activateMocking(context, options));
if (activationError) {
console.error('Failed to enable mocking', activationError);
return null;
}
context.keepAliveInterval = window.setInterval(() => worker.postMessage('KEEPALIVE_REQUEST'), 5000);
return registration;
});
const workerRegistration = startWorkerInstance();
// Defer any network requests until the Service Worker instance is ready.
// This prevents a race condition between the Service Worker registration
// and application's runtime requests (i.e. requests on mount).
if (resolvedOptions.waitUntilReady) {
deferNetworkRequestsUntil(workerRegistration);
}
return workerRegistration;
} | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker: this browser does not support Service Workers (see https://caniuse.com/serviceworkers), or your application is running on an insecure host (consider using HTTPS for custom hostnames).`);
return null;
}
// Remove all previously existing event listeners.
// This way none of the listeners persists between Fast refresh
// of the application's code.
context.events.removeAllListeners();
context.events.addListener(navigator.serviceWorker, 'message', handleRequestWith(context, resolvedOptions));
const [, instance] = yield lib.until(() => getWorkerInstance(resolvedOptions.serviceWorker.url, resolvedOptions.serviceWorker.options, resolvedOptions.findWorker));
if (!instance) {
return null;
}
const [worker, registration] = instance;
if (!worker) {
if (options === null || options === void 0 ? void 0 : options.findWorker) {
console.error(`\
[MSW] Failed to locate the Service Worker registration using a custom "findWorker" predicate.
Please ensure that the custom predicate properly locates the Service Worker registration at "${resolvedOptions.serviceWorker.url}".
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
`);
}
else {
console.error(`\
[MSW] Failed to locate the Service Worker registration.
This most likely means that the worker script URL "${resolvedOptions.serviceWorker.url}" cannot resolve against the actual public hostname (${location.host}). This may happen if your application runs behind a proxy, or has a dynamic hostname.
Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`);
}
return null;
}
context.worker = worker;
context.registration = registration;
context.events.addListener(window, 'beforeunload', () => {
if (worker.state !== 'redundant') {
// Notify the Service Worker that this client has closed.
// Internally, it's similar to disabling the mocking, only
// client close event has a handler that self-terminates
// the Service Worker when there are no open clients.
worker.postMessage('CLIENT_CLOSED');
}
// Make sure we're always clearing the interval - there are reports that not doing this can
// cause memory leaks in headless browser environments.
window.clearInterval(context.keepAliveInterval);
});
// Check if the active Service Worker is the latest published one
const [integrityError] = yield lib.until(() => requestIntegrityCheck(context, worker));
if (integrityError) {
console.error(`\
[MSW] Detected outdated Service Worker: ${integrityError.message}
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
$ npx msw init <PUBLIC_DIR>
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
`);
}
// Signal the Service Worker to enable requests interception
const [activationError] = yield lib.until(() => activateMocking(context, options));
if (activationError) {
console.error('Failed to enable mocking', activationError);
return null;
}
context.keepAliveInterval = window.setInterval(() => worker.postMessage('KEEPALIVE_REQUEST'), 5000);
return registration;
});
const workerRegistration = startWorkerInstance();
// Defer any network requests until the Service Worker instance is ready.
// This prevents a race condition between the Service Worker registration
// and application's runtime requests (i.e. requests on mount).
if (resolvedOptions.waitUntilReady) {
deferNetworkRequestsUntil(workerRegistration);
}
return workerRegistration;
} |
JavaScript | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} |
JavaScript | function isNodeProcess() {
// Check browser environment.
if (typeof global !== 'object') {
return false;
}
// Check nodejs or React Native environment.
if (Object.prototype.toString.call(global.process) === '[object process]' ||
navigator.product === 'ReactNative') {
return true;
}
} | function isNodeProcess() {
// Check browser environment.
if (typeof global !== 'object') {
return false;
}
// Check nodejs or React Native environment.
if (Object.prototype.toString.call(global.process) === '[object process]' ||
navigator.product === 'ReactNative') {
return true;
}
} |
JavaScript | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');
if (hasJsonContent && typeof body !== 'object') {
return jsonParse(body) || body;
}
return body;
}
// Return whatever falsey body value is given.
return body;
} | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');
if (hasJsonContent && typeof body !== 'object') {
return jsonParse(body) || body;
}
return body;
}
// Return whatever falsey body value is given.
return body;
} |
JavaScript | function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util$1.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
} | function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util$1.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
} |
JavaScript | function createSetupServer(...interceptors) {
return function setupServer(...requestHandlers) {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
throw new Error(`[MSW] Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).`);
});
const interceptor = new nodeRequestInterceptor.RequestInterceptor(interceptors);
// Error when attempting to run this function in a browser environment.
if (!isNodeProcess()) {
throw new Error('[MSW] Failed to execute `setupServer` in the environment that is not NodeJS (i.e. a browser). Consider using `setupWorker` instead.');
}
// Store the list of request handlers for the current server instance,
// so it could be modified at a runtime.
let currentHandlers = [...requestHandlers];
return {
listen(options) {
const resolvedOptions = Object.assign({}, DEFAULT_LISTEN_OPTIONS, options);
interceptor.use((req) => __awaiter(this, void 0, void 0, function* () {
const requestHeaders = new lib.Headers(lib.flattenHeadersObject(req.headers || {}));
const requestCookieString = requestHeaders.get('cookie');
const mockedRequest = {
url: req.url,
method: req.method,
// Parse the request's body based on the "Content-Type" header.
body: parseBody(req.body, requestHeaders),
headers: requestHeaders,
cookies: {},
params: {},
redirect: 'manual',
referrer: '',
keepalive: false,
cache: 'default',
mode: 'cors',
referrerPolicy: 'no-referrer',
integrity: '',
destination: 'document',
bodyUsed: false,
credentials: 'same-origin',
};
if (requestCookieString) {
// Set mocked request cookies from the `cookie` header of the original request.
// No need to take `credentials` into account, because in NodeJS requests are intercepted
// _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
// Unlike browser, where interception is on the worker level, _before_ the request happens.
mockedRequest.cookies = parse_1(requestCookieString);
}
if (mockedRequest.headers.get('x-msw-bypass')) {
return;
}
const { response } = yield getResponse(mockedRequest, currentHandlers);
if (!response) {
onUnhandledRequest(mockedRequest, resolvedOptions.onUnhandledRequest);
return;
}
return new Promise((resolve) => {
var _a;
// the node build will use the timers module to ensure @sinon/fake-timers or jest fake timers
// don't affect this timeout.
setTimeout(() => {
resolve({
status: response.status,
statusText: response.statusText,
headers: response.headers.getAllHeaders(),
body: response.body,
});
}, (_a = response.delay) !== null && _a !== void 0 ? _a : 0);
});
}));
},
use(...handlers) {
use(currentHandlers, ...handlers);
},
restoreHandlers() {
restoreHandlers(currentHandlers);
},
resetHandlers(...nextHandlers) {
currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
},
/**
* Prints the list of currently active request handlers.
*/
printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
},
/**
* Stops requests interception by restoring all augmented modules.
*/
close() {
interceptor.restore();
},
};
};
} | function createSetupServer(...interceptors) {
return function setupServer(...requestHandlers) {
requestHandlers.forEach((handler) => {
if (Array.isArray(handler))
throw new Error(`[MSW] Failed to call "setupServer" given an Array of request handlers (setupServer([a, b])), expected to receive each handler individually: setupServer(a, b).`);
});
const interceptor = new nodeRequestInterceptor.RequestInterceptor(interceptors);
// Error when attempting to run this function in a browser environment.
if (!isNodeProcess()) {
throw new Error('[MSW] Failed to execute `setupServer` in the environment that is not NodeJS (i.e. a browser). Consider using `setupWorker` instead.');
}
// Store the list of request handlers for the current server instance,
// so it could be modified at a runtime.
let currentHandlers = [...requestHandlers];
return {
listen(options) {
const resolvedOptions = Object.assign({}, DEFAULT_LISTEN_OPTIONS, options);
interceptor.use((req) => __awaiter(this, void 0, void 0, function* () {
const requestHeaders = new lib.Headers(lib.flattenHeadersObject(req.headers || {}));
const requestCookieString = requestHeaders.get('cookie');
const mockedRequest = {
url: req.url,
method: req.method,
// Parse the request's body based on the "Content-Type" header.
body: parseBody(req.body, requestHeaders),
headers: requestHeaders,
cookies: {},
params: {},
redirect: 'manual',
referrer: '',
keepalive: false,
cache: 'default',
mode: 'cors',
referrerPolicy: 'no-referrer',
integrity: '',
destination: 'document',
bodyUsed: false,
credentials: 'same-origin',
};
if (requestCookieString) {
// Set mocked request cookies from the `cookie` header of the original request.
// No need to take `credentials` into account, because in NodeJS requests are intercepted
// _after_ they happen. Request issuer should have already taken care of sending relevant cookies.
// Unlike browser, where interception is on the worker level, _before_ the request happens.
mockedRequest.cookies = parse_1(requestCookieString);
}
if (mockedRequest.headers.get('x-msw-bypass')) {
return;
}
const { response } = yield getResponse(mockedRequest, currentHandlers);
if (!response) {
onUnhandledRequest(mockedRequest, resolvedOptions.onUnhandledRequest);
return;
}
return new Promise((resolve) => {
var _a;
// the node build will use the timers module to ensure @sinon/fake-timers or jest fake timers
// don't affect this timeout.
setTimeout(() => {
resolve({
status: response.status,
statusText: response.statusText,
headers: response.headers.getAllHeaders(),
body: response.body,
});
}, (_a = response.delay) !== null && _a !== void 0 ? _a : 0);
});
}));
},
use(...handlers) {
use(currentHandlers, ...handlers);
},
restoreHandlers() {
restoreHandlers(currentHandlers);
},
resetHandlers(...nextHandlers) {
currentHandlers = resetHandlers(requestHandlers, ...nextHandlers);
},
/**
* Prints the list of currently active request handlers.
*/
printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
},
/**
* Stops requests interception by restoring all augmented modules.
*/
close() {
interceptor.restore();
},
};
};
} |
JavaScript | printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
} | printHandlers() {
currentHandlers.forEach((handler) => {
const meta = handler.getMetaInfo();
console.log(`\
${source.bold(meta.header)}
Declaration: ${meta.callFrame}
`);
});
} |
JavaScript | function prepareResponse(res) {
const responseHeaders = lib.listToHeaders(res.headers);
return Object.assign(Object.assign({}, res), {
// Parse a response JSON body for preview in the logs
body: parseBody(res.body, responseHeaders) });
} | function prepareResponse(res) {
const responseHeaders = lib.listToHeaders(res.headers);
return Object.assign(Object.assign({}, res), {
// Parse a response JSON body for preview in the logs
body: parseBody(res.body, responseHeaders) });
} |
JavaScript | function matchRequestUrl(url, mask) {
const resolvedMask = getUrlByMask(mask);
const cleanMask = getCleanMask(resolvedMask);
const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
return match(cleanMask, cleanRequestUrl);
} | function matchRequestUrl(url, mask) {
const resolvedMask = getUrlByMask(mask);
const cleanMask = getCleanMask(resolvedMask);
const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);
return match(cleanMask, cleanRequestUrl);
} |
JavaScript | function stringToHeaders(str) {
var lines = str.trim().split(/[\r\n]+/);
return lines.reduce(function (headers, line) {
var parts = line.split(': ');
var name = parts.shift();
var value = parts.join(': ');
headers.append(name, value);
return headers;
}, new Headers());
} | function stringToHeaders(str) {
var lines = str.trim().split(/[\r\n]+/);
return lines.reduce(function (headers, line) {
var parts = line.split(': ');
var name = parts.shift();
var value = parts.join(': ');
headers.append(name, value);
return headers;
}, new Headers());
} |
JavaScript | function objectToHeaders(obj) {
return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {
var values = [].concat(value);
values.forEach(function (value) {
headers.append(name, value);
});
return headers;
}, new Headers());
} | function objectToHeaders(obj) {
return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {
var values = [].concat(value);
values.forEach(function (value) {
headers.append(name, value);
});
return headers;
}, new Headers());
} |
JavaScript | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');
if (hasJsonContent && typeof body !== 'object') {
return jsonParse(body) || body;
}
return body;
}
// Return whatever falsey body value is given.
return body;
} | function parseBody(body, headers) {
var _a;
if (body) {
// If the intercepted request's body has a JSON Content-Type
// parse it into an object, otherwise leave as-is.
const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');
if (hasJsonContent && typeof body !== 'object') {
return jsonParse(body) || body;
}
return body;
}
// Return whatever falsey body value is given.
return body;
} |
JavaScript | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
// because that method is always synchronous.
lib$1.until(() => predicatePromise).then(() => {
window.XMLHttpRequest.prototype.send = originalXhrSend;
this.send(...args);
});
};
// Defer any `fetch` requests until the Service Worker is ready.
const originalFetch = window.fetch;
window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
yield lib$1.until(() => predicatePromise);
window.fetch = originalFetch;
return window.fetch(...args);
});
} | function deferNetworkRequestsUntil(predicatePromise) {
// Defer any `XMLHttpRequest` requests until the Service Worker is ready.
const originalXhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (...args) {
// Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
// because that method is always synchronous.
lib$1.until(() => predicatePromise).then(() => {
window.XMLHttpRequest.prototype.send = originalXhrSend;
this.send(...args);
});
};
// Defer any `fetch` requests until the Service Worker is ready.
const originalFetch = window.fetch;
window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
yield lib$1.until(() => predicatePromise);
window.fetch = originalFetch;
return window.fetch(...args);
});
} |
JavaScript | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker: this browser does not support Service Workers (see https://caniuse.com/serviceworkers), or your application is running on an insecure host (consider using HTTPS for custom hostnames).`);
return null;
}
// Remove all previously existing event listeners.
// This way none of the listeners persists between Fast refresh
// of the application's code.
context.events.removeAllListeners();
context.events.addListener(navigator.serviceWorker, 'message', handleRequestWith(context, resolvedOptions));
const [, instance] = yield lib$1.until(() => getWorkerInstance(resolvedOptions.serviceWorker.url, resolvedOptions.serviceWorker.options, resolvedOptions.findWorker));
if (!instance) {
return null;
}
const [worker, registration] = instance;
if (!worker) {
if (options === null || options === void 0 ? void 0 : options.findWorker) {
console.error(`\
[MSW] Failed to locate the Service Worker registration using a custom "findWorker" predicate.
Please ensure that the custom predicate properly locates the Service Worker registration at "${resolvedOptions.serviceWorker.url}".
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
`);
}
else {
console.error(`\
[MSW] Failed to locate the Service Worker registration.
This most likely means that the worker script URL "${resolvedOptions.serviceWorker.url}" cannot resolve against the actual public hostname (${location.host}). This may happen if your application runs behind a proxy, or has a dynamic hostname.
Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`);
}
return null;
}
context.worker = worker;
context.registration = registration;
context.events.addListener(window, 'beforeunload', () => {
if (worker.state !== 'redundant') {
// Notify the Service Worker that this client has closed.
// Internally, it's similar to disabling the mocking, only
// client close event has a handler that self-terminates
// the Service Worker when there are no open clients.
worker.postMessage('CLIENT_CLOSED');
}
// Make sure we're always clearing the interval - there are reports that not doing this can
// cause memory leaks in headless browser environments.
window.clearInterval(context.keepAliveInterval);
});
// Check if the active Service Worker is the latest published one
const [integrityError] = yield lib$1.until(() => requestIntegrityCheck(context, worker));
if (integrityError) {
console.error(`\
[MSW] Detected outdated Service Worker: ${integrityError.message}
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
$ npx msw init <PUBLIC_DIR>
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
`);
}
// Signal the Service Worker to enable requests interception
const [activationError] = yield lib$1.until(() => activateMocking(context, options));
if (activationError) {
console.error('Failed to enable mocking', activationError);
return null;
}
context.keepAliveInterval = window.setInterval(() => worker.postMessage('KEEPALIVE_REQUEST'), 5000);
return registration;
});
const workerRegistration = startWorkerInstance();
// Defer any network requests until the Service Worker instance is ready.
// This prevents a race condition between the Service Worker registration
// and application's runtime requests (i.e. requests on mount).
if (resolvedOptions.waitUntilReady) {
deferNetworkRequestsUntil(workerRegistration);
}
return workerRegistration;
} | function start(options) {
const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});
const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
if (!('serviceWorker' in navigator)) {
console.error(`[MSW] Failed to register a Service Worker: this browser does not support Service Workers (see https://caniuse.com/serviceworkers), or your application is running on an insecure host (consider using HTTPS for custom hostnames).`);
return null;
}
// Remove all previously existing event listeners.
// This way none of the listeners persists between Fast refresh
// of the application's code.
context.events.removeAllListeners();
context.events.addListener(navigator.serviceWorker, 'message', handleRequestWith(context, resolvedOptions));
const [, instance] = yield lib$1.until(() => getWorkerInstance(resolvedOptions.serviceWorker.url, resolvedOptions.serviceWorker.options, resolvedOptions.findWorker));
if (!instance) {
return null;
}
const [worker, registration] = instance;
if (!worker) {
if (options === null || options === void 0 ? void 0 : options.findWorker) {
console.error(`\
[MSW] Failed to locate the Service Worker registration using a custom "findWorker" predicate.
Please ensure that the custom predicate properly locates the Service Worker registration at "${resolvedOptions.serviceWorker.url}".
More details: https://mswjs.io/docs/api/setup-worker/start#findworker
`);
}
else {
console.error(`\
[MSW] Failed to locate the Service Worker registration.
This most likely means that the worker script URL "${resolvedOptions.serviceWorker.url}" cannot resolve against the actual public hostname (${location.host}). This may happen if your application runs behind a proxy, or has a dynamic hostname.
Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`);
}
return null;
}
context.worker = worker;
context.registration = registration;
context.events.addListener(window, 'beforeunload', () => {
if (worker.state !== 'redundant') {
// Notify the Service Worker that this client has closed.
// Internally, it's similar to disabling the mocking, only
// client close event has a handler that self-terminates
// the Service Worker when there are no open clients.
worker.postMessage('CLIENT_CLOSED');
}
// Make sure we're always clearing the interval - there are reports that not doing this can
// cause memory leaks in headless browser environments.
window.clearInterval(context.keepAliveInterval);
});
// Check if the active Service Worker is the latest published one
const [integrityError] = yield lib$1.until(() => requestIntegrityCheck(context, worker));
if (integrityError) {
console.error(`\
[MSW] Detected outdated Service Worker: ${integrityError.message}
The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:
$ npx msw init <PUBLIC_DIR>
This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.
If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\
`);
}
// Signal the Service Worker to enable requests interception
const [activationError] = yield lib$1.until(() => activateMocking(context, options));
if (activationError) {
console.error('Failed to enable mocking', activationError);
return null;
}
context.keepAliveInterval = window.setInterval(() => worker.postMessage('KEEPALIVE_REQUEST'), 5000);
return registration;
});
const workerRegistration = startWorkerInstance();
// Defer any network requests until the Service Worker instance is ready.
// This prevents a race condition between the Service Worker registration
// and application's runtime requests (i.e. requests on mount).
if (resolvedOptions.waitUntilReady) {
deferNetworkRequestsUntil(workerRegistration);
}
return workerRegistration;
} |
JavaScript | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} | function stop() {
var _a;
(_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');
context.events.removeAllListeners();
window.clearInterval(context.keepAliveInterval);
} |
JavaScript | function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _locations2, _source2, _positions2, _extensions2;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message); // Compute list of blame nodes.
var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
var _source = source;
if (!_source && _nodes) {
var _nodes$0$loc;
_source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;
}
var _positions = positions;
if (!_positions && _nodes) {
_positions = _nodes.reduce(function (list, node) {
if (node.loc) {
list.push(node.loc.start);
}
return list;
}, []);
}
if (_positions && _positions.length === 0) {
_positions = undefined;
}
var _locations;
if (positions && source) {
_locations = positions.map(function (pos) {
return getLocation(source, pos);
});
} else if (_nodes) {
_locations = _nodes.reduce(function (list, node) {
if (node.loc) {
list.push(getLocation(node.loc.source, node.loc.start));
}
return list;
}, []);
}
var _extensions = extensions;
if (_extensions == null && originalError != null) {
var originalExtensions = originalError.extensions;
if (isObjectLike(originalExtensions)) {
_extensions = originalExtensions;
}
}
Object.defineProperties(_assertThisInitialized(_this), {
name: {
value: 'GraphQLError'
},
message: {
value: message,
// By being enumerable, JSON.stringify will include `message` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: true,
writable: true
},
locations: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,
// By being enumerable, JSON.stringify will include `locations` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: _locations != null
},
path: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: path !== null && path !== void 0 ? path : undefined,
// By being enumerable, JSON.stringify will include `path` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: path != null
},
nodes: {
value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined
},
source: {
value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined
},
positions: {
value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined
},
originalError: {
value: originalError
},
extensions: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,
// By being enumerable, JSON.stringify will include `path` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: _extensions != null
}
}); // Include (non-enumerable) stack trace.
if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: originalError.stack,
writable: true,
configurable: true
});
return _possibleConstructorReturn(_this);
} // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);
} else {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: Error().stack,
writable: true,
configurable: true
});
}
return _this;
} | function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _locations2, _source2, _positions2, _extensions2;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message); // Compute list of blame nodes.
var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
var _source = source;
if (!_source && _nodes) {
var _nodes$0$loc;
_source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;
}
var _positions = positions;
if (!_positions && _nodes) {
_positions = _nodes.reduce(function (list, node) {
if (node.loc) {
list.push(node.loc.start);
}
return list;
}, []);
}
if (_positions && _positions.length === 0) {
_positions = undefined;
}
var _locations;
if (positions && source) {
_locations = positions.map(function (pos) {
return getLocation(source, pos);
});
} else if (_nodes) {
_locations = _nodes.reduce(function (list, node) {
if (node.loc) {
list.push(getLocation(node.loc.source, node.loc.start));
}
return list;
}, []);
}
var _extensions = extensions;
if (_extensions == null && originalError != null) {
var originalExtensions = originalError.extensions;
if (isObjectLike(originalExtensions)) {
_extensions = originalExtensions;
}
}
Object.defineProperties(_assertThisInitialized(_this), {
name: {
value: 'GraphQLError'
},
message: {
value: message,
// By being enumerable, JSON.stringify will include `message` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: true,
writable: true
},
locations: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,
// By being enumerable, JSON.stringify will include `locations` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: _locations != null
},
path: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: path !== null && path !== void 0 ? path : undefined,
// By being enumerable, JSON.stringify will include `path` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: path != null
},
nodes: {
value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined
},
source: {
value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined
},
positions: {
value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined
},
originalError: {
value: originalError
},
extensions: {
// Coercing falsy values to undefined ensures they will not be included
// in JSON.stringify() when not provided.
value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,
// By being enumerable, JSON.stringify will include `path` in the
// resulting output. This ensures that the simplest possible GraphQL
// service adheres to the spec.
enumerable: _extensions != null
}
}); // Include (non-enumerable) stack trace.
if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: originalError.stack,
writable: true,
configurable: true
});
return _possibleConstructorReturn(_this);
} // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);
} else {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: Error().stack,
writable: true,
configurable: true
});
}
return _this;
} |
JavaScript | function createGraphQLLink(uri) {
return {
operation: createGraphQLOperationHandler(uri),
query: createGraphQLScopedHandler('query', uri),
mutation: createGraphQLScopedHandler('mutation', uri),
};
} | function createGraphQLLink(uri) {
return {
operation: createGraphQLOperationHandler(uri),
query: createGraphQLScopedHandler('query', uri),
mutation: createGraphQLScopedHandler('mutation', uri),
};
} |
JavaScript | function handleClick(index) {
let currentColorHex
Object.keys(colors).map((value, key) => {
if (key === index) {
currentColorHex = colors[value];
return
}
});
setCurrentColor(currentColorHex);
router.push({pathname: "/colors/" + currentColorHex.name.substring(1)}, undefined, {scroll: false});
} | function handleClick(index) {
let currentColorHex
Object.keys(colors).map((value, key) => {
if (key === index) {
currentColorHex = colors[value];
return
}
});
setCurrentColor(currentColorHex);
router.push({pathname: "/colors/" + currentColorHex.name.substring(1)}, undefined, {scroll: false});
} |
JavaScript | function findXCodeproject(context, callback) {
fs.readdir(iosFolder(context), function(err, data) {
var projectFolder;
var projectName;
// Find the project folder by looking for *.xcodeproj
if (data && data.length) {
data.forEach(function(folder) {
if (folder.match(/\.xcodeproj$/)) {
projectFolder = path.join(iosFolder(context), folder);
projectName = path.basename(folder, '.xcodeproj');
}
});
}
if (!projectFolder || !projectName) {
throw redError('Could not find an .xcodeproj folder in: ' + iosFolder(context));
}
if (err) {
throw redError(err);
}
callback(projectFolder, projectName);
});
} | function findXCodeproject(context, callback) {
fs.readdir(iosFolder(context), function(err, data) {
var projectFolder;
var projectName;
// Find the project folder by looking for *.xcodeproj
if (data && data.length) {
data.forEach(function(folder) {
if (folder.match(/\.xcodeproj$/)) {
projectFolder = path.join(iosFolder(context), folder);
projectName = path.basename(folder, '.xcodeproj');
}
});
}
if (!projectFolder || !projectName) {
throw redError('Could not find an .xcodeproj folder in: ' + iosFolder(context));
}
if (err) {
throw redError(err);
}
callback(projectFolder, projectName);
});
} |
JavaScript | function iosFolder(context) {
return context.opts.cordova.project
? context.opts.cordova.project.root
: path.join(context.opts.projectRoot, 'platforms/ios/');
} | function iosFolder(context) {
return context.opts.cordova.project
? context.opts.cordova.project.root
: path.join(context.opts.projectRoot, 'platforms/ios/');
} |
JavaScript | function draw() {
if (bg.ready) {
ctx.drawImage(bg.image, 0, 0);
}
if (hero.ready) {
ctx.drawImage(hero.image, hero.x, hero.y);
}
monsters.forEach((monster) => {
if (monster.ready) {
ctx.drawImage(monster.image, monster.x, monster.y);
}
});
let remainningTime = SECONDS_PER_ROUND - elapsedTime;
timer.innerHTML = remainningTime;
if (playerName.value !== ""){
ctx.fillText("Player: " + playerName.value,20,40)
}
playerName.value = "";
} | function draw() {
if (bg.ready) {
ctx.drawImage(bg.image, 0, 0);
}
if (hero.ready) {
ctx.drawImage(hero.image, hero.x, hero.y);
}
monsters.forEach((monster) => {
if (monster.ready) {
ctx.drawImage(monster.image, monster.x, monster.y);
}
});
let remainningTime = SECONDS_PER_ROUND - elapsedTime;
timer.innerHTML = remainningTime;
if (playerName.value !== ""){
ctx.fillText("Player: " + playerName.value,20,40)
}
playerName.value = "";
} |
JavaScript | function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, true);
http.send();
return (http.status != 403);
} | function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, true);
http.send();
return (http.status != 403);
} |
JavaScript | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
baseParts.pop();
while (curPart = uriParts.shift())
if (curPart == '..')
baseParts.pop();
else
baseParts.push(curPart);
return baseParts.join('/');
} | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
baseParts.pop();
while (curPart = uriParts.shift())
if (curPart == '..')
baseParts.pop();
else
baseParts.push(curPart);
return baseParts.join('/');
} |
JavaScript | function relativeURI(uri, base) {
// reduce base and uri strings to just their difference string
var baseParts = base.split('/');
baseParts.pop();
base = baseParts.join('/') + '/';
i = 0;
while (base.substr(i, 1) == uri.substr(i, 1))
i++;
while (base.substr(i, 1) != '/')
i--;
base = base.substr(i + 1);
uri = uri.substr(i + 1);
// each base folder difference is thus a backtrack
baseParts = base.split('/');
var uriParts = uri.split('/');
out = '';
while (baseParts.shift())
out += '../';
// finally add uri parts
while (curPart = uriParts.shift())
out += curPart + '/';
return out.substr(0, out.length - 1);
} | function relativeURI(uri, base) {
// reduce base and uri strings to just their difference string
var baseParts = base.split('/');
baseParts.pop();
base = baseParts.join('/') + '/';
i = 0;
while (base.substr(i, 1) == uri.substr(i, 1))
i++;
while (base.substr(i, 1) != '/')
i--;
base = base.substr(i + 1);
uri = uri.substr(i + 1);
// each base folder difference is thus a backtrack
baseParts = base.split('/');
var uriParts = uri.split('/');
out = '';
while (baseParts.shift())
out += '../';
// finally add uri parts
while (curPart = uriParts.shift())
out += curPart + '/';
return out.substr(0, out.length - 1);
} |
JavaScript | function angularGridGlobalFunction(element, gridOptions) {
// see if element is a query selector, or a real element
var eGridDiv;
if (typeof element === 'string') {
eGridDiv = document.querySelector(element);
if (!eGridDiv) {
console.log('WARNING - was not able to find element ' + element + ' in the DOM, Angular Grid initialisation aborted.');
return;
}
}
new Grid(eGridDiv, gridOptions, null, null);
} | function angularGridGlobalFunction(element, gridOptions) {
// see if element is a query selector, or a real element
var eGridDiv;
if (typeof element === 'string') {
eGridDiv = document.querySelector(element);
if (!eGridDiv) {
console.log('WARNING - was not able to find element ' + element + ' in the DOM, Angular Grid initialisation aborted.');
return;
}
}
new Grid(eGridDiv, gridOptions, null, null);
} |
JavaScript | function httpConfig(action, data, additionalConfig) {
var config = {
method: methods[action].toLowerCase(),
url: paths[action]
};
if (data) {
if (resourceName) {
config.data = {};
config.data[resourceName] = data;
} else {
config.data = data;
}
}
angular.extend(config, additionalConfig);
return config;
} | function httpConfig(action, data, additionalConfig) {
var config = {
method: methods[action].toLowerCase(),
url: paths[action]
};
if (data) {
if (resourceName) {
config.data = {};
config.data[resourceName] = data;
} else {
config.data = data;
}
}
angular.extend(config, additionalConfig);
return config;
} |
JavaScript | function configure(obj, suffix) {
angular.forEach(obj, function(v, action) {
this[action + suffix] = function(param) {
if (param === undefined) {
return obj[action];
}
obj[action] = param;
return this;
};
}, this);
} | function configure(obj, suffix) {
angular.forEach(obj, function(v, action) {
this[action + suffix] = function(param) {
if (param === undefined) {
return obj[action];
}
obj[action] = param;
return this;
};
}, this);
} |
JavaScript | moveTo(x, y) {
//Collect Variables
this.planning.start = new Vector(this.x, this.y);
let endPoint = this.scene.tilemap.getPosition(x, y);
this.planning.end = new Vector(endPoint.x, endPoint.y);
let pathVector = this.planning.end.subtract(this.planning.start);
this.planning.distance = pathVector.getLength();
this.planning.direction = pathVector.normalize();
//Start Moving Animation
this.planning.moving = true;
} | moveTo(x, y) {
//Collect Variables
this.planning.start = new Vector(this.x, this.y);
let endPoint = this.scene.tilemap.getPosition(x, y);
this.planning.end = new Vector(endPoint.x, endPoint.y);
let pathVector = this.planning.end.subtract(this.planning.start);
this.planning.distance = pathVector.getLength();
this.planning.direction = pathVector.normalize();
//Start Moving Animation
this.planning.moving = true;
} |
JavaScript | function installSyncSaveDev(packages) {
if (Array.isArray(packages)) {
packages = packages.join(" ");
}
shell.execSync("npm i --save-dev " + packages, {stdio: "inherit"});
} | function installSyncSaveDev(packages) {
if (Array.isArray(packages)) {
packages = packages.join(" ");
}
shell.execSync("npm i --save-dev " + packages, {stdio: "inherit"});
} |
JavaScript | function check(packages, opt) {
var deps = [];
var pkgJson = findPackageJson();
if (!pkgJson) {
throw new Error("Could not find a package.json file");
}
var fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
if (opt.devDependencies) {
deps = deps.concat(Object.keys(fileJson.devDependencies));
}
if (opt.dependencies) {
deps = deps.concat(Object.keys(fileJson.dependencies));
}
return packages.reduce(function(status, pkg) {
status[pkg] = deps.indexOf(pkg) !== -1;
return status;
}, {});
} | function check(packages, opt) {
var deps = [];
var pkgJson = findPackageJson();
if (!pkgJson) {
throw new Error("Could not find a package.json file");
}
var fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
if (opt.devDependencies) {
deps = deps.concat(Object.keys(fileJson.devDependencies));
}
if (opt.dependencies) {
deps = deps.concat(Object.keys(fileJson.dependencies));
}
return packages.reduce(function(status, pkg) {
status[pkg] = deps.indexOf(pkg) !== -1;
return status;
}, {});
} |
JavaScript | function writeTempConfigFile(config, filename, existingTmpDir) {
var tmpFileDir = existingTmpDir || tmp.dirSync({prefix: "eslint-tests-"}).name,
tmpFilePath = path.join(tmpFileDir, filename),
tmpFileContents = JSON.stringify(config);
fs.writeFileSync(tmpFilePath, tmpFileContents);
return tmpFilePath;
} | function writeTempConfigFile(config, filename, existingTmpDir) {
var tmpFileDir = existingTmpDir || tmp.dirSync({prefix: "eslint-tests-"}).name,
tmpFilePath = path.join(tmpFileDir, filename),
tmpFileContents = JSON.stringify(config);
fs.writeFileSync(tmpFilePath, tmpFileContents);
return tmpFilePath;
} |
JavaScript | function checkForBreakAfter(node, msg) {
var paren = context.getTokenAfter(node);
while (paren.value === ")") {
paren = context.getTokenAfter(paren);
}
if (paren.loc.start.line !== node.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.value });
}
} | function checkForBreakAfter(node, msg) {
var paren = context.getTokenAfter(node);
while (paren.value === ")") {
paren = context.getTokenAfter(paren);
}
if (paren.loc.start.line !== node.loc.end.line) {
context.report(node, paren.loc.start, msg, { char: paren.value });
}
} |
JavaScript | function processText(text, configHelper, filename, fix, allowInlineConfig) {
// clear all existing settings for a new file
eslint.reset();
var filePath,
config,
messages,
stats,
fileExtension = path.extname(filename),
processor,
loadedPlugins,
fixedResult;
if (filename) {
filePath = path.resolve(filename);
}
filename = filename || "<text>";
debug("Linting " + filename);
config = configHelper.getConfig(filePath);
if (config.plugins) {
Plugins.loadAll(config.plugins);
}
loadedPlugins = Plugins.getAll();
for (var plugin in loadedPlugins) {
if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) {
processor = loadedPlugins[plugin].processors[fileExtension];
break;
}
}
if (processor) {
debug("Using processor");
var parsedBlocks = processor.preprocess(text, filename);
var unprocessedMessages = [];
parsedBlocks.forEach(function(block) {
unprocessedMessages.push(eslint.verify(block, config, {
filename: filename,
allowInlineConfig: allowInlineConfig
}));
});
// TODO(nzakas): Figure out how fixes might work for processors
messages = processor.postprocess(unprocessedMessages, filename);
} else {
messages = eslint.verify(text, config, {
filename: filename,
allowInlineConfig: allowInlineConfig
});
if (fix) {
debug("Generating fixed text for " + filename);
fixedResult = SourceCodeFixer.applyFixes(eslint.getSourceCode(), messages);
messages = fixedResult.messages;
}
}
stats = calculateStatsPerFile(messages);
var result = {
filePath: filename,
messages: messages,
errorCount: stats.errorCount,
warningCount: stats.warningCount
};
if (fixedResult && fixedResult.fixed) {
result.output = fixedResult.output;
}
return result;
} | function processText(text, configHelper, filename, fix, allowInlineConfig) {
// clear all existing settings for a new file
eslint.reset();
var filePath,
config,
messages,
stats,
fileExtension = path.extname(filename),
processor,
loadedPlugins,
fixedResult;
if (filename) {
filePath = path.resolve(filename);
}
filename = filename || "<text>";
debug("Linting " + filename);
config = configHelper.getConfig(filePath);
if (config.plugins) {
Plugins.loadAll(config.plugins);
}
loadedPlugins = Plugins.getAll();
for (var plugin in loadedPlugins) {
if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) {
processor = loadedPlugins[plugin].processors[fileExtension];
break;
}
}
if (processor) {
debug("Using processor");
var parsedBlocks = processor.preprocess(text, filename);
var unprocessedMessages = [];
parsedBlocks.forEach(function(block) {
unprocessedMessages.push(eslint.verify(block, config, {
filename: filename,
allowInlineConfig: allowInlineConfig
}));
});
// TODO(nzakas): Figure out how fixes might work for processors
messages = processor.postprocess(unprocessedMessages, filename);
} else {
messages = eslint.verify(text, config, {
filename: filename,
allowInlineConfig: allowInlineConfig
});
if (fix) {
debug("Generating fixed text for " + filename);
fixedResult = SourceCodeFixer.applyFixes(eslint.getSourceCode(), messages);
messages = fixedResult.messages;
}
}
stats = calculateStatsPerFile(messages);
var result = {
filePath: filename,
messages: messages,
errorCount: stats.errorCount,
warningCount: stats.warningCount
};
if (fixedResult && fixedResult.fixed) {
result.output = fixedResult.output;
}
return result;
} |
JavaScript | function processFile(filename, configHelper, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig);
return result;
} | function processFile(filename, configHelper, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, configHelper, filename, options.fix, options.allowInlineConfig);
return result;
} |
JavaScript | function CLIEngine(options) {
options = assign(Object.create(null), defaultOptions, options);
/**
* Stored options for this instance
* @type {Object}
*/
this.options = options;
var cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
/**
* cache used to not operate on files that haven't changed since last successful
* execution (e.g. file passed with no errors and no warnings
* @type {Object}
*/
this._fileCache = fileEntryCache.create(cacheFile);
if (!this.options.cache) {
this._fileCache.destroy();
}
// load in additional rules
if (this.options.rulePaths) {
var cwd = this.options.cwd;
this.options.rulePaths.forEach(function(rulesdir) {
debug("Loading rules from " + rulesdir);
rules.load(rulesdir, cwd);
});
}
Object.keys(this.options.rules || {}).forEach(function(name) {
validator.validateRuleOptions(name, this.options.rules[name], "CLI");
}.bind(this));
} | function CLIEngine(options) {
options = assign(Object.create(null), defaultOptions, options);
/**
* Stored options for this instance
* @type {Object}
*/
this.options = options;
var cacheFile = getCacheFile(this.options.cacheLocation || this.options.cacheFile, this.options.cwd);
/**
* cache used to not operate on files that haven't changed since last successful
* execution (e.g. file passed with no errors and no warnings
* @type {Object}
*/
this._fileCache = fileEntryCache.create(cacheFile);
if (!this.options.cache) {
this._fileCache.destroy();
}
// load in additional rules
if (this.options.rulePaths) {
var cwd = this.options.cwd;
this.options.rulePaths.forEach(function(rulesdir) {
debug("Loading rules from " + rulesdir);
rules.load(rulesdir, cwd);
});
}
Object.keys(this.options.rules || {}).forEach(function(name) {
validator.validateRuleOptions(name, this.options.rules[name], "CLI");
}.bind(this));
} |
JavaScript | function hashOfConfigFor(filename) {
var config = configHelper.getConfig(filename);
if (!prevConfig) {
prevConfig = {};
}
// reuse the previously hashed config if the config hasn't changed
if (prevConfig.config !== config) {
// config changed so we need to calculate the hash of the config
// and the hash of the plugins being used
prevConfig.config = config;
var eslintVersion = pkg.version;
prevConfig.hash = md5Hash(eslintVersion + "_" + stringify(config));
}
return prevConfig.hash;
} | function hashOfConfigFor(filename) {
var config = configHelper.getConfig(filename);
if (!prevConfig) {
prevConfig = {};
}
// reuse the previously hashed config if the config hasn't changed
if (prevConfig.config !== config) {
// config changed so we need to calculate the hash of the config
// and the hash of the plugins being used
prevConfig.config = config;
var eslintVersion = pkg.version;
prevConfig.hash = md5Hash(eslintVersion + "_" + stringify(config));
}
return prevConfig.hash;
} |
JavaScript | function executeOnFile(filename, warnIgnored) {
var hashOfConfig;
if (options.ignore !== false) {
if (ignoredPaths.contains(filename, "custom")) {
if (warnIgnored) {
results.push(createIgnoreResult(filename));
}
return;
}
if (ignoredPaths.contains(filename, "default")) {
return;
}
}
filename = path.resolve(filename);
if (processed[filename]) {
return;
}
if (options.cache) {
// get the descriptor for this file
// with the metadata and the flag that determines if
// the file has changed
var descriptor = fileCache.getFileDescriptor(filename);
var meta = descriptor.meta || {};
hashOfConfig = hashOfConfigFor(filename);
var changed = descriptor.changed || meta.hashOfConfig !== hashOfConfig;
if (!changed) {
debug("Skipping file since hasn't changed: " + filename);
// Adding the filename to the processed hashmap
// so the reporting is not affected (showing a warning about .eslintignore being used
// when it is not really used)
processed[filename] = true;
// Add the the cached results (always will be 0 error and 0 warnings)
// cause we don't save to cache files that failed
// to guarantee that next execution will process those files as well
results.push(descriptor.meta.results);
// move to the next file
return;
}
}
debug("Processing " + filename);
processed[filename] = true;
var res = processFile(filename, configHelper, options);
if (options.cache) {
// if a file contains errors or warnings we don't want to
// store the file in the cache so we can guarantee that
// next execution will also operate on this file
if ( res.errorCount > 0 || res.warningCount > 0 ) {
debug("File has problems, skipping it: " + filename);
// remove the entry from the cache
fileCache.removeEntry( filename );
} else {
// since the file passed we store the result here
// TODO: check this as we might not need to store the
// successful runs as it will always should be 0 error 0 warnings
descriptor.meta.hashOfConfig = hashOfConfig;
descriptor.meta.results = res;
}
}
results.push(res);
} | function executeOnFile(filename, warnIgnored) {
var hashOfConfig;
if (options.ignore !== false) {
if (ignoredPaths.contains(filename, "custom")) {
if (warnIgnored) {
results.push(createIgnoreResult(filename));
}
return;
}
if (ignoredPaths.contains(filename, "default")) {
return;
}
}
filename = path.resolve(filename);
if (processed[filename]) {
return;
}
if (options.cache) {
// get the descriptor for this file
// with the metadata and the flag that determines if
// the file has changed
var descriptor = fileCache.getFileDescriptor(filename);
var meta = descriptor.meta || {};
hashOfConfig = hashOfConfigFor(filename);
var changed = descriptor.changed || meta.hashOfConfig !== hashOfConfig;
if (!changed) {
debug("Skipping file since hasn't changed: " + filename);
// Adding the filename to the processed hashmap
// so the reporting is not affected (showing a warning about .eslintignore being used
// when it is not really used)
processed[filename] = true;
// Add the the cached results (always will be 0 error and 0 warnings)
// cause we don't save to cache files that failed
// to guarantee that next execution will process those files as well
results.push(descriptor.meta.results);
// move to the next file
return;
}
}
debug("Processing " + filename);
processed[filename] = true;
var res = processFile(filename, configHelper, options);
if (options.cache) {
// if a file contains errors or warnings we don't want to
// store the file in the cache so we can guarantee that
// next execution will also operate on this file
if ( res.errorCount > 0 || res.warningCount > 0 ) {
debug("File has problems, skipping it: " + filename);
// remove the entry from the cache
fileCache.removeEntry( filename );
} else {
// since the file passed we store the result here
// TODO: check this as we might not need to store the
// successful runs as it will always should be 0 error 0 warnings
descriptor.meta.hashOfConfig = hashOfConfig;
descriptor.meta.results = res;
}
}
results.push(res);
} |
JavaScript | function generateFormatterExamples(formatterInfo, prereleaseVersion) {
var output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo),
filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-formatter-example.html";
if (prereleaseVersion) {
filename = filename.replace("/docs", "/docs/" + prereleaseVersion);
htmlFilename = htmlFilename.replace("/docs", "/docs/" + prereleaseVersion);
}
output.to(filename);
formatterInfo.formatterResults.html.result.to(htmlFilename);
} | function generateFormatterExamples(formatterInfo, prereleaseVersion) {
var output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo),
filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-formatter-example.html";
if (prereleaseVersion) {
filename = filename.replace("/docs", "/docs/" + prereleaseVersion);
htmlFilename = htmlFilename.replace("/docs", "/docs/" + prereleaseVersion);
}
output.to(filename);
formatterInfo.formatterResults.html.result.to(htmlFilename);
} |
JavaScript | function calculateReleaseInfo() {
// get most recent tag
var tags = getVersionTags(),
lastTag = tags[tags.length - 1],
commitFlagPattern = /([a-z]+):/i,
releaseInfo = {};
// get log statements
var logs = execSilent("git log --no-merges --pretty=format:\"* %h %s (%an)\" " + lastTag + "..HEAD").split(/\n/g);
// arrange change types into categories
logs.forEach(function(log) {
var flag = log.match(commitFlagPattern)[1].toLowerCase();
if (!releaseInfo["changelog_" + flag]) {
releaseInfo["changelog_" + flag] = [];
}
releaseInfo["changelog_" + flag].push(log);
});
var output = logs.join("\n"); // and join it into a string
releaseInfo.raw = output;
if (releaseInfo.changelog_breaking) {
releaseInfo.releaseType = "major";
} else if (releaseInfo.changelog_new || releaseInfo.changelog_update) {
releaseInfo.releaseType = "minor";
} else {
releaseInfo.releaseType = "patch";
}
// increment version from current version
releaseInfo.version = "v" + semver.inc(require("./package.json").version, releaseInfo.releaseType);
return releaseInfo;
} | function calculateReleaseInfo() {
// get most recent tag
var tags = getVersionTags(),
lastTag = tags[tags.length - 1],
commitFlagPattern = /([a-z]+):/i,
releaseInfo = {};
// get log statements
var logs = execSilent("git log --no-merges --pretty=format:\"* %h %s (%an)\" " + lastTag + "..HEAD").split(/\n/g);
// arrange change types into categories
logs.forEach(function(log) {
var flag = log.match(commitFlagPattern)[1].toLowerCase();
if (!releaseInfo["changelog_" + flag]) {
releaseInfo["changelog_" + flag] = [];
}
releaseInfo["changelog_" + flag].push(log);
});
var output = logs.join("\n"); // and join it into a string
releaseInfo.raw = output;
if (releaseInfo.changelog_breaking) {
releaseInfo.releaseType = "major";
} else if (releaseInfo.changelog_new || releaseInfo.changelog_update) {
releaseInfo.releaseType = "minor";
} else {
releaseInfo.releaseType = "patch";
}
// increment version from current version
releaseInfo.version = "v" + semver.inc(require("./package.json").version, releaseInfo.releaseType);
return releaseInfo;
} |
JavaScript | function release() {
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
writeChangelog(releaseInfo);
exec("git add .");
exec("git commit -m \"Docs: Autogenerated changelog for " + releaseInfo.version + "\"");
echo("Generating " + releaseInfo.version);
execSilent("npm version " + releaseInfo.version);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
echo("Publishing to npm");
getPackageInfo().files.filter(function(dirPath) {
return fs.lstatSync(dirPath).isDirectory();
}).forEach(nodeCLI.exec.bind(nodeCLI, "linefix"));
exec("npm publish");
echo("Generating site");
target.gensite();
generateBlogPost(releaseInfo);
target.publishsite();
} | function release() {
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
writeChangelog(releaseInfo);
exec("git add .");
exec("git commit -m \"Docs: Autogenerated changelog for " + releaseInfo.version + "\"");
echo("Generating " + releaseInfo.version);
execSilent("npm version " + releaseInfo.version);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
echo("Publishing to npm");
getPackageInfo().files.filter(function(dirPath) {
return fs.lstatSync(dirPath).isDirectory();
}).forEach(nodeCLI.exec.bind(nodeCLI, "linefix"));
exec("npm publish");
echo("Generating site");
target.gensite();
generateBlogPost(releaseInfo);
target.publishsite();
} |
JavaScript | function prerelease(version) {
if (!version) {
echo("Missing prerelease version.");
exit(1);
}
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
// override the version for prereleases
releaseInfo.version = version[0] === "v" ? version : "v" + version;
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
writeChangelog(releaseInfo);
exec("git add .");
exec("git commit -m \"Docs: Autogenerated changelog for " + releaseInfo.version + "\"");
echo("Generating " + releaseInfo.version);
execSilent("npm version " + version);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
// publish to npm
echo("Publishing to npm");
getPackageInfo().files.filter(function(dirPath) {
return fs.lstatSync(dirPath).isDirectory();
}).forEach(nodeCLI.exec.bind(nodeCLI, "linefix"));
exec("npm publish --tag next");
echo("Generating site");
target.gensite(semver.inc(version, "major"));
generateBlogPost(releaseInfo);
echo("Site has not been pushed, please update blog post and push manually.");
} | function prerelease(version) {
if (!version) {
echo("Missing prerelease version.");
exit(1);
}
echo("Updating dependencies");
exec("npm install && npm prune");
echo("Running tests");
target.test();
echo("Calculating changes for release");
var releaseInfo = calculateReleaseInfo();
// override the version for prereleases
releaseInfo.version = version[0] === "v" ? version : "v" + version;
echo("Release is " + releaseInfo.version);
echo("Generating changelog");
writeChangelog(releaseInfo);
exec("git add .");
exec("git commit -m \"Docs: Autogenerated changelog for " + releaseInfo.version + "\"");
echo("Generating " + releaseInfo.version);
execSilent("npm version " + version);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
// publish to npm
echo("Publishing to npm");
getPackageInfo().files.filter(function(dirPath) {
return fs.lstatSync(dirPath).isDirectory();
}).forEach(nodeCLI.exec.bind(nodeCLI, "linefix"));
exec("npm publish --tag next");
echo("Generating site");
target.gensite(semver.inc(version, "major"));
generateBlogPost(releaseInfo);
echo("Site has not been pushed, please update blog post and push manually.");
} |
JavaScript | function createConfigForPerformanceTest() {
var content = [
"root: true",
"env:",
" node: true",
" es6: true",
"rules:"
];
content.push.apply(
content,
ls("lib/rules").map(function(fileName) {
return " " + path.basename(fileName, ".js") + ": 2";
})
);
content.join("\n").to(PERF_ESLINTRC);
} | function createConfigForPerformanceTest() {
var content = [
"root: true",
"env:",
" node: true",
" es6: true",
"rules:"
];
content.push.apply(
content,
ls("lib/rules").map(function(fileName) {
return " " + path.basename(fileName, ".js") + ": 2";
})
);
content.join("\n").to(PERF_ESLINTRC);
} |
JavaScript | function sortTable(n, numeric=false) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tournament_participants");
switching = true;
// Set the sorting direction to ascending:
dir = "asc";
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
rows = table.rows;
/* Loop through all table rows (except the
first, which contains table headers): */
for (i = 1; i < (rows.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Get the two elements you want to compare,
one from current row and one from the next: */
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/* Check if the two rows should switch place,
based on the direction, asc or desc: */
if (dir == "asc") {
if (numeric){
x1 = Number(x.innerHTML)
y1 = Number(y.innerHTML)
if (x1 == 0 ) { x1 = 10000 }
if (y1 == 0 ) { y1 = 10000 }
if (x1 > y1) {
shouldSwitch = true;
break;
}
}
else {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
} else if (dir == "desc") {
if (numeric){
x1 = Number(x.innerHTML)
y1 = Number(y.innerHTML)
if (x1 == 0 ) { x1 = -1000 }
if (y1 == 0 ) { y1 = -1000 }
if (x1 < y1) {
shouldSwitch = true;
break;
}
}
else {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
// Each time a switch is done, increase this count by 1:
switchcount ++;
} else {
/* If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again. */
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
} | function sortTable(n, numeric=false) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tournament_participants");
switching = true;
// Set the sorting direction to ascending:
dir = "asc";
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// Start by saying: no switching is done:
switching = false;
rows = table.rows;
/* Loop through all table rows (except the
first, which contains table headers): */
for (i = 1; i < (rows.length - 1); i++) {
// Start by saying there should be no switching:
shouldSwitch = false;
/* Get the two elements you want to compare,
one from current row and one from the next: */
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/* Check if the two rows should switch place,
based on the direction, asc or desc: */
if (dir == "asc") {
if (numeric){
x1 = Number(x.innerHTML)
y1 = Number(y.innerHTML)
if (x1 == 0 ) { x1 = 10000 }
if (y1 == 0 ) { y1 = 10000 }
if (x1 > y1) {
shouldSwitch = true;
break;
}
}
else {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
} else if (dir == "desc") {
if (numeric){
x1 = Number(x.innerHTML)
y1 = Number(y.innerHTML)
if (x1 == 0 ) { x1 = -1000 }
if (y1 == 0 ) { y1 = -1000 }
if (x1 < y1) {
shouldSwitch = true;
break;
}
}
else {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
// Each time a switch is done, increase this count by 1:
switchcount ++;
} else {
/* If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again. */
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
} |
JavaScript | function extendArray(daddyArray, childArray) {
for (var i = 0; i < childArray.length; i++) {
daddyArray.push(childArray[i]);
}
} | function extendArray(daddyArray, childArray) {
for (var i = 0; i < childArray.length; i++) {
daddyArray.push(childArray[i]);
}
} |
JavaScript | initNProgress() {
$(document).ready(function () {
if (this.isPjax) {
$(document).on('pjax:send', function () {
NProgress.start();
});
$(document).on('pjax:end', function () {
NProgress.done();
});
} else {
$(document).ajaxStart(function() {
NProgress.start();
});
$(document).ajaxComplete(function() {
NProgress.done();
});
}
});
return this;
} | initNProgress() {
$(document).ready(function () {
if (this.isPjax) {
$(document).on('pjax:send', function () {
NProgress.start();
});
$(document).on('pjax:end', function () {
NProgress.done();
});
} else {
$(document).ajaxStart(function() {
NProgress.start();
});
$(document).ajaxComplete(function() {
NProgress.done();
});
}
});
return this;
} |
JavaScript | schema() {
return {
desc: this.desc
};
} | schema() {
return {
desc: this.desc
};
} |
JavaScript | async applyDefaults() {
const requiredOptions = {
long: {},
short: {}
};
const len = this.contexts.length;
log(`Processing default options and environment variables for ${highlight(len)} ${pluralize('context', len)}`);
this.env = {};
// loop through every context
for (let i = len; i; i--) {
const ctx = this.contexts[i - 1];
// init options
for (const options of ctx.options.values()) {
for (const option of options) {
if (option.name) {
const name = option.camelCase || ctx.get('camelCase') ? camelCase(option.name) : option.name;
if (this.argv[name] === undefined) {
let value = option.default;
if (option.datatype === 'bool' && typeof value !== 'boolean') {
value = !!option.negate;
} else if (option.type === 'count') {
value = 0;
}
if (option.multiple && !Array.isArray(value)) {
value = value !== undefined ? [ value ] : [];
}
if (!this._fired.has(option) && typeof option.callback === 'function') {
const newValue = await option.callback({
ctx,
data: this.opts.data,
exitCode: this.opts.exitCode,
input: [ value ],
name,
async next() {},
opts: this.opts,
option,
parser: this,
value
});
if (newValue !== undefined) {
value = newValue;
}
}
this.argv[name] = value;
}
if (option.env && process.env[option.env] !== undefined) {
this.env[name] = option.transform(process.env[option.env]);
}
}
if (option.required) {
if (option.long) {
requiredOptions.long[option.long] = option;
}
if (option.short) {
requiredOptions.short[option.short] = option;
}
} else {
if (option.long) {
delete requiredOptions.long[option.long];
}
if (option.short) {
delete requiredOptions.short[option.short];
}
}
}
}
// init arguments
for (const arg of ctx.args) {
if (arg.name) {
const name = arg.camelCase || ctx.get('camelCase') ? camelCase(arg.name) : arg.name;
if (this.argv[name] === undefined) {
let value = arg.default;
if (arg.multiple && !Array.isArray(value)) {
value = value !== undefined ? [ value ] : [];
}
if (!this._fired.has(arg) && typeof arg.callback === 'function') {
const newValue = await arg.callback({
arg,
ctx,
data: this.opts.data,
exitCode: this.opts.exitCode,
name,
opts: this.opts,
parser: this,
value
});
if (newValue !== undefined) {
value = newValue;
}
}
this.argv[name] = value;
}
if (arg.env && process.env[arg.env] !== undefined) {
this.env[name] = arg.transform(process.env[arg.env]);
}
}
}
}
this.required = new Set(Object.values(requiredOptions.long));
for (const option of Object.values(requiredOptions.short)) {
this.required.add(option);
}
} | async applyDefaults() {
const requiredOptions = {
long: {},
short: {}
};
const len = this.contexts.length;
log(`Processing default options and environment variables for ${highlight(len)} ${pluralize('context', len)}`);
this.env = {};
// loop through every context
for (let i = len; i; i--) {
const ctx = this.contexts[i - 1];
// init options
for (const options of ctx.options.values()) {
for (const option of options) {
if (option.name) {
const name = option.camelCase || ctx.get('camelCase') ? camelCase(option.name) : option.name;
if (this.argv[name] === undefined) {
let value = option.default;
if (option.datatype === 'bool' && typeof value !== 'boolean') {
value = !!option.negate;
} else if (option.type === 'count') {
value = 0;
}
if (option.multiple && !Array.isArray(value)) {
value = value !== undefined ? [ value ] : [];
}
if (!this._fired.has(option) && typeof option.callback === 'function') {
const newValue = await option.callback({
ctx,
data: this.opts.data,
exitCode: this.opts.exitCode,
input: [ value ],
name,
async next() {},
opts: this.opts,
option,
parser: this,
value
});
if (newValue !== undefined) {
value = newValue;
}
}
this.argv[name] = value;
}
if (option.env && process.env[option.env] !== undefined) {
this.env[name] = option.transform(process.env[option.env]);
}
}
if (option.required) {
if (option.long) {
requiredOptions.long[option.long] = option;
}
if (option.short) {
requiredOptions.short[option.short] = option;
}
} else {
if (option.long) {
delete requiredOptions.long[option.long];
}
if (option.short) {
delete requiredOptions.short[option.short];
}
}
}
}
// init arguments
for (const arg of ctx.args) {
if (arg.name) {
const name = arg.camelCase || ctx.get('camelCase') ? camelCase(arg.name) : arg.name;
if (this.argv[name] === undefined) {
let value = arg.default;
if (arg.multiple && !Array.isArray(value)) {
value = value !== undefined ? [ value ] : [];
}
if (!this._fired.has(arg) && typeof arg.callback === 'function') {
const newValue = await arg.callback({
arg,
ctx,
data: this.opts.data,
exitCode: this.opts.exitCode,
name,
opts: this.opts,
parser: this,
value
});
if (newValue !== undefined) {
value = newValue;
}
}
this.argv[name] = value;
}
if (arg.env && process.env[arg.env] !== undefined) {
this.env[name] = arg.transform(process.env[arg.env]);
}
}
}
}
this.required = new Set(Object.values(requiredOptions.long));
for (const option of Object.values(requiredOptions.short)) {
this.required.add(option);
}
} |
JavaScript | async parseWithContext(ctx) {
// print the context's info
log(`Context: ${highlight(ctx.name)}`);
if (!ctx.lookup.empty) {
log(ctx.lookup.toString());
}
await this.parseArg(ctx, 0);
} | async parseWithContext(ctx) {
// print the context's info
log(`Context: ${highlight(ctx.name)}`);
if (!ctx.lookup.empty) {
log(ctx.lookup.toString());
}
await this.parseArg(ctx, 0);
} |
JavaScript | generateHelp() {
const entries = [];
for (const ctxName of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(ctxName).exports[ctxName];
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visible') {
labels.add(alias);
}
}
entries.push({
name,
desc,
label: Array.from(labels).sort((a, b) => {
return a.length === b.length ? a.localeCompare(b) : a.length - b.length;
}).join(', '),
aliases: aliases ? Object.keys(aliases) : null
});
}
}
entries.sort((a, b) => a.label.localeCompare(b.label));
return {
count: entries.length,
entries
};
} | generateHelp() {
const entries = [];
for (const ctxName of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(ctxName).exports[ctxName];
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visible') {
labels.add(alias);
}
}
entries.push({
name,
desc,
label: Array.from(labels).sort((a, b) => {
return a.length === b.length ? a.localeCompare(b) : a.length - b.length;
}).join(', '),
aliases: aliases ? Object.keys(aliases) : null
});
}
}
entries.sort((a, b) => a.label.localeCompare(b.label));
return {
count: entries.length,
entries
};
} |
JavaScript | add(format, params) {
if (!format) {
throw E.INVALID_ARGUMENT('Invalid option format or option', { name: 'format', scope: 'OptionMap.add', value: format });
}
const results = [];
let lastGroup = '';
let options = [];
if (Array.isArray(format)) {
options = format;
} else if (typeof format === 'object' && format.clikit instanceof Set && (format.clikit.has('OptionList') || format.clikit.has('OptionMap'))) {
for (const [ group, opts ] of format.entries()) {
if (group && group !== lastGroup) {
options.push(group);
lastGroup = group;
}
options.push.apply(options, opts);
}
} else if (typeof format === 'object' && (format instanceof Option || !(format.clikit instanceof Set) || !format.clikit.has('Option'))) {
options.push(format);
} else {
options.push(new Option(format, params));
}
// reset group
lastGroup = '';
const add = opt => {
let opts = this.get(lastGroup);
if (!opts) {
this.set(lastGroup, opts = []);
}
opts.push(opt);
results.push(opt);
this.count++;
};
// at this point we have a unified array of stuff
for (const it of options) {
if (typeof it === 'string') {
lastGroup = it;
continue;
}
if (typeof it !== 'object') {
throw E.INVALID_ARGUMENT(`Expected option to be an object: ${it && it.name || it}`, { name: 'option', scope: 'OptionMap.add', value: it });
}
if (it instanceof Option) {
add(it);
} else if (it.clikit instanceof Set) {
add(new Option(it));
} else {
// it is a format-params object
for (const [ format, params ] of Object.entries(it)) {
add(params instanceof Option ? params : new Option(format, params));
}
}
}
return results;
} | add(format, params) {
if (!format) {
throw E.INVALID_ARGUMENT('Invalid option format or option', { name: 'format', scope: 'OptionMap.add', value: format });
}
const results = [];
let lastGroup = '';
let options = [];
if (Array.isArray(format)) {
options = format;
} else if (typeof format === 'object' && format.clikit instanceof Set && (format.clikit.has('OptionList') || format.clikit.has('OptionMap'))) {
for (const [ group, opts ] of format.entries()) {
if (group && group !== lastGroup) {
options.push(group);
lastGroup = group;
}
options.push.apply(options, opts);
}
} else if (typeof format === 'object' && (format instanceof Option || !(format.clikit instanceof Set) || !format.clikit.has('Option'))) {
options.push(format);
} else {
options.push(new Option(format, params));
}
// reset group
lastGroup = '';
const add = opt => {
let opts = this.get(lastGroup);
if (!opts) {
this.set(lastGroup, opts = []);
}
opts.push(opt);
results.push(opt);
this.count++;
};
// at this point we have a unified array of stuff
for (const it of options) {
if (typeof it === 'string') {
lastGroup = it;
continue;
}
if (typeof it !== 'object') {
throw E.INVALID_ARGUMENT(`Expected option to be an object: ${it && it.name || it}`, { name: 'option', scope: 'OptionMap.add', value: it });
}
if (it instanceof Option) {
add(it);
} else if (it.clikit instanceof Set) {
add(new Option(it));
} else {
// it is a format-params object
for (const [ format, params ] of Object.entries(it)) {
add(params instanceof Option ? params : new Option(format, params));
}
}
}
return results;
} |
JavaScript | generateHelp() {
let count = 0;
const groups = {};
const sortFn = (a, b) => {
return a.order < b.order ? -1 : a.order > b.order ? 1 : a.long.localeCompare(b.long);
};
for (const [ groupName, options ] of this.entries()) {
const group = groups[groupName] = [];
for (const opt of options.sort(sortFn)) {
if (!opt.hidden) {
const label = `${opt.short ? `-${opt.short}, ` : ''}` +
`--${opt.negate ? 'no-' : ''}${opt.long}` +
`${opt.isFlag ? '' : ` ${opt.required ? '<' : '['}${opt.hint || 'value'}${opt.required ? '>' : ']'}`}`;
group.push({
aliases: Object.keys(opt.aliases).filter(a => opt.aliases[a]),
datatype: opt.datatype,
default: opt.default,
desc: opt.desc,
hint: opt.hint,
isFlag: opt.isFlag,
label,
long: opt.long,
max: opt.max,
min: opt.min,
name: opt.name,
negate: opt.negate,
required: opt.required,
short: opt.short
});
count++;
}
}
}
return {
count,
groups
};
} | generateHelp() {
let count = 0;
const groups = {};
const sortFn = (a, b) => {
return a.order < b.order ? -1 : a.order > b.order ? 1 : a.long.localeCompare(b.long);
};
for (const [ groupName, options ] of this.entries()) {
const group = groups[groupName] = [];
for (const opt of options.sort(sortFn)) {
if (!opt.hidden) {
const label = `${opt.short ? `-${opt.short}, ` : ''}` +
`--${opt.negate ? 'no-' : ''}${opt.long}` +
`${opt.isFlag ? '' : ` ${opt.required ? '<' : '['}${opt.hint || 'value'}${opt.required ? '>' : ']'}`}`;
group.push({
aliases: Object.keys(opt.aliases).filter(a => opt.aliases[a]),
datatype: opt.datatype,
default: opt.default,
desc: opt.desc,
hint: opt.hint,
isFlag: opt.isFlag,
label,
long: opt.long,
max: opt.max,
min: opt.min,
name: opt.name,
negate: opt.negate,
required: opt.required,
short: opt.short
});
count++;
}
}
}
return {
count,
groups
};
} |
JavaScript | function split(str) {
if (typeof str !== 'string') {
return str;
}
const results = [];
const re = /\x07|\x1b(?:[a-z\d]|\[\?25[hl]|\[[A-Za-z]|\[\d+[A-Za-z]|\[\d+;\d+H|\]\d+[^\x07]+\x07)/;
let m;
while (m = re.exec(str)) {
results.push(m.index ? str.substring(0, m.index) : '');
results.push(str.substr(m.index, m[0].length));
str = str.substring(m.index + m[0].length);
}
if (str) {
results.push(str);
}
return results;
} | function split(str) {
if (typeof str !== 'string') {
return str;
}
const results = [];
const re = /\x07|\x1b(?:[a-z\d]|\[\?25[hl]|\[[A-Za-z]|\[\d+[A-Za-z]|\[\d+;\d+H|\]\d+[^\x07]+\x07)/;
let m;
while (m = re.exec(str)) {
results.push(m.index ? str.substring(0, m.index) : '');
results.push(str.substr(m.index, m[0].length));
str = str.substring(m.index + m[0].length);
}
if (str) {
results.push(str);
}
return results;
} |
JavaScript | function escapeTildes(str) {
let state = [ 0 ];
let s = '';
for (let i = 0, l = str.length; i < l; i++) {
switch (state[0]) {
case 0: // not in an expression
if ((i === 0 || str[i - 1] !== '\\') && str[i] === '$' && str[i + 1] === '{') {
s += str[i++]; // $
s += str[i]; // {
state.unshift(1);
} else if (str[i] === '`') {
s += '\\`';
} else {
s += str[i];
}
break;
case 1: // in an expression
if (str[i] === '}') {
state.shift();
} else if (str[i] === '`') {
state.unshift(2);
}
s += str[i];
break;
case 2: // in template literal
if (str[i] === '`') {
state.shift();
}
s += str[i];
break;
}
}
return s;
} | function escapeTildes(str) {
let state = [ 0 ];
let s = '';
for (let i = 0, l = str.length; i < l; i++) {
switch (state[0]) {
case 0: // not in an expression
if ((i === 0 || str[i - 1] !== '\\') && str[i] === '$' && str[i + 1] === '{') {
s += str[i++]; // $
s += str[i]; // {
state.unshift(1);
} else if (str[i] === '`') {
s += '\\`';
} else {
s += str[i];
}
break;
case 1: // in an expression
if (str[i] === '}') {
state.shift();
} else if (str[i] === '`') {
state.unshift(2);
}
s += str[i];
break;
case 2: // in template literal
if (str[i] === '`') {
state.shift();
}
s += str[i];
break;
}
}
return s;
} |
JavaScript | onOutput(cb) {
if (this.outputCallbacks) {
this.outputCallbacks.push(cb);
} else {
cb(this.outputResolution);
}
return this;
} | onOutput(cb) {
if (this.outputCallbacks) {
this.outputCallbacks.push(cb);
} else {
cb(this.outputResolution);
}
return this;
} |
JavaScript | registerExtension(name, meta, params) {
log(`Registering extension command: ${highlight(`${this.name}:${name}`)}`);
const cmd = new Command(name, {
parent: this,
...params
});
this.exports[name] = Object.assign(cmd, meta);
cmd.isExtension = true;
if (meta?.pkg?.clikit) {
cmd.isCLIKitExtension = true;
cmd.load = async function load() {
log(`Requiring cli-kit extension: ${highlight(this.name)} -> ${highlight(meta.pkg.main)}`);
let ctx;
try {
ctx = require(meta.pkg.main);
if (!ctx || (typeof ctx !== 'object' && typeof ctx !== 'function')) {
throw new Error('Extension must export an object or function');
}
// if this is an ES6 module, grab the default export
if (ctx.__esModule) {
ctx = ctx.default;
}
// if the export was a function, call it now to get its CLI definition
if (typeof ctx === 'function') {
ctx = await ctx(this);
}
if (!ctx || typeof ctx !== 'object') {
throw new Error('Extension does not resolve an object');
}
} catch (err) {
throw E.INVALID_EXTENSION(`Bad extension "${this.name}": ${err.message}`, { name: this.name, scope: 'Extension.load', value: err });
}
this.aliases = ctx.aliases;
this.camelCase = ctx.camelCase;
this.defaultCommand = ctx.defaultCommand;
this.help = ctx.help;
this.remoteHelp = ctx.remoteHelp;
this.treatUnknownOptionsAsArguments = ctx.treatUnknownOptionsAsArguments;
this.version = ctx.version;
this.init({
args: ctx.args,
banner: ctx.banner,
commands: ctx.commands,
desc: ctx.desc || this.desc,
extensions: ctx.extensions,
name: this.name || ctx.name,
options: ctx.options,
parent: this.parent,
title: ctx.title !== 'Global' && ctx.title || this.name
});
const versionOption = this.version && this.lookup.long.version;
if (versionOption && typeof versionOption.callback !== 'function') {
versionOption.callback = async ({ exitCode, opts, next }) => {
if (await next()) {
let { version } = this;
if (typeof version === 'function') {
version = await version(opts);
}
(opts.terminal || this.get('terminal')).stdout.write(`${version}\n`);
exitCode(0);
return false;
}
};
}
if (typeof ctx.action === 'function') {
this.action = ctx.action;
} else {
this.action = async parser => {
if (this.defaultCommand !== 'help' || !this.get('help')) {
const defcmd = this.defaultCommand && this.commands[this.defaultCommand];
if (defcmd) {
return await defcmd.action.call(defcmd, parser);
}
}
return await helpCommand.action.call(helpCommand, parser);
};
}
}.bind(cmd);
}
} | registerExtension(name, meta, params) {
log(`Registering extension command: ${highlight(`${this.name}:${name}`)}`);
const cmd = new Command(name, {
parent: this,
...params
});
this.exports[name] = Object.assign(cmd, meta);
cmd.isExtension = true;
if (meta?.pkg?.clikit) {
cmd.isCLIKitExtension = true;
cmd.load = async function load() {
log(`Requiring cli-kit extension: ${highlight(this.name)} -> ${highlight(meta.pkg.main)}`);
let ctx;
try {
ctx = require(meta.pkg.main);
if (!ctx || (typeof ctx !== 'object' && typeof ctx !== 'function')) {
throw new Error('Extension must export an object or function');
}
// if this is an ES6 module, grab the default export
if (ctx.__esModule) {
ctx = ctx.default;
}
// if the export was a function, call it now to get its CLI definition
if (typeof ctx === 'function') {
ctx = await ctx(this);
}
if (!ctx || typeof ctx !== 'object') {
throw new Error('Extension does not resolve an object');
}
} catch (err) {
throw E.INVALID_EXTENSION(`Bad extension "${this.name}": ${err.message}`, { name: this.name, scope: 'Extension.load', value: err });
}
this.aliases = ctx.aliases;
this.camelCase = ctx.camelCase;
this.defaultCommand = ctx.defaultCommand;
this.help = ctx.help;
this.remoteHelp = ctx.remoteHelp;
this.treatUnknownOptionsAsArguments = ctx.treatUnknownOptionsAsArguments;
this.version = ctx.version;
this.init({
args: ctx.args,
banner: ctx.banner,
commands: ctx.commands,
desc: ctx.desc || this.desc,
extensions: ctx.extensions,
name: this.name || ctx.name,
options: ctx.options,
parent: this.parent,
title: ctx.title !== 'Global' && ctx.title || this.name
});
const versionOption = this.version && this.lookup.long.version;
if (versionOption && typeof versionOption.callback !== 'function') {
versionOption.callback = async ({ exitCode, opts, next }) => {
if (await next()) {
let { version } = this;
if (typeof version === 'function') {
version = await version(opts);
}
(opts.terminal || this.get('terminal')).stdout.write(`${version}\n`);
exitCode(0);
return false;
}
};
}
if (typeof ctx.action === 'function') {
this.action = ctx.action;
} else {
this.action = async parser => {
if (this.defaultCommand !== 'help' || !this.get('help')) {
const defcmd = this.defaultCommand && this.commands[this.defaultCommand];
if (defcmd) {
return await defcmd.action.call(defcmd, parser);
}
}
return await helpCommand.action.call(helpCommand, parser);
};
}
}.bind(cmd);
}
} |
JavaScript | schema() {
return {
...super.schema,
path: this.path
};
} | schema() {
return {
...super.schema,
path: this.path
};
} |
JavaScript | argument(arg) {
this.args.add(arg);
this.rev++;
return this;
} | argument(arg) {
this.args.add(arg);
this.rev++;
return this;
} |
JavaScript | command(cmd, params, clone) {
const cmds = this.commands.add(cmd, params, clone);
for (const cmd of cmds) {
log(`Adding command: ${highlight(cmd.name)} ${note(`(${this.name})`)}`);
this.register(cmd);
}
this.rev++;
return this;
} | command(cmd, params, clone) {
const cmds = this.commands.add(cmd, params, clone);
for (const cmd of cmds) {
log(`Adding command: ${highlight(cmd.name)} ${note(`(${this.name})`)}`);
this.register(cmd);
}
this.rev++;
return this;
} |
JavaScript | extension(ext, name, clone) {
const exts = this.extensions.add(ext, name, clone);
for (const ext of exts) {
log(`Adding extension: ${highlight(ext.name)} ${note(`(${this.name})`)}`);
this.register(ext);
}
this.rev++;
return this;
} | extension(ext, name, clone) {
const exts = this.extensions.add(ext, name, clone);
for (const ext of exts) {
log(`Adding extension: ${highlight(ext.name)} ${note(`(${this.name})`)}`);
this.register(ext);
}
this.rev++;
return this;
} |
JavaScript | init(params, clone) {
if (!params || typeof params !== 'object' || (params.clikit instanceof Set && !params.clikit.has('Context'))) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
if (params.clikit instanceof Set && !params.clikit.has('Context')) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
this.args = new ArgumentList();
this.autoHideBanner = params.autoHideBanner;
this.banner = params.banner;
this.commands = new CommandMap();
this.defaultCommand = params.defaultCommand;
this.desc = params.desc;
this.errorIfUnknownCommand = params.errorIfUnknownCommand;
this.extensions = new ExtensionMap();
this.helpExitCode = params.helpExitCode;
this.helpTemplateFile = params.helpTemplateFile;
this.hideNoBannerOption = params.hideNoBannerOption;
this.hideNoColorOption = params.hideNoColorOption;
this.lookup = new Lookup();
this.name = params.name;
this.nodeVersion = params.nodeVersion;
this.options = new OptionMap();
this.parent = params.parent;
this.rev = 0;
this.showBannerForExternalCLIs = params.showBannerForExternalCLIs;
this.showHelpOnError = params.showHelpOnError;
this.title = params.title || params.name;
this.treatUnknownOptionsAsArguments = !!params.treatUnknownOptionsAsArguments;
this.version = params.version;
params.args && this.argument(params.args);
params.commands && this.command(params.commands, null, clone);
params.extensions && this.extension(params.extensions, null, clone);
params.options && this.option(params.options);
return this;
} | init(params, clone) {
if (!params || typeof params !== 'object' || (params.clikit instanceof Set && !params.clikit.has('Context'))) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
if (params.clikit instanceof Set && !params.clikit.has('Context')) {
throw E.INVALID_ARGUMENT('Expected parameters to be an object or Context', { name: 'params', scope: 'Context.init', value: params });
}
this.args = new ArgumentList();
this.autoHideBanner = params.autoHideBanner;
this.banner = params.banner;
this.commands = new CommandMap();
this.defaultCommand = params.defaultCommand;
this.desc = params.desc;
this.errorIfUnknownCommand = params.errorIfUnknownCommand;
this.extensions = new ExtensionMap();
this.helpExitCode = params.helpExitCode;
this.helpTemplateFile = params.helpTemplateFile;
this.hideNoBannerOption = params.hideNoBannerOption;
this.hideNoColorOption = params.hideNoColorOption;
this.lookup = new Lookup();
this.name = params.name;
this.nodeVersion = params.nodeVersion;
this.options = new OptionMap();
this.parent = params.parent;
this.rev = 0;
this.showBannerForExternalCLIs = params.showBannerForExternalCLIs;
this.showHelpOnError = params.showHelpOnError;
this.title = params.title || params.name;
this.treatUnknownOptionsAsArguments = !!params.treatUnknownOptionsAsArguments;
this.version = params.version;
params.args && this.argument(params.args);
params.commands && this.command(params.commands, null, clone);
params.extensions && this.extension(params.extensions, null, clone);
params.options && this.option(params.options);
return this;
} |
JavaScript | register(it) {
let cmds;
let dest;
if (it.clikit.has('Extension')) {
cmds = Object.values(it.exports);
dest = 'extensions';
} else if (it.clikit.has('Command')) {
cmds = [ it ];
dest = 'commands';
}
if (!cmds) {
return;
}
it.parent = this;
for (const cmd of cmds) {
this.lookup[dest][cmd.name] = cmd;
if (cmd.aliases) {
for (const alias of Object.keys(cmd.aliases)) {
if (!this[dest].has(alias)) {
this.lookup[dest][alias] = cmd;
}
}
}
}
} | register(it) {
let cmds;
let dest;
if (it.clikit.has('Extension')) {
cmds = Object.values(it.exports);
dest = 'extensions';
} else if (it.clikit.has('Command')) {
cmds = [ it ];
dest = 'commands';
}
if (!cmds) {
return;
}
it.parent = this;
for (const cmd of cmds) {
this.lookup[dest][cmd.name] = cmd;
if (cmd.aliases) {
for (const alias of Object.keys(cmd.aliases)) {
if (!this[dest].has(alias)) {
this.lookup[dest][alias] = cmd;
}
}
}
}
} |
JavaScript | generateHelp() {
const entries = [];
for (const { desc, hidden, hint, multiple, name, required } of this) {
if (!hidden) {
entries.push({
desc,
hint,
multiple,
name,
required
});
}
}
return {
count: entries.length,
entries
};
} | generateHelp() {
const entries = [];
for (const { desc, hidden, hint, multiple, name, required } of this) {
if (!hidden) {
entries.push({
desc,
hint,
multiple,
name,
required
});
}
}
return {
count: entries.length,
entries
};
} |
JavaScript | add(cmd, params, clone) {
if (!cmd) {
throw E.INVALID_ARGUMENT('Invalid command', { name: 'cmd', scope: 'CommandMap.add', value: cmd });
}
if (!Command) {
Command = require('./command').default;
}
if (params !== undefined && params !== null) {
if (typeof cmd !== 'string') {
throw E.INVALID_ARGUMENT('Command parameters are only allowed when command is a string', { name: 'cmd', scope: 'CommandMap.add', value: { cmd, params } });
} else if (typeof params === 'function') {
params = { action: params };
} else if (typeof params !== 'object') {
throw E.INVALID_ARGUMENT('Expected command parameters to be an object or function', { name: 'params', scope: 'CommandMap.add', value: { cmd, params } });
}
cmd = new Command(cmd, params);
}
const results = [];
const commands = typeof cmd === 'object' && cmd.clikit instanceof Set && (cmd.clikit.has('CommandList') || cmd.clikit.has('CommandMap')) ?
cmd.values() :
Array.isArray(cmd) ? cmd : [ cmd ];
for (let it of commands) {
cmd = null;
if (!clone && it instanceof Command) {
cmd = it;
} else if (typeof it === 'string') {
// path
it = path.resolve(it);
try {
const files = fs.statSync(it).isDirectory() ? fs.readdirSync(it).map(filename => path.join(it, filename)) : [ it ];
for (const file of files) {
if (jsRegExp.test(file)) {
cmd = new Command(file);
this.set(cmd.name, cmd);
results.push(cmd);
}
}
} catch (e) {
if (e.code === 'ENOENT') {
throw E.FILE_NOT_FOUND(`Command path does not exist: ${it}`, { name: 'command', scope: 'CommandMap.add', value: it });
}
throw e;
}
continue;
} else if (it && typeof it === 'object') {
// ctor params or Command-like
if (it.clikit instanceof Set) {
if (it.clikit.has('Extension')) {
// actions and extensions not supported here
continue;
} else if (it.clikit.has('Command')) {
cmd = new Command(it.name, it);
} else {
throw E.INVALID_COMMAND(`Invalid command: cli-kit type "${Array.from(it.clikit)[0]}" not supported`, { name: 'command', scope: 'CommandMap.add', value: it });
}
} else if (it.name && typeof it.name === 'string') {
// the object is command ctor params
cmd = new Command(it.name, it);
} else {
// an object of command names to a path, ctor params, Command object, or Command-like object
for (const [ name, value ] of Object.entries(it)) {
cmd = new Command(name, value);
this.set(cmd.name, cmd);
results.push(cmd);
}
continue;
}
}
if (cmd instanceof Command) {
this.set(cmd.name, cmd);
results.push(cmd);
} else {
throw E.INVALID_ARGUMENT(`Invalid command "${it}", expected an object`, { name: 'command', scope: 'CommandMap.add', value: it });
}
}
return results;
} | add(cmd, params, clone) {
if (!cmd) {
throw E.INVALID_ARGUMENT('Invalid command', { name: 'cmd', scope: 'CommandMap.add', value: cmd });
}
if (!Command) {
Command = require('./command').default;
}
if (params !== undefined && params !== null) {
if (typeof cmd !== 'string') {
throw E.INVALID_ARGUMENT('Command parameters are only allowed when command is a string', { name: 'cmd', scope: 'CommandMap.add', value: { cmd, params } });
} else if (typeof params === 'function') {
params = { action: params };
} else if (typeof params !== 'object') {
throw E.INVALID_ARGUMENT('Expected command parameters to be an object or function', { name: 'params', scope: 'CommandMap.add', value: { cmd, params } });
}
cmd = new Command(cmd, params);
}
const results = [];
const commands = typeof cmd === 'object' && cmd.clikit instanceof Set && (cmd.clikit.has('CommandList') || cmd.clikit.has('CommandMap')) ?
cmd.values() :
Array.isArray(cmd) ? cmd : [ cmd ];
for (let it of commands) {
cmd = null;
if (!clone && it instanceof Command) {
cmd = it;
} else if (typeof it === 'string') {
// path
it = path.resolve(it);
try {
const files = fs.statSync(it).isDirectory() ? fs.readdirSync(it).map(filename => path.join(it, filename)) : [ it ];
for (const file of files) {
if (jsRegExp.test(file)) {
cmd = new Command(file);
this.set(cmd.name, cmd);
results.push(cmd);
}
}
} catch (e) {
if (e.code === 'ENOENT') {
throw E.FILE_NOT_FOUND(`Command path does not exist: ${it}`, { name: 'command', scope: 'CommandMap.add', value: it });
}
throw e;
}
continue;
} else if (it && typeof it === 'object') {
// ctor params or Command-like
if (it.clikit instanceof Set) {
if (it.clikit.has('Extension')) {
// actions and extensions not supported here
continue;
} else if (it.clikit.has('Command')) {
cmd = new Command(it.name, it);
} else {
throw E.INVALID_COMMAND(`Invalid command: cli-kit type "${Array.from(it.clikit)[0]}" not supported`, { name: 'command', scope: 'CommandMap.add', value: it });
}
} else if (it.name && typeof it.name === 'string') {
// the object is command ctor params
cmd = new Command(it.name, it);
} else {
// an object of command names to a path, ctor params, Command object, or Command-like object
for (const [ name, value ] of Object.entries(it)) {
cmd = new Command(name, value);
this.set(cmd.name, cmd);
results.push(cmd);
}
continue;
}
}
if (cmd instanceof Command) {
this.set(cmd.name, cmd);
results.push(cmd);
} else {
throw E.INVALID_ARGUMENT(`Invalid command "${it}", expected an object`, { name: 'command', scope: 'CommandMap.add', value: it });
}
}
return results;
} |
JavaScript | generateHelp() {
const entries = [];
for (const cmd of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(cmd);
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visible') {
labels.add(alias);
}
}
entries.push({
name,
desc,
label: Array.from(labels).sort((a, b) => {
return a.length === b.length ? a.localeCompare(b) : a.length - b.length;
}).join(', '),
aliases: aliases ? Object.keys(aliases) : null
});
}
}
entries.sort((a, b) => a.label.localeCompare(b.label));
return {
count: entries.length,
entries
};
} | generateHelp() {
const entries = [];
for (const cmd of Array.from(this.keys())) {
const { aliases, clikitHelp, desc, hidden, name } = this.get(cmd);
if (!hidden && !clikitHelp) {
const labels = new Set([ name ]);
for (const [ alias, display ] of Object.entries(aliases)) {
if (display === 'visible') {
labels.add(alias);
}
}
entries.push({
name,
desc,
label: Array.from(labels).sort((a, b) => {
return a.length === b.length ? a.localeCompare(b) : a.length - b.length;
}).join(', '),
aliases: aliases ? Object.keys(aliases) : null
});
}
}
entries.sort((a, b) => a.label.localeCompare(b.label));
return {
count: entries.length,
entries
};
} |
JavaScript | async function namedEntityRecognition(data) {
const result = await makeModelRequest(data, "dslim/bert-large-NER");
if (result && result.length > 0) {
if (result[0].entity_group === 'PER') {
return 'Alive Object';
} else {
return 'Location';
}
}
else {
return 'Not Alive Object';
}
} | async function namedEntityRecognition(data) {
const result = await makeModelRequest(data, "dslim/bert-large-NER");
if (result && result.length > 0) {
if (result[0].entity_group === 'PER') {
return 'Alive Object';
} else {
return 'Location';
}
}
else {
return 'Not Alive Object';
}
} |
JavaScript | async function evaluateTerminalCommands(message, speaker, agent, res, client, channel) {
if (message === "/reset") { // If the user types /reset into the console...
// If there is a response (i.e. this came from a web client, not local terminal)
if (res) {
const result = { result: `${agent} has been reset` };
// Add the status 200 message (message OK)
res.status(200)
// Send the message as JSON
.send(JSON.stringify(result));
} else {
log(`${agent} has been reset`);
}
await database.instance.clearConversations();
return true;
}
else if (message === "/dump") { // If a user types dump, show them logs of convo
// Read conversation history
const conversation = await database.instance.getConversation(agent, speaker, client, channel, false);
// If there is a response (i.e. this came from a web client, not local terminal)
const result = { result: conversation };
if (res) {
// Add the status 200 message (message OK)
res.status(200)
// Send the message as JSON
.send(JSON.stringify(result));
} else {
log(conversation);
}
return true;
}
else if (message === "GET_AGENT_NAME") {
if (res) res.status(200).send(JSON.stringify({ result: agent }));
else log({ result: agent });
return true;
}
} | async function evaluateTerminalCommands(message, speaker, agent, res, client, channel) {
if (message === "/reset") { // If the user types /reset into the console...
// If there is a response (i.e. this came from a web client, not local terminal)
if (res) {
const result = { result: `${agent} has been reset` };
// Add the status 200 message (message OK)
res.status(200)
// Send the message as JSON
.send(JSON.stringify(result));
} else {
log(`${agent} has been reset`);
}
await database.instance.clearConversations();
return true;
}
else if (message === "/dump") { // If a user types dump, show them logs of convo
// Read conversation history
const conversation = await database.instance.getConversation(agent, speaker, client, channel, false);
// If there is a response (i.e. this came from a web client, not local terminal)
const result = { result: conversation };
if (res) {
// Add the status 200 message (message OK)
res.status(200)
// Send the message as JSON
.send(JSON.stringify(result));
} else {
log(conversation);
}
return true;
}
else if (message === "GET_AGENT_NAME") {
if (res) res.status(200).send(JSON.stringify({ result: agent }));
else log({ result: agent });
return true;
}
} |
JavaScript | async function archiveConversation(speaker, agent, _conversation, client, channel) {
// Get configuration settings for agent
const { conversationWindowSize } = await getConfigurationSettingsForAgent(agent);
const conversation = (await database.instance.getConversation(agent, speaker, client, channel, false)).toString().trim();
const conversationLines = conversation.split('\n');
if (conversationLines.length > conversationWindowSize) {
const oldConversationLines = conversationLines.slice(0, Math.max(0, conversationLines.length - conversationWindowSize));
const newConversationLines = conversationLines.slice(Math.min(conversationLines.length - conversationWindowSize));
for(let i = 0; i < oldConversationLines.length; i++) {
await database.instance.setConversation(agent, client, channel, speaker, oldConversationLines[i], true);
}
/*for(let i = 0; i < newConversationLines.length; i++) {
await database.instance.setConversation(agent, client, channel, speaker, newConversationLines[i], false);
}*/
}
} | async function archiveConversation(speaker, agent, _conversation, client, channel) {
// Get configuration settings for agent
const { conversationWindowSize } = await getConfigurationSettingsForAgent(agent);
const conversation = (await database.instance.getConversation(agent, speaker, client, channel, false)).toString().trim();
const conversationLines = conversation.split('\n');
if (conversationLines.length > conversationWindowSize) {
const oldConversationLines = conversationLines.slice(0, Math.max(0, conversationLines.length - conversationWindowSize));
const newConversationLines = conversationLines.slice(Math.min(conversationLines.length - conversationWindowSize));
for(let i = 0; i < oldConversationLines.length; i++) {
await database.instance.setConversation(agent, client, channel, speaker, oldConversationLines[i], true);
}
/*for(let i = 0; i < newConversationLines.length; i++) {
await database.instance.setConversation(agent, client, channel, speaker, newConversationLines[i], false);
}*/
}
} |
JavaScript | async function generateContext(speaker, agent, conversation, message) {
let keywords = []
if (!isInFastMode) {
keywords = keywordExtractor(message, agent);
}
const pr = await Promise.all([keywords,
database.instance.getSpeakersFacts(agent, speaker),
database.instance.getAgentFacts(agent),
database.instance.getRoom(agent),
database.instance.getMorals(),
database.instance.getEthics(agent),
database.instance.getPersonality(agent),
database.instance.getNeedsAndMotivations(agent),
database.instance.getDialogue(agent),
database.instance.getMonologue(agent),
database.instance.getFacts(agent)]);
pr[1] = pr[1].toString().trim().replaceAll('\n\n', '\n');
pr[2] = pr[2].toString().trim().replaceAll('\n\n', '\n');
let kdata = '';
if (!isInFastMode) {
if (pr[0].length > 0) {
kdata = "More context on the chat:\n";
for(let k in pr[0]) {
kdata += 'Q: ' + capitalizeFirstLetter(pr[0][k].word) + '\nA: ' + pr[0][k].info + '\n\n';
}
kdata += '\n';
}
}
// Return a complex context (this will be passed to the transformer for completion)
return (await database.instance.getContext()).toString()
.replaceAll('$room', pr[3].toString())
.replaceAll("$morals", pr[4].toString())
.replaceAll("$ethics", pr[5].toString())
.replaceAll("$personality", pr[6].toString())
.replaceAll("$needsAndMotivations", pr[7].toString())
.replaceAll("$exampleDialog", pr[8].toString())
.replaceAll("$monologue", pr[9].toString())
.replaceAll("$facts", pr[10].toString())
// .replaceAll("$actions", fs.readFileSync(rootAgent + 'actions.txt').toString())
.replaceAll("$speakerFacts", pr[1].toString())
.replaceAll("$agentFacts", pr[2].toString())
.replaceAll('$keywords', kdata)
.replaceAll("$agent", agent)
.replaceAll("$speaker", speaker)
.replaceAll("$conversation", conversation).replaceAll('\\n', '\n').replaceAll('\\t', '\t');
} | async function generateContext(speaker, agent, conversation, message) {
let keywords = []
if (!isInFastMode) {
keywords = keywordExtractor(message, agent);
}
const pr = await Promise.all([keywords,
database.instance.getSpeakersFacts(agent, speaker),
database.instance.getAgentFacts(agent),
database.instance.getRoom(agent),
database.instance.getMorals(),
database.instance.getEthics(agent),
database.instance.getPersonality(agent),
database.instance.getNeedsAndMotivations(agent),
database.instance.getDialogue(agent),
database.instance.getMonologue(agent),
database.instance.getFacts(agent)]);
pr[1] = pr[1].toString().trim().replaceAll('\n\n', '\n');
pr[2] = pr[2].toString().trim().replaceAll('\n\n', '\n');
let kdata = '';
if (!isInFastMode) {
if (pr[0].length > 0) {
kdata = "More context on the chat:\n";
for(let k in pr[0]) {
kdata += 'Q: ' + capitalizeFirstLetter(pr[0][k].word) + '\nA: ' + pr[0][k].info + '\n\n';
}
kdata += '\n';
}
}
// Return a complex context (this will be passed to the transformer for completion)
return (await database.instance.getContext()).toString()
.replaceAll('$room', pr[3].toString())
.replaceAll("$morals", pr[4].toString())
.replaceAll("$ethics", pr[5].toString())
.replaceAll("$personality", pr[6].toString())
.replaceAll("$needsAndMotivations", pr[7].toString())
.replaceAll("$exampleDialog", pr[8].toString())
.replaceAll("$monologue", pr[9].toString())
.replaceAll("$facts", pr[10].toString())
// .replaceAll("$actions", fs.readFileSync(rootAgent + 'actions.txt').toString())
.replaceAll("$speakerFacts", pr[1].toString())
.replaceAll("$agentFacts", pr[2].toString())
.replaceAll('$keywords', kdata)
.replaceAll("$agent", agent)
.replaceAll("$speaker", speaker)
.replaceAll("$conversation", conversation).replaceAll('\\n', '\n').replaceAll('\\t', '\t');
} |
JavaScript | async function handleInput(message, speaker, agent, res, clientName, channelId) {
let start = Date.now()
log("Handling input: " + message);
agent = agent ?? defaultAgent
//if the input is a command, it handles the command and doesn't respond according to the agent
if (await evaluateTerminalCommands(message, speaker, agent, res, clientName, channelId)) return;
const _meta = await database.instance.getMeta(agent, speaker);
if (!_meta || _meta.length <= 0) {
database.instance.setMeta(agent, speaker, JSON.stringify({ messages: 0 }));
}
// Get configuration settings for agent
const { dialogFrequencyPenality,
dialogPresencePenality,
factsUpdateInterval,
useProfanityFilter } = await getConfigurationSettingsForAgent(agent);
// If the profanity filter is enabled in the agent's config...
if (useProfanityFilter && !isInFastMode) {
// Evaluate if the speaker's message is toxic
const { isProfane, isSensitive, response } = await evaluateTextAndRespondIfToxic(speaker, agent, message);
if ((isProfane || isSensitive) && response) {
log(agent + ">>> " + response);
if (res) res.status(200).send(JSON.stringify({ result: response }));
return response;
}
}
// Parse files into objects
const meta = !_meta || _meta.length <= 0 ? { messages: 0 } : JSON.parse(_meta);
let conversation = (await database.instance.getConversation(agent, speaker, clientName, channelId, false)).toString().replaceAll('\n\n', '\n');
conversation += '\n' + speaker + ': ' + message;
// Increment the agent's conversation count for this speaker
meta.messages = meta.messages + 1;
// Archive previous conversation and facts to keep context window small
archiveConversation(speaker, agent, conversation, clientName, channelId);
archiveFacts(speaker, agent, conversation);
let stop = Date.now()
log(`Time Taken to execute load data = ${(stop - start)/1000} seconds`);
start = Date.now()
const context = (await generateContext(speaker, agent, conversation, message)).replace(/(\r\n|\r|\n)+/g, '$1');
console.log(context)
// log('Context:');
// log(context)
// TODO: Wikipedia?
stop = Date.now()
log(`Time Taken to execute create context = ${(stop - start)/1000} seconds`);
start = Date.now()
// searchWikipedia(text.Input) .then( (out) => { log("**** WEAVIATE: " + JSON.stringify(out)); currentState = states.READY; });
// Print the context to the console if running indev mode
// if (process.env.DEBUG == "TRUE") {
// log("*********************** CONTEXT");
// log(context);
// log("***********************");
// };
// Create a data object to pass to the transformer API
const data = {
"prompt": context,
"temperature": 0.9, // TODO -- this should be changeable
"max_tokens": 100, // TODO -- this should be changeable
"top_p": 1, // TODO -- this should be changeable
"frequency_penalty": dialogFrequencyPenality,
"presence_penalty": dialogPresencePenality,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
// Call the transformer API
const { success, choice } = await makeCompletionRequest(data, speaker, agent, "conversation");
stop = Date.now()
log(`Time Taken to execute openai request = ${(stop - start)/1000} seconds`);
start = Date.now()
database.instance.setConversation(agent, clientName, channelId, speaker, message, false);
// If it fails, tell speaker they had an error
if (!success) {
const error = "Sorry, I had an error";
return respondWithMessage(agent, error, res);
};
if (useProfanityFilter && !isInFastMode) {
// Check agent isn't about to say something offensive
const { isProfane, response } = await evaluateTextAndRespondIfToxic(speaker, agent, choice.text, true);
if (isProfane) {
database.instance.setConversation(agent, clientName, channelId, agent, response, false);
return respondWithMessage(agent, response, res);
}
}
//every some messages it gets the facts for the user and the agent
if (meta.messages % factsUpdateInterval == 0) {
const conversation = (await database.instance.getConversation(agent, speaker, clientName, channelId, false)).toString().trim();
const conversationLines = conversation.split('\n');
const updatedConversationLines = conversationLines.filter(line => line != "" && line != "\n").slice(conversationLines.length - factsUpdateInterval * 2).join("\n");
console.log("Forming an opinion about speaker")
formOpinionAboutSpeaker(speaker, agent, updatedConversationLines);
console.log("Formed an opinion about speaker")
summarizeAndStoreFactsAboutSpeaker(speaker, agent, updatedConversationLines);
summarizeAndStoreFactsAboutAgent(speaker, agent, updatedConversationLines + choice.text);
}
database.instance.setMeta(agent, speaker, meta);
let response = choice.text.split('\n')[0];
// Write to conversation to the database
database.instance.setConversation(agent, clientName, channelId, agent, response, false);
log("responding with message", response);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
return respondWithMessage(agent, response, res);
} | async function handleInput(message, speaker, agent, res, clientName, channelId) {
let start = Date.now()
log("Handling input: " + message);
agent = agent ?? defaultAgent
//if the input is a command, it handles the command and doesn't respond according to the agent
if (await evaluateTerminalCommands(message, speaker, agent, res, clientName, channelId)) return;
const _meta = await database.instance.getMeta(agent, speaker);
if (!_meta || _meta.length <= 0) {
database.instance.setMeta(agent, speaker, JSON.stringify({ messages: 0 }));
}
// Get configuration settings for agent
const { dialogFrequencyPenality,
dialogPresencePenality,
factsUpdateInterval,
useProfanityFilter } = await getConfigurationSettingsForAgent(agent);
// If the profanity filter is enabled in the agent's config...
if (useProfanityFilter && !isInFastMode) {
// Evaluate if the speaker's message is toxic
const { isProfane, isSensitive, response } = await evaluateTextAndRespondIfToxic(speaker, agent, message);
if ((isProfane || isSensitive) && response) {
log(agent + ">>> " + response);
if (res) res.status(200).send(JSON.stringify({ result: response }));
return response;
}
}
// Parse files into objects
const meta = !_meta || _meta.length <= 0 ? { messages: 0 } : JSON.parse(_meta);
let conversation = (await database.instance.getConversation(agent, speaker, clientName, channelId, false)).toString().replaceAll('\n\n', '\n');
conversation += '\n' + speaker + ': ' + message;
// Increment the agent's conversation count for this speaker
meta.messages = meta.messages + 1;
// Archive previous conversation and facts to keep context window small
archiveConversation(speaker, agent, conversation, clientName, channelId);
archiveFacts(speaker, agent, conversation);
let stop = Date.now()
log(`Time Taken to execute load data = ${(stop - start)/1000} seconds`);
start = Date.now()
const context = (await generateContext(speaker, agent, conversation, message)).replace(/(\r\n|\r|\n)+/g, '$1');
console.log(context)
// log('Context:');
// log(context)
// TODO: Wikipedia?
stop = Date.now()
log(`Time Taken to execute create context = ${(stop - start)/1000} seconds`);
start = Date.now()
// searchWikipedia(text.Input) .then( (out) => { log("**** WEAVIATE: " + JSON.stringify(out)); currentState = states.READY; });
// Print the context to the console if running indev mode
// if (process.env.DEBUG == "TRUE") {
// log("*********************** CONTEXT");
// log(context);
// log("***********************");
// };
// Create a data object to pass to the transformer API
const data = {
"prompt": context,
"temperature": 0.9, // TODO -- this should be changeable
"max_tokens": 100, // TODO -- this should be changeable
"top_p": 1, // TODO -- this should be changeable
"frequency_penalty": dialogFrequencyPenality,
"presence_penalty": dialogPresencePenality,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
// Call the transformer API
const { success, choice } = await makeCompletionRequest(data, speaker, agent, "conversation");
stop = Date.now()
log(`Time Taken to execute openai request = ${(stop - start)/1000} seconds`);
start = Date.now()
database.instance.setConversation(agent, clientName, channelId, speaker, message, false);
// If it fails, tell speaker they had an error
if (!success) {
const error = "Sorry, I had an error";
return respondWithMessage(agent, error, res);
};
if (useProfanityFilter && !isInFastMode) {
// Check agent isn't about to say something offensive
const { isProfane, response } = await evaluateTextAndRespondIfToxic(speaker, agent, choice.text, true);
if (isProfane) {
database.instance.setConversation(agent, clientName, channelId, agent, response, false);
return respondWithMessage(agent, response, res);
}
}
//every some messages it gets the facts for the user and the agent
if (meta.messages % factsUpdateInterval == 0) {
const conversation = (await database.instance.getConversation(agent, speaker, clientName, channelId, false)).toString().trim();
const conversationLines = conversation.split('\n');
const updatedConversationLines = conversationLines.filter(line => line != "" && line != "\n").slice(conversationLines.length - factsUpdateInterval * 2).join("\n");
console.log("Forming an opinion about speaker")
formOpinionAboutSpeaker(speaker, agent, updatedConversationLines);
console.log("Formed an opinion about speaker")
summarizeAndStoreFactsAboutSpeaker(speaker, agent, updatedConversationLines);
summarizeAndStoreFactsAboutAgent(speaker, agent, updatedConversationLines + choice.text);
}
database.instance.setMeta(agent, speaker, meta);
let response = choice.text.split('\n')[0];
// Write to conversation to the database
database.instance.setConversation(agent, clientName, channelId, agent, response, false);
log("responding with message", response);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
return respondWithMessage(agent, response, res);
} |
JavaScript | async function handleGuildMemberAdd(user) {
const userId = user.user.id
const username = user.user.username
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', 'join', username, utcStr);
// MessageClient.instance.sendUserUpdateEvent('Discord', 'join', username, utcStr)
} | async function handleGuildMemberAdd(user) {
const userId = user.user.id
const username = user.user.username
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', 'join', username, utcStr);
// MessageClient.instance.sendUserUpdateEvent('Discord', 'join', username, utcStr)
} |
JavaScript | async function handleGuildMemberRemove(user) {
const userId = user.user.id
const username = user.user.username
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', 'leave', username, utcStr);
// MessageClient.instance.sendUserUpdateEvent('Discord', 'leave', username, utcStr)
} | async function handleGuildMemberRemove(user) {
const userId = user.user.id
const username = user.user.username
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', 'leave', username, utcStr);
// MessageClient.instance.sendUserUpdateEvent('Discord', 'leave', username, utcStr)
} |
JavaScript | async function handleMessageReactionAdd(reaction, user) {
const { message } = reaction
const emojiName = emoji.getName(reaction.emoji)
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', message.channel.id, message.id, message.content, user.username, emojiName, utcStr);
// MessageClient.instance.sendMessageReactionAdd('Discord', message.channel.id, message.id, message.content, user.username, emojiName, utcStr)
} | async function handleMessageReactionAdd(reaction, user) {
const { message } = reaction
const emojiName = emoji.getName(reaction.emoji)
const dateNow = new Date();
var utc = new Date(dateNow.getUTCFullYear(), dateNow.getUTCMonth(), dateNow.getUTCDate(), dateNow.getUTCHours(), dateNow.getUTCMinutes(), dateNow.getUTCSeconds());
const utcStr = dateNow.getDate() + '/' + (dateNow.getMonth() + 1) + '/' + dateNow.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
// TODO: Replace me with direct message handler
log('Discord', message.channel.id, message.id, message.content, user.username, emojiName, utcStr);
// MessageClient.instance.sendMessageReactionAdd('Discord', message.channel.id, message.id, message.content, user.username, emojiName, utcStr)
} |
JavaScript | async function ban (client, message, args, author, addPing, channel) {
const pw = args.parsed_words
if (pw === undefined || pw.length !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const { mentions } = message
log(JSON.stringify(mentions))
if (mentions === undefined || mentions.users === undefined || mentions.users.size !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const user = mentions.users.first().id
await database.instance.banUser(user, 'discord')
message.channel.send('banned user: ' + `<@!${user}>`)
message.channel.stopTyping();
} | async function ban (client, message, args, author, addPing, channel) {
const pw = args.parsed_words
if (pw === undefined || pw.length !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const { mentions } = message
log(JSON.stringify(mentions))
if (mentions === undefined || mentions.users === undefined || mentions.users.size !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const user = mentions.users.first().id
await database.instance.banUser(user, 'discord')
message.channel.send('banned user: ' + `<@!${user}>`)
message.channel.stopTyping();
} |
JavaScript | async function commands (client, message, args, author, addPing, channel) {
let str = ''
client.helpFields[0].commands.forEach(function (item, index) {
if (item[3].length <= 2000 && item[3].length > 0) {
str += '!' + item[0] + ' - ' + item[3] + '\n'
}
});
if (str.length === 0) client.embed.description = 'empty response'
message.channel.send(str);
message.channel.stopTyping();
} | async function commands (client, message, args, author, addPing, channel) {
let str = ''
client.helpFields[0].commands.forEach(function (item, index) {
if (item[3].length <= 2000 && item[3].length > 0) {
str += '!' + item[0] + ' - ' + item[3] + '\n'
}
});
if (str.length === 0) client.embed.description = 'empty response'
message.channel.send(str);
message.channel.stopTyping();
} |
JavaScript | async function ping(client, message, args, author, addPing, channel) {
if ( args.grpc_args.message === undefined || args.grpc_args.message === '' || args.grpc_args.message.replace(/\s/g, '').length === 0) {
client.embed.description = 'Wrong format, !ping message'
message.channel.send(client.embed)
client.embed.desscription = ''
message.channel.stopTyping();
return
}
args.grpc_args['client_name'] = 'discord'
args.grpc_args['chat_id'] = channel
const date = new Date();
const utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
const utcStr = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
args.grpc_args['createdAt'] = utcStr
let parentId = ''
if (args.grpc_args['isThread'] === true) {
parentId = args.grpc_args['parentId']
}
// TODO: Replace me with direct message handler
// MessageClient.instance.sendMessage(args.grpc_args['message'], message.id, 'Discord', args.grpc_args['chat_id'], utcStr, addPing, author.username, 'parentId:' + parentId)
log(args.grpc_args['message'], message.id, 'Discord', args.grpc_args['chat_id'], utcStr, addPing, author.username, 'parentId:' + parentId)
} | async function ping(client, message, args, author, addPing, channel) {
if ( args.grpc_args.message === undefined || args.grpc_args.message === '' || args.grpc_args.message.replace(/\s/g, '').length === 0) {
client.embed.description = 'Wrong format, !ping message'
message.channel.send(client.embed)
client.embed.desscription = ''
message.channel.stopTyping();
return
}
args.grpc_args['client_name'] = 'discord'
args.grpc_args['chat_id'] = channel
const date = new Date();
const utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
const utcStr = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes() + ':' + utc.getSeconds()
args.grpc_args['createdAt'] = utcStr
let parentId = ''
if (args.grpc_args['isThread'] === true) {
parentId = args.grpc_args['parentId']
}
// TODO: Replace me with direct message handler
// MessageClient.instance.sendMessage(args.grpc_args['message'], message.id, 'Discord', args.grpc_args['chat_id'], utcStr, addPing, author.username, 'parentId:' + parentId)
log(args.grpc_args['message'], message.id, 'Discord', args.grpc_args['chat_id'], utcStr, addPing, author.username, 'parentId:' + parentId)
} |
JavaScript | async function pingagent (client, message, args, author, addPing, channel) {
if (args.grpc_args.message === undefined || args.grpc_args.message === '' || args.grpc_args.message.replace(/\s/g, '').length === 0
|| args.grpc_args.message.includes('agent=') || args.grpc_args.agent === undefined || args.grpc_args.agent === '' || args.grpc_args.agent.replace(/\s/g, '').length === 0) {
client.embed.description = 'Wrong format, !pingagent agent=agent message=value'
message.channel.send(client.embed)
client.embed.desscription = ''
message.channel.stopTyping();
return
}
// TODO: Replace me with direct message handler
log('Discord', message.channel.id, message.id, args.grpc_args['message'], args.grpc_args['agent'], addPing, author.username);
// MessageClient.instance.sendPingSoloAgent('Discord', message.channel.id, message.id, args.grpc_args['message'], args.grpc_args['agent'], addPing, author.username)
} | async function pingagent (client, message, args, author, addPing, channel) {
if (args.grpc_args.message === undefined || args.grpc_args.message === '' || args.grpc_args.message.replace(/\s/g, '').length === 0
|| args.grpc_args.message.includes('agent=') || args.grpc_args.agent === undefined || args.grpc_args.agent === '' || args.grpc_args.agent.replace(/\s/g, '').length === 0) {
client.embed.description = 'Wrong format, !pingagent agent=agent message=value'
message.channel.send(client.embed)
client.embed.desscription = ''
message.channel.stopTyping();
return
}
// TODO: Replace me with direct message handler
log('Discord', message.channel.id, message.id, args.grpc_args['message'], args.grpc_args['agent'], addPing, author.username);
// MessageClient.instance.sendPingSoloAgent('Discord', message.channel.id, message.id, args.grpc_args['message'], args.grpc_args['agent'], addPing, author.username)
} |
JavaScript | async function unban (client, message, args, author, addPing, channel) {
const pw = args.parsed_words
if (pw === undefined || pw.length !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const { mentions } = message
log(JSON.stringify(mentions))
if (mentions === undefined || mentions.users === undefined || mentions.users.size !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const user = mentions.users.first().id
await database.instance.unbanUser(user, 'discord')
message.channel.send('unbanned user: ' + `<@!${user}>`)
message.channel.stopTyping();
} | async function unban (client, message, args, author, addPing, channel) {
const pw = args.parsed_words
if (pw === undefined || pw.length !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const { mentions } = message
log(JSON.stringify(mentions))
if (mentions === undefined || mentions.users === undefined || mentions.users.size !== 1) {
message.channel.send('invalid command structure!')
message.channel.stopTyping();
return
}
const user = mentions.users.first().id
await database.instance.unbanUser(user, 'discord')
message.channel.send('unbanned user: ' + `<@!${user}>`)
message.channel.stopTyping();
} |
JavaScript | async function browserWindow(options) {
log('Making new browser');
if (fs.existsSync("/.dockerenv"))
{
options.headless = true
options.args = (options.args || []).concat(['--no-sandbox', '--disable-setuid-sandbox'])
}
return await puppeteer.launch(options);
} | async function browserWindow(options) {
log('Making new browser');
if (fs.existsSync("/.dockerenv"))
{
options.headless = true
options.args = (options.args || []).concat(['--no-sandbox', '--disable-setuid-sandbox'])
}
return await puppeteer.launch(options);
} |
JavaScript | async clickSelectorClassRegex(selector, classRegex) {
if (this.autoLog)
log(`Clicking for a ${selector} matching ${classRegex}`);
await this.page.evaluate((selector, classRegex) => {
classRegex = new RegExp(classRegex);
let buttons = Array.from(document.querySelectorAll(selector));
let enterButton = buttons.find(button => Array.from(button.classList).some(c => classRegex.test(c)));
if (enterButton)
enterButton.click();
}, selector, classRegex.toString().slice(1, -1));
} | async clickSelectorClassRegex(selector, classRegex) {
if (this.autoLog)
log(`Clicking for a ${selector} matching ${classRegex}`);
await this.page.evaluate((selector, classRegex) => {
classRegex = new RegExp(classRegex);
let buttons = Array.from(document.querySelectorAll(selector));
let enterButton = buttons.find(button => Array.from(button.classList).some(c => classRegex.test(c)));
if (enterButton)
enterButton.click();
}, selector, classRegex.toString().slice(1, -1));
} |