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, '<')
.replace(/>/g, '>')
.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="number">$1</span>')
.replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
}
|
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 one chance in a million of a collision)
See http://en.wikipedia.org/wiki/Birthday_problem
|
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 real array
for (var i = 0; i < task.arguments.length; i += 1) { newArguments.push(task.arguments[i]); }
var lastArg = task.arguments[task.arguments.length - 1];
// Always tell the queue task is complete. Execute callback if any was given.
if (typeof lastArg === 'function') {
// Callback was supplied
newArguments[newArguments.length - 1] = function () {
if (typeof setImmediate === 'function') {
setImmediate(cb);
} else {
process.nextTick(cb);
}
lastArg.apply(null, arguments);
};
} else if (!lastArg && task.arguments.length !== 0) {
// false/undefined/null supplied as callbback
newArguments[newArguments.length - 1] = function () { cb(); };
} else {
// Nothing supplied as callback
newArguments.push(function () { cb(); });
}
task.fn.apply(task.this, newArguments);
}, 1);
}
|
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 fields)
@param {Boolean} options.unique Optional, enforce a unique constraint (default: false)
@param {Boolean} options.sparse Optional, allow a sparse index (we can have documents for which fieldName is undefined) (default: false)
|
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');
}
if (k.indexOf('.') !== -1) {
throw new Error('Field names cannot contain a .');
}
}
|
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 object
But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names...
|
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, strictKeys)); });
return res;
}
if (typeof obj === 'object') {
res = {};
Object.keys(obj).forEach(function (k) {
if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {
res[k] = deepCopy(obj[k], strictKeys);
}
});
return res;
}
return undefined; // For now everything else is undefined. We should probably throw an error instead
}
|
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 : -1; }
if (b === null) { return a === null ? 0 : 1; }
// Numbers
if (typeof a === 'number') { return typeof b === 'number' ? compareNSB(a, b) : -1; }
if (typeof b === 'number') { return typeof a === 'number' ? compareNSB(a, b) : 1; }
// Strings
if (typeof a === 'string') { return typeof b === 'string' ? compareStrings(a, b) : -1; }
if (typeof b === 'string') { return typeof a === 'string' ? compareStrings(a, b) : 1; }
// Booleans
if (typeof a === 'boolean') { return typeof b === 'boolean' ? compareNSB(a, b) : -1; }
if (typeof b === 'boolean') { return typeof a === 'boolean' ? compareNSB(a, b) : 1; }
// Dates
if (util.isDate(a)) { return util.isDate(b) ? compareNSB(a.getTime(), b.getTime()) : -1; }
if (util.isDate(b)) { return util.isDate(a) ? compareNSB(a.getTime(), b.getTime()) : 1; }
// Arrays (first element is most significant and so on)
if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; }
if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; }
// Objects
aKeys = Object.keys(a).sort();
bKeys = Object.keys(b).sort();
for (i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) {
comp = compareThings(a[aKeys[i]], b[bKeys[i]]);
if (comp !== 0) { return comp; }
}
return compareNSB(aKeys.length, bKeys.length);
}
|
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, null, number, strings, boolean, dates, arrays, objects
Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!)
@param {Function} _compareStrings String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)
|
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) {
if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
obj[fieldParts[0]] = {};
}
modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
}
};
}
|
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) { throw new Error("You cannot change a document's _id"); }
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
throw new Error("You cannot mix modifiers and normal fields");
}
if (dollarFirstChars.length === 0) {
// Simply replace the object with the update query contents
newDoc = deepCopy(updateQuery);
newDoc._id = obj._id;
} else {
// Apply modifiers
modifiers = _.uniq(keys);
newDoc = deepCopy(obj);
modifiers.forEach(function (m) {
var keys;
if (!modifierFunctions[m]) { throw new Error("Unknown modifier " + m); }
// Can't rely on Object.keys throwing on non objects since ES6
// Not 100% satisfying as non objects can be interpreted as objects but no false negatives so we can live with it
if (typeof updateQuery[m] !== 'object') {
throw new Error("Modifier " + m + "'s argument must be an object");
}
keys = Object.keys(updateQuery[m]);
keys.forEach(function (k) {
modifierFunctions[m](newDoc, k, updateQuery[m][k]);
});
});
}
// Check result is valid and return it
checkObject(newDoc);
if (obj._id !== newDoc._id) { throw new Error("You can't change a document's _id"); }
return newDoc;
}
|
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.length === 1) { return obj[fieldParts[0]]; }
if (util.isArray(obj[fieldParts[0]])) {
// If the next field is an integer, return only this item of the array
i = parseInt(fieldParts[1], 10);
if (typeof i === 'number' && !isNaN(i)) {
return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2))
}
// Return the array of values
objs = new Array();
for (i = 0; i < obj[fieldParts[0]].length; i += 1) {
objs.push(getDotValue(obj[fieldParts[0]][i], fieldParts.slice(1)));
}
return objs;
} else {
return getDotValue(obj[fieldParts[0]], fieldParts.slice(1));
}
}
|
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
if (util.isDate(a) || util.isDate(b)) { return util.isDate(a) && util.isDate(b) && a.getTime() === b.getTime(); }
// Arrays (no match since arrays are used as a $in)
// undefined (no match since they mean field doesn't exist and can't be serialized)
if ((!(util.isArray(a) && util.isArray(b)) && (util.isArray(a) || util.isArray(b))) || a === undefined || b === undefined) { return false; }
// General objects (check for deep equality)
// a and b should be objects at this point
try {
aKeys = Object.keys(a);
bKeys = Object.keys(b);
} catch (e) {
return false;
}
if (aKeys.length !== bKeys.length) { return false; }
for (i = 0; i < aKeys.length; i += 1) {
if (bKeys.indexOf(aKeys[i]) === -1) { return false; }
if (!areThingsEqual(a[aKeys[i]], b[aKeys[i]])) { return false; }
}
return true;
}
|
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) || isPrimitiveType(query)) {
return matchQueryPart({ needAKey: obj }, 'needAKey', query);
}
// Normal query
queryKeys = Object.keys(query);
for (i = 0; i < queryKeys.length; i += 1) {
queryKey = queryKeys[i];
queryValue = query[queryKey];
if (queryKey[0] === '$') {
if (!logicalOperators[queryKey]) { throw new Error("Unknown logical operator " + queryKey); }
if (!logicalOperators[queryKey](obj, queryValue)) { return false; }
} else {
if (!matchQueryPart(obj, queryKey, queryValue)) { return false; }
}
}
return true;
}
|
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 array, try to perform an exact match
if (util.isArray(queryValue)) {
return matchQueryPart(obj, queryKey, queryValue, true);
}
// Check if we are using an array-specific comparison function
if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue)) {
keys = Object.keys(queryValue);
for (i = 0; i < keys.length; i += 1) {
if (arrayComparisonFunctions[keys[i]]) { return matchQueryPart(obj, queryKey, queryValue, true); }
}
}
// If not, treat it as an array of { obj, query } where there needs to be at least one match
for (i = 0; i < objValue.length; i += 1) {
if (matchQueryPart({ k: objValue[i] }, 'k', queryValue)) { return true; } // k here could be any string
}
return false;
}
// queryValue is an actual object. Determine whether it contains comparison operators
// or only normal fields. Mixed objects are not allowed
if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue) && !util.isArray(queryValue)) {
keys = Object.keys(queryValue);
firstChars = _.map(keys, function (item) { return item[0]; });
dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; });
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
throw new Error("You cannot mix operators and normal fields");
}
// queryValue is an object of this form: { $comparisonOperator1: value1, ... }
if (dollarFirstChars.length > 0) {
for (i = 0; i < keys.length; i += 1) {
if (!comparisonFunctions[keys[i]]) { throw new Error("Unknown comparison function " + keys[i]); }
if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) { return false; }
}
return true;
}
}
// Using regular expressions with basic querying
if (util.isRegExp(queryValue)) { return comparisonFunctions.$regex(objValue, queryValue); }
// queryValue is either a native value or a normal object
// Basic matching is possible
if (!areThingsEqual(objValue, queryValue)) { return false; }
return true;
}
|
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 && this.filename.charAt(this.filename.length - 1) === '~') {
throw new Error("The datafile name can't end with a ~, which is reserved for crash safe backup files");
}
// After serialization and before deserialization hooks with some basic sanity checks
if (options.afterSerialization && !options.beforeDeserialization) {
throw new Error("Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss");
}
if (!options.afterSerialization && options.beforeDeserialization) {
throw new Error("Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss");
}
this.afterSerialization = options.afterSerialization || function (s) { return s; };
this.beforeDeserialization = options.beforeDeserialization || function (s) { return s; };
for (i = 1; i < 30; i += 1) {
for (j = 0; j < 10; j += 1) {
randomString = customUtils.uid(i);
if (this.beforeDeserialization(this.afterSerialization(randomString)) !== randomString) {
throw new Error("beforeDeserialization is not the reverse of afterSerialization, cautiously refusing to start NeDB to prevent dataloss");
}
}
}
// For NW apps, store data in the same directory where NW stores application data
if (this.filename && options.nodeWebkitAppName) {
console.log("==================================================================");
console.log("WARNING: The nodeWebkitAppName option is deprecated");
console.log("To get the path to the directory where Node Webkit stores the data");
console.log("for your app, use the internal nw.gui module like this");
console.log("require('nw.gui').App.dataPath");
console.log("See https://github.com/rogerwang/node-webkit/issues/500");
console.log("==================================================================");
this.filename = Persistence.getNWAppFilename(options.nodeWebkitAppName, 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 such as cookies and local storage (the best place to store data in my opinion)
|
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; })
;
docs.length.should.equal(3);
Object.keys(doc1).length.should.equal(2);
doc1.somedata.should.equal('ok');
doc1._id.should.equal(id1);
Object.keys(doc2).length.should.equal(2);
doc2.newDoc.should.equal('yes');
doc2._id.should.equal(id2);
Object.keys(doc3).length.should.equal(2);
doc3.newDoc.should.equal('yes');
doc3._id.should.equal(id3);
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 exception
Mocha's exception handling mechanism interferes with this since it already registers a listener on uncaughtException
which we need to use since findOne is not called in the same turn of the event loop (so no try/catch)
So we remove all current listeners, put our own which when called will register the former listeners (incl. Mocha's) again.
Note: maybe using an in-memory only NeDB would give us an easier solution
|
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; })
;
docs.length.should.equal(3);
assert.deepEqual(doc1, { somedata: 'ok', _id: doc1._id });
// doc2 or doc3 was modified. Since we sort on _id and it is random
// it can be either of two situations
try {
assert.deepEqual(doc2, { newDoc: 'yes', _id: doc2._id });
assert.deepEqual(doc3, { somedata: 'again', _id: doc3._id });
} catch (e) {
assert.deepEqual(doc2, { somedata: 'again', plus: 'additional data', _id: doc2._id });
assert.deepEqual(doc3, { newDoc: 'yes', _id: doc3._id });
}
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 exception
Mocha's exception handling mechanism interferes with this since it already registers a listener on uncaughtException
which we need to use since findOne is not called in the same turn of the event loop (so no try/catch)
So we remove all current listeners, put our own which when called will register the former listeners (incl. Mocha's) again.
Note: maybe using an in-memory only NeDB would give us an easier solution
|
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 exception
Mocha's exception handling mechanism interferes with this since it already registers a listener on uncaughtException
which we need to use since findOne is not called in the same turn of the event loop (so no try/catch)
So we remove all current listeners, put our own which when called will register the former listeners (incl. Mocha's) again.
Note: maybe using an in-memory only NeDB would give us an easier solution
|
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.stack.substr(backtrace.name.length);
throw backtrace;
}
};
}
return function(err) {
if (err) {
throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
}
};
}
|
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 will be incomplete on crash
// write(fd, buffer, offset, length, position, callback)
fs.write(fd, buffer, offset, l, position, function(writeErr, written) {
if (writeErr) {
if (isUserFd) {
if (callback) callback(writeErr);
} else {
fs.close(fd, function() {
if (callback) callback(writeErr);
});
}
} else {
onePassDone = true;
if (written === length) {
if (isUserFd) {
if (callback) callback(null);
} else {
fs.close(fd, callback);
}
} else {
offset += written;
length -= written;
if (position !== null) {
position += written;
}
writeAll(fd, isUserFd, buffer, offset, length, position, callback);
}
}
});
}
|
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 },
} = await WebAssembly.instantiateStreaming(
await fetch(avifWasmBinaryFile, { cache: "force-cache" }),
imports,
);
const malloc = wasm.__wbindgen_malloc;
const free = wasm.__wbindgen_free;
const pointer = wasm.__wbindgen_add_to_stack_pointer;
const n1 = bytes.length;
const p1 = malloc(n1, 1);
const r = pointer(-16);
try {
new Uint8Array(wasm.memory.buffer).set(bytes, p1);
wasm.avif_from_imagedata(r, p1, n1, width, height, quality, speed);
const arr = new Int32Array(wasm.memory.buffer);
const p2 = arr[r / 4];
const n2 = arr[r / 4 + 1];
const res = new Uint8Array(wasm.memory.buffer)
.subarray(p2, p2 + n2)
.slice();
free(p2, n2);
return res;
} finally {
pointer(16);
}
}
|
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 },
} = await WebAssembly.instantiateStreaming(
await fetch(avifWasmBinaryFile, { cache: "force-cache" }),
imports,
);
const malloc = wasm.__wbindgen_malloc;
const free = wasm.__wbindgen_free;
const pointer = wasm.__wbindgen_add_to_stack_pointer;
const n1 = bytes.length;
const p1 = malloc(n1, 1);
const r = pointer(-16);
try {
new Uint8Array(wasm.memory.buffer).set(bytes, p1);
wasm.avif_from_imagedata(r, p1, n1, width, height, quality, speed);
const arr = new Int32Array(wasm.memory.buffer);
const p2 = arr[r / 4];
const n2 = arr[r / 4 + 1];
const res = new Uint8Array(wasm.memory.buffer)
.subarray(p2, p2 + n2)
.slice();
free(p2, n2);
return res;
} finally {
pointer(16);
}
}
|
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: (char) => {
err += String.fromCharCode(char);
if (char === 10) {
console.error(err);
if (isStrict) {
reject(err);
}
}
},
arguments: command,
// input: new Uint8Array(image.buffer),
input: data,
folder: folder,
output: (res) => {
resolve(res);
resolved = true;
},
}).then(() => {
(0, _io.flush)();
if (!resolved) {
reject();
}
resetModule();
});
});
}
|
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: (char) => {
err += String.fromCharCode(char);
if (char === 10) {
console.error(err);
if (isStrict) {
reject(err);
}
}
},
arguments: command,
// input: new Uint8Array(image.buffer),
input: data,
folder: folder,
output: (res) => {
resolve(res);
resolved = true;
},
}).then(() => {
(0, _io.flush)();
if (!resolved) {
reject();
}
resetModule();
});
});
}
|
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 (done) return;
done = true;
reject(self, ex);
}
}
|
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);
},
reject
);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
|
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':
eventText = red(value.eventType);
break;
case 'renamed':
eventText = yellow(value.eventType);
break;
default:
eventText = yellow(value.eventType);
}
console.log(`\t${magenta(value.path)} was ${eventText}`);
}
console.log('Generating files');
try {
await generate(program.output);
} catch (e) {
showError(e);
}
}
|
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] || {};
const config = Object.keys(conditionFilesGeneration).length > 0
? conditionFilesGeneration
: conditionalGeneration;
const subject = config?.subject;
// conditionalFiles becomes deprecated with this PR, and soon will be removed.
// TODO: https://github.com/asyncapi/generator/issues/1553
if (Object.keys(conditionFilesGeneration).length > 0 && subject) {
return conditionalFilesGenerationDeprecatedVersion(
asyncapiDocument,
templateConfig,
matchedConditionPath,
templateParams
);
} else if (Object.keys(conditionalGeneration).length > 0) {
// Case when the subject is present in conditionalGeneration
if (subject) {
return conditionalSubjectGeneration(
asyncapiDocument,
templateConfig,
matchedConditionPath
);
}
return conditionalParameterGeneration(templateConfig,matchedConditionPath,templateParams);
}
}
|
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 {Object} templateParams - Parameters passed to the template.
@param {AsyncAPIDocument} asyncapiDocument - The AsyncAPI document used for evaluating conditions.
@returns {Promise<boolean>} A promise that resolves to `true` if the condition is met, allowing the file or folder to render; otherwise, resolves to `false`.
|
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];
return validateStatus(parameterValue, matchedConditionPath, templateConfig);
}
|
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/folder being conditionally generated.
@param {Object} templateParams - The parameters passed to the generator, usually user input or default values.
@returns {Promise<boolean>} - Resolves to `true` if the parameter passes validation, `false` otherwise.
|
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 configuration object that contains `conditionalFiles` rules.
@param {string} matchedConditionPath - The path of the file/folder being conditionally generated.
@param {Object} templateParams - The parameters passed to the generator, usually user input or default values.
@returns {Boolean} - Returns `true` if the file should be included; `false` if it should be skipped.
|
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.subject) {
return true;
}
const { subject } = fileCondition;
const server = templateParams.server && asyncapiDocument.servers().get(templateParams.server);
const source = jmespath.search({
...asyncapiDocument.json(),
...{
server: server ? server.json() : undefined,
},
}, subject);
if (!source) {
log.debug(logMessage.relativeSourceFileNotGenerated(matchedConditionPath, subject));
return false;
}
return validateStatus(source, matchedConditionPath, templateConfig);
}
|
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 configuration object that contains `conditionalFiles` rules.
@param {String} matchedConditionPath - The relative path to the directory of the source file.
@param {Object} templateParams - Parameters passed to the template.
@returns {Boolean} - Returns `true` if the file should be included; `false` if it should be skipped.
|
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 = validation(argument);
if (!isValid) {
if (templateConfig.conditionalGeneration?.[matchedConditionPath]) {
log.debug(logMessage.conditionalGenerationMatched(matchedConditionPath));
} else {
// conditionalFiles becomes deprecated with this PR, and soon will be removed.
// TODO: https://github.com/asyncapi/generator/issues/1553
log.debug(logMessage.conditionalFilesMatched(matchedConditionPath));
}
return false;
}
return true;
}
|
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 resolves to false if the generation should be skipped, true otherwise.
|
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
});
walker.on('file', async (root, stats, next) => {
try {
const filePath = path.resolve(
templateDir,
path.resolve(root, stats.name)
);
registerTypeScript(filePath);
// If it's a module constructor, inject dependencies to ensure consistent usage in remote templates in other projects or plain directories.
delete require.cache[require.resolve(filePath)];
const mod = require(filePath);
addFilters(nunjucks, mod);
next();
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', async () => {
resolve();
});
});
}
|
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.
@param {String} filtersDir Directory where local filters are 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 = filtersModule;
try {
//first we try to grab module with filters by the module name
//this is when generation is used on production using remote templates
mod = require(filterName);
} catch (error) {
//in case template is local but was not installed in node_modules of the generator then we need to explicitly provide modules location
try {
filterName = path.resolve(templateDir, DEFAULT_MODULES_DIR, filtersModule);
mod = require(filterName);
} catch (e) {
//sometimes it may happen that template is located in node_modules with other templates and its filter package is on the same level as template, as it is shared with other templates
try {
filterName = path.resolve(templateDir, '../..', filtersModule);
mod = require(filterName);
} catch (error) {
//in rare cases, especially in isolated tests, it may happen that installation
//ends but is not yet fully completed, so initial require of the same path do not work
//but in next attempt it works
//we need to keep this workaround until we find a solution
mod = require(filterName);
}
}
}
return addFilters(nunjucks, mod);
});
await Promise.all(promises);
}
|
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 is located.
@param {Object} templateConfig Template configuration.
|
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 {Object} filters Module with functions.
|
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);
if (!templateName) throw new Error('No template name has been specified.');
if (!entrypoint && !targetDir) throw new Error('No target directory has been specified.');
if (!['fs', 'string'].includes(output)) throw new Error(`Invalid output type ${output}. Valid values are 'fs' and 'string'.`);
/** @type {Boolean} Whether to compile the template or use the cached transpiled version provided by template in '__transpiled' folder. */
this.compile = compile;
/** @type {Object} Npm registry information. */
this.registry = registry;
/** @type {String} Name of the template to generate. */
this.templateName = templateName;
/** @type {String} Path to the directory where the files will be generated. */
this.targetDir = targetDir;
/** @type {String} Name of the file to use as the entry point for the rendering process. Use in case you want to use only a specific template file. Note: this potentially avoids rendering every file in the template. */
this.entrypoint = entrypoint;
/** @type {String[]} List of globs to skip when regenerating the template. */
this.noOverwriteGlobs = noOverwriteGlobs || [];
/** @type {Object<String, Boolean | String | String[]>} Object with hooks to disable. The key is a hook type. If key has "true" value, then the generator skips all hooks from the given type. If the value associated with a key is a string with the name of a single hook, then the generator skips only this single hook name. If the value associated with a key is an array of strings, then the generator skips only hooks from the array. */
this.disabledHooks = disabledHooks || {};
/** @type {String} Type of output. Can be either 'fs' (default) or 'string'. Only available when entrypoint is set. */
this.output = output;
/** @type {Boolean} Force writing of the generated files to given directory even if it is a git repo with unstaged files or not empty dir. Default is set to false. */
this.forceWrite = forceWrite;
/** @type {Boolean} Enable more specific errors in the console. At the moment it only shows specific errors about filters. Keep in mind that as a result errors about template are less descriptive. */
this.debug = debug;
/** @type {Boolean} Install the template and its dependencies, even when the template has already been installed. */
this.install = install;
/** @type {Object} The template configuration. */
this.templateConfig = {};
/** @type {Object} Hooks object with hooks functions grouped by the hook type. */
this.hooks = {};
/** @type {Object} Maps schema URL to folder. */
this.mapBaseUrlToFolder = mapBaseUrlToFolder;
// Load template configuration
/** @type {Object} The template parameters. The structure for this object is based on each individual template. */
this.templateParams = {};
Object.keys(templateParams).forEach(key => {
const self = this;
Object.defineProperty(this.templateParams, key, {
enumerable: true,
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];
}
});
});
}
|
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-template', path.resolve(__dirname, 'example'), {
templateParams: {
sidebarOrganization: 'byTags'
}
});
@param {String} templateName Name of the template to generate.
@param {String} targetDir Path to the directory where the files will be generated.
@param {Object} options
@param {Object<string, string>} [options.templateParams] Optional parameters to pass to the template. Each template define their own params.
@param {String} [options.entrypoint] Name of the file to use as the entry point for the rendering process. Use in case you want to use only a specific template file. Note: this potentially avoids rendering every file in the template.
@param {String[]} [options.noOverwriteGlobs] List of globs to skip when regenerating the template.
@param {Object<String, Boolean | String | String[]>} [options.disabledHooks] Object with hooks to disable. The key is a hook type. If key has "true" value, then the generator skips all hooks from the given type. If the value associated with a key is a string with the name of a single hook, then the generator skips only this single hook name. If the value associated with a key is an array of strings, then the generator skips only hooks from the array.
@param {String} [options.output='fs'] Type of output. Can be either 'fs' (default) or 'string'. Only available when entrypoint is set.
@param {Boolean} [options.forceWrite=false] Force writing of the generated files to given directory even if it is a git repo with unstaged files or not empty dir. Default is set to false.
@param {Boolean} [options.install=false] Install the template and its dependencies, even when the template has already been installed.
@param {Boolean} [options.debug=false] Enable more specific errors in the console. At the moment it only shows specific errors about filters. Keep in mind that as a result errors about template are less descriptive.
@param {Boolean} [options.compile=true] Whether to compile the template or use the cached transpiled version provided by template in '__transpiled' folder
@param {Object<String, String>} [options.mapBaseUrlToFolder] Optional parameter to map schema references from a base url to a local base folder e.g. url=https://schema.example.com/crm/ folder=./test/docs/ .
@param {Object} [options.registry] Optional parameter with private registry configuration
@param {String} [options.registry.url] Parameter to pass npm registry url
@param {String} [options.registry.auth] Optional parameter to pass npm registry username and password encoded with base64, formatted like username:password value should be encoded
@param {String} [options.registry.token] Optional parameter to pass npm registry auth token that you can grab from .npmrc file
|
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.executeAfterHook();
}
|
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</caption>
try {
await generator.generate(myAsyncAPIdocument);
console.log('Done!');
} catch (e) {
console.error(e);
}
@param {AsyncAPIDocument | string} asyncapiDocument - AsyncAPIDocument object to use as source.
@param {Object} [parseOptions={}] - AsyncAPI Parser parse options.
Check out {@link https://www.github.com/asyncapi/parser-js|@asyncapi/parser} for more information.
Remember to use the right options for the right parser depending on the template you are using.
@return {Promise<void>} A Promise that resolves when the generation is completed.
|
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 "asyncapiDocument" must be a non-empty string or an already parsed AsyncAPI document.');
}
this.asyncapi = this.originalAsyncAPI = asyncapiDocument;
}
|
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 directory fails and forceWrite is not enabled.
|
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 this.loadTemplateConfig();
return { templatePkgName, templatePkgPath };
}
|
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, templatePkgPath: string }>}
A promise that resolves to an object containing the name and path of the installed template.
|
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.templateConfig)) {
await registerFilters(this.nunjucks, this.templateConfig, this.templateDir, FILTERS_DIRNAME);
}
await registerHooks(this.hooks, this.templateConfig, this.templateDir, HOOKS_DIRNAME);
await this.launchHook('generate:before');
}
|
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 filters, hooks, and launches the 'generate:before' hook if applicable.
@async
@param {*} parseOptions - Options for parsing the AsyncAPI document.
@returns {Promise<void>} A promise that resolves when the configuration is completed.
|
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') {
await this.generateFile(this.asyncapi, path.basename(entrypointPath), path.dirname(entrypointPath));
await this.launchHook('generate:after');
} else if (this.output === 'string') {
return await this.renderFile(this.asyncapi, entrypointPath);
}
} else {
await this.generateDirectoryStructure(this.asyncapi);
}
}
|
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 entrypoint is specified, generates the directory structure.
@async
@returns {Promise<void>} A promise that resolves when the entrypoint logic is completed.
|
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.templateConfig);
} else {
/** @type {AsyncAPIDocument} Parsed AsyncAPI schema. See {@link https://github.com/asyncapi/parser-js/blob/master/API.md#module_@asyncapi/parser+AsyncAPIDocument|AsyncAPIDocument} for details on object structure. */
const { document, diagnostics } = await parse(asyncapiDocument, parseOptions, this);
if (!document) {
const err = new Error('Input is not a correct AsyncAPI document so it cannot be processed.');
err.diagnostics = diagnostics;
for (const diag of diagnostics) {
console.error(
`Diagnostic err: ${diag['message']} in path ${JSON.stringify(diag['path'])} starting `+
`L${diag['range']['start']['line'] + 1} C${diag['range']['start']['character']}, ending `+
`L${diag['range']['end']['line'] + 1} C${diag['range']['end']['character']}`
);
}
throw err;
} else {
this.asyncapi = document;
}
}
}
|
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, parseOptions);
}
|
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</caption>
const asyncapiString = `
asyncapi: '2.0.0'
info:
title: Example
version: 1.0.0
...
`;
try {
await generator.generateFromString(asyncapiString);
console.log('Done!');
} catch (e) {
console.error(e);
}
@param {String} asyncapiString AsyncAPI string to use as source.
@param {Object} [parseOptions={}] AsyncAPI Parser parse options. Check out {@link https://www.github.com/asyncapi/parser-js|@asyncapi/parser} for more information.
@deprecated Use the `generate` function instead. Just change the function name and it works out of the box.
@return {Promise<TemplateRenderResult|undefined>}
|
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('https://example.com/asyncapi.yaml');
console.log('Done!');
} catch (e) {
console.error(e);
}
@param {String} asyncapiURL Link to AsyncAPI file
@return {Promise<TemplateRenderResult|undefined>}
|
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!');
} catch (e) {
console.error(e);
}
@param {String} asyncapiFile AsyncAPI file to use as source.
@return {Promise<TemplateRenderResult|undefined>}
|
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');
const content = await Generator.getTemplateFile('@asyncapi/html-template', 'partials/content.html', '~/my-templates');
@static
@param {String} templateName Name of the template to generate.
@param {String} filePath Path to the file to render. Relative to the template directory.
@param {String} [templatesDir=DEFAULT_TEMPLATES_DIR] Path to the directory where the templates are installed.
@return {Promise}
|
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 = registryUrl.replace(/^https?:\/\//, '');
//doing basic if/else so basically only one auth type is used and token as more secure is primary
if (this.registry.token) {
authorizationName = `//${domainName}:_authToken`;
arbOptions[authorizationName] = this.registry.token;
} else if (this.registry.auth) {
authorizationName = `//${domainName}:_auth`;
arbOptions[authorizationName] = this.registry.auth;
}
//not sharing in logs neither token nor auth for security reasons
log.debug(`Using npm registry ${registryUrl} and authorization type ${authorizationName} to handle template installation.`);
}
|
@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;
log.debug(logMessage.templateSource(pkgPath));
if (packageVersion) log.debug(logMessage.templateVersion(packageVersion));
return {
name: installedPkg.name,
path: pkgPath
};
} catch (e) {
log.debug(logMessage.packageNotAvailable(installedPkg), e);
// We did our best. Proceed with installation...
}
}
const debugMessage = force ? logMessage.TEMPLATE_INSTALL_FLAG_MSG : logMessage.TEMPLATE_INSTALL_DISK_MSG;
log.debug(logMessage.installationDebugMessage(debugMessage));
if (isFileSystemPath(this.templateName)) log.debug(logMessage.NPM_INSTALL_TRIGGER);
const config = new Config({
definitions,
flatten,
shorthands,
npmPath
});
await config.load();
const arbOptions = {...{path: ROOT_DIR}, ...config.flat};
if (Object.keys(this.registry).length !== 0) {
this.initialiseArbOptions(arbOptions);
}
const arb = new Arborist(arbOptions);
try {
const installResult = await arb.reify({
add: [this.templateName],
saveType: 'prod',
save: false
});
const addResult = arb[Symbol.for('resolvedAdd')];
if (!addResult) throw new Error('Unable to resolve the name of the added package. It was most probably not added to node_modules successfully');
const packageName = addResult[0].name;
const packageVersion = installResult.children.get(packageName).version;
const packagePath = installResult.children.get(packageName).path;
if (!isFileSystemPath(this.templateName)) log.debug(logMessage.templateSuccessfullyInstalled(packageName, packagePath));
if (packageVersion) log.debug(logMessage.templateVersion(packageVersion));
return {
name: packageName,
path: packagePath,
};
} catch (err) {
throw new Error(`Installation failed: ${ err.message }`);
}
}
|
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);
});
});
asyncapiDocument.components().channelParameters().all().forEach(parameter => {
parameters.set(parameter.id(), parameter);
});
} else {
if (asyncapiDocument.hasChannels()) {
asyncapiDocument.channelNames().forEach(channelName => {
const channel = asyncapiDocument.channel(channelName);
for (const [key, value] of Object.entries(channel.parameters())) {
parameters.set(key, value);
}
});
}
if (asyncapiDocument.hasComponents()) {
for (const [key, value] of Object.entries(asyncapiDocument.components().parameters())) {
parameters.set(key, value);
}
}
}
return parameters;
}
|
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.filesGenerationHandler(asyncapiDocument, root, stats, next);
} catch (e) {
reject(e);
}
});
walker.on('directory', async (root, stats, next) => {
try {
await this.ignoredDirHandler(root, stats, next);
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', async () => {
resolve();
});
});
}
|
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 = true;
if (conditionalEntry) {
shouldGenerate = await isGenerationConditionMet(
this.templateConfig,
relativeDir,
this.templateParams,
this.asyncapiDocument
);
if (!shouldGenerate) {
log.debug(logMessage.conditionalGenerationMatched(relativeDir));
}
}
if (!shouldIgnoreDir(relativeDir) && shouldGenerate) {
xfs.mkdirpSync(dirPath);
}
next();
}
|
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(asyncapiDocument.messages().all(), 'id'),
securityScheme: convertCollectionToObject(asyncapiDocument.components().securitySchemes().all(), 'id'),
schema: convertCollectionToObject(asyncapiDocument.components().schemas().all(), 'id'),
objectSchema: convertCollectionToObject(asyncapiDocument.schemas().all().filter(schema => schema.type() === 'object'), 'id'),
parameter: convertMapToObject(this.getAllParameters(asyncapiDocument)),
everySchema: convertCollectionToObject(asyncapiDocument.schemas().all(), 'id'),
};
} else {
const objectSchema = {};
asyncapiDocument.allSchemas().forEach((schema, schemaId) => { if (schema.type() === 'object') objectSchema[schemaId] = schema; });
fileNamesForSeparation = {
channel: asyncapiDocument.channels(),
message: convertMapToObject(asyncapiDocument.allMessages()),
securityScheme: asyncapiDocument.components() ? asyncapiDocument.components().securitySchemes() : {},
schema: asyncapiDocument.components() ? asyncapiDocument.components().schemas() : {},
objectSchema,
parameter: convertMapToObject(this.getAllParameters(asyncapiDocument)),
everySchema: convertMapToObject(asyncapiDocument.allSchemas()),
};
}
// Check if the filename dictates it should be separated
let wasSeparated = false;
for (const prop in fileNamesForSeparation) {
if (Object.hasOwn(fileNamesForSeparation, prop) && stats.name.includes(`$$${prop}$$`)) {
await this.generateSeparateFiles(asyncapiDocument, fileNamesForSeparation[prop], prop, stats.name, root);
const templateFilePath = path.relative(this.templateContentDir, path.resolve(root, stats.name));
fs.unlink(path.resolve(this.targetDir, templateFilePath), next);
wasSeparated = true;
//The filename can only contain 1 specifier (message, scheme etc)
break;
}
}
// If it was not separated process normally
if (!wasSeparated) {
await this.generateFile(asyncapiDocument, stats.name, root);
next();
}
}
|
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.
@param {Function} next Callback function
|
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));
});
return Promise.all(promises);
}
|
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 file to generate for each security schema.
@param {String} baseDir Base directory of the given file name.
@returns {Promise}
|
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)) {
const filenamesFromHooks = await this.launchHook(setFileTemplateNameHookName, { originalFilename: filename });
//Use the result of the first hook
filename = filenamesFromHooks[0];
} else {
filename = filenamify(filename, { replacement: '-', maxLength: 255 });
}
const newFileName = fileName.replace(`\$\$${template}\$\$`, filename);
const targetFile = path.resolve(this.targetDir, relativeBaseDir, newFileName);
const relativeTargetFile = path.relative(this.targetDir, targetFile);
const shouldOverwriteFile = await this.shouldOverwriteFile(relativeTargetFile);
if (!shouldOverwriteFile) return;
//Ensure the same object are parsed to the renderFile method as before.
const temp = {};
const key = template === 'everySchema' || template === 'objectSchema' ? 'schema' : template;
temp[`${key}Name`] = name;
temp[key] = component;
await this.renderAndWriteToFile(asyncapiDocument, path.resolve(baseDir, fileName), targetFile, temp);
}
|
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 template filename to replace.
@param {String} fileName Name of the file to generate for each security schema.
@param {String} baseDir Base directory of the given file name.
@returns {Promise}
|
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 saveRenderedReactContent(renderContent, outputpath, this.noOverwriteGlobs);
} else {
await writeFile(outputpath, renderContent);
}
}
|
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] Extra data to pass to the template.
|
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(this.targetDir, this.maybeRenameSourceFile(relativeSourceFile));
const relativeTargetFile = path.relative(this.targetDir, targetFile);
let shouldGenerate = true;
if (shouldIgnoreFile(relativeSourceFile)) return;
if (!(await this.shouldOverwriteFile(relativeTargetFile))) return;
// conditionalFiles becomes deprecated with this PR, and soon will be removed.
// TODO: https://github.com/asyncapi/generator/issues/1553
let conditionalPath = '';
if (
this.templateConfig.conditionalFiles &&
this.templateConfig.conditionalGeneration
) {
log.debug(
'Both \'conditionalFiles\' and \'conditionalGeneration\' are defined. Ignoring \'conditionalFiles\' and using \'conditionalGeneration\' only.'
);
}
if (this.templateConfig.conditionalGeneration?.[relativeSourceDirectory]) {
conditionalPath = relativeSourceDirectory;
} else if (this.templateConfig.conditionalGeneration?.[relativeSourceFile]) {
conditionalPath = relativeSourceFile;
} else
if (this.templateConfig.conditionalFiles?.[relativeSourceFile]) {
// conditionalFiles becomes deprecated with this PR, and soon will be removed.
// TODO: https://github.com/asyncapi/generator/issues/1553
conditionalPath = relativeSourceDirectory;
}
if (conditionalPath) {
shouldGenerate = await isGenerationConditionMet(
this.templateConfig,
conditionalPath,
this.templateParams,
asyncapiDocument
);
}
if (!shouldGenerate) {
if (this.templateConfig.conditionalFiles?.[relativeSourceFile]) {
// conditionalFiles becomes deprecated with this PR, and soon will be removed.
// TODO: https://github.com/asyncapi/generator/issues/1553
return log.debug(logMessage.conditionalFilesMatched(relativeSourceFile));
}
return log.debug(logMessage.conditionalGenerationMatched(conditionalPath));
}
if (this.isNonRenderableFile(relativeSourceFile)) return await copyFile(sourceFile, targetFile);
await this.renderAndWriteToFile(asyncapiDocument, sourceFile, targetFile);
log.debug(`Successfully rendered template and wrote file ${relativeSourceFile} to location: ${targetFile}`);
}
|
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 name
|
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.originalAsyncAPI);
}
const templateString = await readFile(filePath, 'utf8');
return renderNunjucks(asyncapiDocument, templateString, filePath, extraTemplateData, this.templateParams, this.originalAsyncAPI, this.nunjucks);
}
|
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|Array<TemplateRenderResult>|undefined>}
|
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, {
enumerable: true,
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
|
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 = hooks.map(async (hook) => {
if (typeof hook !== 'function') return;
if (disabledHooks.includes(hook.name)) return;
return await hook(this, hookArguments);
}).filter(Boolean);
return Promise.all(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 = [disabledHooks];
return !!hooks.filter(h => !disabledHooks.includes(h.name)).length;
}
|
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 workDir inside repo is declared in .gitignore
const workDir = path.relative(root, dir);
if (workDir) {
const checkGitIgnore = await gitInfo.checkIgnore(workDir);
if (checkGitIgnore.length !== 0) return;
}
const gitStatus = await gitInfo.status();
//New files are not tracked and not visible as modified
const hasUntrackedUnstagedFiles = gitStatus.not_added.length !== 0;
const stagedFiles = gitStatus.staged;
const modifiedFiles = gitStatus.modified;
const hasModifiedUstagedFiles = (modifiedFiles.filter(e => stagedFiles.indexOf(e) === -1)).length !== 0;
if (hasModifiedUstagedFiles || hasUntrackedUnstagedFiles) throw new Error(`"${this.targetDir}" is in a git repository with unstaged changes. Please commit your changes before proceeding or add proper directory to .gitignore file. You can also use the --force-write flag to skip this rule (not recommended).`);
} else {
const isDirEmpty = (await readDir(dir)).length === 0;
if (!isDirEmpty) throw new Error(`"${this.targetDir}" is not an empty directory. You might override your work. To skip this rule, please make your code a git repository or use the --force-write flag (not recommended).`);
}
}
|
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 hooks are located.
|
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
});
walker.on('file', async (root, stats, next) => {
try {
const filePath = path.resolve(templateDir, path.resolve(root, stats.name));
registerTypeScript(filePath);
delete require.cache[require.resolve(filePath)];
const mod = require(filePath);
addHook(hooks, mod);
next();
} catch (e) {
reject(e);
}
});
walker.on('errors', (root, nodeStatsArray) => {
reject(nodeStatsArray);
});
walker.on('end', async () => {
resolve(hooks);
});
});
}
|
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 hooksModuleName => {
let mod;
try {
//first we try to grab module with hooks by the module name
//this is when generation is used on production using remote templates
mod = require(hooksModuleName);
} catch (error) {
//in case template is local but was not installed in node_modules of the generator then we need to explicitly provide modules location
mod = require(path.resolve(templateDir, DEFAULT_MODULES_DIR, hooksModuleName));
}
const configHooksArray = [].concat(configHooks[hooksModuleName]);
addHook(hooks, mod, configHooksArray);
});
await Promise.all(promises);
return hooks;
}
|
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).forEach(hookType => {
const moduleHooksArray = [].concat(mod[hookType]);
moduleHooksArray.forEach(hook => {
if (config && !config.includes(hook.name)) return;
hooks[hookType] = hooks[hookType] || [];
hooks[hookType].push(hook);
});
});
return hooks;
}
|
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 configured in template configuration
|
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 resolvers = [];
if (generator?.mapBaseUrlToFolder?.url) {
resolvers.push(...getMapBaseUrlToFolderResolvers(generator.mapBaseUrlToFolder));
}
if (oldOptions.resolve) {
resolvers.push(...convertOldResolvers(oldOptions.resolve));
}
if (resolvers.length) {
newOptions.__unstable = {};
newOptions.__unstable.resolver = {
resolvers,
};
}
return newOptions;
}
|
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.readFile(localpath, (err, data) => {
if (err) {
reject(`Error opening file "${localpath}"`);
} else {
resolve(data.toString());
}
});
} catch (err) {
reject(`Error opening file "${localpath}"`);
}
}));
}
};
return [
{ schema: 'http', ...resolver, },
{ schema: 'https', ...resolver, },
];
}
|
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/.
@return {{read(*, *, *): Promise<unknown>, canRead(*): boolean, order: number}}
|
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 {
resolve(data.toString());
}
});
} catch (err) {
reject(`Error opening file "${localpath}"`);
}
}));
}
|
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/.
@return {{read(*, *, *): Promise<unknown>, canRead(*): boolean, order: number}}
|
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: (uri) => {
return resolver.read({ url: uri.valueOf(), extension: uri.suffix() });
}
};
});
}
|
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/.
@return {{read(*, *, *): Promise<unknown>, canRead(*): boolean, order: number}}
|
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 canRead === 'function') {
return canRead({ url: value, extension: uri.suffix() });
}
return false;
}
|
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/.
@return {{read(*, *, *): Promise<unknown>, canRead(*): boolean, order: number}}
|
canReadFn
|
javascript
|
asyncapi/generator
|
apps/generator/lib/parser.js
|
https://github.com/asyncapi/generator/blob/master/apps/generator/lib/parser.js
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.