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 filterLeaks(ok) { return filter(keys(global), function(key){ var matched = filter(ok, function(ok){ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); return key == ok; }); return matched.length == 0 && (!global.navigator || 'onerror' !== key); }); }
Filter leaks with the given globals flagged as `ok`. @param {Array} ok @return {Array} @api private
filterLeaks
javascript
louischatriot/nedb
browser-version/test/mocha.js
https://github.com/louischatriot/nedb/blob/master/browser-version/test/mocha.js
MIT
function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; }
Initialize a new `Suite` with the given `title` and `ctx`. @param {String} title @param {Context} ctx @api private
Suite
javascript
louischatriot/nedb
browser-version/test/mocha.js
https://github.com/louischatriot/nedb/blob/master/browser-version/test/mocha.js
MIT
function Test(title, fn) { Runnable.call(this, title, fn); this.pending = !fn; this.type = 'test'; }
Initialize a new `Test` with the given `title` and callback `fn`. @param {String} title @param {Function} fn @api private
Test
javascript
louischatriot/nedb
browser-version/test/mocha.js
https://github.com/louischatriot/nedb/blob/master/browser-version/test/mocha.js
MIT
function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="numb...
Highlight the given string of `js`. @param {String} js @return {String} @api private
highlight
javascript
louischatriot/nedb
browser-version/test/mocha.js
https://github.com/louischatriot/nedb/blob/master/browser-version/test/mocha.js
MIT
function findById (docs, id) { return _.find(docs, function (doc) { return doc._id === id; }) || null; }
Given a docs array and an id, return the document whose id matches, or null if none is found
findById
javascript
louischatriot/nedb
browser-version/test/nedb-browser.js
https://github.com/louischatriot/nedb/blob/master/browser-version/test/nedb-browser.js
MIT
function Cursor (db, query, execFn) { this.db = db; this.query = query || {}; if (execFn) { this.execFn = execFn; } }
Create a new cursor for this collection @param {Datastore} db - The datastore this cursor is bound to @param {Query} query - The query this cursor will operate on @param {Function} execFn - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
Cursor
javascript
louischatriot/nedb
lib/cursor.js
https://github.com/louischatriot/nedb/blob/master/lib/cursor.js
MIT
function callback (error, res) { if (self.execFn) { return self.execFn(error, res, _callback); } else { return _callback(error, res); } }
Get all matching elements Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne This is an internal function, use exec which uses the executor @param {Function} callback - Signature: err, results
callback
javascript
louischatriot/nedb
lib/cursor.js
https://github.com/louischatriot/nedb/blob/master/lib/cursor.js
MIT
function uid (len) { return crypto.randomBytes(Math.ceil(Math.max(8, len * 2))) .toString('base64') .replace(/[+\/]/g, '') .slice(0, len); }
Return a random alphanumerical string of length len There is a very small probability (less than 1/1,000,000) for the length to be less than len (il the base64 conversion yields too many pluses and slashes) but that's not an issue here The probability of a collision is extremely small (need 3*10^12 documents to have on...
uid
javascript
louischatriot/nedb
lib/customUtils.js
https://github.com/louischatriot/nedb/blob/master/lib/customUtils.js
MIT
function Executor () { this.buffer = []; this.ready = false; // This queue will execute all commands, one-by-one in order this.queue = async.queue(function (task, cb) { var newArguments = []; // task.arguments is an array-like object on which adding a new field doesn't work, so we transform it into a ...
Responsible for sequentially executing actions on the database
Executor
javascript
louischatriot/nedb
lib/executor.js
https://github.com/louischatriot/nedb/blob/master/lib/executor.js
MIT
function checkValueEquality (a, b) { return a === b; }
Two indexed pointers are equal iif they point to the same place
checkValueEquality
javascript
louischatriot/nedb
lib/indexes.js
https://github.com/louischatriot/nedb/blob/master/lib/indexes.js
MIT
function Index (options) { this.fieldName = options.fieldName; this.unique = options.unique || false; this.sparse = options.sparse || false; this.treeOptions = { unique: this.unique, compareKeys: model.compareThings, checkValueEquality: checkValueEquality }; this.reset(); // No data in the beginning }
Create a new index All methods on an index guarantee that either the whole operation was successful and the index changed or the operation was unsuccessful and an error is thrown while the index is unchanged @param {String} options.fieldName On which field should the index apply (can use dot notation to index on sub fi...
Index
javascript
louischatriot/nedb
lib/indexes.js
https://github.com/louischatriot/nedb/blob/master/lib/indexes.js
MIT
function checkKey (k, v) { if (typeof k === 'number') { k = k.toString(); } if (k[0] === '$' && !(k === '$$date' && typeof v === 'number') && !(k === '$$deleted' && v === true) && !(k === '$$indexCreated') && !(k === '$$indexRemoved')) { throw new Error('Field names cannot begin with the $ character'); ...
Check a key, throw an error if the key is non valid @param {String} k key @param {Model} v value, needed to treat the Date edge case Non-treatable edge cases here: if part of the object if of the form { $$date: number } or { $$deleted: true } Its serialized-then-deserialized version it will transformed into a Date obje...
checkKey
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function checkObject (obj) { if (util.isArray(obj)) { obj.forEach(function (o) { checkObject(o); }); } if (typeof obj === 'object' && obj !== null) { Object.keys(obj).forEach(function (k) { checkKey(k, obj[k]); checkObject(obj[k]); }); } }
Check a DB object and throw an error if it's not valid Works by applying the above checkKey function to all fields recursively
checkObject
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function deserialize (rawData) { return JSON.parse(rawData, function (k, v) { if (k === '$$date') { return new Date(v); } if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; } if (v && v.$$date) { return v.$$date; } return v; }); }
From a one-line representation of an object generate by the serialize function Return the object itself
deserialize
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function deepCopy (obj, strictKeys) { var res; if ( typeof obj === 'boolean' || typeof obj === 'number' || typeof obj === 'string' || obj === null || (util.isDate(obj)) ) { return obj; } if (util.isArray(obj)) { res = []; obj.forEach(function (o) { res.push(deepCopy(o, ...
Deep copy a DB object The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields where the keys are valid, i.e. don't begin with $ and don't contain a .
deepCopy
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function compareNSB (a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; }
Utility functions for comparing things Assumes type checking was already done (a and b already have the same type) compareNSB works for numbers, strings and booleans
compareNSB
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function compareArrays (a, b) { var i, comp; for (i = 0; i < Math.min(a.length, b.length); i += 1) { comp = compareThings(a[i], b[i]); if (comp !== 0) { return comp; } } // Common section was identical, longest one wins return compareNSB(a.length, b.length); }
Utility functions for comparing things Assumes type checking was already done (a and b already have the same type) compareNSB works for numbers, strings and booleans
compareArrays
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function compareThings (a, b, _compareStrings) { var aKeys, bKeys, comp, i , compareStrings = _compareStrings || compareNSB; // undefined if (a === undefined) { return b === undefined ? 0 : -1; } if (b === undefined) { return a === undefined ? 0 : 1; } // null if (a === null) { return b === null ? 0 :...
Compare { things U undefined } Things are defined as any native types (string, number, boolean, null, date) and objects We need to compare with undefined as it will be used in indexes In the case of objects and arrays, we deep-compare If two objects dont have the same type, the (arbitrary) type hierarchy is: undefined,...
compareThings
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function createModifierFunction (modifier) { return function (obj, field, value) { var fieldParts = typeof field === 'string' ? field.split('.') : field; if (fieldParts.length === 1) { lastStepModifierFunctions[modifier](obj, field, value); } else { if (obj[fieldParts[0]] === undefined) { ...
Updates the value of the field, only if specified field is smaller than the current value of the field
createModifierFunction
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function modify (obj, updateQuery) { var keys = Object.keys(updateQuery) , firstChars = _.map(keys, function (item) { return item[0]; }) , dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; }) , newDoc, modifiers ; if (keys.indexOf('_id') !== -1 && updateQuery._id !== obj._id)...
Modify a DB object according to an update query
modify
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function getDotValue (obj, field) { var fieldParts = typeof field === 'string' ? field.split('.') : field , i, objs; if (!obj) { return undefined; } // field cannot be empty so that means we should return undefined so that nothing can match if (fieldParts.length === 0) { return obj; } if (fieldParts.le...
Get a value from object with dot notation @param {Object} obj @param {String} field
getDotValue
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function areThingsEqual (a, b) { var aKeys , bKeys , i; // Strings, booleans, numbers, null if (a === null || typeof a === 'string' || typeof a === 'boolean' || typeof a === 'number' || b === null || typeof b === 'string' || typeof b === 'boolean' || typeof b === 'number') { return a === b; } // Dates ...
Check whether 'things' are equal Things are defined as any native types (string, number, boolean, null, date) and objects In the case of object, we check deep equality Returns true if they are, false otherwise
areThingsEqual
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function areComparable (a, b) { if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) && typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) { return false; } if (typeof a !== typeof b) { return false; } return true; }
Check that two values are comparable
areComparable
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function match (obj, query) { var queryKeys, queryKey, queryValue, i; // Primitive query against a primitive type // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later // But I don't have time for a cleaner implementation now if (isPrimitiveType(obj) || is...
Tell if a given document matches a query @param {Object} obj Document to check @param {Object} query
match
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function matchQueryPart (obj, queryKey, queryValue, treatObjAsValue) { var objValue = getDotValue(obj, queryKey) , i, keys, firstChars, dollarFirstChars; // Check if the value is an array if we don't force a treatment as value if (util.isArray(objValue) && !treatObjAsValue) { // If the queryValue is an a...
Match an object against a specific { key: value } part of a query if the treatObjAsValue flag is set, don't try to match every part separately, but the array as a whole
matchQueryPart
javascript
louischatriot/nedb
lib/model.js
https://github.com/louischatriot/nedb/blob/master/lib/model.js
MIT
function Persistence (options) { var i, j, randomString; this.db = options.db; this.inMemoryOnly = this.db.inMemoryOnly; this.filename = this.db.filename; this.corruptAlertThreshold = options.corruptAlertThreshold !== undefined ? options.corruptAlertThreshold : 0.1; if (!this.inMemoryOnly && this.filename...
Create a new Persistence object for database options.db @param {Datastore} options.db @param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where Node Webkit stores application data suc...
Persistence
javascript
louischatriot/nedb
lib/persistence.js
https://github.com/louischatriot/nedb/blob/master/lib/persistence.js
MIT
function testPostUpdateState (cb) { d.find({}, function (err, docs) { var doc1 = _.find(docs, function (d) { return d._id === id1; }) , doc2 = _.find(docs, function (d) { return d._id === id2; }) , doc3 = _.find(docs, function (d) { return d._id === id3; }) ; ...
Complicated behavior here. Basically we need to test that when a user function throws an exception, it is not caught in NeDB and the callback called again, transforming a user error into a NeDB error. So we need a way to check that the callback is called only once and the exception thrown is indeed the client exceptio...
testPostUpdateState
javascript
louischatriot/nedb
test/db.test.js
https://github.com/louischatriot/nedb/blob/master/test/db.test.js
MIT
function testPostUpdateState (cb) { d.find({}, function (err, docs) { var doc1 = _.find(docs, function (d) { return d._id === id1; }) , doc2 = _.find(docs, function (d) { return d._id === id2; }) , doc3 = _.find(docs, function (d) { return d._id === id3; }) ; ...
Complicated behavior here. Basically we need to test that when a user function throws an exception, it is not caught in NeDB and the callback called again, transforming a user error into a NeDB error. So we need a way to check that the callback is called only once and the exception thrown is indeed the client exceptio...
testPostUpdateState
javascript
louischatriot/nedb
test/db.test.js
https://github.com/louischatriot/nedb/blob/master/test/db.test.js
MIT
function testPostUpdateState (cb) { d.find({}, function (err, docs) { docs.length.should.equal(1); Object.keys(docs[0]).length.should.equal(2); docs[0]._id.should.equal(id1); docs[0].somedata.should.equal('ok'); return cb(); }); }
Complicated behavior here. Basically we need to test that when a user function throws an exception, it is not caught in NeDB and the callback called again, transforming a user error into a NeDB error. So we need a way to check that the callback is called only once and the exception thrown is indeed the client exceptio...
testPostUpdateState
javascript
louischatriot/nedb
test/db.test.js
https://github.com/louischatriot/nedb/blob/master/test/db.test.js
MIT
function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. if (DEBUG) { var backtrace = new Error(); return function(err) { if (err) { backtrace.stack = err.name + ': ' + err.message + backtrace.s...
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
rethrow
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); }
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
maybeCallback
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
function isFd(path) { return (path >>> 0) === path; }
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
isFd
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
function assertEncoding(encoding) { if (encoding && !Buffer.isEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } }
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
assertEncoding
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
function writeAll(fd, isUserFd, buffer, offset, length, position, callback_) { var callback = maybeCallback(arguments[arguments.length - 1]); if (onePassDone) { process.exit(1); } // Crash on purpose before rewrite done var l = Math.min(5000, length); // Force write by chunks of 5000 bytes to ensure data wil...
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
writeAll
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
function writeFd(fd, isUserFd) { var buffer = (data instanceof Buffer) ? data : new Buffer('' + data, options.encoding || 'utf8'); var position = /a/.test(flag) ? null : 0; writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback); }
Load and modify part of fs to ensure writeFile will crash after writing 5000 bytes
writeFd
javascript
louischatriot/nedb
test_lac/loadAndCrash.test.js
https://github.com/louischatriot/nedb/blob/master/test_lac/loadAndCrash.test.js
MIT
avif = async (bytes, width, height, quality = 50, speed = 6) => { const imports = { wbg: { __wbg_log_12edb8942696c207: (p, n) => { new TextDecoder().decode( new Uint8Array(wasm.memory.buffer).subarray(p, p + n), ); }, }, }; const { instance: { exports: wasm }, }...
Encodes the supplied ImageData rgba array. @param {Uint8Array} bytes @param {number} width @param {number} height @param {number} quality (1 to 100) @param {number} speed (1 to 10) @return {Uint8Array}
avif
javascript
joye61/pic-smaller
src/engines/AvifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/AvifWasmModule.js
MIT
avif = async (bytes, width, height, quality = 50, speed = 6) => { const imports = { wbg: { __wbg_log_12edb8942696c207: (p, n) => { new TextDecoder().decode( new Uint8Array(wasm.memory.buffer).subarray(p, p + n), ); }, }, }; const { instance: { exports: wasm }, }...
Encodes the supplied ImageData rgba array. @param {Uint8Array} bytes @param {number} width @param {number} height @param {number} quality (1 to 100) @param {number} speed (1 to 10) @return {Uint8Array}
avif
javascript
joye61/pic-smaller
src/engines/AvifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/AvifWasmModule.js
MIT
stdout = (char) => { out += String.fromCharCode(char); if (char === 10) { console.log(out); out = ""; } }
Process stdout stream @param {number} char Next char in stream
stdout
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
stdout = (char) => { out += String.fromCharCode(char); if (char === 10) { console.log(out); out = ""; } }
Process stdout stream @param {number} char Next char in stream
stdout
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
stderr = (char) => { err += String.fromCharCode(char); if (char === 10) { console.error(err); err = ""; } }
Process stderr stream @param {number} char Next char in stream
stderr
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
stderr = (char) => { err += String.fromCharCode(char); if (char === 10) { console.error(err); err = ""; } }
Process stderr stream @param {number} char Next char in stream
stderr
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
encode = async (obj = {}) => { let { data = null, command = [], folder = [], isStrict = false } = obj; await initModule(); return new Promise((resolve, reject) => { let resolved = false; let err = ""; gifsicle_c({ stdout: _io.stdout, // stderr: _io.stderr, stderr: ...
Encode an input image using Gifsicle @async @param {Buffer} data Image input buffer @param {EncodeOptions} command @returns {Buffer} Processed image buffer
encode
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
encode = async (obj = {}) => { let { data = null, command = [], folder = [], isStrict = false } = obj; await initModule(); return new Promise((resolve, reject) => { let resolved = false; let err = ""; gifsicle_c({ stdout: _io.stdout, // stderr: _io.stderr, stderr: ...
Encode an input image using Gifsicle @async @param {Buffer} data Image input buffer @param {EncodeOptions} command @returns {Buffer} Processed image buffer
encode
javascript
joye61/pic-smaller
src/engines/GifWasmModule.js
https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js
MIT
function doResolve(fn, self) { var done = false; try { fn( function(value) { if (done) return; done = true; resolve(self, value); }, function(reason) { if (done) return; done = true; reject(self, reason); } ); } catch (ex) { if (d...
Take a potentially misbehaving resolver function and make sure onFulfilled and onRejected are only called once. Makes no guarantees about asynchrony.
doResolve
javascript
webkul/coolhue
distro/CoolHue.sketchplugin/Contents/Sketch/coolhue.js
https://github.com/webkul/coolhue/blob/master/distro/CoolHue.sketchplugin/Contents/Sketch/coolhue.js
MIT
function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call( val, function(val) { res(i, val); }, r...
Take a potentially misbehaving resolver function and make sure onFulfilled and onRejected are only called once. Makes no guarantees about asynchrony.
res
javascript
webkul/coolhue
distro/CoolHue.sketchplugin/Contents/Sketch/coolhue.js
https://github.com/webkul/coolhue/blob/master/distro/CoolHue.sketchplugin/Contents/Sketch/coolhue.js
MIT
async function watcherHandler(changedFiles) { console.clear(); console.log('[WATCHER] Change detected'); for (const [, value] of Object.entries(changedFiles)) { let eventText; switch (value.eventType) { case 'changed': eventText = green(value.eventType); break; case 'removed': ev...
Generates the files based on the template. @param {*} targetDir The path to the target directory.
watcherHandler
javascript
asyncapi/generator
apps/generator/cli.js
https://github.com/asyncapi/generator/blob/master/apps/generator/cli.js
Apache-2.0
async function isGenerationConditionMet ( templateConfig, matchedConditionPath, templateParams, asyncapiDocument ) { const conditionFilesGeneration = templateConfig?.conditionalFiles?.[matchedConditionPath] || {}; const conditionalGeneration = templateConfig?.conditionalGeneration?.[matchedConditionPath] |...
Determines whether the generation of a file or folder should be skipped based on conditions defined in the template configuration. @param {Object} templateConfig - The template configuration containing conditional logic. @param {string} matchedConditionPath - The matched path used to find applicable conditions. @param...
isGenerationConditionMet
javascript
asyncapi/generator
apps/generator/lib/conditionalGeneration.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/conditionalGeneration.js
Apache-2.0
async function conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams) { const conditionalGenerationConfig = templateConfig.conditionalGeneration?.[matchedConditionPath]; const parameterName = conditionalGenerationConfig.parameter; const parameterValue = templateParams[parameterName];...
Evaluates whether a template path should be conditionally generated based on a parameter defined in the template configuration. @private @async @function conditionalParameterGeneration @param {Object} templateConfig - The full template configuration object. @param {string} matchedConditionPath - The path of the file/f...
conditionalParameterGeneration
javascript
asyncapi/generator
apps/generator/lib/conditionalGeneration.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/conditionalGeneration.js
Apache-2.0
async function conditionalFilesGenerationDeprecatedVersion ( asyncapiDocument, templateConfig, matchedConditionPath, templateParams ) { return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams); }
Determines whether a file should be conditionally included based on the provided subject expression and optional validation logic defined in the template configuration. @private @param {Object} asyncapiDocument - The parsed AsyncAPI document instance used for context evaluation. @param {Object} templateConfig - The con...
conditionalFilesGenerationDeprecatedVersion
javascript
asyncapi/generator
apps/generator/lib/conditionalGeneration.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/conditionalGeneration.js
Apache-2.0
async function conditionalSubjectGeneration ( asyncapiDocument, templateConfig, matchedConditionPath, templateParams ) { const fileCondition = templateConfig.conditionalGeneration?.[matchedConditionPath] || templateConfig.conditionalFiles?.[matchedConditionPath]; if (!fileCondition || !fileCondition.subjec...
Determines whether a file should be conditionally included based on the provided subject expression and optional validation logic defined in the template configuration. @private @param {Object} asyncapiDocument - The parsed AsyncAPI document instance used for context evaluation. @param {Object} templateConfig - The con...
conditionalSubjectGeneration
javascript
asyncapi/generator
apps/generator/lib/conditionalGeneration.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/conditionalGeneration.js
Apache-2.0
async function validateStatus( argument, matchedConditionPath, templateConfig ) { const validation = templateConfig.conditionalGeneration?.[matchedConditionPath]?.validate || templateConfig.conditionalFiles?.[matchedConditionPath]?.validate; if (!validation) { return false; } const isValid = valida...
Validates the argument value based on the provided validation schema. @param {any} argument The value to validate. @param {String} matchedConditionPath The matched condition path. @param {Object} templateConfig - The template configuration containing conditional logic. @return {Promise<Boolean>} A promise that resolve...
validateStatus
javascript
asyncapi/generator
apps/generator/lib/conditionalGeneration.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/conditionalGeneration.js
Apache-2.0
function registerLocalFilters(nunjucks, templateDir, filtersDir) { return new Promise((resolve, reject) => { const localFilters = path.resolve(templateDir, filtersDir); if (!fs.existsSync(localFilters)) return resolve(); const walker = xfs.walk(localFilters, { followLinks: false }); walke...
Registers the local template filters. @deprecated This method is deprecated. For more details, see the release notes: https://github.com/asyncapi/generator/releases/tag/%40asyncapi%2Fgenerator%402.6.0 @private @param {Object} nunjucks Nunjucks environment. @param {String} templateDir Directory where template is located...
registerLocalFilters
javascript
asyncapi/generator
apps/generator/lib/filtersRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/filtersRegistry.js
Apache-2.0
async function registerConfigFilters(nunjucks, templateDir, templateConfig) { const confFilters = templateConfig.filters; const DEFAULT_MODULES_DIR = 'node_modules'; if (!Array.isArray(confFilters)) return; const promises = confFilters.map(async filtersModule => { let mod; let filterName = filtersModul...
Registers the additionally configured filters. @deprecated This method is deprecated. For more details, see the release notes: https://github.com/asyncapi/generator/releases/tag/%40asyncapi%2Fgenerator%402.6.0 @private @param {Object} nunjucks Nunjucks environment. @param {String} templateDir Directory where template i...
registerConfigFilters
javascript
asyncapi/generator
apps/generator/lib/filtersRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/filtersRegistry.js
Apache-2.0
function addFilters(nunjucks, filters) { Object.getOwnPropertyNames(filters).forEach((key) => { const value = filters[key]; if (!(value instanceof Function)) return; if (isAsyncFunction(value)) { nunjucks.addFilter(key, value, true); } else { nunjucks.addFilter(key, value); } }); }
Add filter functions to Nunjucks environment. Only owned functions from the module are added. @deprecated This method is deprecated. For more details, see the release notes: https://github.com/asyncapi/generator/releases/tag/%40asyncapi%2Fgenerator%402.6.0 @private @param {Object} nunjucks Nunjucks environment. @param ...
addFilters
javascript
asyncapi/generator
apps/generator/lib/filtersRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/filtersRegistry.js
Apache-2.0
constructor(templateName, targetDir, { templateParams = {}, entrypoint, noOverwriteGlobs, disabledHooks, output = 'fs', forceWrite = false, install = false, debug = false, mapBaseUrlToFolder = {}, registry = {}, compile = true } = {}) { const options = arguments[arguments.length - 1]; this.verifyoptions(options...
Instantiates a new Generator object. @example const path = require('path'); const generator = new Generator('@asyncapi/html-template', path.resolve(__dirname, 'example')); @example <caption>Passing custom params to the template</caption> const path = require('path'); const generator = new Generator('@asyncapi/html-te...
constructor
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
get() { if (!self.templateConfig.parameters?.[key]) { throw new Error(`Template parameter "${key}" has not been defined in the Generator Configuration. Please make sure it's listed there before you use it in your template.`); } return templateParams[key]; }
@type {Object} The template parameters. The structure for this object is based on each individual template.
get
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
verifyoptions(Options) { if (typeof Options !== 'object') return []; const invalidOptions = Object.keys(Options).filter(param => !GENERATOR_OPTIONS.includes(param)); if (invalidOptions.length > 0) { throw new Error(`These options are not supported by the generator: ${invalidOptions.join(', ')}`); ...
Check if the Registry Options are valid or not. @private @param {Object} invalidRegOptions Invalid Registry Options.
verifyoptions
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generate(asyncapiDocument, parseOptions = {}) { this.validateAsyncAPIDocument(asyncapiDocument); await this.setupOutput(); this.setLogLevel(); await this.installAndSetupTemplate(); await this.configureTemplateWorkflow(parseOptions); await this.handleEntrypoint(); await this.executeAft...
Generates files from a given template and an AsyncAPIDocument object. @async @example await generator.generate(myAsyncAPIdocument); console.log('Done!'); @example generator .generate(myAsyncAPIdocument) .then(() => { console.log('Done!'); }) .catch(console.error); @example <caption>Using async/await</cap...
generate
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
validateAsyncAPIDocument(asyncapiDocument) { const isAlreadyParsedDocument = isAsyncAPIDocument(asyncapiDocument); const isParsableCompatible = asyncapiDocument && typeof asyncapiDocument === 'string'; if (!isAlreadyParsedDocument && !isParsableCompatible) { throw new Error('Parameter "asyncapiDocume...
Validates the provided AsyncAPI document. @param {*} asyncapiDocument - The AsyncAPI document to be validated. @throws {Error} Throws an error if the document is not valid. @since 10/9/2023 - 4:26:33 PM
validateAsyncAPIDocument
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async setupOutput() { if (this.output === 'fs') { await this.setupFSOutput(); } else if (this.output === 'string' && this.entrypoint === undefined) { throw new Error('Parameter entrypoint is required when using output = "string"'); } }
Sets up the output configuration based on the specified output type. @example const generator = new Generator(); await generator.setupOutput(); @async @throws {Error} If 'output' is set to 'string' without providing 'entrypoint'.
setupOutput
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async setupFSOutput() { // Create directory if not exists xfs.mkdirpSync(this.targetDir); // Verify target directory if forceWrite is not enabled if (!this.forceWrite) { await this.verifyTargetDir(this.targetDir); } }
Sets up the file system (FS) output configuration. This function creates the target directory if it does not exist and verifies the target directory if forceWrite is not enabled. @async @returns {Promise<void>} A promise that fulfills when the setup is complete. @throws {Error} If verification of the target director...
setupFSOutput
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
setLogLevel() { if (this.debug) log.setLevel('debug'); }
Sets the log level based on the debug option. If the debug option is enabled, the log level is set to 'debug'. @returns {void}
setLogLevel
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async installAndSetupTemplate() { const { name: templatePkgName, path: templatePkgPath } = await this.installTemplate(this.install); this.templateDir = templatePkgPath; this.templateName = templatePkgName; this.templateContentDir = path.resolve(this.templateDir, TEMPLATE_CONTENT_DIRNAME); await thi...
Installs and sets up the template for code generation. This function installs the specified template using the provided installation option, sets up the necessary directory paths, loads the template configuration, and returns information about the installed template. @async @returns {Promise<{ templatePkgName: string...
installAndSetupTemplate
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async configureTemplateWorkflow(parseOptions) { // Parse input and validate template configuration await this.parseInput(this.asyncapi, parseOptions); validateTemplateConfig(this.templateConfig, this.templateParams, this.asyncapi); await this.configureTemplate(); if (!isReactTemplate(this.templateCo...
Configures the template workflow based on provided parsing options. This function performs the following steps: 1. Parses the input AsyncAPI document using the specified parse options. 2. Validates the template configuration and parameters. 3. Configures the template based on the parsed AsyncAPI document. 4. Registers...
configureTemplateWorkflow
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async handleEntrypoint() { if (this.entrypoint) { const entrypointPath = path.resolve(this.templateContentDir, this.entrypoint); if (!(await exists(entrypointPath))) { throw new Error(`Template entrypoint "${entrypointPath}" couldn't be found.`); } if (this.output === 'fs') { ...
Handles the logic for the template entrypoint. If an entrypoint is specified: - Resolves the absolute path of the entrypoint file. - Throws an error if the entrypoint file doesn't exist. - Generates a file or renders content based on the output type. - Launches the 'generate:after' hook if the output is 'fs'. If no e...
handleEntrypoint
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async executeAfterHook() { await this.launchHook('generate:after'); }
Executes the 'generate:after' hook. Launches the after-hook to perform additional actions after code generation. @async @returns {Promise<void>} A promise that resolves when the after-hook execution is completed.
executeAfterHook
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async parseInput(asyncapiDocument, parseOptions = {}) { const isAlreadyParsedDocument = isAsyncAPIDocument(asyncapiDocument); // use the expected document API based on `templateConfig.apiVersion` value if (isAlreadyParsedDocument) { this.asyncapi = getProperApiDocument(asyncapiDocument, this.templateC...
Parse the generator input based on the template `templateConfig.apiVersion` value.
parseInput
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async configureTemplate() { if (isReactTemplate(this.templateConfig) && this.compile) { await configureReact(this.templateDir, this.templateContentDir, TRANSPILED_TEMPLATE_LOCATION); } else { this.nunjucks = configureNunjucks(this.debug, this.templateDir); } }
Configure the templates based the desired renderer.
configureTemplate
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateFromString(asyncapiString, parseOptions = {}) { const isParsableCompatible = asyncapiString && typeof asyncapiString === 'string'; if (!isParsableCompatible) { throw new Error('Parameter "asyncapiString" must be a non-empty string.'); } return await this.generate(asyncapiString, pars...
Generates files from a given template and AsyncAPI string. @example const asyncapiString = ` asyncapi: '2.0.0' info: title: Example version: 1.0.0 ... `; generator .generateFromString(asyncapiString) .then(() => { console.log('Done!'); }) .catch(console.error); @example <caption>Using async/await</cap...
generateFromString
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateFromURL(asyncapiURL) { const doc = await fetchSpec(asyncapiURL); return await this.generate(doc, { path: asyncapiURL }); }
Generates files from a given template and AsyncAPI file stored on external server. @example generator .generateFromURL('https://example.com/asyncapi.yaml') .then(() => { console.log('Done!'); }) .catch(console.error); @example <caption>Using async/await</caption> try { await generator.generateFromURL('h...
generateFromURL
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateFromFile(asyncapiFile) { const doc = await readFile(asyncapiFile, { encoding: 'utf8' }); return await this.generate(doc, { path: asyncapiFile }); }
Generates files from a given template and AsyncAPI file. @example generator .generateFromFile('asyncapi.yaml') .then(() => { console.log('Done!'); }) .catch(console.error); @example <caption>Using async/await</caption> try { await generator.generateFromFile('asyncapi.yaml'); console.log('Done!'); } ca...
generateFromFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
static async getTemplateFile(templateName, filePath, templatesDir = DEFAULT_TEMPLATES_DIR) { return await readFile(path.resolve(templatesDir, templateName, filePath), 'utf8'); }
Returns the content of a given template file. @example const Generator = require('@asyncapi/generator'); const content = await Generator.getTemplateFile('@asyncapi/html-template', 'partials/content.html'); @example <caption>Using a custom `templatesDir`</caption> const Generator = require('@asyncapi/generator'); cons...
getTemplateFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
initialiseArbOptions(arbOptions) { let registryUrl = 'registry.npmjs.org'; let authorizationName = 'anonymous'; const providedRegistry = this.registry.url; if (providedRegistry) { arbOptions.registry = providedRegistry; registryUrl = providedRegistry; } const domainName = registryU...
@private @param {Object} arbOptions ArbOptions to intialise the Registry details.
initialiseArbOptions
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async installTemplate(force = false) { if (!force) { let pkgPath; let installedPkg; let packageVersion; try { installedPkg = getTemplateDetails(this.templateName, PACKAGE_JSON_FILENAME); pkgPath = installedPkg?.pkgPath; packageVersion = installedPkg?.version; ...
Downloads and installs a template and its dependencies @param {Boolean} [force=false] Whether to force installation (and skip cache) or not.
installTemplate
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
getAllParameters(asyncapiDocument) { const parameters = new Map(); if (usesNewAPI(this.templateConfig)) { asyncapiDocument.channels().all().forEach(channel => { channel.parameters().all().forEach(parameter => { parameters.set(parameter.id(), parameter); }); }); async...
Returns all the parameters on the AsyncAPI document. @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source.
getAllParameters
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
generateDirectoryStructure(asyncapiDocument) { return new Promise((resolve, reject) => { xfs.mkdirpSync(this.targetDir); const walker = xfs.walk(this.templateContentDir, { followLinks: false }); walker.on('file', async (root, stats, next) => { try { await this.fil...
Generates the directory structure. @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source. @return {Promise}
generateDirectoryStructure
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async ignoredDirHandler(root, stats, next) { const relativeDir = path.relative(this.templateContentDir, path.resolve(root, stats.name)); const dirPath = path.resolve(this.targetDir, relativeDir); const conditionalEntry = this.templateConfig?.conditionalGeneration?.[relativeDir]; let shouldGenerate = tr...
Makes sure that during directory structure generation ignored dirs are not modified @private @param {String} root Dir name. @param {String} stats Information about the file. @param {Function} next Callback function
ignoredDirHandler
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async filesGenerationHandler(asyncapiDocument, root, stats, next) { let fileNamesForSeparation = {}; if (usesNewAPI(this.templateConfig)) { fileNamesForSeparation = { channel: convertCollectionToObject(asyncapiDocument.channels().all(), 'address'), message: convertCollectionToObject(asynca...
Makes sure that during directory structure generation ignored dirs are not modified @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source. @param {String} objectMap Map of schemas of type object @param {String} root Dir name. @param {String} stats Information about the file. @p...
filesGenerationHandler
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateSeparateFiles(asyncapiDocument, array, template, fileName, baseDir) { const promises = []; Object.keys(array).forEach((name) => { const component = array[name]; promises.push(this.generateSeparateFile(asyncapiDocument, name, component, template, fileName, baseDir)); }); retur...
Generates all the files for each in array @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source. @param {Array} array The components/channels to generate the separeted files for. @param {String} template The template filename to replace. @param {String} fileName Name of the fil...
generateSeparateFiles
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateSeparateFile(asyncapiDocument, name, component, template, fileName, baseDir) { const relativeBaseDir = path.relative(this.templateContentDir, baseDir); const setFileTemplateNameHookName = 'setFileTemplateName'; let filename = name; if (this.isHookAvailable(setFileTemplateNameHookName)) { ...
Generates a file for a component/channel @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source. @param {String} name The name of the component (filename to use) @param {Object} component The component/channel object used to generate the file. @param {String} template The templa...
generateSeparateFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async renderAndWriteToFile(asyncapiDocument, templateFilePath, outputpath, extraTemplateData) { const renderContent = await this.renderFile(asyncapiDocument, templateFilePath, extraTemplateData); if (renderContent === undefined) { return; } else if (isReactTemplate(this.templateConfig)) { await ...
Renders a template and writes the result into a file. @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to pass to the template. @param {String} templateFilePath Path to the input file being rendered. @param {String} outputPath Path to the resulting rendered file. @param {Object} [extraTemplateData...
renderAndWriteToFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async generateFile(asyncapiDocument, fileName, baseDir) { const sourceFile = path.resolve(baseDir, fileName); const relativeSourceFile = path.relative(this.templateContentDir, sourceFile); const relativeSourceDirectory = relativeSourceFile.split(path.sep)[0] || '.'; const targetFile = path.resolve(th...
Generates a file. @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to use as the source. @param {String} fileName Name of the file to generate for each channel. @param {String} baseDir Base directory of the given file name. @return {Promise}
generateFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
maybeRenameSourceFile(sourceFile) { switch (path.basename(sourceFile)) { case GIT_IGNORE_FILENAME: return path.join(path.dirname(sourceFile), '.gitignore'); case NPM_IGNORE_FILENAME: return path.join(path.dirname(sourceFile), '.npmignore'); default: return sourceFile; } }
It may rename the source file name in cases where special names are not supported, like .gitignore or .npmignore. Since we're using npm to install templates, these files are never downloaded (that's npm behavior we can't change). @private @param {String} sourceFile Path to the source file @returns {String} New path na...
maybeRenameSourceFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async renderFile(asyncapiDocument, filePath, extraTemplateData = {}) { if (isReactTemplate(this.templateConfig)) { return await renderReact(asyncapiDocument, filePath, extraTemplateData, this.templateDir, this.templateContentDir, TRANSPILED_TEMPLATE_LOCATION, this.templateParams, this.debug, this.originalAsyn...
Renders the content of a file and outputs it. @private @param {AsyncAPIDocument} asyncapiDocument AsyncAPI document to pass to the template. @param {String} filePath Path to the file you want to render. @param {Object} [extraTemplateData] Extra data to pass to the template. @return {Promise<string|TemplateRenderResult...
renderFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
isNonRenderableFile(fileName) { const nonRenderableFiles = this.templateConfig.nonRenderableFiles || []; return Array.isArray(nonRenderableFiles) && (nonRenderableFiles.some(globExp => minimatch(fileName, globExp)) || (isReactTemplate(this.templateConfig) && !isJsFile(fileName))); }
Checks if a given file name matches the list of non-renderable files. @private @param {string} fileName Name of the file to check against a list of glob patterns. @return {boolean}
isNonRenderableFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async shouldOverwriteFile(filePath) { if (!Array.isArray(this.noOverwriteGlobs)) return true; const fileExists = await exists(path.resolve(this.targetDir, filePath)); if (!fileExists) return true; return !this.noOverwriteGlobs.some(globExp => minimatch(filePath, globExp)); }
Checks if a given file should be overwritten. @private @param {string} filePath Path to the file to check against a list of glob patterns. @return {Promise<boolean>}
shouldOverwriteFile
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async loadDefaultValues() { const parameters = this.templateConfig.parameters; const defaultValues = Object.keys(parameters || {}).filter(key => parameters[key].default); defaultValues.filter(dv => this.templateParams[dv] === undefined).forEach(dv => Object.defineProperty(this.templateParams, dv, { ...
Loads default values of parameters from template config. If value was already set as parameter it will not be overriden. @private
loadDefaultValues
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
get() { return parameters[dv].default; }
Loads default values of parameters from template config. If value was already set as parameter it will not be overriden. @private
get
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async launchHook(hookName, hookArguments) { let disabledHooks = this.disabledHooks[hookName] || []; if (disabledHooks === true) return; if (typeof disabledHooks === 'string') disabledHooks = [disabledHooks]; const hooks = this.hooks[hookName]; if (!Array.isArray(hooks)) return; const promises =...
Launches all the hooks registered at a given hook point/name. @param {string} hookName @param {*} hookArguments @private
launchHook
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
isHookAvailable(hookName) { const hooks = this.hooks[hookName]; if (this.disabledHooks[hookName] === true || !Array.isArray(hooks) || hooks.length === 0) return false; let disabledHooks = this.disabledHooks[hookName] || []; if (typeof disabledHooks === 'string') disabledHooks = [disabledHo...
Check if any hooks are available @param {string} hookName @private
isHookAvailable
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async verifyTargetDir(dir) { const isGitRepo = await git(dir).checkIsRepo(); if (isGitRepo) { //Need to figure out root of the repository to properly verify .gitignore const root = await git(dir).revparse(['--show-toplevel']); const gitInfo = git(root); //Skipping verification if workD...
Check if given directory is a git repo with unstaged changes and is not in .gitignore or is not empty @private @param {String} dir Directory that needs to be tested for a given condition.
verifyTargetDir
javascript
asyncapi/generator
apps/generator/lib/generator.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/generator.js
Apache-2.0
async function registerHooks (hooks, templateConfig, templateDir, hooksDir) { await registerLocalHooks(hooks, templateDir, hooksDir); if (templateConfig && Object.keys(templateConfig).length > 0) await registerConfigHooks(hooks, templateDir, templateConfig); return hooks; }
Registers all template hooks. @param {Object} hooks Object that stores information about all available hook functions grouped by the type of the hook. @param {Object} templateConfig Template configuration. @param {String} templateDir Directory where template is located. @param {String} hooksDir Directory where local ho...
registerHooks
javascript
asyncapi/generator
apps/generator/lib/hooksRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/hooksRegistry.js
Apache-2.0
async function registerLocalHooks(hooks, templateDir, hooksDir) { return new Promise(async (resolve, reject) => { const localHooks = path.resolve(templateDir, hooksDir); if (!await exists(localHooks)) return resolve(hooks); const walker = xfs.walk(localHooks, { followLinks: false }); ...
Loads the local template hooks from default location. @private @param {Object} hooks Object that stores information about all available hook functions grouped by the type of the hook. @param {String} templateDir Directory where template is located. @param {String} hooksDir Directory where local hooks are located.
registerLocalHooks
javascript
asyncapi/generator
apps/generator/lib/hooksRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/hooksRegistry.js
Apache-2.0
async function registerConfigHooks(hooks, templateDir, templateConfig) { const configHooks = templateConfig.hooks; const DEFAULT_MODULES_DIR = 'node_modules'; if (typeof configHooks !== 'object' || !Object.keys(configHooks).length > 0) return; const promises = Object.keys(configHooks).map(async hooksModuleNam...
Loads the template hooks provided in template config. @private @param {Object} hooks Object that stores information about all available hook functions grouped by the type of the hook. @param {String} templateDir Directory where template is located. @param {String} templateConfig Template configuration.
registerConfigHooks
javascript
asyncapi/generator
apps/generator/lib/hooksRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/hooksRegistry.js
Apache-2.0
function addHook(hooks, mod, config) { /** * ESM `export default { ... }` is transpiled to: * module.exports = { default: { ... } }; * First check the `default` object, and if it exists the override mod to `default`. */ if (typeof mod.default === 'object') { mod = mod.default; } Object.keys(mod...
Add hook from given module to list of available hooks @private @param {Object} hooks Object that stores information about all available hook functions grouped by the type of the hook. @param {Object} mod Single module with object of hook functions grouped by the type of the hook @param {Array} config List of hooks conf...
addHook
javascript
asyncapi/generator
apps/generator/lib/hooksRegistry.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/hooksRegistry.js
Apache-2.0
function convertOldOptionsToNew(oldOptions, generator) { if (!oldOptions) return; const newOptions = {}; if (typeof oldOptions.path === 'string') { newOptions.source = oldOptions.path; } if (typeof oldOptions.applyTraits === 'boolean') { newOptions.applyTraits = oldOptions.applyTraits; } const r...
Converts old parser options to the new format. @private - This function should not be used outside this module. @param {object} oldOptions - The old options to convert. @param {object} generator - The generator instance. @returns {object} The converted options.
convertOldOptionsToNew
javascript
asyncapi/generator
apps/generator/lib/parser.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
Apache-2.0
function getMapBaseUrlToFolderResolvers({ url: baseUrl, folder: baseDir }) { const resolver = { order: 1, canRead: true, read(uri) { return new Promise(((resolve, reject) => { const path = uri.toString(); const localpath = path.replace(baseUrl, baseDir); try { fs.re...
Creates a custom resolver that maps urlToFolder.url to urlToFolder.folder Building your custom resolver is explained here: https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html @private @param {object} urlToFolder to resolve url e.g. https://schema.example.com/crm/ to a folder e.g. ./test/docs/. @re...
getMapBaseUrlToFolderResolvers
javascript
asyncapi/generator
apps/generator/lib/parser.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
Apache-2.0
read(uri) { return new Promise(((resolve, reject) => { const path = uri.toString(); const localpath = path.replace(baseUrl, baseDir); try { fs.readFile(localpath, (err, data) => { if (err) { reject(`Error opening file "${localpath}"`); } else...
Creates a custom resolver that maps urlToFolder.url to urlToFolder.folder Building your custom resolver is explained here: https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html @private @param {object} urlToFolder to resolve url e.g. https://schema.example.com/crm/ to a folder e.g. ./test/docs/. @re...
read
javascript
asyncapi/generator
apps/generator/lib/parser.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
Apache-2.0
function convertOldResolvers(resolvers = {}) { // NOSONAR if (Object.keys(resolvers).length === 0) return []; return Object.entries(resolvers).map(([protocol, resolver]) => { return { schema: protocol, order: resolver.order || 1, canRead: (uri) => canReadFn(uri, resolver.canRead), read:...
Creates a custom resolver that maps urlToFolder.url to urlToFolder.folder Building your custom resolver is explained here: https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html @private @param {object} urlToFolder to resolve url e.g. https://schema.example.com/crm/ to a folder e.g. ./test/docs/. @re...
convertOldResolvers
javascript
asyncapi/generator
apps/generator/lib/parser.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
Apache-2.0
function canReadFn(uri, canRead) { const value = uri.valueOf(); if (typeof canRead === 'boolean') return canRead; if (typeof canRead === 'string') return canRead === value; if (Array.isArray(canRead)) return canRead.includes(value); if (canRead instanceof RegExp) return canRead.test(value); if (typeof canRe...
Creates a custom resolver that maps urlToFolder.url to urlToFolder.folder Building your custom resolver is explained here: https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html @private @param {object} urlToFolder to resolve url e.g. https://schema.example.com/crm/ to a folder e.g. ./test/docs/. @re...
canReadFn
javascript
asyncapi/generator
apps/generator/lib/parser.js
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
Apache-2.0