code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
const sortLUISJSON = async function(LUISJSON) { // sort intents first LUISJSON.intents.sort(sortComparers.compareNameFn); LUISJSON.composites.sort(sortComparers.compareNameFn); LUISJSON.entities.sort(sortComparers.compareNameFn); LUISJSON.closedLists.sort(sortComparers.compareNameFn); LUISJSON.regex_entities.sort(sortComparers.compareNameFn); LUISJSON.model_features.sort(sortComparers.compareNameFn); LUISJSON.patternAnyEntities.sort(sortComparers.compareNameFn); LUISJSON.prebuiltEntities.sort(sortComparers.compareNameFn); LUISJSON.utterances.sort(sortComparers.compareIntentFn); };
Helper function to return sorted LUIS JSON model @param {Object} LUISJSON
sortLUISJSON ( LUISJSON )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
const sortQnAJSON = async function(QnAJSON) { (QnAJSON.qnaList || []).forEach(pair => { pair.questions.sort(sortComparers.compareFn); }); QnAJSON.qnaList.sort(sortComparers.compareQn); };
Helper function to return sorted QnA JSON model @param {Object} QnAJSON
sortQnAJSON ( QnAJSON )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
const sortQnAAltJSON = async function(QnAAltJSON) { (QnAAltJSON.wordAlterations || []).forEach(word => { word.alterations.sort(sortComparers.compareFn); }); QnAAltJSON.wordAlterations.sort(sortComparers.compareAltName); };
Helper function to return sorted QnA Alterations pair @param {Object} QnAAltJSON
sortQnAAltJSON ( QnAAltJSON )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
const objectSortByStartPos = function (objectArray) { let ObjectByStartPos = objectArray.slice(0); ObjectByStartPos.sort(function(a,b) { return a.startPos - b.startPos; }); return ObjectByStartPos; };
helper function sort entities list by starting position @param {object} objectArray array of entity objects @returns {object} sorted entities array by start position
objectSortByStartPos ( objectArray )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
const updateUtterancesList = function (srcCollection, tgtCollection, attribute) { (srcCollection || []).forEach(srcItem => { let matchInTarget = tgtCollection.find(item => item.intent.name == srcItem.intent); if(matchInTarget.utterances.length === 0) { addUtteranceToCollection(attribute, srcItem, matchInTarget); return; } if(!matchInTarget.utterances.find(item => item.text == srcItem[attribute])) { addUtteranceToCollection(attribute, srcItem, matchInTarget); return; } }); }
helper function to add utterances to collection if it does not exist @param {object[]} tgtCollection target collection of utterance objects @param {object []} srcCollection source collection of utterance objects @param {string} attribute attribute to check on and copy over @returns {void}
updateUtterancesList ( srcCollection , tgtCollection , attribute )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
const addUtteranceToCollection = function (attribute, srcItem, matchInTarget) { if(attribute === 'text') { matchInTarget.utterances.push(srcItem); } else { matchInTarget.utterances.push(new helperClasses.uttereances(srcItem.pattern,srcItem.intent,[])); } }
helper function to add utterances to collection based on src type (pattern or utterance) @param {string} attribute attribute to check on and copy over @param {object} srcItem source object @param {object []} matchInTarget target collection of objects @returns {void}
addUtteranceToCollection ( attribute , srcItem , matchInTarget )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU-helpers.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU-helpers.js
MIT
generateMarkdown: async function(program) { let outFolder = process.cwd(); let LUISJSON = new helperClasses.readerObject(); let QnAJSON = new helperClasses.readerObject(); let QnAAltJSON = new helperClasses.readerObject(); let outFileContent; let outFileName = ''; if(program.out_folder) { if(path.isAbsolute(program.out_folder)) { outFolder = program.out_folder; } else { outFolder = path.resolve('', program.out_folder); } if(!fs.existsSync(outFolder)) { throw(new exception(retCode.errorCode.OUTPUT_FOLDER_INVALID, 'Output folder ' + outFolder + ' does not exist')); } } // Do we have a LUIS file? If so, get that and load into memory if(program.LUIS_File) { try { LUISJSON.model = await parseLUISFile(program.LUIS_File); } catch (err) { throw(err); } LUISJSON.sourceFile = program.LUIS_File; } //do we have a QnA JSON file? If so, get that and load into memory if(program.QNA_FILE) { try { QnAJSON.model = await parseQnAJSONFile(program.QNA_FILE); } catch (err) { throw (err); } QnAJSON.sourceFile = program.QNA_FILE; } //do we have a QnA alterations file? If so, get that and load into memory if(program.QNA_ALTERATION_FILE) { try { QnAAltJSON.model = await parseQnAJSONFile(program.QNA_ALTERATION_FILE); } catch (err) { throw (err); } QnAAltJSON.sourceFile = program.QNA_ALTERATION_FILE; } // do we have stdin specified? if(program.stdin) { let parsedJsonFromStdin; try { parsedJsonFromStdin = JSON.parse(await stdin()); } catch (err) { throw (new exception(retCode.errorCode.INVALID_INPUT, `Sorry, unable to parse stdin as JSON! \n\n ${JSON.stringify(err, null, 2)}\n\n`)); } if (await validateLUISJSON(parsedJsonFromStdin)) { // if validation did not throw, then ground this as valid LUIS JSON LUISJSON.model = parsedJsonFromStdin; LUISJSON.sourceFile = 'stdin'; } else if (parsedJsonFromStdin.qnaList || parsedJsonFromStdin.qnaDocuments) { QnAJSON.model = parsedJsonFromStdin; QnAJSON.sourceFile = 'stdin'; } else { throw (new exception(retCode.errorCode.INVALID_INPUT, `Sorry, unable to parse stdin as LUIS or QnA Maker model!`)); } } if(program.sort) { // sort LUIS, QnA and QnAAltJson await toLUHelpers.sortCollections(LUISJSON, QnAJSON, QnAAltJSON); } // construct the markdown file content outFileContent = await toLUHelpers.constructMdFileHelper(LUISJSON, QnAJSON, QnAAltJSON, program.LUIS_File, program.QNA_FILE, program.skip_header, program.model_info) if(!outFileContent) { throw(new exception(retCode.errorCode.UNKNOWN_ERROR,'Sorry, Unable to generate .lu file content!')); } if (!program.stdout) { // write out the file if(!program.lu_File) { if(LUISJSON.sourceFile) { outFileName += path.basename(LUISJSON.sourceFile, path.extname(LUISJSON.sourceFile)); } if(QnAJSON.sourceFile) { outFileName += path.basename(QnAJSON.sourceFile, path.extname(QnAJSON.sourceFile)); } program.lu_File = outFileName + '.lu'; } else { if(program.lu_File.lastIndexOf('.lu') === -1) { program.lu_File += '.lu'; } } outFileName = path.join(outFolder, program.lu_File); try { fs.writeFileSync(outFileName, outFileContent, 'utf-8'); } catch (err) { throw(new exception(retCode.errorCode.UNABLE_TO_WRITE_FILE, 'Unable to write LU file - ' + outFileName)); } if(program.verbose) process.stdout.write(outFileContent); if(program.verbose) process.stdout.write(chalk.default.italic('Successfully wrote to ' + path.join(outFolder, program.lu_File))); } else { process.stdout.write(outFileContent); } }
Function to take commander program object and construct markdown file for specified input @param {object} program parsed commander program object @returns {void} nothing @throws {exception} Throws on errors. exception object includes errCode and text.
generateMarkdown ( program )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU.js
MIT
const openFileAndReadContent = async function(file) { // catch if input file is a folder if(fs.lstatSync(file).isDirectory()) { throw (new exception(retCode.errorCode.FILE_OPEN_ERROR, 'Sorry, "' + file + '" is a directory! Please try a LUIS/ QnA Maker JSON file as input.')); } if(!fs.existsSync(path.resolve(file))) { throw(new exception(retCode.errorCode.FILE_OPEN_ERROR, 'Sorry unable to open [' + file + ']')); } let fileContent = txtfile.readSync(file); if (!fileContent) { throw(new exception(retCode.errorCode.FILE_OPEN_ERROR, 'Sorry, error reading file: ' + file)); } return fileContent; };
Helper function to read a file and return file content @param {string} file Input file name @returns {string} File content @throws {exception} Throws on errors. exception object includes errCode and text.
openFileAndReadContent ( file )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU.js
MIT
const parseLUISFile = async function(file) { let LUISFileContent, LUISJSON; try { LUISFileContent = await openFileAndReadContent(file); } catch (err) { throw(err); } try { LUISJSON = JSON.parse(LUISFileContent); } catch (err) { throw (new exception(retCode.errorCode.INVALID_INPUT_FILE, 'Sorry, error parsing file as LUIS JSON: ' + file)); } await validateLUISJSON(LUISJSON); return LUISJSON; };
Helper function to parse QnAMaker TSV file into a JSON object @param {String} file input LUIS JSON file name @returns {object} LUIS JSON object @throws {exception} Throws on errors. exception object includes errCode and text.
parseLUISFile ( file )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU.js
MIT
const validateLUISJSON = async function(LUISJSON) { if(!LUISJSON.intents && !LUISJSON.entities) { return false; } if(LUISJSON.regex_features && LUISJSON.regex_features.length !== 0) { throw(new exception(retCode.errorCode.INVALID_INPUT_FILE, 'Sorry, input LUIS JSON file has references to regex_features. Cannot convert to .lu file.')); } return true; };
Helper to validate input LUIS JSON @param {Object} LUISJsonBlob parsed LUIS JSON blob @throws {exception} Throws on errors. Exception object includes errCode and text.
validateLUISJSON ( LUISJSON )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU.js
MIT
const parseQnAJSONFile = async function(file){ let QnAFileContent, QnAJSON; try { QnAFileContent = await openFileAndReadContent(file); } catch (err) { throw(err); } try { QnAJSON = JSON.parse(QnAFileContent); } catch (err) { throw (new exception(retCode.errorCode.INVALID_INPUT_FILE, 'Sorry, error parsing file as QnA JSON: ' + file)); } return QnAJSON; }
Helper function to parse LUIS JSON file into a JSON object @param {String} file Input QnA TSV file name @returns {object} LUIS JSON object @throws {exception} Throws on errors. exception object includes errCode and text.
parseQnAJSONFile ( file )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/toLU.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/toLU.js
MIT
constructor(filePath, includeInCollate) { this.filePath = filePath?filePath:''; if(includeInCollate === undefined) this.includeInCollate = true; else this.includeInCollate = includeInCollate; }
@property {Boolean} includeInCollate
constructor ( filePath , includeInCollate )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/classes/filesToParse.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/classes/filesToParse.js
MIT
parserObject.create = function(LUISJsonStructure, qnaJsonStructure, lQnaAlterations, srcFile, includeInCollate) { let parserObj = new parserObject(); parserObj.LUISJsonStructure = (LUISJsonStructure || new LUIS()); parserObj.qnaJsonStructure = (qnaJsonStructure || new QnA()); parserObj.qnaAlterations = (lQnaAlterations || new qnaAlterations.qnaAlterations()); parserObj.srcFile = (srcFile || undefined); if(includeInCollate === undefined) parserObj.includeInCollate = true; else parserObj.includeInCollate = includeInCollate; return parserObj; }
Helper method to create a parser object based on arbitrary attributes passed in. @param {Object} LUISJsonStructure @param {Object} qnaJsonStructure @param {Object} lQnaAlterations @param {Object} srcFile @param {Object} includeInCollate
parserObject.create ( LUISJsonStructure , qnaJsonStructure , lQnaAlterations , srcFile , includeInCollate )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/classes/parserObject.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/classes/parserObject.js
MIT
constructor(wordAlterations) { this.wordAlterations = wordAlterations?wordAlterations:[]; }
@property {alterations []} wordAlterations
constructor ( wordAlterations )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/classes/qnaAlterations.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/classes/qnaAlterations.js
MIT
constructor(errCode, text) { if(errCode === Object(errCode)) { this.text = errCode.text?errCode.text:''; this.errCode = errCode.errCode?errCode.errCode:99; } else { this.text = text?text:''; this.errCode = errCode?errCode:99; } }
@param {string} errCode @param {string} text
constructor ( errCode , text )
javascript
microsoft/botbuilder-tools
packages/Ludown/lib/classes/exception.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Ludown/lib/classes/exception.js
MIT
const classTpl = (cfg) => { return `/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const {ServiceBase} = require('./serviceBase'); class ${cfg.className} extends ServiceBase { constructor() { super('${cfg.url}'); } ${operationTpl(cfg.operations)} } module.exports = ${cfg.className}; `; };
Services template extends ServiceBase
classTpl
javascript
microsoft/botbuilder-tools
packages/QnAMaker/swag.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/swag.js
MIT
const operationTpl = (operations) => { let tpl = ''; Object.keys(operations).forEach(key => { const operation = operations[key]; tpl += ` /** * ${operation.description || operation.summary} */ ${operation.name}(params${operation.entityName ? ` , ${operation.entityName}` : ''}${(operation.entityType ? `/* ${operation.entityType} */` : '')}) { return this.createRequest('${operation.pathFragment}', params, '${operation.method}'${operation.entityName ? ', ' + operation.entityName : ''}); }`; }); return tpl; };
Operation method template. Used to populate the operations array used in the classTpl
operationTpl
javascript
microsoft/botbuilder-tools
packages/QnAMaker/swag.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/swag.js
MIT
function findEntity(swaggerOperation) { return (swaggerOperation.parameters || []).find(param => param.in === 'body'); }
Finds the entity (if present) that should be passed as the body of the request. PUT, POST and PATCH only. @param {*} swaggerOperation The swagger operation containing an array of params to search @returns {*} The operation containing the info about the body of the request
findEntity ( swaggerOperation )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/swag.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/swag.js
MIT
function findRootAndNodeFromPath(path) { const parts = path.split('/'); let i = parts.length; const info = {}; while (i--) { if (parts[i] && !/({[\w]+})/.test(parts[i])) { info.node = parts[i]; break; } } while (i--) { if (parts[i] && /({knowledgeBaseID})/i.test(parts[i]) && parts[i + 1]) { info.root = parts[i + 1]; break; } } return info; }
Finds the root and node from a url path. if {knowledgeBaseID} exist withing the path, these become the root and the first bracket pair after are the node. @param {string} path The endpoint path to parse @returns {{root:string, node:string}} The object containing the root and node
findRootAndNodeFromPath ( path )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/swag.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/swag.js
MIT
async function getHelpContents(args, output) { if ('!' in args) { return getAllCommands(output); } if (args._.length == 0) { return getGeneralHelpContents(output); } else if (args._.length == 1) { return getVerbHelp(args._[0], output); } else if (args._.length >= 2) { const serviceManifest = getServiceManifest(args); if (serviceManifest) { const { operation } = serviceManifest; output.write(`${operation.description}\n\n`); output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`); } else { return getVerbHelp(args._[0], output); } } const serviceManifest = getServiceManifest(args); if (serviceManifest) { return getHelpContentsForService(serviceManifest, output); } return getGeneralHelpContents(output); }
Retrieves help content vie the qnamaker.json from the arguments input by the user. @param args The arguments input by the user @returns {Promise<*>}
getHelpContents ( args , output )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/help.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/help.js
MIT
module.exports = async function qnamaker(config, serviceManifest, args, requestBody) { // Provide the config to the ServiceBase ServiceBase.config = config; // If a request body is specified and a typed data model // is available, create it and pass the source in. // This guarantees the endpoint will get only the // properties it expects since the user can specify // any json file with any number of properties that // may or may not be valid. const {identifier, operation} = serviceManifest; let requestBodyDataModel; // Allow untyped request bodies to seep through unchanged if (requestBody && operation.entityType && dataModels[operation.entityType]) { requestBodyDataModel = dataModels[operation.entityType].fromJSON(requestBody); } // Create the target service and kick off the request. const service = new api[identifier](); const response = await service[operation.name](args, (requestBodyDataModel || requestBody)); const text = await response.text(); try { return JSON.parse(text); } catch (e) { return text; } };
Entry into the program flow from the CLI This function orchestrates the instantiation of the service containing the operation to call. If a body is specified, the typed data model is created and the source object containing the properties is passed in. This is necessary to guarantee the endpoint receives a clean data model. @param {*} config The .luisrc file containing the configuration options @param {*} serviceManifest The manifest entry containing the details of the service to invoke. @param {*} args The arguments to use as the params for the request @param {*} requestBody The request body to send to the endpoint @returns {Promise<*|Promise|{enumerable}|void|JSON|Promise<any>>}
qnamaker ( config , serviceManifest , args , requestBody )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/index.js
MIT
function insertParametersFromObject(parameterizedString, sourceObj) { let result; let payload = parameterizedString; while ((result = tokenRegExp.exec(parameterizedString))) { const token = result[1]; const propertyName = token.replace(/[{}]/g, ''); if (!(propertyName in sourceObj)) { continue; } payload = payload.replace(token, '' + sourceObj[propertyName]); } return payload; }
Replaces parameterized strings with the value from the corresponding source object's property. @param parameterizedString {string} The String containing parameters represented by braces @param sourceObj {*} The object containing the properties to transfer. @returns {string} The string containing the replaced parameters from the source object.
insertParametersFromObject ( parameterizedString , sourceObj )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/utils/insertParametersFromObject.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/utils/insertParametersFromObject.js
MIT
module.exports = function deriveParamsFromPath(path) { const params = []; const reg = /(?:{)([\w]+)(?:})/g; let result; while ((result = reg.exec(path))) { params.push(result[1]); } return params; };
Derives required parameters from the tokenized path @param {string} path The tokenized path @returns {string[]} An array of named params
deriveParamsFromPath ( path )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/utils/deriveParamsFromPath.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/utils/deriveParamsFromPath.js
MIT
getOperationDetails(params) { return this.createRequest('', params, 'GET'); }
Gets details of a specific long running operation.
getOperationDetails ( params )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/operations.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/operations.js
MIT
constructor(relativeEndpoint, useEndpoint) { this.relativeEndpoint = relativeEndpoint; this.useEndpoint = (useEndpoint === true); }
@param {String} relativeEndpoint the endpoint for this service @param {bool} useEndpoint (default is false) if true, use the endpoint service url, not the admin service url
constructor ( relativeEndpoint , useEndpoint )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/serviceBase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/serviceBase.js
MIT
createRequest(pathFragment, params, method, dataModel = null) { const { commonHeaders: headers, relativeEndpoint } = this; const { kbId } = ServiceBase.config; if (this.useEndpoint) headers.Authorization = "EndpointKey " + ServiceBase.config.endpointKey || params.endpointKey; else headers['Ocp-Apim-Subscription-Key'] = ServiceBase.config.subscriptionKey || params.subscriptionKey; let requestEndpoint; if (this.useEndpoint) requestEndpoint = params.hostname; else requestEndpoint = params.legacy ? "https://westus.api.cognitive.microsoft.com/qnamaker/v3.0" : "https://westus.api.cognitive.microsoft.com/qnamaker/v4.0"; const tokenizedUrl = requestEndpoint + relativeEndpoint + pathFragment; // Order is important since we want to allow the user to // override their config with the data in the params object. params = Object.assign({}, (dataModel || {}), { kbId }, params); ServiceBase.validateParams(tokenizedUrl, params); let URL = insertParametersFromObject(tokenizedUrl, params); if (method === 'get' && ('skip' in params || 'take' in params)) { const { skip, take } = params; URL += '?'; if (!isNaN(+skip)) { URL += `skip=${~~skip}`; } if (!isNaN(+take)) { URL += !isNaN(+skip) ? `&take=${~~take}` : `take=${~~take}`; } } const body = dataModel ? JSON.stringify(dataModel) : undefined; if (params.debug) { console.log(`${method.toUpperCase()} ${URL}`); if (headers) console.log(`HEADERS:${JSON.stringify(headers)}`); if (body) console.log(body); } return fetch(URL, { headers, method, body }); }
Creates a request to the specified endpoint and returns a promise. @param {string} pathFragment An additional fragment to append to the endpoint @param {*} params An object containing the named params to be used to hydrate the tokenized url @param {'get'|'post'|'put'|'PATCH'|'delete'} method The method for the request @param {*} dataModel The data model to pass in as the request body @returns {Promise<Response>} The promise representing the request
createRequest ( pathFragment , params , method , dataModel = null )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/serviceBase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/serviceBase.js
MIT
ServiceBase.validateParams = function (tokenizedUrl, params) { const paramsFromPath = deriveParamsFromPath(tokenizedUrl); paramsFromPath.forEach(param => { if (!(param in params)) { const error = new Error(`The required param "${param}" is missing.`); error.name = 'ArgumentError'; throw error; } }); };
Validates the params object and will throw if a required param is missing. @param tokenizedUrl @param params
ServiceBase.validateParams ( tokenizedUrl , params )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/serviceBase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/serviceBase.js
MIT
updateKnowledgebase(params, updateKb/* UpdateKbOperationDTO */) { return this.createRequest('', params, 'PATCH', updateKb); }
Asynchronous operation to modify a knowledgebase.
updateKnowledgebase ( params , updateKb )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/knowledgebase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/knowledgebase.js
MIT
publishKnowledgebase(params) { return this.createRequest('', params, 'POST'); }
Publishes all changes in test index of a knowledgebase to its prod index.
publishKnowledgebase ( params )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/knowledgebase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/knowledgebase.js
MIT
deleteKnowledgebase(params) { return this.createRequest('', params, 'DELETE'); }
Deletes the knowledgebase and all its data.
deleteKnowledgebase ( params )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/knowledgebase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/knowledgebase.js
MIT
getKnowledgebaseDetails(params) { return this.createRequest('', params, 'GET'); }
Gets details of a specific knowledgebase.
getKnowledgebaseDetails ( params )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/knowledgebase.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/knowledgebase.js
MIT
createKnowledgebase(params , createKbPayload/* CreateKbDTO */) { return this.createRequest('', params, 'POST', createKbPayload); }
Asynchronous operation to create a new knowledgebase.
createKnowledgebase ( params , createKbPayload )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/createasync.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/createasync.js
MIT
constructor({knowledgebases /* KnowledgebaseDTO[] */} = {}) { Object.assign(this, {knowledgebases /* KnowledgebaseDTO[] */}); }
@property {KnowledgebaseDTO[]} knowledgebases
constructor ( { knowledgebases } = { } )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/dataModels/knowledgebasesDto.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/dataModels/knowledgebasesDto.js
MIT
constructor({primaryEndpointKey /* string */,secondaryEndpointKey /* string */} = {}) { Object.assign(this, {primaryEndpointKey /* string */,secondaryEndpointKey /* string */}); }
@property {string} secondaryEndpointKey
constructor ( { primaryEndpointKey , secondaryEndpointKey } = { } )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/dataModels/endpointKeysDto.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/dataModels/endpointKeysDto.js
MIT
constructor({wordAlterations /* AlterationsDTO[] */} = {}) { Object.assign(this, {wordAlterations /* AlterationsDTO[] */}); }
@property {AlterationsDTO[]} wordAlterations
constructor ( { wordAlterations } = { } )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/lib/api/dataModels/wordAlterationsDto.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/lib/api/dataModels/wordAlterationsDto.js
MIT
async function initializeConfig() { await stdoutAsync(chalk.cyan.bold('\nThis util will walk you through creating a .qnamakerrc file\n\nPress ^C at any time to quit.\n\n')); const questions = [ 'What is your QnAMaker access/subscription key? (found on the Cognitive Services Azure portal page under "access keys") ', 'What would you like to use as your active knowledgebase ID? [none] ' ]; const prompt = readline.createInterface({ input: process.stdin, output: process.stdout, }); const answers = []; for (let i = 0; i < questions.length; i++) { const question = questions[i]; const answer = await new Promise((resolve) => { function doPrompt(promptMessage) { prompt.question(promptMessage, response => { resolve(response); }); } doPrompt(question); }); answers.push(answer.trim()); } let [subscriptionKey, kbId] = answers; const config = Object.assign({}, {subscriptionKey, kbId}); if (subscriptionKey && kbId) { await updateKbId(config); } try { await new Promise((resolve, reject) => { const confirmation = `\n\nDoes this look ok?\n${JSON.stringify(config, null, 2)}\n[Yes]/No: `; prompt.question(confirmation, response => { /^(y|yes)$/.test((response || 'yes').toLowerCase()) ? resolve(response) : reject(); }); }); } catch (e) { return false; } await fs.writeJson(path.join(process.cwd(), '.qnamakerrc'), config, {spaces: 2}); return true; }
Walks the user though the creation of the .qnamakerrc file and writes it to disk. The knowledge base ID and subscription key are optional but if omitted, --\knowledgeBaseID and --subscriptionKey flags may be required for some commands. @returns {Promise<*>}
initializeConfig ( )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/bin/qnamaker.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/bin/qnamaker.js
MIT
async function handleError(error) { process.stderr.write('\n' + chalk.red.bold(error + '\n\n')); await help(args); return 1; }
Exits with a non-zero status and prints the error if present or displays the help @param error
handleError ( error )
javascript
microsoft/botbuilder-tools
packages/QnAMaker/bin/qnamaker.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/QnAMaker/bin/qnamaker.js
MIT
module.exports = async function readContents(fileContents, args = {}) { if (args.static || args.s) { now = new Date(2015, 9, 15, 12, 0, 0, 0).getTime(); } // Resolve file paths based on the input file with a fallback to the cwd workingDirectory = args.in ? path.dirname(path.resolve(args.in)) : __dirname; const activities = []; const lines = fileLineIterator(fileContents.trim() + NEWLINE); // Aggregate the contents of each line until // we reach a new activity. let aggregate = ''; // Read each line, derive activities with messages, then // return them as the payload let conversationId = getHashCode(fileContents); args.bot = 'bot'; args.users = []; let inHeader = true; for (let line of lines) { // pick up settings from the first lines if (inHeader && configurationRegExp.test(line)) { const [optionName, value, ...rest] = line.trim().split('='); if (rest.length) { throw new Error('Malformed configurations options detected. Options must be in the format optionName=optionValue'); } switch (optionName.trim()) { case 'user': case 'users': args.users = value.split(','); break; case 'bot': args.bot = value.trim(); break; } continue; } if (inHeader) { inHeader = false; if (!Array.isArray(args.users) || !args.users.length) args.users = ['user']; // starting the transcript, initialize the bot/user data accounts initConversation(args, conversationId, activities); } // process transcript lines if (args.newMessageRegEx.test(line)) { // process aggregate activites aggregate = aggregate.trim(); if (aggregate.length > 0) { const newActivities = await readCommandsFromAggregate(args, aggregate); if (newActivities) { activities.push(...newActivities); } } let matches = args.newMessageRegEx.exec(line); let speaker = matches[1]; let customRecipient = matches[3]; args.from = args.accounts[speaker.toLowerCase()]; if (customRecipient) { args.recipient = args.accounts[customRecipient.toLowerCase()]; } else { // pick recipient based on role if (args.from.role == 'bot') { // default for bot is last user args.recipient = args.accounts[args.user.toLowerCase()]; } else { // default recipient for a user is the bot args.recipient = args.accounts[args.bot.toLowerCase()]; // remember this user as last user to speak args.user = args.from.name; args.accounts.user = args.accounts[args.user.toLowerCase()]; } } // aggregate starts new with this line aggregate = line.substr(matches[0].length).trim() + NEWLINE; } else { // Not a new message but could contain // an activity on the line by itself. aggregate += line + NEWLINE; } } // end of file, process aggregate if (aggregate && aggregate.trim().length > 0) { const newActivities = await readCommandsFromAggregate(args, aggregate); if (newActivities) { activities.push(...newActivities); } } return activities; };
Entry for dialog parsing. @param fileContents UTF-8 encoded bytes to parse. @param args The k/v pair representing the configuration options @returns {Promise<Array>} Resolves with an array of Activity objects.
readContents ( fileContents , args = { } )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
function createConversationUpdate(args, membersAdded, membersRemoved) { let conversationUpdateActivity = createActivity({ type: activitytypes.conversationupdate, recipient: args[args.botId], conversationId: args.conversation.id }); conversationUpdateActivity.membersAdded = membersAdded || []; conversationUpdateActivity.membersRemoved = membersRemoved || []; conversationUpdateActivity.timestamp = getIncrementedDate(100); return conversationUpdateActivity; }
create ConversationUpdate Activity @param {*} args @param {ChannelAccount} from @param {ChannelAccount[]} membersAdded @param {ChannelAccount[]} membersRemoved
createConversationUpdate ( args , membersAdded , membersRemoved )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
async function readCommandsFromAggregate(args, aggregate) { const newActivities = []; commandRegExp.lastIndex = 0; let result; let delay = messageTimeGap; let currentActivity = createActivity({ type: activitytypes.Message, from: args.from, recipient: args.recipient, conversationId: args.conversation.id }); currentActivity.text = ''; while ((result = commandRegExp.exec(aggregate))) { // typeOrField should always be listed first let match = result[1]; // result[] doesn't have [] on it let lines = match.split(NEWLINE); let split = lines[0].indexOf('='); let typeOrField = split > 0 ? lines[0].substring(0, split).trim() : lines[0].trim(); let rest = (split > 0) ? lines[0].substring(split + 1).trim() : undefined; if (lines.length > 1) rest = match.substr(match.indexOf(NEWLINE) + NEWLINE.length); const type = activitytypes[typeOrField.toLowerCase()]; const field = activityfield[typeOrField.toLowerCase()]; const instruction = instructions[typeOrField.toLowerCase()]; // This isn't an activity - bail if (!type && !field && !instruction) { // skip unknown tag let value = aggregate.substr(0, result.index + result[0].length); currentActivity.text += value; aggregate = aggregate.substring(value.length); continue; } // Indicates a new activity - // As more activity types are supported, this should // become a util or helper class. if (type) { let text = aggregate.substr(0, result.index).trim(); if (text.length > 0) { currentActivity.text = text; currentActivity.timestamp = getIncrementedDate(delay); newActivities.push(currentActivity); // reset delay = messageTimeGap; currentActivity = createActivity({ type: activitytypes.Message, from: args.from, recipient: args.recipient, conversationId: args.conversation.id }); currentActivity.text = ''; } aggregate = aggregate.substr(result.index); switch (type) { case activitytypes.typing: { let newActivity = createActivity({ type, recipient: args.recipient, from: args.from, conversationId: args.conversation.id }); newActivity.timestamp = getIncrementedDate(100); newActivities.push(newActivity); break; } case activitytypes.conversationupdate: processConversationUpdate(args, newActivities, rest); break; } } else if (instruction) { switch (instruction) { case instructions.delay: delay = parseInt(rest); break; } } else if (field) { // As more activity fields are supported, // this should become a util or helper class. switch (field) { case activityfield.attachment: await addAttachment(currentActivity, rest); break; case activityfield.attachmentlayout: addAttachmentLayout(currentActivity, rest); break; case activityfield.suggestions: addSuggestions(currentActivity, rest); break; case activityfield.basiccard: case activityfield.herocard: addCard(cardContentTypes.hero, currentActivity, rest); break; case activityfield.thumbnailcard: addCard(cardContentTypes.thumbnail, currentActivity, rest); break; case activityfield.animationcard: addCard(cardContentTypes.animation, currentActivity, rest); break; case activityfield.mediacard: addCard(cardContentTypes.media, currentActivity, rest); break; case activityfield.audiocard: addCard(cardContentTypes.audio, currentActivity, rest); break; case activityfield.videocard: addCard(cardContentTypes.video, currentActivity, rest); break; // case activityfield.receiptcard: // addCard(cardContentTypes.receipt, currentActivity, rest); // break; case activityfield.signincard: addCard(cardContentTypes.signin, currentActivity, rest); break; case activityfield.oauthcard: addCard(cardContentTypes.oauth, currentActivity, rest); break; } } // Trim off this activity or activity field and continue. aggregate = aggregate.replace(`[${result[1]}]`, ''); commandRegExp.lastIndex = 0; } currentActivity.text += aggregate.trim(); currentActivity.timestamp = getIncrementedDate(delay); // if we have content, then add it if (currentActivity.text.length > 0 || (currentActivity.attachments && currentActivity.attachments.length > 0) || (currentActivity.suggestedActions && currentActivity.suggestedActions.actions.length > 0)) { newActivities.push(currentActivity); } return newActivities.length ? newActivities : null; }
Reads activities from a text aggregate. Aggregates form when multiple activities occur in the context of a single participant as is the case for attachments. @param {string} aggregate The aggregate text to derive activities from. @param {Activity} currentActivity The Activity currently in context @param {string} recipient The recipient of the Activity @param {string} from The sender of the Activity @param {string} conversationId The id of the channel @returns {Promise<*>} Resolves to the number of new activities encountered or null if no new activities resulted
readCommandsFromAggregate ( args , aggregate )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
async function addAttachment(activity, arg) { let parts = arg.trim().split(' '); let contentUrl = parts[0].trim(); let contentType = (parts.length > 1) ? parts[1].trim() : undefined; if (contentType) { contentType = contentType.toLowerCase(); if (cardContentTypes[contentType]) contentType = cardContentTypes[contentType]; } else { contentType = mime.lookup(contentUrl) || cardContentTypes[path.extname(contentUrl)]; if (!contentType && contentUrl && contentUrl.indexOf('http') == 0) { let options = { method: 'HEAD', uri: contentUrl }; let response = await request(options); contentType = response['content-type'].split(';')[0]; } } const charset = mime.charset(contentType); // if not a url if (contentUrl.indexOf('http') != 0) { // read the file let content = await readAttachmentFile(contentUrl, contentType); // if it is not a card if (!isCard(contentType) && charset !== 'UTF-8') { // send as base64 contentUrl = `data:${contentType};base64,${new Buffer(content).toString('base64')}`; content = undefined; } else { contentUrl = undefined; } return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl, content })); } // send as contentUrl return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl })); }
Adds an attachment to the activity. If a mimetype is specified, it is used as is. Otherwise, it is derived from the file extension. @param {Activity} activity The activity to add the attachment to @param {*} contentUrl contenturl @param {*} contentType contentType @returns {Promise<number>} The new number of attachments for the activity
addAttachment ( activity , arg )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
async function readAttachmentFile(fileLocation, contentType) { let resolvedFileLocation = path.join(workingDirectory, fileLocation); let exists = fs.pathExistsSync(resolvedFileLocation); // fallback to cwd if (!exists) { resolvedFileLocation = path.resolve(fileLocation); } // Throws if the fallback does not exist. if (contentType.includes('json') || isCard(contentType)) { return fs.readJsonSync(resolvedFileLocation); } else { return fs.readFileSync(resolvedFileLocation); } }
Utility function for reading the attachment @param fileLocation @param contentType @returns {*}
readAttachmentFile ( fileLocation , contentType )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
function createActivity({ type = ActivityTypes.Message, recipient, from, conversationId }) { const activity = new Activity({ from, recipient, type, id: '' + activityId++ }); activity.conversation = new ConversationAccount({ id: conversationId }); return activity; }
Utility for creating a new serializable Activity. @param {ActivityTypes} type The Activity type @param {string} to The recipient of the Activity @param {string} from The sender of the Activity @param {string} conversationId The id of the conversation @returns {Activity} The newly created activity
createActivity ( { type = ActivityTypes . Message , recipient , from , conversationId } )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
function* fileLineIterator(fileContents) { var parts = fileContents.split(/\r?\n/); for (let part of parts) { yield part; } } function getHashCode(contents) {
Generator producing a well-known Symbol for iterating each line in the UTF-8 encoded string. @param {string} fileContents The contents containing the lines to iterate.
fileLineIterator ( fileContents )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/index.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/index.js
MIT
constructor({ contentType = '', contentUrl = undefined, content = undefined } = {}) { Object.assign(this, { contentType, contentUrl, content }); }
@param contentType @param contentUrl @param content
constructor ( { contentType = '' , contentUrl = undefined , content = undefined } = { } )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/serializable/attachment.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/serializable/attachment.js
MIT
constructor({attachments, conversation, id, recipient, from, text, timestamp, type, channelId = 'chatdown'} = {}) { Object.assign(this, {attachments, conversation, id, recipient, from, text, timestamp, type, channelId}); }
@param attachments @param conversation @param id @param recipient @param from @param text @param timestamp @param type @param channelId
constructor ( { attachments , conversation , id , recipient , from , text , timestamp , type , channelId = 'chatdown' } = { } )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/serializable/activity.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/serializable/activity.js
MIT
constructor({isGroup, name, id} = {}) { Object.assign(this, {isGroup, name, id}); }
@param isGroup @param name @param id
constructor ( { isGroup , name , id } = { } )
javascript
microsoft/botbuilder-tools
packages/Chatdown/lib/serializable/conversationAccount.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/lib/serializable/conversationAccount.js
MIT
function getInput(args) { if (args._.length > 0) { args.in = args._[0]; return txtfile.readSync(path.resolve(args.in)); } else { return new Promise((resolve, reject) => { const { stdin } = process; let timeout = setTimeout(reject, 1000); let input = ''; stdin.setEncoding('utf8'); stdin.on('data', chunk => { if (timeout) { clearTimeout(timeout); timeout = null; } input += chunk; }); stdin.on('end', () => { resolve(input); }); stdin.on('error', error => reject(error)); }); } }
Retrieves the content to be parsed from a file if the --in argument was specified or from the stdin stream otherwise. Currently, interactive mode is not supported and will timeout if no data is received from stdin within 1000ms. @param args An object containing the argument k/v pairs @returns {Promise} a Promise that resolves to the content to be parsed
getInput ( args )
javascript
microsoft/botbuilder-tools
packages/Chatdown/bin/chatdown.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/bin/chatdown.js
MIT
async function writeOut(activities, args) { const { out } = args; //Is this used? Doesn't seem to be... const output = JSON.stringify(activities, null, 2); await new Promise((done, reject) => process.stdout.write(output, "utf-8", () => done())); return true; }
Writes the output either to a file if --out is specified or to stdout otherwise. @param {Array<Activity>} activities The array of activities resulting from the dialog read @param args An object containing the argument k/v pairs @returns {Promise<string>|boolean} The path of the file to write or true if written to stdout
writeOut ( activities , args )
javascript
microsoft/botbuilder-tools
packages/Chatdown/bin/chatdown.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/bin/chatdown.js
MIT
async function processFiles(inputDir, outputDir) { return new Promise(async (resolve, reject) => { let files = glob.sync(inputDir, { "ignore": ["**/node_modules/**"] }); for (let i = 0; i < files.length; i++) { try { let fileName = files[i]; if (files[i].lastIndexOf("/") != -1) { fileName = files[i].substr(files[i].lastIndexOf("/")) } fileName = fileName.split(".")[0]; let activities = await chatdown(txtfile.readSync(files[i])); let writeFile = `${outputDir}/${fileName}.transcript`; await fs.ensureFile(writeFile); await fs.writeJson(writeFile, activities, { spaces: 2 }); } catch (e) { reject(e); } } resolve(files.length); }); }
Processes multiple files, and writes them to the output directory. @param {string} inputDir String representing a glob that specifies the input directory @param {string} outputDir String representing the output directory for the processesd files @returns {Promise<string>|boolean} The length of the files array that was processes
processFiles ( inputDir , outputDir )
javascript
microsoft/botbuilder-tools
packages/Chatdown/bin/chatdown.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/bin/chatdown.js
MIT
async function runProgram() { const args = minimist(process.argv.slice(2)); if (args.prefix) { intercept(function(txt) { return `[${pkg.name}]\n${txt}`; }); } let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` }) .catch(error => pkg.version); if (semver.gt(latest, pkg.version)) { process.stderr.write(chalk.default.white(`\n Update available `)); process.stderr.write(chalk.default.grey(`${pkg.version}`)); process.stderr.write(chalk.default.white(` -> `)); process.stderr.write(chalk.default.greenBright(`${latest}\n`)); process.stderr.write(chalk.default.white(` Run `)); process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `)); process.stderr.write(chalk.default.white(`to update.\n`)); } process.stdout.write(chalk.default.white(`\n\n-----------------------------------------------------------\n`)); process.stdout.write(chalk.default.redBright(` NOTICE:\n`)); process.stdout.write(chalk.default.whiteBright(` This tool has been deprecated.\n`)); process.stdout.write(chalk.default.white(` All functionality was ported over to the new BF CLI.\n`)); process.stdout.write(chalk.default.white(` To learn more visit `)); process.stdout.write(chalk.default.blueBright(`https://aka.ms/NewBFCLI\n`)); process.stdout.write(chalk.default.white(`-----------------------------------------------------------\n\n`)); if (args.version || args.v) { process.stdout.write(pkg.version); return 0; } if (args.h || args.help) { help(process.stdout); return 0; } if (args.f || args.folder) { let inputDir = args.f.trim(); let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./"; if (outputDir.substr(0, 2) === "./") { outputDir = path.resolve(process.cwd(), outputDir.substr(2)) } const len = await processFiles(inputDir, outputDir); process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`); return len; } else { const fileContents = await getInput(args); if (fileContents) { const activities = await chatdown(fileContents, args); const writeConfirmation = await writeOut(activities, args); if (typeof writeConfirmation === 'string') { process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`); } return 0; } else { help(); return -1; } } }
Runs the program @returns {Promise<void>}
runProgram ( )
javascript
microsoft/botbuilder-tools
packages/Chatdown/bin/chatdown.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/bin/chatdown.js
MIT
function exitWithError(error) { if (error instanceof Error) { process.stderr.write(chalk.red(error)); } else { help(); } process.exit(1); }
Utility function that exist the process with an optional error. If an Error is received, the error message is written to stdout, otherwise, the help content are displayed. @param {*} error Either an instance of Error or null
exitWithError ( error )
javascript
microsoft/botbuilder-tools
packages/Chatdown/bin/chatdown.js
https://github.com/microsoft/botbuilder-tools/blob/master/packages/Chatdown/bin/chatdown.js
MIT
var addToPerformanceTimeline = function() { };
Adds an object to our internal Performance Timeline array. Will be blank if the environment supports PT.
addToPerformanceTimeline ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
var clearEntriesFromPerformanceTimeline = function() { };
Clears the specified entry types from our timeline array. Will be blank if the environment supports PT.
clearEntriesFromPerformanceTimeline ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
addToPerformanceTimeline = function(obj) { performanceTimeline.push(obj); // // If we insert a measure, its startTime may be out of order // from the rest of the entries because the use can use any // mark as the start time. If so, note we have to sort it before // returning getEntries(); // if (obj.entryType === "measure") { performanceTimelineRequiresSort = true; } };
Adds an object to our internal Performance Timeline array. @param {Object} obj PerformanceEntry
addToPerformanceTimeline ( obj )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
var ensurePerformanceTimelineOrder = function() { if (!performanceTimelineRequiresSort) { return; } // // Measures, which may be in this list, may enter the list in // an unsorted order. For example: // // 1. measure("a") // 2. mark("start_mark") // 3. measure("b", "start_mark") // 4. measure("c") // 5. getEntries() // // When calling #5, we should return [a,c,b] because technically the start time // of c is "0" (navigationStart), which will occur before b's start time due to the mark. // performanceTimeline.sort(function(a, b) { return a.startTime - b.startTime; }); performanceTimelineRequiresSort = false; };
Ensures our PT array is in the correct sorted order (by startTime)
ensurePerformanceTimelineOrder ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
clearEntriesFromPerformanceTimeline = function(entryType, name) { // clear all entries from the perf timeline i = 0; while (i < performanceTimeline.length) { if (performanceTimeline[i].entryType !== entryType) { // unmatched entry type i++; continue; } if (typeof name !== "undefined" && performanceTimeline[i].name !== name) { // unmatched name i++; continue; } // this entry matches our criteria, remove just it performanceTimeline.splice(i, 1); } };
Clears the specified entry types from our timeline array. @param {string} entryType Entry type (eg "mark" or "measure") @param {string} [name] Entry name (optional)
clearEntriesFromPerformanceTimeline ( entryType , name )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.getEntries = function() { ensurePerformanceTimelineOrder(); // get a copy of all of our entries var entries = performanceTimeline.slice(0); // if there was a native version of getEntries, add that if (hasNativeGetEntriesButNotUserTiming && origGetEntries) { // merge in native Array.prototype.push.apply(entries, origGetEntries.call(window.performance)); // sort by startTime entries.sort(function(a, b) { return a.startTime - b.startTime; }); } return entries; };
Gets all entries from the Performance Timeline. http://www.w3.org/TR/performance-timeline/#dom-performance-getentries NOTE: This will only ever return marks and measures. @returns {PerformanceEntry[]} Array of PerformanceEntrys
window.performance.getEntries ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.getEntriesByType = function(entryType) { // we only support marks/measures if (typeof entryType === "undefined" || (entryType !== "mark" && entryType !== "measure")) { if (hasNativeGetEntriesButNotUserTiming && origGetEntriesByType) { // native version exists, forward return origGetEntriesByType.call(window.performance, entryType); } return []; } // see note in ensurePerformanceTimelineOrder() on why this is required if (entryType === "measure") { ensurePerformanceTimelineOrder(); } // find all entries of entryType var entries = []; for (i = 0; i < performanceTimeline.length; i++) { if (performanceTimeline[i].entryType === entryType) { entries.push(performanceTimeline[i]); } } return entries; };
Gets all entries from the Performance Timeline of the specified type. http://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbytype NOTE: This will only work for marks and measures. @param {string} entryType Entry type (eg "mark" or "measure") @returns {PerformanceEntry[]} Array of PerformanceEntrys
window.performance.getEntriesByType ( entryType )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.getEntriesByName = function(name, entryType) { if (entryType && entryType !== "mark" && entryType !== "measure") { if (hasNativeGetEntriesButNotUserTiming && origGetEntriesByName) { // native version exists, forward return origGetEntriesByName.call(window.performance, name, entryType); } return []; } // see note in ensurePerformanceTimelineOrder() on why this is required if (typeof entryType !== "undefined" && entryType === "measure") { ensurePerformanceTimelineOrder(); } // find all entries of the name and (optionally) type var entries = []; for (i = 0; i < performanceTimeline.length; i++) { if (typeof entryType !== "undefined" && performanceTimeline[i].entryType !== entryType) { continue; } if (performanceTimeline[i].name === name) { entries.push(performanceTimeline[i]); } } if (hasNativeGetEntriesButNotUserTiming && origGetEntriesByName) { // merge in native Array.prototype.push.apply(entries, origGetEntriesByName.call(window.performance, name, entryType)); // sort by startTime entries.sort(function(a, b) { return a.startTime - b.startTime; }); } return entries; };
Gets all entries from the Performance Timeline of the specified name, and optionally, type. http://www.w3.org/TR/performance-timeline/#dom-performance-getentriesbyname NOTE: This will only work for marks and measures. @param {string} name Entry name @param {string} [entryType] Entry type (eg "mark" or "measure") @returns {PerformanceEntry[]} Array of PerformanceEntrys
window.performance.getEntriesByName ( name , entryType )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.mark = function(markName) { var now = window.performance.now(); // mark name is required if (typeof markName === "undefined") { throw new SyntaxError("Mark name must be specified"); } // mark name can't be a NT timestamp if (window.performance.timing && markName in window.performance.timing) { throw new SyntaxError("Mark name is not allowed"); } if (!marks[markName]) { marks[markName] = []; } marks[markName].push(now); // add to perf timeline as well addToPerformanceTimeline({ entryType: "mark", name: markName, startTime: now, duration: 0 }); };
UserTiming mark http://www.w3.org/TR/user-timing/#dom-performance-mark @param {string} markName Mark name
window.performance.mark ( markName )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.clearMarks = function(markName) { if (!markName) { // clear all marks marks = {}; } else { marks[markName] = []; } clearEntriesFromPerformanceTimeline("mark", markName); };
UserTiming clear marks http://www.w3.org/TR/user-timing/#dom-performance-clearmarks @param {string} markName Mark name
window.performance.clearMarks ( markName )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.measure = function(measureName, startMark, endMark) { var now = window.performance.now(); if (typeof measureName === "undefined") { throw new SyntaxError("Measure must be specified"); } // if there isn't a startMark, we measure from navigationStart to now if (!startMark) { // add to perf timeline as well addToPerformanceTimeline({ entryType: "measure", name: measureName, startTime: 0, duration: now }); return; } // // If there is a startMark, check for it first in the NavigationTiming interface, // then check our own marks. // var startMarkTime = 0; if (window.performance.timing && startMark in window.performance.timing) { // mark cannot have a timing of 0 if (startMark !== "navigationStart" && window.performance.timing[startMark] === 0) { throw new Error(startMark + " has a timing of 0"); } // time is the offset of this mark to navigationStart's time startMarkTime = window.performance.timing[startMark] - window.performance.timing.navigationStart; } else if (startMark in marks) { startMarkTime = marks[startMark][marks[startMark].length - 1]; } else { throw new Error(startMark + " mark not found"); } // // If there is a endMark, check for it first in the NavigationTiming interface, // then check our own marks. // var endMarkTime = now; if (endMark) { endMarkTime = 0; if (window.performance.timing && endMark in window.performance.timing) { // mark cannot have a timing of 0 if (endMark !== "navigationStart" && window.performance.timing[endMark] === 0) { throw new Error(endMark + " has a timing of 0"); } // time is the offset of this mark to navigationStart's time endMarkTime = window.performance.timing[endMark] - window.performance.timing.navigationStart; } else if (endMark in marks) { endMarkTime = marks[endMark][marks[endMark].length - 1]; } else { throw new Error(endMark + " mark not found"); } } // add to our measure array var duration = endMarkTime - startMarkTime; // add to perf timeline as well addToPerformanceTimeline({ entryType: "measure", name: measureName, startTime: startMarkTime, duration: duration }); };
UserTiming measure http://www.w3.org/TR/user-timing/#dom-performance-measure @param {string} measureName Measure name @param {string} [startMark] Start mark name @param {string} [endMark] End mark name
window.performance.measure ( measureName , startMark , endMark )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
window.performance.clearMeasures = function(measureName) { clearEntriesFromPerformanceTimeline("measure", measureName); };
UserTiming clear measures http://www.w3.org/TR/user-timing/#dom-performance-clearmeasures @param {string} measureName Measure name
window.performance.clearMeasures ( measureName )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.109.0/UserTiming/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.109.0/UserTiming/raw.js
MIT
get: function() { return this.innerHTML; },
@this {!HTMLElement} @return {string}
get ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/HTMLTemplateElement/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/HTMLTemplateElement/raw.js
MIT
set: function(text) { this.innerHTML = text; }
@this {!HTMLElement} @param {string}
set ( text )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/HTMLTemplateElement/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/HTMLTemplateElement/raw.js
MIT
function IntersectionObserverEntry(entry) { this.time = entry.time; this.target = entry.target; this.rootBounds = entry.rootBounds; this.boundingClientRect = entry.boundingClientRect; this.intersectionRect = entry.intersectionRect || getEmptyRect(); try { this.isIntersecting = !!entry.intersectionRect; } catch (err) { // This means we are using the IntersectionObserverEntry polyfill which has only defined a getter } // Calculates the intersection ratio. var targetRect = this.boundingClientRect; var targetArea = targetRect.width * targetRect.height; var intersectionRect = this.intersectionRect; var intersectionArea = intersectionRect.width * intersectionRect.height; // Sets intersection ratio. if (targetArea) { // Round the intersection ratio to avoid floating point math issues: // https://github.com/w3c/IntersectionObserver/issues/324 this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4)); } else { // If area is zero and is intersecting, sets to 1, otherwise to 0 this.intersectionRatio = this.isIntersecting ? 1 : 0; } }
Creates the global IntersectionObserverEntry constructor. https://w3c.github.io/IntersectionObserver/#intersection-observer-entry @param {Object} entry A dictionary of instance properties. @constructor
IntersectionObserverEntry ( entry )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function IntersectionObserver(callback, opt_options) { var options = opt_options || {}; if (typeof callback != 'function') { throw new Error('callback must be a function'); } if (options.root && options.root.nodeType != 1) { throw new Error('root must be an Element'); } // Binds and throttles `this._checkForIntersections`. this._checkForIntersections = throttle( this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT); // Private properties. this._callback = callback; this._observationTargets = []; this._queuedEntries = []; this._rootMarginValues = this._parseRootMargin(options.rootMargin); // Public properties. this.thresholds = this._initThresholds(options.threshold); this.root = options.root || null; this.rootMargin = this._rootMarginValues.map(function(margin) { return margin.value + margin.unit; }).join(' '); }
Creates the global IntersectionObserver constructor. https://w3c.github.io/IntersectionObserver/#intersection-observer-interface @param {Function} callback The function to be invoked after intersection changes have queued. The function is not invoked if the queue has been emptied by calling the `takeRecords` method. @param {Object=} opt_options Optional configuration options. @constructor
IntersectionObserver ( callback , opt_options )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype.observe = function(target) { var isTargetAlreadyObserved = this._observationTargets.some(function(item) { return item.element == target; }); if (isTargetAlreadyObserved) { return; } if (!(target && target.nodeType == 1)) { throw new Error('target must be an Element'); } this._registerInstance(); this._observationTargets.push({element: target, entry: null}); this._monitorIntersections(); this._checkForIntersections(); };
Starts observing a target element for intersection changes based on the thresholds values. @param {Element} target The DOM element to observe.
IntersectionObserver.prototype.observe ( target )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype.unobserve = function(target) { this._observationTargets = this._observationTargets.filter(function(item) { return item.element != target; }); if (!this._observationTargets.length) { this._unmonitorIntersections(); this._unregisterInstance(); } };
Stops observing a target element for intersection changes. @param {Element} target The DOM element to observe.
IntersectionObserver.prototype.unobserve ( target )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype.disconnect = function() { this._observationTargets = []; this._unmonitorIntersections(); this._unregisterInstance(); };
Stops observing all target elements for intersection changes.
IntersectionObserver.prototype.disconnect ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype.takeRecords = function() { var records = this._queuedEntries.slice(); this._queuedEntries = []; return records; };
Returns any queue entries that have not yet been reported to the callback and clears the queue. This can be used in conjunction with the callback to obtain the absolute most up-to-date intersection information. @return {Array} The currently queued entries.
IntersectionObserver.prototype.takeRecords ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._initThresholds = function(opt_threshold) { var threshold = opt_threshold || [0]; if (!Array.isArray(threshold)) threshold = [threshold]; return threshold.sort().filter(function(t, i, a) { if (typeof t != 'number' || isNaN(t) || t < 0 || t > 1) { throw new Error('threshold must be a number between 0 and 1 inclusively'); } return t !== a[i - 1]; }); };
Accepts the threshold value from the user configuration object and returns a sorted array of unique threshold values. If a value is not between 0 and 1 and error is thrown. @private @param {Array|number=} opt_threshold An optional threshold value or a list of threshold values, defaulting to [0]. @return {Array} A sorted list of unique and valid threshold values.
IntersectionObserver.prototype._initThresholds ( opt_threshold )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._monitorIntersections = function() { if (!this._monitoringIntersections) { this._monitoringIntersections = true; // If a poll interval is set, use polling instead of listening to // resize and scroll events or DOM mutations. if (this.POLL_INTERVAL) { this._monitoringInterval = setInterval( this._checkForIntersections, this.POLL_INTERVAL); } else { addEvent(window, 'resize', this._checkForIntersections, true); addEvent(document, 'scroll', this._checkForIntersections, true); if (this.USE_MUTATION_OBSERVER && 'MutationObserver' in window) { this._domObserver = new MutationObserver(this._checkForIntersections); this._domObserver.observe(document, { attributes: true, childList: true, characterData: true, subtree: true }); } } } };
Starts polling for intersection changes if the polling is not already happening, and if the page's visibility state is visible. @private
IntersectionObserver.prototype._monitorIntersections ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._unmonitorIntersections = function() { if (this._monitoringIntersections) { this._monitoringIntersections = false; clearInterval(this._monitoringInterval); this._monitoringInterval = null; removeEvent(window, 'resize', this._checkForIntersections, true); removeEvent(document, 'scroll', this._checkForIntersections, true); if (this._domObserver) { this._domObserver.disconnect(); this._domObserver = null; } } };
Stops polling for intersection changes. @private
IntersectionObserver.prototype._unmonitorIntersections ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._getRootRect = function() { var rootRect; if (this.root) { rootRect = getBoundingClientRect(this.root); } else { // Use <html>/<body> instead of window since scroll bars affect size. var html = document.documentElement; var body = document.body; rootRect = { top: 0, left: 0, right: html.clientWidth || body.clientWidth, width: html.clientWidth || body.clientWidth, bottom: html.clientHeight || body.clientHeight, height: html.clientHeight || body.clientHeight }; } return this._expandRectByRootMargin(rootRect); };
Returns the root rect after being expanded by the rootMargin value. @return {Object} The expanded root rect. @private
IntersectionObserver.prototype._getRootRect ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._expandRectByRootMargin = function(rect) { var margins = this._rootMarginValues.map(function(margin, i) { return margin.unit == 'px' ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100; }); var newRect = { top: rect.top - margins[0], right: rect.right + margins[1], bottom: rect.bottom + margins[2], left: rect.left - margins[3] }; newRect.width = newRect.right - newRect.left; newRect.height = newRect.bottom - newRect.top; return newRect; };
Accepts a rect and expands it by the rootMargin value. @param {Object} rect The rect object to expand. @return {Object} The expanded rect. @private
IntersectionObserver.prototype._expandRectByRootMargin ( rect )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._rootIsInDom = function() { return !this.root || containsDeep(document, this.root); };
Returns whether or not the root element is an element and is in the DOM. @return {boolean} True if the root element is an element and is in the DOM. @private
IntersectionObserver.prototype._rootIsInDom ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._rootContainsTarget = function(target) { return containsDeep(this.root || document, target); };
Returns whether or not the target element is a child of root. @param {Element} target The target element to check. @return {boolean} True if the target element is a child of root. @private
IntersectionObserver.prototype._rootContainsTarget ( target )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._registerInstance = function() { if (registry.indexOf(this) < 0) { registry.push(this); } };
Adds the instance to the global IntersectionObserver registry if it isn't already present. @private
IntersectionObserver.prototype._registerInstance ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._unregisterInstance = function() { var index = registry.indexOf(this); if (index != -1) registry.splice(index, 1); };
Removes the instance from the global IntersectionObserver registry. @private
IntersectionObserver.prototype._unregisterInstance ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function now() { return window.performance && performance.now && performance.now(); }
Returns the result of the performance.now() method or null in browsers that don't support the API. @return {number} The elapsed time since the page was requested.
now ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function throttle(fn, timeout) { var timer = null; return function () { if (!timer) { timer = setTimeout(function() { fn(); timer = null; }, timeout); } }; }
Throttles a function and delays its execution, so it's only called at most once within a given time period. @param {Function} fn The function to throttle. @param {number} timeout The amount of time that must pass before the function can be called again. @return {Function} The throttled function.
throttle ( fn , timeout )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function addEvent(node, event, fn, opt_useCapture) { if (typeof node.addEventListener == 'function') { node.addEventListener(event, fn, opt_useCapture || false); } else if (typeof node.attachEvent == 'function') { node.attachEvent('on' + event, fn); } }
Adds an event handler to a DOM node ensuring cross-browser compatibility. @param {Node} node The DOM node to add the event handler to. @param {string} event The event name. @param {Function} fn The event handler to add. @param {boolean} opt_useCapture Optionally adds the even to the capture phase. Note: this only works in modern browsers.
addEvent ( node , event , fn , opt_useCapture )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function removeEvent(node, event, fn, opt_useCapture) { if (typeof node.removeEventListener == 'function') { node.removeEventListener(event, fn, opt_useCapture || false); } else if (typeof node.detatchEvent == 'function') { node.detatchEvent('on' + event, fn); } }
Removes a previously added event handler from a DOM node. @param {Node} node The DOM node to remove the event handler from. @param {string} event The event name. @param {Function} fn The event handler to remove. @param {boolean} opt_useCapture If the event handler was added with this flag set to true, it should be set to true here in order to remove it.
removeEvent ( node , event , fn , opt_useCapture )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function computeRectIntersection(rect1, rect2) { var top = Math.max(rect1.top, rect2.top); var bottom = Math.min(rect1.bottom, rect2.bottom); var left = Math.max(rect1.left, rect2.left); var right = Math.min(rect1.right, rect2.right); var width = right - left; var height = bottom - top; return (width >= 0 && height >= 0) && { top: top, bottom: bottom, left: left, right: right, width: width, height: height }; }
Returns the intersection between two rect objects. @param {Object} rect1 The first rect. @param {Object} rect2 The second rect. @return {?Object} The intersection rect or undefined if no intersection is found.
computeRectIntersection ( rect1 , rect2 )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function getBoundingClientRect(el) { var rect; try { rect = el.getBoundingClientRect(); } catch (err) { // Ignore Windows 7 IE11 "Unspecified error" // https://github.com/w3c/IntersectionObserver/pull/205 } if (!rect) return getEmptyRect(); // Older IE if (!(rect.width && rect.height)) { rect = { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; }
Shims the native getBoundingClientRect for compatibility with older IE. @param {Element} el The element whose bounding rect to get. @return {Object} The (possibly shimmed) rect of the element.
getBoundingClientRect ( el )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function getEmptyRect() { return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 }; }
Returns an empty rect object. An empty rect is returned when an element is not in the DOM. @return {Object} The empty rect.
getEmptyRect ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function containsDeep(parent, child) { var node = child; while (node) { if (node == parent) return true; node = getParentNode(node); } return false; }
Checks to see if a parent element contains a child element (including inside shadow DOM). @param {Node} parent The parent element. @param {Node} child The child element. @return {boolean} True if the parent node contains the child node.
containsDeep ( parent , child )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function getParentNode(node) { var parent = node.parentNode; if (parent && parent.nodeType == 11 && parent.host) { // If the parent is a shadow root, return the host element. return parent.host; } if (parent && parent.assignedSlot) { // If the parent is distributed in a <slot>, return the parent of a slot. return parent.assignedSlot.parentNode; } return parent; }
Gets the parent node of an element or its host element if the parent node is a shadow root. @param {Node} node The node whose parent to get. @return {Node|null} The parent node or null if no parent exists.
getParentNode ( node )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
IntersectionObserver.prototype._checkForIntersections = function() { var rootIsInDom = this._rootIsInDom(); var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect(); this._observationTargets.forEach(function(item) { var target = item.element; var targetRect = getBoundingClientRect(target); var rootContainsTarget = this._rootContainsTarget(target); var oldEntry = item.entry; var intersectionRect = rootIsInDom && rootContainsTarget && this._computeTargetAndRootIntersection(target, rootRect); var newEntry = item.entry = new IntersectionObserverEntry({ time: now(), target: target, boundingClientRect: targetRect, rootBounds: rootRect, intersectionRect: intersectionRect }); if (!oldEntry) { this._queuedEntries.push(newEntry); } else if (rootIsInDom && rootContainsTarget) { // If the new entry intersection ratio has crossed any of the // thresholds, add a new entry. if (this._hasCrossedThreshold(oldEntry, newEntry)) { this._queuedEntries.push(newEntry); } } else { // If the root is not in the DOM or target is not contained within // root but the previous entry for this target had an intersection, // add a new record indicating removal. if (oldEntry && oldEntry.isIntersecting) { this._queuedEntries.push(newEntry); } } }, this); if (this._queuedEntries.length) { this._callback(this.takeRecords(), this); } }; /** * Accepts a target and root rect computes the intersection between then * following the algorithm in the spec. * TODO(philipwalton): at this time clip-path is not considered. * https://w3c.github.io/IntersectionObserver/#calculate-intersection-rect-algo * @param {Element} target The target DOM element * @param {Object} rootRect The bounding rect of the root after being * expanded by the rootMargin value. * @return {?Object} The final intersection rect object or undefined if no * intersection is found. * @private */ IntersectionObserver.prototype._computeTargetAndRootIntersection = function(target, rootRect) { // If the element isn't displayed, an intersection can't happen. if (window.getComputedStyle(target).display == 'none') return; var targetRect = getBoundingClientRect(target); var intersectionRect = targetRect; var parent = getParentNode(target); var atRoot = false; while (!atRoot) { var parentRect = null; var parentComputedStyle = parent.nodeType == 1 ? window.getComputedStyle(parent) : {}; // If the parent isn't displayed, an intersection can't happen. if (parentComputedStyle.display == 'none') return; if (parent == this.root || parent == document) { atRoot = true; parentRect = rootRect; } else { // If the element has a non-visible overflow, and it's not the <body> // or <html> element, update the intersection rect. // Note: <body> and <html> cannot be clipped to a rect that's not also // the document rect, so no need to compute a new intersection. if (parent != document.body && parent != document.documentElement && parentComputedStyle.overflow != 'visible') { parentRect = getBoundingClientRect(parent); } } // If either of the above conditionals set a new parentRect, // calculate new intersection data. if (parentRect) { intersectionRect = computeRectIntersection(parentRect, intersectionRect); if (!intersectionRect) break; } parent = getParentNode(parent); } return intersectionRect; }; /** * Returns the root rect after being expanded by the rootMargin value. * @return {Object} The expanded root rect. * @private */ IntersectionObserver.prototype._getRootRect = function() { var rootRect; if (this.root) { rootRect = getBoundingClientRect(this.root); } else { // Use <html>/<body> instead of window since scroll bars affect size. var html = document.documentElement; var body = document.body; rootRect = { top: 0, left: 0, right: html.clientWidth || body.clientWidth, width: html.clientWidth || body.clientWidth, bottom: html.clientHeight || body.clientHeight, height: html.clientHeight || body.clientHeight }; } return this._expandRectByRootMargin(rootRect); }; /** * Accepts a rect and expands it by the rootMargin value. * @param {Object} rect The rect object to expand. * @return {Object} The expanded rect. * @private */ IntersectionObserver.prototype._expandRectByRootMargin = function(rect) { var margins = this._rootMarginValues.map(function(margin, i) { return margin.unit == 'px' ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100; }); var newRect = { top: rect.top - margins[0], right: rect.right + margins[1], bottom: rect.bottom + margins[2], left: rect.left - margins[3] }; newRect.width = newRect.right - newRect.left; newRect.height = newRect.bottom - newRect.top; return newRect; }; /** * Accepts an old and new entry and returns true if at least one of the * threshold values has been crossed. * @param {?IntersectionObserverEntry} oldEntry The previous entry for a * particular target element or null if no previous entry exists. * @param {IntersectionObserverEntry} newEntry The current entry for a * particular target element. * @return {boolean} Returns true if a any threshold has been crossed. * @private */ IntersectionObserver.prototype._hasCrossedThreshold = function(oldEntry, newEntry) { // To make comparing easier, an entry that has a ratio of 0 // but does not actually intersect is given a value of -1 var oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1; var newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1; // Ignore unchanged ratios if (oldRatio === newRatio) return; for (var i = 0; i < this.thresholds.length; i++) { var threshold = this.thresholds[i]; // Return true if an entry matches a threshold or if the new ratio // and the old ratio are on the opposite sides of a threshold. if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { return true; } } }; /** * Returns whether or not the root element is an element and is in the DOM. * @return {boolean} True if the root element is an element and is in the DOM. * @private */ IntersectionObserver.prototype._rootIsInDom = function() { return !this.root || containsDeep(document, this.root); }; /** * Returns whether or not the target element is a child of root. * @param {Element} target The target element to check. * @return {boolean} True if the target element is a child of root. * @private */ IntersectionObserver.prototype._rootContainsTarget = function(target) { return containsDeep(this.root || document, target); }; /** * Adds the instance to the global IntersectionObserver registry if it isn't * already present. * @private */ IntersectionObserver.prototype._registerInstance = function() { if (registry.indexOf(this) < 0) { registry.push(this); } }; /** * Removes the instance from the global IntersectionObserver registry. * @private */ IntersectionObserver.prototype._unregisterInstance = function() { var index = registry.indexOf(this); if (index != -1) registry.splice(index, 1); }; /** * Returns the result of the performance.now() method or null in browsers * that don't support the API. * @return {number} The elapsed time since the page was requested. */ function now() { return window.performance && performance.now && performance.now(); } /** * Throttles a function and delays its execution, so it's only called at most * once within a given time period. * @param {Function} fn The function to throttle. * @param {number} timeout The amount of time that must pass before the * function can be called again. * @return {Function} The throttled function. */ function throttle(fn, timeout) { var timer = null; return function () { if (!timer) { timer = setTimeout(function() { fn(); timer = null; }, timeout); } }; } /** * Adds an event handler to a DOM node ensuring cross-browser compatibility. * @param {Node} node The DOM node to add the event handler to. * @param {string} event The event name. * @param {Function} fn The event handler to add. * @param {boolean} opt_useCapture Optionally adds the even to the capture * phase. Note: this only works in modern browsers. */ function addEvent(node, event, fn, opt_useCapture) { if (typeof node.addEventListener == 'function') { node.addEventListener(event, fn, opt_useCapture || false); } else if (typeof node.attachEvent == 'function') { node.attachEvent('on' + event, fn); } } /** * Removes a previously added event handler from a DOM node. * @param {Node} node The DOM node to remove the event handler from. * @param {string} event The event name. * @param {Function} fn The event handler to remove. * @param {boolean} opt_useCapture If the event handler was added with this * flag set to true, it should be set to true here in order to remove it. */ function removeEvent(node, event, fn, opt_useCapture) { if (typeof node.removeEventListener == 'function') { node.removeEventListener(event, fn, opt_useCapture || false); } else if (typeof node.detatchEvent == 'function') { node.detatchEvent('on' + event, fn); } } /** * Returns the intersection between two rect objects. * @param {Object} rect1 The first rect. * @param {Object} rect2 The second rect. * @return {?Object} The intersection rect or undefined if no intersection * is found. */ function computeRectIntersection(rect1, rect2) { var top = Math.max(rect1.top, rect2.top); var bottom = Math.min(rect1.bottom, rect2.bottom); var left = Math.max(rect1.left, rect2.left); var right = Math.min(rect1.right, rect2.right); var width = right - left; var height = bottom - top; return (width >= 0 && height >= 0) && { top: top, bottom: bottom, left: left, right: right, width: width, height: height }; } /** * Shims the native getBoundingClientRect for compatibility with older IE. * @param {Element} el The element whose bounding rect to get. * @return {Object} The (possibly shimmed) rect of the element. */ function getBoundingClientRect(el) { var rect; try { rect = el.getBoundingClientRect(); } catch (err) { // Ignore Windows 7 IE11 "Unspecified error" // https://github.com/w3c/IntersectionObserver/pull/205 } if (!rect) return getEmptyRect(); // Older IE if (!(rect.width && rect.height)) { rect = { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.right - rect.left, height: rect.bottom - rect.top }; } return rect; } /** * Returns an empty rect object. An empty rect is returned when an element * is not in the DOM. * @return {Object} The empty rect. */ function getEmptyRect() { return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 }; } /** * Checks to see if a parent element contains a child element (including inside * shadow DOM). * @param {Node} parent The parent element. * @param {Node} child The child element. * @return {boolean} True if the parent node contains the child node. */ function containsDeep(parent, child) { var node = child; while (node) { if (node == parent) return true; node = getParentNode(node); } return false; } /** * Gets the parent node of an element or its host element if the parent node * is a shadow root. * @param {Node} node The node whose parent to get. * @return {Node|null} The parent node or null if no parent exists. */ function getParentNode(node) { var parent = node.parentNode; if (parent && parent.nodeType == 11 && parent.host) { // If the parent is a shadow root, return the host element. return parent.host; } if (parent && parent.assignedSlot) { // If the parent is distributed in a <slot>, return the parent of a slot. return parent.assignedSlot.parentNode; } return parent; } // Exposes the constructors globally. window.IntersectionObserver = IntersectionObserver; window.IntersectionObserverEntry = IntersectionObserverEntry; }(window, document));
Scans each observation target for intersection changes and adds them to the internal entries queue. If new entries are found, it schedules the callback to be invoked. @private
IntersectionObserver.prototype._checkForIntersections ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.46.0/IntersectionObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.46.0/IntersectionObserver/raw.js
MIT
function getIndex(arr, key) { var result = -1; arr.some(function (entry, index) { if (entry[0] === key) { result = index; return true; } return false; }); return result; }
Returns index in provided array that matches the specified key. @param {Array<Array>} arr @param {*} key @returns {number}
getIndex ( arr , key )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
class_1.prototype.set = function (key, value) { var index = getIndex(this.__entries__, key); if (~index) { this.__entries__[index][1] = value; } else { this.__entries__.push([key, value]); } };
@param {*} key @param {*} value @returns {void}
class_1.prototype.set ( key , value )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
class_1.prototype.forEach = function (callback, ctx) { if (ctx === void 0) { ctx = null; } for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) { var entry = _a[_i]; callback.call(ctx, entry[1], entry[0]); } };
@param {Function} callback @param {*} [ctx=null] @returns {void}
class_1.prototype.forEach ( callback , ctx )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
var MapShim = (function () { if (typeof Map !== 'undefined') { return Map; } /** * Returns index in provided array that matches the specified key. * * @param {Array<Array>} arr * @param {*} key * @returns {number} */ function getIndex(arr, key) { var result = -1; arr.some(function (entry, index) { if (entry[0] === key) { result = index; return true; } return false; }); return result; } return /** @class */ (function () { function class_1() { this.__entries__ = []; } Object.defineProperty(class_1.prototype, "size", { /** * @returns {boolean} */ get: function () { return this.__entries__.length; }, enumerable: true, configurable: true }); /** * @param {*} key * @returns {*} */ class_1.prototype.get = function (key) { var index = getIndex(this.__entries__, key); var entry = this.__entries__[index]; return entry && entry[1]; }; /** * @param {*} key * @param {*} value * @returns {void} */ class_1.prototype.set = function (key, value) { var index = getIndex(this.__entries__, key); if (~index) { this.__entries__[index][1] = value; } else { this.__entries__.push([key, value]); } }; /** * @param {*} key * @returns {void} */ class_1.prototype.delete = function (key) { var entries = this.__entries__; var index = getIndex(entries, key); if (~index) { entries.splice(index, 1); } }; /** * @param {*} key * @returns {void} */ class_1.prototype.has = function (key) { return !!~getIndex(this.__entries__, key); }; /** * @returns {void} */ class_1.prototype.clear = function () { this.__entries__.splice(0); }; /** * @param {Function} callback * @param {*} [ctx=null] * @returns {void} */ class_1.prototype.forEach = function (callback, ctx) { if (ctx === void 0) { ctx = null; } for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) { var entry = _a[_i]; callback.call(ctx, entry[1], entry[0]); } }; return class_1; }()); })();
A collection of shims that provide minimal functionality of the ES6 collections. These implementations are not meant to be used outside of the ResizeObserver modules as they cover only a limited range of use cases. /* eslint-disable require-jsdoc, valid-jsdoc
(anonymous) ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
var requestAnimationFrame$1 = (function () { if (typeof requestAnimationFrame === 'function') { // It's required to use a bounded function because IE sometimes throws // an "Invalid calling object" error if rAF is invoked without the global // object on the left hand side. return requestAnimationFrame.bind(global$1); } return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); }; })();
A shim for the requestAnimationFrame which falls back to the setTimeout if first one is not supported. @returns {number} Requests' identifier.
(anonymous) ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
function resolvePending() { if (leadingCall) { leadingCall = false; callback(); } if (trailingCall) { proxy(); } }
Invokes the original callback function and schedules new invocation if the "proxy" was called during current request. @returns {void}
resolvePending ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
function timeoutCallback() { requestAnimationFrame$1(resolvePending); }
Callback invoked after the specified delay. It will further postpone invocation of the original function delegating it to the requestAnimationFrame. @returns {void}
timeoutCallback ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
function proxy() { var timeStamp = Date.now(); if (leadingCall) { // Reject immediately following calls. if (timeStamp - lastCallTime < trailingTimeout) { return; } // Schedule new call to be in invoked when the pending one is resolved. // This is important for "transitions" which never actually start // immediately so there is a chance that we might miss one if change // happens amids the pending invocation. trailingCall = true; } else { leadingCall = true; trailingCall = false; setTimeout(timeoutCallback, delay); } lastCallTime = timeStamp; }
Schedules invocation of the original function. @returns {void}
proxy ( )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT
function throttle (callback, delay) { var leadingCall = false, trailingCall = false, lastCallTime = 0; /** * Invokes the original callback function and schedules new invocation if * the "proxy" was called during current request. * * @returns {void} */ function resolvePending() { if (leadingCall) { leadingCall = false; callback(); } if (trailingCall) { proxy(); } } /** * Callback invoked after the specified delay. It will further postpone * invocation of the original function delegating it to the * requestAnimationFrame. * * @returns {void} */ function timeoutCallback() { requestAnimationFrame$1(resolvePending); } /** * Schedules invocation of the original function. * * @returns {void} */ function proxy() { var timeStamp = Date.now(); if (leadingCall) { // Reject immediately following calls. if (timeStamp - lastCallTime < trailingTimeout) { return; } // Schedule new call to be in invoked when the pending one is resolved. // This is important for "transitions" which never actually start // immediately so there is a chance that we might miss one if change // happens amids the pending invocation. trailingCall = true; } else { leadingCall = true; trailingCall = false; setTimeout(timeoutCallback, delay); } lastCallTime = timeStamp; } return proxy; }
Creates a wrapper function which ensures that provided callback will be invoked only once during the specified delay period. @param {Function} callback - Function to be invoked after the delay period. @param {number} delay - Delay after which to invoke callback. @returns {Function}
throttle ( callback , delay )
javascript
polyfillpolyfill/polyfill-service
polyfill-libraries/3.52.1/ResizeObserver/raw.js
https://github.com/polyfillpolyfill/polyfill-service/blob/master/polyfill-libraries/3.52.1/ResizeObserver/raw.js
MIT