code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
module.exports = function fastPartialConstructor (fn) {
var boundLength = arguments.length - 1,
boundArgs;
boundArgs = new Array(boundLength);
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = arguments[i + 1];
}
return function partialed () {
var length = arguments.length,
args = new Array(boundLength + length),
i;
for (i = 0; i < boundLength; i++) {
args[i] = boundArgs[i];
}
for (i = 0; i < length; i++) {
args[boundLength + i] = arguments[i];
}
var thisContext = Object.create(fn.prototype),
result = applyWithContext(fn, thisContext, args);
if (result != null && (typeof result === 'object' || typeof result === 'function')) {
return result;
}
else {
return thisContext;
}
};
}; | # Partial Constructor
Partially apply a constructor function. The returned function
will work with or without the `new` keyword.
@param {Function} fn The constructor function to partially apply.
@param {mixed} args, ... Arguments to pre-bind.
@return {Function} The partially applied constructor. | fastPartialConstructor ( fn ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastTry (fn) {
try {
return fn();
}
catch (e) {
if (!(e instanceof Error)) {
return new Error(e);
}
else {
return e;
}
}
}; | # Try
Allows functions to be optimised by isolating `try {} catch (e) {}` blocks
outside the function declaration. Returns either the result of the function or an Error
object if one was thrown. The caller should then check for `result instanceof Error`.
```js
var result = fast.try(myFunction);
if (result instanceof Error) {
console.log('something went wrong');
}
else {
console.log('result:', result);
}
```
@param {Function} fn The function to invoke.
@return {mixed} The result of the function, or an `Error` object. | fastTry ( fn ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastAssign (target) {
var totalArgs = arguments.length,
source, i, totalKeys, keys, key, j;
for (i = 1; i < totalArgs; i++) {
source = arguments[i];
keys = Object.keys(source);
totalKeys = keys.length;
for (j = 0; j < totalKeys; j++) {
key = keys[j];
target[key] = source[key];
}
}
return target;
}; | Analogue of Object.assign().
Copies properties from one or more source objects to
a target object. Existing keys on the target object will be overwritten.
> Note: This differs from spec in some important ways:
> 1. Will throw if passed non-objects, including `undefined` or `null` values.
> 2. Does not support the curious Exception handling behavior, exceptions are thrown immediately.
> For more details, see:
> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
@param {Object} target The target object to copy properties to.
@param {Object} source, ... The source(s) to copy properties from.
@return {Object} The updated target object. | fastAssign ( target ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastCloneObject (input) {
var keys = Object.keys(input),
total = keys.length,
cloned = {},
i, key;
for (i = 0; i < total; i++) {
key = keys[i];
cloned[key] = input[key];
}
return cloned;
}; | # Clone Object
Shallow clone a simple object.
> Note: Prototypes and non-enumerable properties will not be copied!
@param {Object} input The object to clone.
@return {Object} The cloned object. | fastCloneObject ( input ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastFilterObject (subject, fn, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
result = {},
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
i, key;
for (i = 0; i < length; i++) {
key = keys[i];
if (iterator(subject[key], key, subject)) {
result[key] = subject[key];
}
}
return result;
}; | # Filter
A fast object `.filter()` implementation.
@param {Object} subject The object to filter.
@param {Function} fn The filter function.
@param {Object} thisContext The context for the filter.
@return {Object} The new object containing the filtered results. | fastFilterObject ( subject , fn , thisContext ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastForEachObject (subject, fn, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
key, i;
for (i = 0; i < length; i++) {
key = keys[i];
iterator(subject[key], key, subject);
}
}; | # For Each
A fast object `.forEach()` implementation.
@param {Object} subject The object to iterate over.
@param {Function} fn The visitor function.
@param {Object} thisContext The context for the visitor. | fastForEachObject ( subject , fn , thisContext ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastMapObject (subject, fn, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
result = {},
iterator = thisContext !== undefined ? bindInternal3(fn, thisContext) : fn,
i, key;
for (i = 0; i < length; i++) {
key = keys[i];
result[key] = iterator(subject[key], key, subject);
}
return result;
}; | # Map
A fast object `.map()` implementation.
@param {Object} subject The object to map over.
@param {Function} fn The mapper function.
@param {Object} thisContext The context for the mapper.
@return {Object} The new object containing the results. | fastMapObject ( subject , fn , thisContext ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastReduceObject (subject, fn, initialValue, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,
i, key, result;
if (initialValue === undefined) {
i = 1;
result = subject[keys[0]];
}
else {
i = 0;
result = initialValue;
}
for (; i < length; i++) {
key = keys[i];
result = iterator(result, subject[key], key, subject);
}
return result;
}; | # Reduce
A fast object `.reduce()` implementation.
@param {Object} subject The object to reduce over.
@param {Function} fn The reducer function.
@param {mixed} initialValue The initial value for the reducer, defaults to subject[0].
@param {Object} thisContext The context for the reducer.
@return {mixed} The final result. | fastReduceObject ( subject , fn , initialValue , thisContext ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastValues (obj) {
var keys = Object.keys(obj),
length = keys.length,
values = new Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
}; | # Values
Return all the (enumerable) property values for an object.
Like Object.keys() but for values.
@param {Object} obj The object to retrieve values from.
@return {Array} An array containing property values. | fastValues ( obj ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
module.exports = function fastIntern (string) {
container[string] = true;
var interned = Object.keys(container)[0];
delete container[interned];
return interned;
}; | Intern a string to make comparisons faster.
> Note: This is a relatively expensive operation, you
shouldn't usually do the actual interning at runtime, instead
use this at compile time to make future work faster.
@param {String} string The string to intern.
@return {String} The interned string. | fastIntern ( string ) | javascript | codemix/fast.js | dist/fast.js | https://github.com/codemix/fast.js/blob/master/dist/fast.js | MIT |
exports.fns = function () {
var length = arguments.length,
args = new Array(length),
fns = new Array(20),
i;
for (i = 0; i < length; i++) {
args[i] = arguments[i];
}
for (i = 0; i < 20; i++) {
fns[i] = Function.apply(null, args);
}
var pointer = -1;
return function () {
if (pointer++ > 20) {
pointer = 0;
}
return fns[pointer % 20];
};
}; | Function factory.
Accepts the same arguments as the Function constructor, creates 20 duplicate
but unique instances of the function and returns a function which will infinitely
return each function in a cycle.
This is used to ensure that the benchmarks do not only measure monomorphic performance.
@return {Function} A function which will keep on returning the defined functions. | exports.fns ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
support.iteratesOwnFirst = (function() {
var props = [];
function ctor() { this.x = 1; }
ctor.prototype = { 'y': 1 };
for (var prop in new ctor) { props.push(prop); }
return props[0] == 'x';
}()); | Detect if own properties are iterated before inherited properties (all but IE < 9).
@name iteratesOwnLast
@memberOf Benchmark.support
@type Boolean | (anonymous) ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function Benchmark(name, fn, options) {
var me = this;
// allow instance creation without the `new` operator
if (me == null || me.constructor != Benchmark) {
return new Benchmark(name, fn, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
}
else if (isClassOf(name, 'Function')) {
// 2 arguments (fn, options)
options = fn;
fn = name;
}
else if (isClassOf(fn, 'Object')) {
// 2 arguments (name, options)
options = fn;
fn = null;
me.name = name;
}
else {
// 3 arguments (name, fn [, options])
me.name = name;
}
setOptions(me, options);
me.id || (me.id = ++counter);
me.fn == null && (me.fn = fn);
me.stats = deepClone(me.stats);
me.times = deepClone(me.times);
} | The Benchmark constructor.
@constructor
@param {String} name A name to identify the benchmark.
@param {Function|String} fn The test to benchmark.
@param {Object} [options={}] Options object.
@example
// basic usage (the `new` operator is optional)
var bench = new Benchmark(fn);
// or using a name first
var bench = new Benchmark('foo', fn);
// or with options
var bench = new Benchmark('foo', fn, {
// displayed by Benchmark#toString if `name` is not available
'id': 'xyz',
// called when the benchmark starts running
'onStart': onStart,
// called after each run cycle
'onCycle': onCycle,
// called when aborted
'onAbort': onAbort,
// called when a test errors
'onError': onError,
// called when reset
'onReset': onReset,
// called when the benchmark completes running
'onComplete': onComplete,
// compiled/called before the test loop
'setup': setup,
// compiled/called after the test loop
'teardown': teardown
});
// or name and options
var bench = new Benchmark('foo', {
// a flag to indicate the benchmark is deferred
'defer': true,
// benchmark test function
'fn': function(deferred) {
// call resolve() when the deferred test is finished
deferred.resolve();
}
});
// or options only
var bench = new Benchmark({
// benchmark name
'name': 'foo',
// benchmark test as a string
'fn': '[1,2,3,4].sort()'
});
// a test's `this` binding is set to the benchmark instance
var bench = new Benchmark('foo', function() {
'My name is '.concat(this.name); // My name is foo
}); | Benchmark ( name , fn , options ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function Deferred(clone) {
var me = this;
if (me == null || me.constructor != Deferred) {
return new Deferred(clone);
}
me.benchmark = clone;
clock(me);
} | The Deferred constructor.
@constructor
@memberOf Benchmark
@param {Object} clone The cloned benchmark instance. | Deferred ( clone ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function Event(type) {
var me = this;
return (me == null || me.constructor != Event)
? new Event(type)
: (type instanceof Event)
? type
: extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type);
} | The Event constructor.
@constructor
@memberOf Benchmark
@param {String|Object} type The event type. | Event ( type ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function Suite(name, options) {
var me = this;
// allow instance creation without the `new` operator
if (me == null || me.constructor != Suite) {
return new Suite(name, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
} else {
// 2 arguments (name [, options])
me.name = name;
}
setOptions(me, options);
} | The Suite constructor.
@constructor
@memberOf Benchmark
@param {String} name A name to identify the suite.
@param {Object} [options={}] Options object.
@example
// basic usage (the `new` operator is optional)
var suite = new Benchmark.Suite;
// or using a name first
var suite = new Benchmark.Suite('foo');
// or with options
var suite = new Benchmark.Suite('foo', {
// called when the suite starts running
'onStart': onStart,
// called between running benchmarks
'onCycle': onCycle,
// called when aborted
'onAbort': onAbort,
// called when a test errors
'onError': onError,
// called when reset
'onReset': onReset,
// called when the suite completes running
'onComplete': onComplete
}); | Suite ( name , options ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function concat() {
var value,
j = -1,
length = arguments.length,
result = slice.call(this),
index = result.length;
while (++j < length) {
value = arguments[j];
if (isClassOf(value, 'Array')) {
for (var k = 0, l = value.length; k < l; k++, index++) {
if (k in value) {
result[index] = value[k];
}
}
} else {
result[index++] = value;
}
}
return result;
} | Creates an array containing the elements of the host array followed by the
elements of each argument in order.
@memberOf Benchmark.Suite
@returns {Array} The new array. | concat ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function insert(start, deleteCount, elements) {
// `result` should have its length set to the `deleteCount`
// see https://bugs.ecmascript.org/show_bug.cgi?id=332
var deleteEnd = start + deleteCount,
elementCount = elements ? elements.length : 0,
index = start - 1,
length = start + elementCount,
object = this,
result = Array(deleteCount),
tail = slice.call(object, deleteEnd);
// delete elements from the array
while (++index < deleteEnd) {
if (index in object) {
result[index - start] = object[index];
delete object[index];
}
}
// insert elements
index = start - 1;
while (++index < length) {
object[index] = elements[index - start];
}
// append tail elements
start = index--;
length = max(0, (object.length >>> 0) - deleteCount + elementCount);
while (++index < length) {
if ((index - start) in tail) {
object[index] = tail[index - start];
} else if (index in object) {
delete object[index];
}
}
// delete excess elements
deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
while (deleteCount--) {
index = length + deleteCount;
if (index in object) {
delete object[index];
}
}
object.length = length;
return result;
} | Utility function used by `shift()`, `splice()`, and `unshift()`.
@private
@param {Number} start The index to start inserting elements.
@param {Number} deleteCount The number of elements to delete from the insert point.
@param {Array} elements The elements to insert.
@returns {Array} An array of deleted elements. | insert ( start , deleteCount , elements ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function reverse() {
var upperIndex,
value,
index = -1,
object = Object(this),
length = object.length >>> 0,
middle = floor(length / 2);
if (length > 1) {
while (++index < middle) {
upperIndex = length - index - 1;
value = upperIndex in object ? object[upperIndex] : uid;
if (index in object) {
object[upperIndex] = object[index];
} else {
delete object[upperIndex];
}
if (value != uid) {
object[index] = value;
} else {
delete object[index];
}
}
}
return object;
} | Rearrange the host array's elements in reverse order.
@memberOf Benchmark.Suite
@returns {Array} The reversed array. | reverse ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function shift() {
return insert.call(this, 0, 1)[0];
} | Removes the first element of the host array and returns it.
@memberOf Benchmark.Suite
@returns {Mixed} The first element of the array. | shift ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function slice(start, end) {
var index = -1,
object = Object(this),
length = object.length >>> 0,
result = [];
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
start--;
end = end == null ? length : toInteger(end);
end = end < 0 ? max(length + end, 0) : min(end, length);
while ((++index, ++start) < end) {
if (start in object) {
result[index] = object[start];
}
}
return result;
} | Creates an array of the host array's elements from the start index up to,
but not including, the end index.
@memberOf Benchmark.Suite
@param {Number} start The starting index.
@param {Number} end The end index.
@returns {Array} The new array. | slice ( start , end ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function splice(start, deleteCount) {
var object = Object(this),
length = object.length >>> 0;
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
// support the de-facto SpiderMonkey extension
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters
// https://bugs.ecmascript.org/show_bug.cgi?id=429
deleteCount = arguments.length == 1
? length - start
: min(max(toInteger(deleteCount), 0), length - start);
return insert.call(object, start, deleteCount, slice.call(arguments, 2));
} | Allows removing a range of elements and/or inserting elements into the
host array.
@memberOf Benchmark.Suite
@param {Number} start The start index.
@param {Number} deleteCount The number of elements to delete.
@param {Mixed} [val1, val2, ...] values to insert at the `start` index.
@returns {Array} An array of removed elements. | splice ( start , deleteCount ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function toInteger(value) {
value = +value;
return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
} | Converts the specified `value` to an integer.
@private
@param {Mixed} value The value to convert.
@returns {Number} The resulting integer. | toInteger ( value ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function unshift() {
var object = Object(this);
insert.call(object, 0, 0, arguments);
return object.length;
} | Appends arguments to the host array.
@memberOf Benchmark.Suite
@returns {Number} The new length. | unshift ( ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function bind(fn, thisArg) {
return function() { fn.apply(thisArg, arguments); };
} | A generic `Function#bind` like method.
@private
@param {Function} fn The function to be bound to `thisArg`.
@param {Mixed} thisArg The `this` binding for the given function.
@returns {Function} The bound function. | bind ( fn , thisArg ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function delay(bench, fn) {
bench._timerId = setTimeout(fn, bench.delay * 1e3);
} | Delay the execution of a function based on the benchmark's `delay` property.
@private
@param {Object} bench The benchmark instance.
@param {Object} fn The function to execute. | delay ( bench , fn ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function destroyElement(element) {
trash.appendChild(element);
trash.innerHTML = '';
} | Destroys the given element.
@private
@param {Element} element The element to destroy. | destroyElement ( element ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function getFirstArgument(fn) {
return (!hasKey(fn, 'toString') &&
(/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || '';
} | Gets the name of the first argument from a function's source.
@private
@param {Function} fn The function.
@returns {String} The argument name. | getFirstArgument ( fn ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
function getMean(sample) {
return reduce(sample, function(sum, x) {
return sum + x;
}) / sample.length || 0;
} | Computes the arithmetic mean of a sample.
@private
@param {Array} sample The sample.
@returns {Number} The mean. | getMean ( sample ) | javascript | codemix/fast.js | dist/bench.js | https://github.com/codemix/fast.js/blob/master/dist/bench.js | MIT |
module.exports = function fastReduceRightObject (subject, fn, initialValue, thisContext) {
var keys = Object.keys(subject),
length = keys.length,
iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,
i, key, result;
if (initialValue === undefined) {
i = length - 2;
result = subject[keys[length - 1]];
}
else {
i = length - 1;
result = initialValue;
}
for (; i >= 0; i--) {
key = keys[i];
result = iterator(result, subject[key], key, subject);
}
return result;
}; | # Reduce Right
A fast object `.reduceRight()` implementation.
@param {Object} subject The object to reduce over.
@param {Function} fn The reducer function.
@param {mixed} initialValue The initial value for the reducer, defaults to subject[0].
@param {Object} thisContext The context for the reducer.
@return {mixed} The final result. | fastReduceRightObject ( subject , fn , initialValue , thisContext ) | javascript | codemix/fast.js | object/reduceRight.js | https://github.com/codemix/fast.js/blob/master/object/reduceRight.js | MIT |
function isNative( fn ) {
return rnative.test( fn + "" );
} | For feature detection
@param {Function} fn The function to test for native support | isNative ( fn ) | javascript | ZohaibAhmed/ChatGPT-Google | js/jquery/jquery.js | https://github.com/ZohaibAhmed/ChatGPT-Google/blob/master/js/jquery/jquery.js | MIT |
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
} | Checks document order of two siblings
@param {Element} a
@param {Element} b
@returns Returns -1 if a precedes b, 1 if a follows b | siblingCheck ( a , b ) | javascript | ZohaibAhmed/ChatGPT-Google | js/jquery/jquery.js | https://github.com/ZohaibAhmed/ChatGPT-Google/blob/master/js/jquery/jquery.js | MIT |
export default function swipeDetect(el, callback = () => {}) { | Mobile touch direction detect
@example
let el = document.getElementById('someElement');
swipeDetect(el, function(swipedir){
// swipedir contains either "none", "left", "right", "top", or "down"
if (swipedir =='left')
alert('You just swiped left!')
})
@export
@param {DOMElement} el
@param {function} callback | swipeDetect | javascript | devrsi0n/React-2048-game | src/utils/mobileEvents.js | https://github.com/devrsi0n/React-2048-game/blob/master/src/utils/mobileEvents.js | MIT |
const getDiscoverList = (params) => wxRequest(params, apiMall + '/emall/goods/list?cateidOne=1&cateidTwo=0&price=0&sales=2'); | 获取发现好商品接口
@param {[type]} params [description]
@return {[type]} [description] | getDiscoverList | javascript | dyq086/wepy-mall | src/api/api.js | https://github.com/dyq086/wepy-mall/blob/master/src/api/api.js | MIT |
function getDefaultOpts(simple) {
'use strict';
var defaultOptions = {
omitExtraWLInCodeBlocks: {
defaultValue: false,
describe: 'Omit the default extra whiteline added to code blocks',
type: 'boolean'
},
noHeaderId: {
defaultValue: false,
describe: 'Turn on/off generated header id',
type: 'boolean'
},
prefixHeaderId: {
defaultValue: false,
describe: 'Specify a prefix to generated header ids',
type: 'string'
},
headerLevelStart: {
defaultValue: false,
describe: 'The header blocks level start',
type: 'integer'
},
parseImgDimensions: {
defaultValue: false,
describe: 'Turn on/off image dimension parsing',
type: 'boolean'
},
simplifiedAutoLink: {
defaultValue: false,
describe: 'Turn on/off GFM autolink style',
type: 'boolean'
},
literalMidWordUnderscores: {
defaultValue: false,
describe: 'Parse midword underscores as literal underscores',
type: 'boolean'
},
strikethrough: {
defaultValue: false,
describe: 'Turn on/off strikethrough support',
type: 'boolean'
},
tables: {
defaultValue: false,
describe: 'Turn on/off tables support',
type: 'boolean'
},
tablesHeaderId: {
defaultValue: false,
describe: 'Add an id to table headers',
type: 'boolean'
},
ghCodeBlocks: {
defaultValue: true,
describe: 'Turn on/off GFM fenced code blocks support',
type: 'boolean'
},
tasklists: {
defaultValue: false,
describe: 'Turn on/off GFM tasklist support',
type: 'boolean'
},
smoothLivePreview: {
defaultValue: false,
describe: 'Prevents weird effects in live previews due to incomplete input',
type: 'boolean'
},
smartIndentationFix: {
defaultValue: false,
description: 'Tries to smartly fix identation in es6 strings',
type: 'boolean'
}
};
if (simple === false) {
return JSON.parse(JSON.stringify(defaultOptions));
}
var ret = {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
ret[opt] = defaultOptions[opt].defaultValue;
}
}
return ret;
} | showdown: https://github.com/showdownjs/showdown
author: Di (微信小程序开发工程师)
organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
垂直微信小程序开发交流社区
github地址: https://github.com/icindy/wxParse
for: 微信小程序富文本解析
detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184 | getDefaultOpts ( simple ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.setOption = function (key, value) {
'use strict';
globalOptions[key] = value;
return this;
}; | Set a global option
@static
@param {string} key
@param {*} value
@returns {showdown} | showdown.setOption ( key , value ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.getOption = function (key) {
'use strict';
return globalOptions[key];
}; | Get a global option
@static
@param {string} key
@returns {*} | showdown.getOption ( key ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.getOptions = function () {
'use strict';
return globalOptions;
}; | Get the global options
@static
@returns {{}} | showdown.getOptions ( ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.resetOptions = function () {
'use strict';
globalOptions = getDefaultOpts(true);
}; | Reset global options to the default values
@static | showdown.resetOptions ( ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.setFlavor = function (name) {
'use strict';
if (flavor.hasOwnProperty(name)) {
var preset = flavor[name];
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
globalOptions[option] = preset[option];
}
}
}
}; | Set the flavor showdown should use as default
@param {string} name | showdown.setFlavor ( name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.getDefaultOptions = function (simple) {
'use strict';
return getDefaultOpts(simple);
}; | Get the default options
@static
@param {boolean} [simple=true]
@returns {{}} | showdown.getDefaultOptions ( simple ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.subParser = function (name, func) {
'use strict';
if (showdown.helper.isString(name)) {
if (typeof func !== 'undefined') {
parsers[name] = func;
} else {
if (parsers.hasOwnProperty(name)) {
return parsers[name];
} else {
throw Error('SubParser named ' + name + ' not registered!');
}
}
}
}; | Get or set a subParser
subParser(name) - Get a registered subParser
subParser(name, func) - Register a subParser
@static
@param {string} name
@param {function} [func]
@returns {*} | showdown.subParser ( name , func ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.extension = function (name, ext) {
'use strict';
if (!showdown.helper.isString(name)) {
throw Error('Extension \'name\' must be a string');
}
name = showdown.helper.stdExtName(name);
// Getter
if (showdown.helper.isUndefined(ext)) {
if (!extensions.hasOwnProperty(name)) {
throw Error('Extension named ' + name + ' is not registered!');
}
return extensions[name];
// Setter
} else {
// Expand extension if it's wrapped in a function
if (typeof ext === 'function') {
ext = ext();
}
// Ensure extension is an array
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExtension = validate(ext, name);
if (validExtension.valid) {
extensions[name] = ext;
} else {
throw Error(validExtension.error);
}
}
}; | Gets or registers an extension
@static
@param {string} name
@param {object|function=} ext
@returns {*} | showdown.extension ( name , ext ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.getAllExtensions = function () {
'use strict';
return extensions;
}; | Gets all extensions registered
@returns {{}} | showdown.getAllExtensions ( ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.removeExtension = function (name) {
'use strict';
delete extensions[name];
}; | Remove an extension
@param {string} name | showdown.removeExtension ( name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
function validate(extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!ext.regex instanceof RegExp) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
} | Validate extension
@param {array} extension
@param {string} name
@returns {{valid: boolean, error: string}} | validate ( extension , name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.validateExtension = function (ext) {
'use strict';
var validateExtension = validate(ext, null);
if (!validateExtension.valid) {
console.warn(validateExtension.error);
return false;
}
return true;
}; | Validate extension
@param {object} ext
@returns {boolean} | showdown.validateExtension ( ext ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.isString = function isString(a) {
'use strict';
return (typeof a === 'string' || a instanceof String);
}; | Check if var is string
@static
@param {string} a
@returns {boolean} | isString ( a ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.isFunction = function isFunction(a) {
'use strict';
var getType = {};
return a && getType.toString.call(a) === '[object Function]';
}; | Check if var is a function
@static
@param {string} a
@returns {boolean} | isFunction ( a ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.forEach = function forEach(obj, callback) {
'use strict';
if (typeof obj.forEach === 'function') {
obj.forEach(callback);
} else {
for (var i = 0; i < obj.length; i++) {
callback(obj[i], i, obj);
}
}
}; | ForEach helper function
@static
@param {*} obj
@param {function} callback | forEach ( obj , callback ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.isArray = function isArray(a) {
'use strict';
return a.constructor === Array;
}; | isArray helper function
@static
@param {*} a
@returns {boolean} | isArray ( a ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.isUndefined = function isUndefined(value) {
'use strict';
return typeof value === 'undefined';
}; | Check if value is undefined
@static
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is `undefined`, else `false`. | isUndefined ( value ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.stdExtName = function (s) {
'use strict';
return s.replace(/[_-]||\s/g, '').toLowerCase();
}; | Standardidize extension name
@static
@param {string} s extension name
@returns {string} | showdown.helper.stdExtName ( s ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.escapeCharacters = function escapeCharacters(text, charsToEscape, afterBackslash) {
'use strict';
// First we have to escape the escape characters so that
// we can build a character class out of them
var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
if (afterBackslash) {
regexString = '\\\\' + regexString;
}
var regex = new RegExp(regexString, 'g');
text = text.replace(regex, escapeCharactersCallback);
return text;
}; | Escape characters in a string
@static
@param {string} text
@param {string} charsToEscape
@param {boolean} afterBackslash
@returns {XML|string|void|*} | escapeCharacters ( text , charsToEscape , afterBackslash ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {
'use strict';
var matchPos = rgxFindMatchPos (str, left, right, flags),
results = [];
for (var i = 0; i < matchPos.length; ++i) {
results.push([
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
]);
}
return results;
}; | matchRecursiveRegExp
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT License
Accepts a string to search, a left and right format delimiter
as regex patterns, and optional regex flags. Returns an array
of matches, allowing nested instances of left/right delimiters.
Use the "g" flag to return all matches, otherwise only the
first is returned. Be careful to ensure that the left and
right format delimiters produce mutually exclusive matches.
Backreferences are not supported within the right delimiter
due to how it is internally combined with the left delimiter.
When matching strings whose format delimiters are unbalanced
to the left or right, the output is intentionally as a
conventional regex library with recursion support would
produce, e.g. "<<x>" and "<x>>" both produce ["x"] when using
"<" and ">" as the delimiters (both strings contain a single,
balanced instance of "<x>").
examples:
matchRecursiveRegExp("test", "\\(", "\\)")
returns: []
matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
returns: ["t<<e>><s>", ""]
matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
returns: ["test"] | showdown.helper.matchRecursiveRegExp ( str , left , right , flags ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
'use strict';
if (!showdown.helper.isFunction(replacement)) {
var repStr = replacement;
replacement = function () {
return repStr;
};
}
var matchPos = rgxFindMatchPos(str, left, right, flags),
finalStr = str,
lng = matchPos.length;
if (lng > 0) {
var bits = [];
if (matchPos[0].wholeMatch.start !== 0) {
bits.push(str.slice(0, matchPos[0].wholeMatch.start));
}
for (var i = 0; i < lng; ++i) {
bits.push(
replacement(
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
)
);
if (i < lng - 1) {
bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
}
}
if (matchPos[lng - 1].wholeMatch.end < str.length) {
bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
}
finalStr = bits.join('');
}
return finalStr;
}; | @param {string} str
@param {string|function} replacement
@param {string} left
@param {string} right
@param {string} flags
@returns {string} | showdown.helper.replaceRecursiveRegExp ( str , replacement , left , right , flags ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
function _parseExtension(ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty(listeners)) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
} | Parse extension
@param {*} ext
@param {string} [name='']
@private | _parseExtension ( ext , name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
function legacyExtensionLoading(ext, name) {
if (typeof ext === 'function') {
ext = ext(new showdown.Converter());
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var valid = validate(ext, name);
if (!valid.valid) {
throw Error(valid.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
default:// should never reach here
throw Error('Extension loader error: Type unrecognized!!!');
}
}
} | LEGACY_SUPPORT
@param {*} ext
@param {string} name | legacyExtensionLoading ( ext , name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
function listen(name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
} | Listen to an event
@param {string} name
@param {function} callback | listen ( name , callback ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this._dispatch = function dispatch (evtName, text, options, globals) {
if (listeners.hasOwnProperty(evtName)) {
for (var ei = 0; ei < listeners[evtName].length; ++ei) {
var nText = listeners[evtName][ei](evtName, text, this, options, globals);
if (nText && typeof nText !== 'undefined') {
text = nText;
}
}
}
return text;
}; | Dispatch an event
@private
@param {string} evtName Event name
@param {string} text Text
@param {{}} options Converter Options
@param {{}} globals
@returns {string} | dispatch ( evtName , text , options , globals ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.listen = function (name, callback) {
listen(name, callback);
return this;
}; | Listen to an event
@param {string} name
@param {function} callback
@returns {showdown.Converter} | this.listen ( name , callback ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.makeHtml = function (text) {
//check if text is not falsy
if (!text) {
return text;
}
var globals = {
gHtmlBlocks: [],
gHtmlMdBlocks: [],
gHtmlSpans: [],
gUrls: {},
gTitles: {},
gDimensions: {},
gListLevel: 0,
hashLinkCounts: {},
langExtensions: langExtensions,
outputModifiers: outputModifiers,
converter: this,
ghCodeBlocks: []
};
// attacklab: Replace ~ with ~T
// This lets us use tilde as an escape char to avoid md5 hashes
// The choice of character is arbitrary; anything that isn't
// magic in Markdown will work.
text = text.replace(/~/g, '~T');
// attacklab: Replace $ with ~D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\$/g, '~D');
// Standardize line endings
text = text.replace(/\r\n/g, '\n'); // DOS to Unix
text = text.replace(/\r/g, '\n'); // Mac to Unix
if (options.smartIndentationFix) {
text = rTrimInputText(text);
}
// Make sure text begins and ends with a couple of newlines:
//text = '\n\n' + text + '\n\n';
text = text;
// detab
text = showdown.subParser('detab')(text, options, globals);
// stripBlankLines
text = showdown.subParser('stripBlankLines')(text, options, globals);
//run languageExtensions
showdown.helper.forEach(langExtensions, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// run the sub parsers
text = showdown.subParser('hashPreCodeTags')(text, options, globals);
text = showdown.subParser('githubCodeBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLSpans')(text, options, globals);
text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
text = showdown.subParser('blockGamut')(text, options, globals);
text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
// attacklab: Restore dollar signs
text = text.replace(/~D/g, '$$');
// attacklab: Restore tildes
text = text.replace(/~T/g, '~');
// Run output modifiers
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
return text;
}; | Converts a markdown string into HTML
@param {string} text
@returns {*} | this.makeHtml ( text ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.setOption = function (key, value) {
options[key] = value;
}; | Set an option of this Converter instance
@param {string} key
@param {*} value | this.setOption ( key , value ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.getOption = function (key) {
return options[key];
}; | Get the option of this Converter instance
@param {string} key
@returns {*} | this.getOption ( key ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.getOptions = function () {
return options;
}; | Get the options of this Converter instance
@returns {{}} | this.getOptions ( ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.addExtension = function (extension, name) {
name = name || null;
_parseExtension(extension, name);
}; | Add extension to THIS converter
@param {{}} extension
@param {string} [name=null] | this.addExtension ( extension , name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
}; | Use a global registered extension with THIS converter
@param {string} extensionName Name of the previously registered extension | this.useExtension ( extensionName ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.setFlavor = function (name) {
if (flavor.hasOwnProperty(name)) {
var preset = flavor[name];
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
}
}
}
}; | Set the flavor THIS converter should use
@param {string} name | this.setFlavor ( name ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var a = 0; a < extension.length; ++a) {
var ext = extension[a];
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions[i].splice(i, 1);
}
}
for (var ii = 0; ii < outputModifiers.length; ++i) {
if (outputModifiers[ii] === ext) {
outputModifiers[ii].splice(i, 1);
}
}
}
}; | Remove an extension from THIS converter.
Note: This is a costly operation. It's better to initialize a new converter
and specify the extensions you wish to use
@param {Array} extension | this.removeExtension ( extension ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
this.getAllExtensions = function () {
return {
language: langExtensions,
output: outputModifiers
};
}; | Get all extension of THIS converter
@returns {{language: Array, output: Array}} | this.getAllExtensions ( ) | javascript | dyq086/wepy-mall | src/plugins/wxParse/showdown.js | https://github.com/dyq086/wepy-mall/blob/master/src/plugins/wxParse/showdown.js | MIT |
export function parseEnvironmentOptions(config) {
const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR');
const options = env?.SVELTE_INSPECTOR_OPTIONS;
const toggle = env?.SVELTE_INSPECTOR_TOGGLE;
if (options) {
try {
const parsed = JSON.parse(options);
const parsedType = typeof parsed;
if (parsedType === 'boolean') {
return parsed;
} else if (parsedType === 'object') {
if (Array.isArray(parsed)) {
throw new Error('invalid type, expected object map but got array');
}
const parsedKeys = Object.keys(parsed);
const defaultKeys = Object.keys(defaultInspectorOptions);
const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k));
if (unknownKeys.length) {
config.logger.warn(
`[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join(
', '
)}`
);
for (const key of unknownKeys) {
delete parsed[key];
}
}
debug('loaded environment config', parsed);
return parsed;
}
} catch (e) {
config.logger.error(
`[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}`
);
}
} else if (toggle) {
const keyConfig = {
toggleKeyCombo: toggle
};
debug('loaded environment config', keyConfig);
return keyConfig;
}
} | @param {import('vite').ResolvedConfig} config
@returns {Partial<import('./public.d.ts').Options> | boolean | void} | parseEnvironmentOptions ( config ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte-inspector/src/options.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte-inspector/src/options.js | MIT |
export function vitePreprocess(opts) {
/** @type {import('svelte/compiler').PreprocessorGroup} */
const preprocessor = { name: 'vite-preprocess' };
if (opts?.script === true) {
preprocessor.script = viteScript().script;
}
if (opts?.style !== false) {
const styleOpts = typeof opts?.style == 'object' ? opts?.style : undefined;
preprocessor.style = viteStyle(styleOpts).style;
}
return preprocessor;
} | @param {import('./public.d.ts').VitePreprocessOptions} [opts]
@returns {import('svelte/compiler').PreprocessorGroup} | vitePreprocess ( opts ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/preprocess.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/preprocess.js | MIT |
async function createCssTransform(style, config) {
/** @type {import('vite').ResolvedConfig} */
let resolvedConfig;
// @ts-expect-error special prop added if running in v-p-s
if (style.__resolvedConfig) {
// @ts-expect-error not typed
resolvedConfig = style.__resolvedConfig;
} else if (isResolvedConfig(config)) {
resolvedConfig = config;
} else {
// default to "build" if no NODE_ENV is set to avoid running in dev mode for svelte-check etc.
const useBuild = !process.env.NODE_ENV || process.env.NODE_ENV === 'production';
const command = useBuild ? 'build' : 'serve';
const defaultMode = useBuild ? 'production' : 'development';
resolvedConfig = await resolveConfig(config, command, defaultMode, defaultMode, false);
}
return async (code, filename) => {
return preprocessCSS(code, filename, resolvedConfig);
};
} | @param {import('svelte/compiler').Preprocessor} style
@param {import('vite').ResolvedConfig | import('vite').InlineConfig} config
@returns {Promise<CssTransform>} | createCssTransform ( style , config ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/preprocess.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/preprocess.js | MIT |
function isResolvedConfig(config) {
return !!config.inlineConfig;
} | @param {any} config
@returns {config is import('vite').ResolvedConfig} | isResolvedConfig ( config ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/preprocess.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/preprocess.js | MIT |
export async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) {
if (!cache.has(svelteRequest)) {
// file hasn't been requested yet (e.g. async component)
log.debug(
`handleHotUpdate called before initial transform for ${svelteRequest.id}`,
undefined,
'hmr'
);
return;
}
const { read, server, modules } = ctx;
const cachedJS = cache.getJS(svelteRequest);
const cachedCss = cache.getCSS(svelteRequest);
const content = await read();
/** @type {import('./types/compile.d.ts').CompileData} */
let compileData;
try {
compileData = await compileSvelte(svelteRequest, content, options);
cache.update(compileData);
} catch (e) {
cache.setError(svelteRequest, e);
throw toRollupError(e, options);
}
const affectedModules = [...modules];
const cssIdx = modules.findIndex((m) => m.id === svelteRequest.cssId);
if (cssIdx > -1) {
const cssUpdated = cssChanged(cachedCss, compileData.compiled.css);
if (!cssUpdated) {
log.debug(`skipping unchanged css for ${svelteRequest.cssId}`, undefined, 'hmr');
affectedModules.splice(cssIdx, 1);
}
}
const jsIdx = modules.findIndex((m) => m.id === svelteRequest.id);
if (jsIdx > -1) {
const jsUpdated = jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename);
if (!jsUpdated) {
log.debug(`skipping unchanged js for ${svelteRequest.id}`, undefined, 'hmr');
affectedModules.splice(jsIdx, 1);
// transform won't be called, log warnings here
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
}
}
// TODO is this enough? see also: https://github.com/vitejs/vite/issues/2274
const ssrModulesToInvalidate = affectedModules.filter((m) => !!m.ssrTransformResult);
if (ssrModulesToInvalidate.length > 0) {
log.debug(
`invalidating modules ${ssrModulesToInvalidate.map((m) => m.id).join(', ')}`,
undefined,
'hmr'
);
ssrModulesToInvalidate.forEach((moduleNode) => server.moduleGraph.invalidateModule(moduleNode));
}
if (affectedModules.length > 0) {
log.debug(
`handleHotUpdate for ${svelteRequest.id} result: ${affectedModules
.map((m) => m.id)
.join(', ')}`,
undefined,
'hmr'
);
}
return affectedModules;
} | Vite-specific HMR handling
@param {Function} compileSvelte
@param {import('vite').HmrContext} ctx
@param {import('./types/id.d.ts').SvelteRequest} svelteRequest
@param {import('./utils/vite-plugin-svelte-cache.js').VitePluginSvelteCache} cache
@param {import('./types/options.d.ts').ResolvedOptions} options
@returns {Promise<import('vite').ModuleNode[] | void>} | handleHotUpdate ( compileSvelte , ctx , svelteRequest , cache , options ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/handle-hot-update.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/handle-hot-update.js | MIT |
function cssChanged(prev, next) {
return !isCodeEqual(prev?.code, next?.code);
} | @param {import('./types/compile.d.ts').Code | null} [prev]
@param {import('./types/compile.d.ts').Code | null} [next]
@returns {boolean} | cssChanged ( prev , next ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/handle-hot-update.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/handle-hot-update.js | MIT |
function jsChanged(prev, next, filename) {
const prevJs = prev?.code;
const nextJs = next?.code;
const isStrictEqual = isCodeEqual(prevJs, nextJs);
if (isStrictEqual) {
return false;
}
const isLooseEqual = isCodeEqual(normalizeJsCode(prevJs), normalizeJsCode(nextJs));
if (!isStrictEqual && isLooseEqual) {
log.debug(
`ignoring compiler output js change for ${filename} as it is equal to previous output after normalization`,
undefined,
'hmr'
);
}
return !isLooseEqual;
} | @param {import('./types/compile.d.ts').Code | null} [prev]
@param {import('./types/compile.d.ts').Code | null} [next]
@param {string} [filename]
@returns {boolean} | jsChanged ( prev , next , filename ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/handle-hot-update.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/handle-hot-update.js | MIT |
function isCodeEqual(prev, next) {
if (!prev && !next) {
return true;
}
if ((!prev && next) || (prev && !next)) {
return false;
}
return prev === next;
} | @param {string} [prev]
@param {string} [next]
@returns {boolean} | isCodeEqual ( prev , next ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/handle-hot-update.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/handle-hot-update.js | MIT |
function normalizeJsCode(code) {
if (!code) {
return code;
}
return code.replace(/\s*\badd_location\s*\([^)]*\)\s*;?/g, '');
} | remove code that only changes metadata and does not require a js update for the component to keep working
1) add_location() calls. These add location metadata to elements, only used by some dev tools
2) ... maybe more (or less) in the future
@param {string} [code]
@returns {string | undefined} | normalizeJsCode ( code ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/handle-hot-update.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/handle-hot-update.js | MIT |
export function svelte(inlineOptions) {
if (process.env.DEBUG != null) {
log.setLevel('debug');
}
validateInlineOptions(inlineOptions);
const cache = new VitePluginSvelteCache();
// updated in configResolved hook
/** @type {import('./types/id.d.ts').IdParser} */
let requestParser;
/** @type {import('./types/id.d.ts').ModuleIdParser} */
let moduleRequestParser;
/** @type {import('./types/options.d.ts').ResolvedOptions} */
let options;
/** @type {import('vite').ResolvedConfig} */
let viteConfig;
/** @type {import('./types/compile.d.ts').CompileSvelte} */
let compileSvelte;
/** @type {import('./types/plugin-api.d.ts').PluginAPI} */
const api = {};
/** @type {import('vite').Plugin[]} */
const plugins = [
{
name: 'vite-plugin-svelte',
// make sure our resolver runs before vite internal resolver to resolve svelte field correctly
enforce: 'pre',
api,
async config(config, configEnv) {
// setup logger
if (process.env.DEBUG) {
log.setLevel('debug');
} else if (config.logLevel) {
log.setLevel(config.logLevel);
}
// @ts-expect-error temporarily lend the options variable until fixed in configResolved
options = await preResolveOptions(inlineOptions, config, configEnv);
// extra vite config
const extraViteConfig = await buildExtraViteConfig(options, config);
log.debug('additional vite config', extraViteConfig, 'config');
return extraViteConfig;
},
configEnvironment(name, config, opts) {
ensureConfigEnvironmentMainFields(name, config, opts);
// @ts-expect-error the function above should make `resolve.mainFields` non-nullable
config.resolve.mainFields.unshift('svelte');
ensureConfigEnvironmentConditions(name, config, opts);
// @ts-expect-error the function above should make `resolve.conditions` non-nullable
config.resolve.conditions.push('svelte');
},
async configResolved(config) {
options = resolveOptions(options, config, cache);
patchResolvedViteConfig(config, options);
requestParser = buildIdParser(options);
compileSvelte = createCompileSvelte();
viteConfig = config;
// TODO deep clone to avoid mutability from outside?
api.options = options;
log.debug('resolved options', options, 'config');
},
async buildStart() {
if (!options.prebundleSvelteLibraries) return;
const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options);
if (isSvelteMetadataChanged) {
// Force Vite to optimize again. Although we mutate the config here, it works because
// Vite's optimizer runs after `buildStart()`.
viteConfig.optimizeDeps.force = true;
}
},
configureServer(server) {
options.server = server;
setupWatchers(options, cache, requestParser);
},
async load(id, opts) {
const ssr = !!opts?.ssr;
const svelteRequest = requestParser(id, !!ssr);
if (svelteRequest) {
const { filename, query, raw } = svelteRequest;
if (raw) {
const code = await loadRaw(svelteRequest, compileSvelte, options);
// prevent vite from injecting sourcemaps in the results.
return {
code,
map: {
mappings: ''
}
};
} else {
if (query.svelte && query.type === 'style') {
const css = cache.getCSS(svelteRequest);
if (css) {
return css;
}
}
// prevent vite asset plugin from loading files as url that should be compiled in transform
if (viteConfig.assetsInclude(filename)) {
log.debug(`load returns raw content for ${filename}`, undefined, 'load');
return fs.readFileSync(filename, 'utf-8');
}
}
}
},
async resolveId(importee, importer, opts) {
const ssr = !!opts?.ssr;
const svelteRequest = requestParser(importee, ssr);
if (svelteRequest?.query.svelte) {
if (
svelteRequest.query.type === 'style' &&
!svelteRequest.raw &&
!svelteRequest.query.inline
) {
// return cssId with root prefix so postcss pipeline of vite finds the directory correctly
// see https://github.com/sveltejs/vite-plugin-svelte/issues/14
log.debug(
`resolveId resolved virtual css module ${svelteRequest.cssId}`,
undefined,
'resolve'
);
return svelteRequest.cssId;
}
}
},
async transform(code, id, opts) {
const ssr = !!opts?.ssr;
const svelteRequest = requestParser(id, ssr);
if (!svelteRequest || svelteRequest.query.type === 'style' || svelteRequest.raw) {
return;
}
let compileData;
try {
compileData = await compileSvelte(svelteRequest, code, options);
} catch (e) {
cache.setError(svelteRequest, e);
throw toRollupError(e, options);
}
logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
cache.update(compileData);
if (compileData.dependencies?.length) {
if (options.server) {
for (const dep of compileData.dependencies) {
ensureWatchedFile(options.server.watcher, dep, options.root);
}
} else if (options.isBuild && viteConfig.build.watch) {
for (const dep of compileData.dependencies) {
this.addWatchFile(dep);
}
}
}
return {
...compileData.compiled.js,
meta: {
vite: {
lang: compileData.lang
}
}
};
},
handleHotUpdate(ctx) {
if (!options.compilerOptions.hmr || !options.emitCss) {
return;
}
const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
if (svelteRequest) {
return handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options);
}
},
async buildEnd() {
await options.stats?.finishAll();
}
},
{
name: 'vite-plugin-svelte-module',
enforce: 'post',
async configResolved() {
moduleRequestParser = buildModuleIdParser(options);
},
async transform(code, id, opts) {
const ssr = !!opts?.ssr;
const moduleRequest = moduleRequestParser(id, ssr);
if (!moduleRequest) {
return;
}
try {
const compileResult = svelteCompiler.compileModule(code, {
dev: !viteConfig.isProduction,
generate: ssr ? 'server' : 'client',
filename: moduleRequest.filename
});
logCompilerWarnings(moduleRequest, compileResult.warnings, options);
return compileResult.js;
} catch (e) {
throw toRollupError(e, options);
}
}
},
svelteInspector()
];
return plugins;
} | @param {Partial<import('./public.d.ts').Options>} [inlineOptions]
@returns {import('vite').Plugin[]} | svelte ( inlineOptions ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/index.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/index.js | MIT |
function buildExtraPreprocessors(options, config) {
/** @type {import('svelte/compiler').PreprocessorGroup[]} */
const prependPreprocessors = [];
/** @type {import('svelte/compiler').PreprocessorGroup[]} */
const appendPreprocessors = [];
// @ts-expect-error not typed
const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p?.sveltePreprocess);
if (pluginsWithPreprocessorsDeprecated.length > 0) {
log.warn(
`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated
.map((p) => p.name)
.join(', ')}`
);
// patch plugin to avoid breaking
pluginsWithPreprocessorsDeprecated.forEach((p) => {
if (!p.api) {
p.api = {};
}
if (p.api.sveltePreprocess === undefined) {
// @ts-expect-error not typed
p.api.sveltePreprocess = p.sveltePreprocess;
} else {
log.error(
`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`
);
}
});
}
/** @type {import('vite').Plugin[]} */
const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess);
/** @type {import('vite').Plugin[]} */
const ignored = [];
/** @type {import('vite').Plugin[]} */
const included = [];
for (const p of pluginsWithPreprocessors) {
if (
options.ignorePluginPreprocessors === true ||
(Array.isArray(options.ignorePluginPreprocessors) &&
options.ignorePluginPreprocessors?.includes(p.name))
) {
ignored.push(p);
} else {
included.push(p);
}
}
if (ignored.length > 0) {
log.debug(
`Ignoring svelte preprocessors defined by these vite plugins: ${ignored
.map((p) => p.name)
.join(', ')}`,
undefined,
'preprocess'
);
}
if (included.length > 0) {
log.debug(
`Adding svelte preprocessors defined by these vite plugins: ${included
.map((p) => p.name)
.join(', ')}`,
undefined,
'preprocess'
);
appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
}
return { prependPreprocessors, appendPreprocessors };
} | @param {import('../types/options.d.ts').ResolvedOptions} options
@param {import('vite').ResolvedConfig} config
@returns {{
prependPreprocessors: import('svelte/compiler').PreprocessorGroup[],
appendPreprocessors: import('svelte/compiler').PreprocessorGroup[]
}} | buildExtraPreprocessors ( options , config ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/preprocess.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/preprocess.js | MIT |
export function addExtraPreprocessors(options, config) {
const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
if (!options.preprocess) {
options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
} else if (Array.isArray(options.preprocess)) {
options.preprocess.unshift(...prependPreprocessors);
options.preprocess.push(...appendPreprocessors);
} else {
options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
}
}
} | @param {import('../types/options.d.ts').ResolvedOptions} options
@param {import('vite').ResolvedConfig} config | addExtraPreprocessors ( options , config ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/preprocess.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/preprocess.js | MIT |
update(compileData) {
this.#errors.delete(compileData.normalizedFilename);
this.#updateCSS(compileData);
this.#updateJS(compileData);
this.#updateDependencies(compileData);
} | @param {import('../types/compile.d.ts').CompileData} compileData | update ( compileData ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | MIT |
has(svelteRequest) {
const id = svelteRequest.normalizedFilename;
return this.#errors.has(id) || this.#js.has(id) || this.#css.has(id);
} | @param {import('../types/id.d.ts').SvelteRequest} svelteRequest
@returns {boolean} | has ( svelteRequest ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | MIT |
setError(svelteRequest, error) {
// keep dependency info, otherwise errors in dependants would not trigger an update after fixing
// because they are no longer watched
this.remove(svelteRequest, true);
this.#errors.set(svelteRequest.normalizedFilename, error);
} | @param {import('../types/id.d.ts').SvelteRequest} svelteRequest
@param {any} error | setError ( svelteRequest , error ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | MIT |
async function findPackageInfo(file) {
/** @type {PackageInfo} */
const info = {
name: '$unknown',
version: '0.0.0-unknown',
path: '$unknown'
};
let path = await findClosestPkgJsonPath(file, (pkgPath) => {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
if (pkg.name != null) {
info.name = pkg.name;
if (pkg.version != null) {
info.version = pkg.version;
}
info.svelte = pkg.svelte;
return true;
}
return false;
});
// return normalized path with appended '/' so .startsWith works for future file checks
path = normalizePath(dirname(path ?? file)) + '/';
info.path = path;
return info;
} | utility to get some info from the closest package.json with a "name" set
@param {string} file to find info for
@returns {Promise<PackageInfo>} | findPackageInfo ( file ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/vite-plugin-svelte-cache.js | MIT |
export function safeBase64Hash(input) {
if (hashes[input]) {
return hashes[input];
}
//TODO if performance really matters, use a faster one like xx-hash etc.
// should be evenly distributed because short input length and similarities in paths could cause collisions otherwise
// OR DON'T USE A HASH AT ALL, what about a simple counter?
const md5 = crypto.createHash('md5');
md5.update(input);
const hash = toSafe(md5.digest('base64')).slice(0, hash_length);
hashes[input] = hash;
return hash;
} | replaces +/= in base64 output so they don't interfere
@param {string} input
@returns {string} base64 hash safe to use in any context | safeBase64Hash ( input ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/hash.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/hash.js | MIT |
function toSafe(base64) {
return base64.replace(replaceRE, (x) => replacements[x]);
} | @param {string} base64
@returns {string} | toSafe ( base64 ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/hash.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/hash.js | MIT |
function splitId(id) {
const parts = id.split('?', 2);
const filename = parts[0];
const rawQuery = parts[1];
return { filename, rawQuery };
} | @param {string} id
@returns {{ filename: string, rawQuery: string }} | splitId ( id ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) {
const query = parseRequestQuery(rawQuery);
const rawOrDirect = !!(query.raw || query.direct);
if (query.url || (!query.svelte && rawOrDirect)) {
// skip requests with special vite tags
return;
}
const raw = rawOrDirect;
const normalizedFilename = normalize(filename, root);
const cssId = createVirtualImportId(filename, root, 'style');
return {
id,
filename,
normalizedFilename,
cssId,
query,
timestamp,
ssr,
raw
};
} | @param {string} id
@param {string} filename
@param {string} rawQuery
@param {string} root
@param {number} timestamp
@param {boolean} ssr
@returns {import('../types/id.d.ts').SvelteRequest | undefined} | parseToSvelteRequest ( id , filename , rawQuery , root , timestamp , ssr ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function createVirtualImportId(filename, root, type) {
const parts = ['svelte', `type=${type}`];
if (type === 'style') {
parts.push('lang.css');
}
if (existsInRoot(filename, root)) {
filename = root + filename;
} else if (filename.startsWith(VITE_FS_PREFIX)) {
filename = IS_WINDOWS
? filename.slice(VITE_FS_PREFIX.length) // remove /@fs/ from /@fs/C:/...
: filename.slice(VITE_FS_PREFIX.length - 1); // remove /@fs from /@fs/home/user
}
// return same virtual id format as vite-plugin-vue eg ...App.svelte?svelte&type=style&lang.css
return `${filename}?${parts.join('&')}`;
} | @param {string} filename
@param {string} root
@param {import('../types/id.d.ts').SvelteQueryTypes} type
@returns {string} | createVirtualImportId ( filename , root , type ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function parseRequestQuery(rawQuery) {
const query = Object.fromEntries(new URLSearchParams(rawQuery));
for (const key in query) {
if (query[key] === '') {
// @ts-expect-error not boolean
query[key] = true;
}
}
const compilerOptions = query.compilerOptions;
if (compilerOptions) {
if (!((query.raw || query.direct) && TYPES_WITH_COMPILER_OPTIONS.includes(query.type))) {
throw new Error(
`Invalid compilerOptions in query ${rawQuery}. CompilerOptions are only supported for raw or direct queries with type in "${TYPES_WITH_COMPILER_OPTIONS.join(
', '
)}" e.g. '?svelte&raw&type=script&compilerOptions={"generate":"server","dev":false}`
);
}
try {
const parsed = JSON.parse(compilerOptions);
const invalid = Object.keys(parsed).filter(
(key) => !SUPPORTED_COMPILER_OPTIONS.includes(key)
);
if (invalid.length) {
throw new Error(
`Invalid compilerOptions in query ${rawQuery}: ${invalid.join(
', '
)}. Supported: ${SUPPORTED_COMPILER_OPTIONS.join(', ')}`
);
}
query.compilerOptions = parsed;
} catch (e) {
log.error('failed to parse request query compilerOptions', e);
throw e;
}
}
return /** @type {import('../types/id.d.ts').RequestQuery}*/ query;
} | @param {string} rawQuery
@returns {import('../types/id.d.ts').RequestQuery} | parseRequestQuery ( rawQuery ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
export function normalize(filename, normalizedRoot) {
return stripRoot(normalizePath(filename), normalizedRoot);
} | posixify and remove root at start
@param {string} filename
@param {string} normalizedRoot
@returns {string} | normalize ( filename , normalizedRoot ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function existsInRoot(filename, root) {
if (filename.startsWith(VITE_FS_PREFIX)) {
return false; // vite already tagged it as out of root
}
return fs.existsSync(root + filename);
} | @param {string} filename
@param {string} root
@returns {boolean} | existsInRoot ( filename , root ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function stripRoot(normalizedFilename, normalizedRoot) {
return normalizedFilename.startsWith(normalizedRoot + '/')
? normalizedFilename.slice(normalizedRoot.length)
: normalizedFilename;
} | @param {string} normalizedFilename
@param {string} normalizedRoot
@returns {string} | stripRoot ( normalizedFilename , normalizedRoot ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function buildFilter(include, exclude, extensions) {
const rollupFilter = createFilter(include, exclude);
return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext));
} | @param {import('../public.d.ts').Options['include'] | undefined} include
@param {import('../public.d.ts').Options['exclude'] | undefined} exclude
@param {string[]} extensions
@returns {(filename: string) => boolean} | buildFilter ( include , exclude , extensions ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function buildModuleFilter(include, exclude, infixes, extensions) {
const rollupFilter = createFilter(include, exclude);
return (filename) => {
const basename = path.basename(filename);
return (
rollupFilter(filename) &&
infixes.some((infix) => basename.includes(infix)) &&
extensions.some((ext) => basename.endsWith(ext))
);
};
} | @param {import('../public.d.ts').Options['include'] | undefined} include
@param {import('../public.d.ts').Options['exclude'] | undefined} exclude
@param {string[]} infixes
@param {string[]} extensions
@returns {(filename: string) => boolean} | buildModuleFilter ( include , exclude , infixes , extensions ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
export function buildIdParser(options) {
const { include, exclude, extensions, root } = options;
const normalizedRoot = normalizePath(root);
const filter = buildFilter(include, exclude, extensions ?? []);
return (id, ssr, timestamp = Date.now()) => {
const { filename, rawQuery } = splitId(id);
if (filter(filename)) {
return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
}
};
} | @param {import('../types/options.d.ts').ResolvedOptions} options
@returns {import('../types/id.d.ts').IdParser} | buildIdParser ( options ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
export function buildModuleIdParser(options) {
const {
include,
exclude,
infixes = DEFAULT_SVELTE_MODULE_INFIX,
extensions = DEFAULT_SVELTE_MODULE_EXT
} = options?.experimental?.compileModule ?? {};
const root = options.root;
const normalizedRoot = normalizePath(root);
const filter = buildModuleFilter(include, exclude, infixes, extensions);
return (id, ssr, timestamp = Date.now()) => {
const { filename, rawQuery } = splitId(id);
if (filter(filename)) {
return parseToSvelteModuleRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr);
}
};
} | @param {import('../types/options.d.ts').ResolvedOptions} options
@returns {import('../types/id.d.ts').ModuleIdParser} | buildModuleIdParser ( options ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
function parseToSvelteModuleRequest(id, filename, rawQuery, root, timestamp, ssr) {
const query = parseRequestQuery(rawQuery);
if (query.url || query.raw || query.direct) {
// skip requests with special vite tags
return;
}
const normalizedFilename = normalize(filename, root);
return {
id,
filename,
normalizedFilename,
query,
timestamp,
ssr
};
} | @param {string} id
@param {string} filename
@param {string} rawQuery
@param {string} root
@param {number} timestamp
@param {boolean} ssr
@returns {import('../types/id.d.ts').SvelteModuleRequest | undefined} | parseToSvelteModuleRequest ( id , filename , rawQuery , root , timestamp , ssr ) | javascript | sveltejs/vite-plugin-svelte | packages/vite-plugin-svelte/src/utils/id.js | https://github.com/sveltejs/vite-plugin-svelte/blob/master/packages/vite-plugin-svelte/src/utils/id.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.