code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function isTemplateCompatible(generator, apiVersion) { const generatorVersion = getGeneratorVersion(); if (typeof generator === 'string' && !semver.satisfies(generatorVersion, generator, {includePrerelease: true})) { throw new Error(`This template is not compatible with the current version of the generator (${g...
Checks if template is compatible with the version of the generator that is used @private @param {String} generator Information about supported generator version that is part of the template configuration @param {String} generator Information about supported Parser-API version that is part of the template configuration
isTemplateCompatible
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function isRequiredParamProvided(configParams, templateParams) { const missingParams = Object.keys(configParams || {}) .filter(key => configParams[key].required && !templateParams[key]); if (missingParams.length) { throw new Error(`This template requires the following missing params: ${missingParams}.`); ...
Checks if parameters described in template configuration as required are passed to the generator @private @param {Object} configParams Parameters specified in template configuration @param {Object} templateParams All parameters provided to generator
isRequiredParamProvided
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function getParamSuggestion(wrongParam, configParams) { const sortInt = (a, b) => { return a[0] - b[0]; }; return Object.keys(configParams).map(param => [levenshtein(wrongParam, param), param]).sort(sortInt)[0][1]; }
Provides a hint for a user about correct parameter name. @private @param {Object} wrongParam Incorrectly written parameter @param {Object} configParams Parameters specified in template configuration
getParamSuggestion
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
sortInt = (a, b) => { return a[0] - b[0]; }
Provides a hint for a user about correct parameter name. @private @param {Object} wrongParam Incorrectly written parameter @param {Object} configParams Parameters specified in template configuration
sortInt
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
sortInt = (a, b) => { return a[0] - b[0]; }
Provides a hint for a user about correct parameter name. @private @param {Object} wrongParam Incorrectly written parameter @param {Object} configParams Parameters specified in template configuration
sortInt
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function isProvidedParameterSupported(configParams, templateParams) { const wrongParams = Object.keys(templateParams || {}).filter(key => !configParams?.[key]); if (!wrongParams.length) return; if (!configParams) throw new Error('This template doesn\'t have any params.'); let suggestionsString = ''; wrongP...
Checks if parameters provided to generator is supported by the template @private @param {Object} configParams Parameters specified in template configuration @param {Object} templateParams All parameters provided to generator
isProvidedParameterSupported
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function isServerProtocolSupported(server, supportedProtocols, paramsServerName) { if (server && Array.isArray(supportedProtocols) && !supportedProtocols.includes(server.protocol())) { throw new Error(`Server "${paramsServerName}" uses the ${server.protocol()} protocol but this template only supports the followin...
Checks if given AsyncAPI document has servers with protocol that is supported by the template @private @param {Object} server Server object from AsyncAPI file @param {String[]} supportedProtocols Supported protocols specified in template configuration @param {String} paramsServerName Name of the server specified as a p...
isServerProtocolSupported
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function isProvidedTemplateRendererSupported(templateConfig) { const supportedRenderers = [undefined, 'react', 'nunjucks']; if (supportedRenderers.includes(templateConfig.renderer)) { return; } throw new Error(`We do not support '${templateConfig.renderer}' as a renderer for a template. Only 'react' or 'nu...
Checks if the the provided renderer are supported (no renderer are also supported, defaults to nunjucks) @param {Object} templateConfig Template configuration.
isProvidedTemplateRendererSupported
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function isServerProvidedInDocument(server, paramsServerName) { if (typeof paramsServerName === 'string' && !server) throw new Error(`Couldn't find server with name ${paramsServerName}.`); }
Checks if given AsyncAPI document has servers with protocol that is supported by the template @private @param {Object} server Server object from AsyncAPI file @param {String} paramsServerName Name of the server specified as a param for the generator
isServerProvidedInDocument
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function validateConditionalFiles(conditionalFiles) { if (typeof conditionalFiles === 'object') { const fileNames = Object.keys(conditionalFiles); fileNames.forEach(fileName => { const def = conditionalFiles[fileName]; if (typeof def.subject !== 'string') throw new Error(`Invalid conditional file...
Checks if conditional files are specified properly in the template @private @param {Object} conditionalFiles conditions specified in the template config
validateConditionalFiles
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
function validateConditionalGeneration(conditionalGeneration) { if (!conditionalGeneration || typeof conditionalGeneration !== 'object') return; for (const [fileName, def] of Object.entries(conditionalGeneration)) { const { subject, parameter, validation } = def; if (subject && typeof subject !== 'string...
Validates conditionalGeneration settings in the template config. @private @param {Object} conditionalGeneration - The conditions specified in the template config.
validateConditionalGeneration
javascript
asyncapi/generator
apps/generator/lib/templateConfigValidator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/templateConfigValidator.js
Apache-2.0
constructor(paths, ignorePaths) { if (Array.isArray(paths)) { this.paths = paths; } else { this.paths = [paths]; } //Ensure all backwards slashes are replaced with forward slash based on the requirement from chokidar for (const pathIndex in this.paths) { const path = this.paths[pat...
Class to watch for change in certain file(s)
constructor
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
initiateWatchOnPath(path, changeCallback, errorCallback) { const watcher = chokidar.watch(path, {ignoreInitial: true, ignored: this.ignorePaths}); watcher.on('all', (eventType, changedPath) => this.fileChanged(path, changedPath, eventType, changeCallback, errorCallback)); this.watchers[path] = watcher; }
Initiates watch on a path. @param {*} path The path the watcher is listening on. @param {*} changeCallback Callback to call when changed occur. @param {*} errorCallback Calback to call when it is no longer possible to watch a file.
initiateWatchOnPath
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
async watch(changeCallback, errorCallback) { for (const index in this.paths) { const path = this.paths[index]; this.initiateWatchOnPath(path, changeCallback, errorCallback); } }
This method initiate the watch for change in all files @param {*} callback called when the file(s) change
watch
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
fileChanged(listenerPath, changedPath, eventType, changeCallback, errorCallback) { try { if (fs.existsSync(listenerPath)) { const newEventType = this.convertEventType(eventType); this.filesChanged[changedPath] = { eventType: newEventType, path: changedPath}; // Since multiple changes c...
Should be called when a file has changed one way or another. @param {*} listenerPath The path the watcher is listening on. @param {*} changedPath The file/dir that was changed @param {*} eventType What kind of change @param {*} changeCallback Callback to call when changed occur. @param {*} errorCallback Calback to call...
fileChanged
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
convertEventType(currentEventType) { let newEventType = currentEventType; //Change the naming of the event type switch (newEventType) { case 'unlink': case 'unlinkDir': newEventType = 'removed'; break; case 'addDir': case 'add': newEventType = 'added'; break; case...
Convert the event type to a more usefull one. @param {*} currentEventType The current event type (from chokidar)
convertEventType
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
getAllNonExistingPaths() { const unknownPaths = []; for (const index in this.paths) { const path = this.paths[index]; if (!fs.existsSync(path)) { unknownPaths.push(path); } } return unknownPaths; }
Get all paths which no longer exists
getAllNonExistingPaths
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
closeWatcher(path) { // Ensure if called before `watch` to do nothing if (path !== null) { const watcher = this.watchers[path]; if (watcher !== null) { watcher.close(); this.watchers[path] = null; } else { //Watcher not found for path } } }
Closes an active watcher down. @param {*} path The path to close the watcher for.
closeWatcher
javascript
asyncapi/generator
apps/generator/lib/watcher.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/watcher.js
Apache-2.0
saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => { let filePath = outputPath; // Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files. let permissions = 0o666; const content = renderedContent.content; if (con...
Save the single rendered react content based on the meta data available. @private @param {TemplateRenderResult} renderedContent the react content rendered @param {String} outputPath Path to the file being rendered.
saveContentToFile
javascript
asyncapi/generator
apps/generator/lib/renderer/react.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/renderer/react.js
Apache-2.0
saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => { let filePath = outputPath; // Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files. let permissions = 0o666; const content = renderedContent.content; if (con...
Save the single rendered react content based on the meta data available. @private @param {TemplateRenderResult} renderedContent the react content rendered @param {String} outputPath Path to the file being rendered.
saveContentToFile
javascript
asyncapi/generator
apps/generator/lib/renderer/react.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/renderer/react.js
Apache-2.0
function markdown2html(md) { return Markdown().render(md || ''); }
Turns Markdown into HTML @md {string} - String with valid Markdown syntax @returns {string} HTML string
markdown2html
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function getPayloadExamples(msg) { const examples = msg.examples(); if (Array.isArray(examples) && examples.some(e => e.payload)) { // Instead of flat or flatmap use this. const messageExamples = _.flatMap(examples) .map(e => { if (!e.payload) return; return { name: e.name, ...
Extracts example from the message payload @msg {object} - Parser Message function @returns {object}
getPayloadExamples
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function getHeadersExamples(msg) { const examples = msg.examples(); if (Array.isArray(examples) && examples.some(e => e.headers)) { // Instead of flat or flatmap use this. const messageExamples = _.flatMap(examples) .map(e => { if (!e.headers) return; return { name: e.name, ...
Extracts example from the message header @msg {object} - Parser Message function @returns {object}
getHeadersExamples
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function generateExample(schema, options) { return JSON.stringify(OpenAPISampler.sample(schema, options || {}) || '', null, 2); }
Generate string with example from provided schema @schema {object} - Schema object as JSON and not Schema model map @options {object} - Options object. Supported options are listed here https://github.com/Redocly/openapi-sampler#usage @returns {string}
generateExample
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function oneLine(str) { if (!str) return str; return str.replace(/\n/g, ' '); }
Turns multiline string into one liner @str {string} - Any multiline string @returns {string}
oneLine
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function docline(field, fieldName, scopePropName) { /* eslint-disable sonarjs/cognitive-complexity */ const getType = (f) => f.type() || 'string'; const getDescription = (f) => f.description() ? ` - ${f.description().replace(/\r?\n|\r/g, '')}` : ''; const getDefault = (f, type) => (f.default() && type === 'stri...
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
docline
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildLineCore = (type, def, pName, fName) => { const paramName = `${pName}${fName}`; const defaultValue = def !== undefined ? `=${def}` : ''; return `* @param {${type}} ${paramName}${defaultValue}`; }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildLineCore
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildLineCore = (type, def, pName, fName) => { const paramName = `${pName}${fName}`; const defaultValue = def !== undefined ? `=${def}` : ''; return `* @param {${type}} ${paramName}${defaultValue}`; }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildLineCore
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildLine = (f, fName, pName) => { const type = getType(f); const def = getDefault(f, type); const line = buildLineCore(type, def, getPName(pName), fName); return line + (type === 'object' ? '' : getDescription(f)); }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildLine
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildLine = (f, fName, pName) => { const type = getType(f); const def = getDefault(f, type); const line = buildLineCore(type, def, getPName(pName), fName); return line + (type === 'object' ? '' : getDescription(f)); }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildLine
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildObjectLines = (f, fName, pName) => { const properties = f.properties(); const mainLine = buildLine(f, fName, pName); return `${mainLine }\n${ Object.keys(properties).map((propName) => buildLine(properties[propName], propName, `${getPName(pName)}${fName}`) ).join('\n')}`; }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildObjectLines
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
buildObjectLines = (f, fName, pName) => { const properties = f.properties(); const mainLine = buildLine(f, fName, pName); return `${mainLine }\n${ Object.keys(properties).map((propName) => buildLine(properties[propName], propName, `${getPName(pName)}${fName}`) ).join('\n')}`; }
Generate JSDoc from message properties of the header and the payload @example docline( Schema { _json: { type: 'integer', minimum: 0, maximum: 100, 'x-parser-schema-id': '<anonymous-schema-3>' } }, my-app-header, options.message.headers ) Returned value will be -> * @param {int...
buildObjectLines
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
function replaceServerVariablesWithValues(url, serverVariables) { const getVariablesNamesFromUrl = (inputUrl) => { const result = []; let array = []; const regEx = /{([^}]+)}/g; while ((array = regEx.exec(inputUrl)) !== null) { result.push([array[0], array[1]]); } return result; }; ...
Helper function to replace server variables in the url with actual values @url {string} - url string @serverserverVariables {Object} - Variables model map @returns {string}
replaceServerVariablesWithValues
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
getVariablesNamesFromUrl = (inputUrl) => { const result = []; let array = []; const regEx = /{([^}]+)}/g; while ((array = regEx.exec(inputUrl)) !== null) { result.push([array[0], array[1]]); } return result; }
Helper function to replace server variables in the url with actual values @url {string} - url string @serverserverVariables {Object} - Variables model map @returns {string}
getVariablesNamesFromUrl
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
getVariablesNamesFromUrl = (inputUrl) => { const result = []; let array = []; const regEx = /{([^}]+)}/g; while ((array = regEx.exec(inputUrl)) !== null) { result.push([array[0], array[1]]); } return result; }
Helper function to replace server variables in the url with actual values @url {string} - url string @serverserverVariables {Object} - Variables model map @returns {string}
getVariablesNamesFromUrl
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
getVariableValue = (object, variable) => { const keyValue = object[variable]._json; if (keyValue) return keyValue.default ?? keyValue.enum?.[0]; }
Helper function to replace server variables in the url with actual values @url {string} - url string @serverserverVariables {Object} - Variables model map @returns {string}
getVariableValue
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
getVariableValue = (object, variable) => { const keyValue = object[variable]._json; if (keyValue) return keyValue.default ?? keyValue.enum?.[0]; }
Helper function to replace server variables in the url with actual values @url {string} - url string @serverserverVariables {Object} - Variables model map @returns {string}
getVariableValue
javascript
asyncapi/generator
apps/nunjucks-filters/src/customFilters.js
https://github.com/asyncapi/generator/blob/master/apps/nunjucks-filters/src/customFilters.js
Apache-2.0
async function Models({ asyncapi, language = 'python', format = 'toPascalCase', presets, constraints }) { // Get the selected generator and file extension, defaulting to Python if unknown const { generator: GeneratorClass, extension } = generatorConfig[language] || generatorConfig.python; // Create the generator...
Generates and returns an array of model files based on the AsyncAPI document. @param {Object} params - The parameters for the function. @param {AsyncAPIDocumentInterface} params.asyncapi - Parsed AsyncAPI document object. @param {Language} [params.language='python'] - Target programming language for the generated mode...
Models
javascript
asyncapi/generator
packages/components/src/components/models.js
https://github.com/asyncapi/generator/blob/master/packages/components/src/components/models.js
Apache-2.0
function getOperationMessages(operation) { if (!operation) { throw new Error('Operation object must be provided.'); } const messages = operation.messages(); if (messages.isEmpty()) { return null; } return messages.all(); }
Get messages related to the provided operation. @param {object} operation - The AsyncAPI operation object. @throws {Error} If opeartion object is not provided or is invalid. @returns {null} if there are no messages @returns messages resulting from operation
getOperationMessages
javascript
asyncapi/generator
packages/helpers/src/operations.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/operations.js
Apache-2.0
function getMessageExamples(message) { if (!message) { throw new Error('Message object must be provided.'); } const examples = message.examples(); if (examples.isEmpty()) { return null; } return examples; }
Get examples related to the provided message. @param {object} message @returns {Array} - An array of examples for the provided message. @returns {null} if there are no examples @throws {Error} If message object is not provided or is invalid.
getMessageExamples
javascript
asyncapi/generator
packages/helpers/src/operations.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/operations.js
Apache-2.0
getServerUrl = (server) => { let url = server.host(); //might be that somebody by mistake duplicated protocol info inside the host field //we need to make sure host do not hold protocol info if (server.protocol() && !url.includes(`${server.protocol()}://`)) { url = `${server.protocol()}://${url}`; } i...
Get server URL from AsyncAPI server object. @param {object} server - The AsyncAPI server object. return {string} - The server URL.
getServerUrl
javascript
asyncapi/generator
packages/helpers/src/servers.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
Apache-2.0
getServerUrl = (server) => { let url = server.host(); //might be that somebody by mistake duplicated protocol info inside the host field //we need to make sure host do not hold protocol info if (server.protocol() && !url.includes(`${server.protocol()}://`)) { url = `${server.protocol()}://${url}`; } i...
Get server URL from AsyncAPI server object. @param {object} server - The AsyncAPI server object. return {string} - The server URL.
getServerUrl
javascript
asyncapi/generator
packages/helpers/src/servers.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
Apache-2.0
getServer = (servers, serverName) => { if (!servers) { throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.'); } if (!serverName) { throw new Error('Server name must be provided.'); } if (!servers.has(serverName)) { throw new Error(`Server "${serverName}" not found in Async...
Retrieve a server object from the provided AsyncAPI servers collection. @param {Map<string, object>} servers - A map of server names to AsyncAPI server objects. @param {string} serverName - The name of the server to retrieve. @throws {Error} If any of the parameter is missing or invalid. @returns {object} The AsyncA...
getServer
javascript
asyncapi/generator
packages/helpers/src/servers.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
Apache-2.0
getServer = (servers, serverName) => { if (!servers) { throw new Error('Provided AsyncAPI document doesn\'t contain Servers object.'); } if (!serverName) { throw new Error('Server name must be provided.'); } if (!servers.has(serverName)) { throw new Error(`Server "${serverName}" not found in Async...
Retrieve a server object from the provided AsyncAPI servers collection. @param {Map<string, object>} servers - A map of server names to AsyncAPI server objects. @param {string} serverName - The name of the server to retrieve. @throws {Error} If any of the parameter is missing or invalid. @returns {object} The AsyncA...
getServer
javascript
asyncapi/generator
packages/helpers/src/servers.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/servers.js
Apache-2.0
getInfo = (asyncapi) => { if (!asyncapi) { throw new Error('Make sure you pass AsyncAPI document as an argument.'); } if (!asyncapi.info) { throw new Error('Provided AsyncAPI document doesn\'t contain Info object.'); } const info = asyncapi.info(); if (!info) { throw new Error('AsyncAPI document...
Validate and retrieve the AsyncAPI info object from an AsyncAPI document. Throws an error if the provided AsyncAPI document has no `info` section. @param {object} asyncapi - The AsyncAPI document object. @returns {object} The validated info object from the AsyncAPI document.
getInfo
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
getInfo = (asyncapi) => { if (!asyncapi) { throw new Error('Make sure you pass AsyncAPI document as an argument.'); } if (!asyncapi.info) { throw new Error('Provided AsyncAPI document doesn\'t contain Info object.'); } const info = asyncapi.info(); if (!info) { throw new Error('AsyncAPI document...
Validate and retrieve the AsyncAPI info object from an AsyncAPI document. Throws an error if the provided AsyncAPI document has no `info` section. @param {object} asyncapi - The AsyncAPI document object. @returns {object} The validated info object from the AsyncAPI document.
getInfo
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
getTitle = asyncapi => { const info = getInfo(asyncapi); if (!info.title) { throw new Error('Provided AsyncAPI document info field doesn\'t contain title.'); } const title = info.title(); if (title === '') { throw new Error('AsyncAPI document title cannot be an empty string.'); } return title; ...
Validate and retrieve the AsyncAPI title parameter in the info object. Throws an error if the provided AsyncAPI info object lacks a `title` parameter. @param {object} asyncapi - The AsyncAPI document object. @throws {Error} When `title` is `null` or `undefined` or `empty string` . @returns {string} The retrieved `ti...
getTitle
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
getTitle = asyncapi => { const info = getInfo(asyncapi); if (!info.title) { throw new Error('Provided AsyncAPI document info field doesn\'t contain title.'); } const title = info.title(); if (title === '') { throw new Error('AsyncAPI document title cannot be an empty string.'); } return title; ...
Validate and retrieve the AsyncAPI title parameter in the info object. Throws an error if the provided AsyncAPI info object lacks a `title` parameter. @param {object} asyncapi - The AsyncAPI document object. @throws {Error} When `title` is `null` or `undefined` or `empty string` . @returns {string} The retrieved `ti...
getTitle
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
getClientName = (asyncapi, appendClientSuffix, customClientName) => { if (customClientName) { return customClientName; } const title = getTitle(asyncapi); const baseName = `${title.replace(/\s+/g, '') // Remove all spaces .replace(/^./, char => char.toUpperCase())}`; // Make the first letter uppercase ...
Get client name from AsyncAPI info.title or uses a custom name if provided. @param {object} info - The AsyncAPI info object. @param {boolean} appendClientSuffix - Whether to append "Client" to the generated name @param {string} [customClientName] - Optional custom client name to use instead of generating from title @...
getClientName
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
getClientName = (asyncapi, appendClientSuffix, customClientName) => { if (customClientName) { return customClientName; } const title = getTitle(asyncapi); const baseName = `${title.replace(/\s+/g, '') // Remove all spaces .replace(/^./, char => char.toUpperCase())}`; // Make the first letter uppercase ...
Get client name from AsyncAPI info.title or uses a custom name if provided. @param {object} info - The AsyncAPI info object. @param {boolean} appendClientSuffix - Whether to append "Client" to the generated name @param {string} [customClientName] - Optional custom client name to use instead of generating from title @...
getClientName
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
listFiles = async (dir) => { const dirElements = await readdir(dir, { withFileTypes: true }); // Filter to only files, map to full paths return dirElements .filter(dirE => dirE.isFile()) .map(dirE => dirE.name); }
Get client name from AsyncAPI info.title or uses a custom name if provided. @param {object} info - The AsyncAPI info object. @param {boolean} appendClientSuffix - Whether to append "Client" to the generated name @param {string} [customClientName] - Optional custom client name to use instead of generating from title @...
listFiles
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
listFiles = async (dir) => { const dirElements = await readdir(dir, { withFileTypes: true }); // Filter to only files, map to full paths return dirElements .filter(dirE => dirE.isFile()) .map(dirE => dirE.name); }
Get client name from AsyncAPI info.title or uses a custom name if provided. @param {object} info - The AsyncAPI info object. @param {boolean} appendClientSuffix - Whether to append "Client" to the generated name @param {string} [customClientName] - Optional custom client name to use instead of generating from title @...
listFiles
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
toSnakeCase = (inputStr) => { return inputStr .replace(/\W+/g, ' ') .split(/ |\B(?=[A-Z])/) .map((word) => word.toLowerCase()) .join('_'); }
Convert a camelCase or PascalCase string to snake_case. If the string is already in snake_case, it will be returned unchanged. @param {string} camelStr - The string to convert to snake_case @returns {string} The converted snake_case string
toSnakeCase
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
toSnakeCase = (inputStr) => { return inputStr .replace(/\W+/g, ' ') .split(/ |\B(?=[A-Z])/) .map((word) => word.toLowerCase()) .join('_'); }
Convert a camelCase or PascalCase string to snake_case. If the string is already in snake_case, it will be returned unchanged. @param {string} camelStr - The string to convert to snake_case @returns {string} The converted snake_case string
toSnakeCase
javascript
asyncapi/generator
packages/helpers/src/utils.js
https://github.com/asyncapi/generator/blob/master/packages/helpers/src/utils.js
Apache-2.0
async function waitForTestSuccess(url) { while (true) { try { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); if (!response.ok) { console.error(`Request failed with status: ${response.status}`); break; ...
Polls the Microcks API every 2 seconds until a test with the given ID reports success. @param {string} url - link to endpoint providing info on particular test @returns {Promise<boolean>} Resolves with `true` when the test is marked as successful.
waitForTestSuccess
javascript
asyncapi/generator
packages/templates/clients/websocket/test/javascript/utils.js
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
Apache-2.0
async function waitForMessage(a, expectedMessage, timeout = 3000, interval = 10) { const start = Date.now(); while (Date.now() - start < timeout) { if (a.some(message => message.includes(expectedMessage))) { return; } await delay(interval); } throw new Error(`Expected message "${expectedMessag...
Wait for a specific message to appear in the spy's log calls. @param {array} a - array with messages @param {string} expectedMessage - The message to look for in logs. @param {number} timeout - Maximum time (in ms) to wait. Default is 3000ms. @param {number} interval - How long to wait (in ms) until next check. Default...
waitForMessage
javascript
asyncapi/generator
packages/templates/clients/websocket/test/javascript/utils.js
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
Apache-2.0
async function delay(time = 1000) { return new Promise(resolve => setTimeout(resolve, time)); }
Delay execution by a specified time. @param {number} time - Delay duration in milliseconds. Default is 1000ms. @returns {Promise<void>} Resolves after the specified delay.
delay
javascript
asyncapi/generator
packages/templates/clients/websocket/test/javascript/utils.js
https://github.com/asyncapi/generator/blob/master/packages/templates/clients/websocket/test/javascript/utils.js
Apache-2.0
function validate(extension, name) { 'use strict'; var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension', ret = { valid: true, error: '' }; if (!showdown.helper.isArray(extension)) { extension = [extension]; } for (var i = 0; i < extension.length; ...
Validate extension @param {array} extension @param {string} name @returns {{valid: boolean, error: string}}
validate
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function escapeCharactersCallback(wholeMatch, m1) { 'use strict'; var charCodeToEscape = m1.charCodeAt(0); return '~E' + charCodeToEscape + 'E'; }
Standardidize extension name @static @param {string} s extension name @returns {string}
escapeCharactersCallback
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
rgxFindMatchPos = function (str, left, right, flags) { 'use strict'; var f = flags || '', g = f.indexOf('g') > -1, x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')), l = new RegExp(left, f.replace(/g/g, '')), pos = [], t, s, m, start, end; do { t = 0; while ((m = x.exec(st...
Escape characters in a string @static @param {string} text @param {string} charsToEscape @param {boolean} afterBackslash @returns {XML|string|void|*}
rgxFindMatchPos
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function _parseExtension(ext, name) { name = name || null; // If it's a string, the extension was previously loaded if (showdown.helper.isString(ext)) { ext = showdown.helper.stdExtName(ext); name = ext; // LEGACY_SUPPORT CODE if (showdown.extensions[ext]) { console.warn('D...
Parse extension @param {*} ext @param {string} [name=''] @private
_parseExtension
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function listen(name, callback) { if (!showdown.helper.isString(name)) { throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given'); } if (typeof callback !== 'function') { throw Error('Invalid argument in converter.listen() method: callba...
Listen to an event @param {string} name @param {function} callback
listen
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function rTrimInputText(text) { var rsp = text.match(/^\s*/)[0].length, rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm'); return text.replace(rgx, ''); }
Listen to an event @param {string} name @param {function} callback
rTrimInputText
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
writeAnchorTag = function (wholeMatch, m1, m2, m3, m4, m5, m6, m7) { if (showdown.helper.isUndefined(m7)) { m7 = ''; } wholeMatch = m1; var linkText = m2, linkId = m3.toLowerCase(), url = m4, title = m7; if (!url) { if (!linkId) { // lower-case and turn e...
Turn Markdown link shortcuts into XHTML <a> tags.
writeAnchorTag
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function replaceLink(wm, link) { var lnkTxt = link; if (/^www\./i.test(link)) { link = link.replace(/^www\./i, 'http://www.'); } return '<a href="' + link + '">' + lnkTxt + '</a>'; }
Turn Markdown link shortcuts into XHTML <a> tags.
replaceLink
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function replaceMail(wholeMatch, m1) { var unescapedStr = showdown.subParser('unescapeSpecialChars')(m1); return showdown.subParser('encodeEmailAddress')(unescapedStr); }
Turn Markdown link shortcuts into XHTML <a> tags.
replaceMail
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
repFunc = function (wholeMatch, match, left, right) { var txt = wholeMatch; // check if this html element is marked as markdown // if so, it's contents should be parsed as markdown if (left.search(/\bmarkdown\b/) !== -1) { txt = left + globals.converter.makeHtml(match) + right; } ...
Handle github codeblocks prior to running HashHTML so that HTML contained within the codeblock gets escaped properly Example: ```ruby def hello_world(x) puts "Hello, #{x}" end ```
repFunc
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
repFunc = function (wholeMatch, match, left, right) { // encode html entities var codeblock = left + showdown.subParser('encodeCode')(match) + right; return '\n\n~G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n'; }
Hash span elements that should not be parsed as markdown
repFunc
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function headerId(m) { var title, escapedId = m.replace(/[^\w]/g, '').toLowerCase(); if (globals.hashLinkCounts[escapedId]) { title = escapedId + '-' + (globals.hashLinkCounts[escapedId]++); } else { title = escapedId; globals.hashLinkCounts[escapedId] = 1; } // Prefix id to prev...
Hash span elements that should not be parsed as markdown
headerId
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) { var gUrls = globals.gUrls, gTitles = globals.gTitles, gDims = globals.gDimensions; linkId = linkId.toLowerCase(); if (!title) { title = ''; } if (url === '' || url === null) { if...
Turn Markdown image shortcuts into <img> tags.
writeImageTag
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function processListItems (listStr, trimTrailing) { // The $g_list_level global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // // We do this because when we're not inside a l...
Process the contents of a single ordered or unordered list, splitting it into individual list items. @param {string} listStr @param {boolean} trimTrailing @returns {string}
processListItems
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function parseConsecutiveLists(list, listType, trimTrailing) { // check if we caught 2 or more consecutive lists by mistake // we use the counterRgx, meaning if listType is UL we look for UL and vice versa var counterRxg = (listType === 'ul') ? /^ {0,2}\d+\.[ \t]/gm : /^ {0,2}[*+-][ \t]/gm, subLists =...
Check and parse consecutive lists (better fix for issue #142) @param {string} list @param {string} listType @param {boolean} trimTrailing @returns {string}
parseConsecutiveLists
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function parseStyles(sLine) { if (/^:[ \t]*--*$/.test(sLine)) { return ' style="text-align:left;"'; } else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) { return ' style="text-align:right;"'; } else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) { return ' style="text-align:center;"'; } else { r...
Strips link definitions from text, stores the URLs and titles in hash references. Link defs are in the form: ^[id]: url "optional title" ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 [ \t]* \n? // maybe...
parseStyles
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function parseHeaders(header, style) { var id = ''; header = header.trim(); if (options.tableHeaderId) { id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"'; } header = showdown.subParser('spanGamut')(header, options, globals); return '<th' + id + style + '>' + header + '</th>\n'...
Strips link definitions from text, stores the URLs and titles in hash references. Link defs are in the form: ^[id]: url "optional title" ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 [ \t]* \n? // maybe...
parseHeaders
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function parseCells(cell, style) { var subText = showdown.subParser('spanGamut')(cell, options, globals); return '<td' + style + '>' + subText + '</td>\n'; }
Strips link definitions from text, stores the URLs and titles in hash references. Link defs are in the form: ^[id]: url "optional title" ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 [ \t]* \n? // maybe...
parseCells
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
function buildTable(headers, cells) { var tb = '<table>\n<thead>\n<tr>\n', tblLgn = headers.length; for (var i = 0; i < tblLgn; ++i) { tb += headers[i]; } tb += '</tr>\n</thead>\n<tbody>\n'; for (i = 0; i < cells.length; ++i) { tb += '<tr>\n'; for (var ii = 0; ii < tblLgn...
Strips link definitions from text, stores the URLs and titles in hash references. Link defs are in the form: ^[id]: url "optional title" ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 [ \t]* \n? // maybe...
buildTable
javascript
iamdarcy/hioshop-miniprogram
lib/wxParse/showdown.js
https://github.com/iamdarcy/hioshop-miniprogram/blob/master/lib/wxParse/showdown.js
MIT
render() { return Children.only(this.props.children) }
This is a utility wrapper component that will allow our higher order component to get a ref handle on our wrapped components html. @see https://gist.github.com/jimfb/32b587ee6177665fb4cf
render
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
function Placeholder({ className, style }) { // Lets create the props for the temp element. const phProps = {} // We will use any provided className/style or else make the temp // container take the full available space. if (!className && !style) { phProps.style = { width: '100%', height: '100%' } } el...
This is a utility wrapper component that will allow our higher order component to get a ref handle on our wrapped components html. @see https://gist.github.com/jimfb/32b587ee6177665fb4cf
Placeholder
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
renderWrapper = (WrappedComponent) => { function SizeMeRenderer(props) { const { explicitRef, className, style, size, disablePlaceholder, onSize, ...restProps } = props const noSizeData = size == null || (size.width == null && size.height == null) cons...
As we need to maintain a ref on the root node that is rendered within our SizeMe component we need to wrap our entire render in a sub component. Without this, we lose the DOM ref after the placeholder is removed from the render and the actual component is rendered. It took me forever to figure this out, so tread extra ...
renderWrapper
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
renderWrapper = (WrappedComponent) => { function SizeMeRenderer(props) { const { explicitRef, className, style, size, disablePlaceholder, onSize, ...restProps } = props const noSizeData = size == null || (size.width == null && size.height == null) cons...
As we need to maintain a ref on the root node that is rendered within our SizeMe component we need to wrap our entire render in a sub component. Without this, we lose the DOM ref after the placeholder is removed from the render and the actual component is rendered. It took me forever to figure this out, so tread extra ...
renderWrapper
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
function SizeMeRenderer(props) { const { explicitRef, className, style, size, disablePlaceholder, onSize, ...restProps } = props const noSizeData = size == null || (size.width == null && size.height == null) const renderPlaceholder = noSizeData && !disab...
As we need to maintain a ref on the root node that is rendered within our SizeMe component we need to wrap our entire render in a sub component. Without this, we lose the DOM ref after the placeholder is removed from the render and the actual component is rendered. It took me forever to figure this out, so tread extra ...
SizeMeRenderer
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
componentDidMount() { this.detector = resizeDetector(resizeDetectorStrategy) this.determineStrategy(this.props) this.handleDOMNode() }
:: config -> Component -> WrappedComponent Higher order component that allows the wrapped component to become aware of it's size, by receiving it as an object within it's props. @param monitorWidth Default true, whether changes in the element's width should be monitored, causing a size property to be broadcast. ...
componentDidMount
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
componentDidUpdate() { this.determineStrategy(this.props) this.handleDOMNode() }
:: config -> Component -> WrappedComponent Higher order component that allows the wrapped component to become aware of it's size, by receiving it as an object within it's props. @param monitorWidth Default true, whether changes in the element's width should be monitored, causing a size property to be broadcast. ...
componentDidUpdate
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
componentWillUnmount() { // Change our size checker to a noop just in case we have some // late running events. this.hasSizeChanged = () => undefined this.checkIfSizeChanged = () => undefined this.uninstall() }
:: config -> Component -> WrappedComponent Higher order component that allows the wrapped component to become aware of it's size, by receiving it as an object within it's props. @param monitorWidth Default true, whether changes in the element's width should be monitored, causing a size property to be broadcast. ...
componentWillUnmount
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
render() { const disablePlaceholder = withSize.enableSSRBehaviour || withSize.noPlaceholders || noPlaceholder || this.strategy === 'callback' const size = { ...this.state } return ( <SizeMeRenderWrapper explicitRef={this.refCallback...
:: config -> Component -> WrappedComponent Higher order component that allows the wrapped component to become aware of it's size, by receiving it as an object within it's props. @param monitorWidth Default true, whether changes in the element's width should be monitored, causing a size property to be broadcast. ...
render
javascript
ctrlplusb/react-sizeme
src/with-size.js
https://github.com/ctrlplusb/react-sizeme/blob/master/src/with-size.js
MIT
shallowCompare = (obj1, obj2) => { const obj1Keys = Object.keys(obj1); return ( obj1Keys.length === Object.keys(obj2).length && obj1Keys.every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]) ); }
Shallow compares two objects. @param {Object} obj1 The first object to compare. @param {Object} obj2 The second object to compare.
shallowCompare
javascript
reach/router
src/lib/utils.js
https://github.com/reach/router/blob/master/src/lib/utils.js
MIT
shallowCompare = (obj1, obj2) => { const obj1Keys = Object.keys(obj1); return ( obj1Keys.length === Object.keys(obj2).length && obj1Keys.every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]) ); }
Shallow compares two objects. @param {Object} obj1 The first object to compare. @param {Object} obj2 The second object to compare.
shallowCompare
javascript
reach/router
src/lib/utils.js
https://github.com/reach/router/blob/master/src/lib/utils.js
MIT
async function setupCamera() { if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { throw new Error( 'Browser API navigator.mediaDevices.getUserMedia not available'); } const video = document.getElementById('video'); video.width = videoWidth; video.height = videoHeight; const...
Loads a the camera to be used in the demo
setupCamera
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
async function loadVideo() { const video = await setupCamera(); video.play(); return video; }
Loads a the camera to be used in the demo
loadVideo
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
function setupGui(cameras) { if (cameras.length > 0) { guiState.camera = cameras[0].deviceId; } const gui = new dat.GUI({width: 300}); let multi = gui.addFolder('Image'); gui.add(guiState, 'avatarSVG', Object.keys(avatarSvgs)).onChange(() => parseSVG(avatarSvgs[guiState.avatarSVG])); multi.open(); ...
Sets up dat.gui controller on the top-right of the window
setupGui
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
function setupFPS() { stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom document.getElementById('main').appendChild(stats.dom); }
Sets up a frames per second panel on the top-left of the window
setupFPS
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
function detectPoseInRealTime(video) { const canvas = document.getElementById('output'); const keypointCanvas = document.getElementById('keypoints'); const videoCtx = canvas.getContext('2d'); const keypointCtx = keypointCanvas.getContext('2d'); canvas.width = videoWidth; canvas.height = videoHeight; keyp...
Feeds an image to posenet to estimate poses - this is where the magic happens. This function loops with a requestAnimationFrame method.
detectPoseInRealTime
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
async function poseDetectionFrame() { // Begin monitoring code for frames per second stats.begin(); let poses = []; videoCtx.clearRect(0, 0, videoWidth, videoHeight); // Draw video videoCtx.save(); videoCtx.scale(-1, 1); videoCtx.translate(-videoWidth, 0); videoCtx.drawImage(vid...
Feeds an image to posenet to estimate poses - this is where the magic happens. This function loops with a requestAnimationFrame method.
poseDetectionFrame
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
function setupCanvas() { mobile = isMobile(); if (mobile) { canvasWidth = Math.min(window.innerWidth, window.innerHeight); canvasHeight = canvasWidth; videoWidth *= 0.7; videoHeight *= 0.7; } canvasScope = paper.default; let canvas = document.querySelector('.illustration-canvas');; canvas...
Feeds an image to posenet to estimate poses - this is where the magic happens. This function loops with a requestAnimationFrame method.
setupCanvas
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
async function bindPage() { setupCanvas(); toggleLoadingUI(true); setStatusText('Loading PoseNet model...'); posenet = await posenet_module.load({ architecture: defaultPoseNetArchitecture, outputStride: defaultStride, inputResolution: defaultInputResolution, multiplier: defaultMultiplier, q...
Kicks off the demo by loading the posenet model, finding and loading available camera devices, and setting off the detectPoseInRealTime function.
bindPage
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
async function parseSVG(target) { let svgScope = await SVGUtils.importSVG(target /* SVG string or file path */); let skeleton = new Skeleton(svgScope); illustration = new PoseIllustration(canvasScope); illustration.bindSkeleton(skeleton, svgScope); }
Kicks off the demo by loading the posenet model, finding and loading available camera devices, and setting off the detectPoseInRealTime function.
parseSVG
javascript
yemount/pose-animator
camera.js
https://github.com/yemount/pose-animator/blob/master/camera.js
Apache-2.0
function drawResults(image, canvas, faceDetection, poses) { renderImageToCanvas(image, [VIDEO_WIDTH, VIDEO_HEIGHT], canvas); const ctx = canvas.getContext('2d'); poses.forEach((pose) => { if (pose.score >= defaultMinPoseConfidence) { if (guiState.showKeypoints) { drawKeypoints(pose.keypoints, de...
Draws a pose if it passes a minimum confidence onto a canvas. Only the pose's keypoints that pass a minPartConfidence are drawn.
drawResults
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
async function loadImage(imagePath) { const image = new Image(); const promise = new Promise((resolve, reject) => { image.crossOrigin = ''; image.onload = () => { resolve(image); } }); image.src = imagePath; return promise; }
Draws a pose if it passes a minimum confidence onto a canvas. Only the pose's keypoints that pass a minPartConfidence are drawn.
loadImage
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
function multiPersonCanvas() { return document.querySelector('#multi canvas'); }
Draws a pose if it passes a minimum confidence onto a canvas. Only the pose's keypoints that pass a minPartConfidence are drawn.
multiPersonCanvas
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0
function getIllustrationCanvas() { return document.querySelector('.illustration-canvas'); }
Draws a pose if it passes a minimum confidence onto a canvas. Only the pose's keypoints that pass a minPartConfidence are drawn.
getIllustrationCanvas
javascript
yemount/pose-animator
static_image.js
https://github.com/yemount/pose-animator/blob/master/static_image.js
Apache-2.0