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 |
---|---|---|---|---|---|---|---|
prepareContent: function(reader, from, length, compression, uncompressedSize) {
return function() {
var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
var uncompressedFileData = compression.uncompress(compressedFileData);
if (uncompressedFileData.length !== uncompressedSize) {
throw new Error("Bug : uncompressed data size mismatch");
}
return uncompressedFileData;
};
}, | Prepare the function used to generate the uncompressed content from this ZipFile.
@param {DataReader} reader the reader to use.
@param {number} from the offset from where we should read the data.
@param {number} length the length of the data to read.
@param {JSZip.compression} compression the compression used on this file.
@param {number} uncompressedSize the uncompressed size to expect.
@return {Function} the callback to get the uncompressed content (the type depends of the DataReader class). | prepareContent ( reader , from , length , compression , uncompressedSize ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
readLocalPart: function(reader) {
var compression, localExtraFieldsLength;
// we already know everything from the central dir !
// If the central dir data are false, we are doomed.
// On the bright side, the local part is scary : zip64, data descriptors, both, etc.
// The less data we get here, the more reliable this should be.
// Let's skip the whole header and dash to the data !
reader.skip(22);
// in some zip created on windows, the filename stored in the central dir contains \ instead of /.
// Strangely, the filename here is OK.
// I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
// or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
// Search "unzip mismatching "local" filename continuing with "central" filename version" on
// the internet.
//
// I think I see the logic here : the central directory is used to display
// content and the local directory is used to extract the files. Mixing / and \
// may be used to display \ to windows users and use / when extracting the files.
// Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
this.fileNameLength = reader.readInt(2);
localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
this.fileName = reader.readString(this.fileNameLength);
reader.skip(localExtraFieldsLength);
if (this.compressedSize == -1 || this.uncompressedSize == -1) {
throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
}
compression = utils.findCompression(this.compressionMethod);
if (compression === null) { // no compression found
throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
}
this.decompressed = new CompressedObject();
this.decompressed.compressedSize = this.compressedSize;
this.decompressed.uncompressedSize = this.uncompressedSize;
this.decompressed.crc32 = this.crc32;
this.decompressed.compressionMethod = this.compressionMethod;
this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
// we need to compute the crc32...
if (this.loadOptions.checkCRC32) {
this.decompressed = utils.transformTo("string", this.decompressed.getContent());
if (jszipProto.crc32(this.decompressed) !== this.crc32) {
throw new Error("Corrupted zip : CRC32 mismatch");
}
}
}, | Read the local part of a zip file and add the info in this object.
@param {DataReader} reader the reader to use. | readLocalPart ( reader ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
readCentralPart: function(reader) {
this.versionMadeBy = reader.readString(2);
this.versionNeeded = reader.readInt(2);
this.bitFlag = reader.readInt(2);
this.compressionMethod = reader.readString(2);
this.date = reader.readDate();
this.crc32 = reader.readInt(4);
this.compressedSize = reader.readInt(4);
this.uncompressedSize = reader.readInt(4);
this.fileNameLength = reader.readInt(2);
this.extraFieldsLength = reader.readInt(2);
this.fileCommentLength = reader.readInt(2);
this.diskNumberStart = reader.readInt(2);
this.internalFileAttributes = reader.readInt(2);
this.externalFileAttributes = reader.readInt(4);
this.localHeaderOffset = reader.readInt(4);
if (this.isEncrypted()) {
throw new Error("Encrypted zip are not supported");
}
this.fileName = reader.readString(this.fileNameLength);
this.readExtraFields(reader);
this.parseZIP64ExtraField(reader);
this.fileComment = reader.readString(this.fileCommentLength);
// warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
}, | Read the central part of a zip file and add the info in this object.
@param {DataReader} reader the reader to use. | readCentralPart ( reader ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
parseZIP64ExtraField: function(reader) {
if (!this.extraFields[0x0001]) {
return;
}
// should be something, preparing the extra reader
var extraReader = new StringReader(this.extraFields[0x0001].value);
// I really hope that these 64bits integer can fit in 32 bits integer, because js
// won't let us have more.
if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
this.uncompressedSize = extraReader.readInt(8);
}
if (this.compressedSize === utils.MAX_VALUE_32BITS) {
this.compressedSize = extraReader.readInt(8);
}
if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
this.localHeaderOffset = extraReader.readInt(8);
}
if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
this.diskNumberStart = extraReader.readInt(4);
}
}, | Parse the ZIP64 extra field and merge the info in the current ZipEntry.
@param {DataReader} reader the reader to use. | parseZIP64ExtraField ( reader ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
handleUTF8: function() {
if (this.useUTF8()) {
this.fileName = jszipProto.utf8decode(this.fileName);
this.fileComment = jszipProto.utf8decode(this.fileComment);
} else {
var upath = this.findExtraFieldUnicodePath();
if (upath !== null) {
this.fileName = upath;
}
var ucomment = this.findExtraFieldUnicodeComment();
if (ucomment !== null) {
this.fileComment = ucomment;
}
}
}, | Apply an UTF8 transformation if needed. | handleUTF8 ( ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
findExtraFieldUnicodePath: function() {
var upathField = this.extraFields[0x7075];
if (upathField) {
var extraReader = new StringReader(upathField.value);
// wrong version
if (extraReader.readInt(1) !== 1) {
return null;
}
// the crc of the filename changed, this field is out of date.
if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
return null;
}
return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
}
return null;
}, | Find the unicode path declared in the extra field, if any.
@return {String} the unicode path, null otherwise. | findExtraFieldUnicodePath ( ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
findExtraFieldUnicodeComment: function() {
var ucommentField = this.extraFields[0x6375];
if (ucommentField) {
var extraReader = new StringReader(ucommentField.value);
// wrong version
if (extraReader.readInt(1) !== 1) {
return null;
}
// the crc of the comment changed, this field is out of date.
if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
return null;
}
return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
}
return null;
} | Find the unicode comment declared in the extra field, if any.
@return {String} the unicode comment, null otherwise. | findExtraFieldUnicodeComment ( ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
}; | new Deflate(options)
- options (Object): zlib deflate options.
Creates new deflator instance with specified params. Throws exception
on bad params. Supported options:
- `level`
- `windowBits`
- `memLevel`
- `strategy`
[http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
for more information on these.
Additional options, for internal needs:
- `chunkSize` - size of generated data chunks (16K by default)
- `raw` (Boolean) - do raw deflate
- `gzip` (Boolean) - create gzip wrapper
- `to` (String) - if equal to 'string', then result will be "binary string"
(each char code [0..255])
- `header` (Object) - custom header for gzip
- `text` (Boolean) - true if compressed data believed to be text
- `time` (Number) - modification time, unix timestamp
- `os` (Number) - operation system code
- `extra` (Array) - array of bytes with extra data (max 65536)
- `name` (String) - file name (binary string)
- `comment` (String) - comment (binary string)
- `hcrc` (Boolean) - true if header crc should be added
##### Example:
```javascript
var pako = require('pako')
, chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
, chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
var deflate = new pako.Deflate({ level: 3});
deflate.push(chunk1, false);
deflate.push(chunk2, true); // true -> last chunk
if (deflate.err) { throw new Error(deflate.err); }
console.log(deflate.result);
```
* | Deflate ( options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
return true;
}; | Deflate#push(data[, mode]) -> Boolean
- data (Uint8Array|Array|String): input data. Strings will be converted to
utf8 byte sequence.
- mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
new compressed chunks. Returns `true` on success. The last data block must have
mode Z_FINISH (or `true`). That flush internal pending buffers and call
[[Deflate#onEnd]].
On fail call [[Deflate#onEnd]] with error code and return false.
We strongly recommend to use `Uint8Array` on input for best speed (output
array format is detected automatically). Also, don't skip last param and always
use the same type in your code (boolean or number). That will improve JS speed.
For regular `Array`-s make sure all elements are [0..255].
##### Example
```javascript
push(chunk, false); // push one of data chunks
...
push(chunk, true); // push last chunk
```
* | Deflate.prototype.push ( data , mode ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
}; | Deflate#onData(chunk) -> Void
- chunk (Uint8Array|Array|String): ouput data. Type of array depends
on js engine support. When string output requested, each chunk
will be string.
By default, stores data blocks in `chunks[]` property and glue
those in `onEnd`. Override this handler, if you need another behaviour.
* | Deflate.prototype.onData ( chunk ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
}; | Deflate#onEnd(status) -> Void
- status (Number): deflate status. 0 (Z_OK) on success,
other if not.
Called once after you tell deflate that input stream complete
or error happenned. By default - join collected chunks,
free memory and fill `results` / `err` properties.
* | Deflate.prototype.onEnd ( status ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
} | deflate(data[, options]) -> Uint8Array|Array|String
- data (Uint8Array|Array|String): input data to compress.
- options (Object): zlib deflate options.
Compress `data` with deflate alrorythm and `options`.
Supported options are:
- level
- windowBits
- memLevel
- strategy
[http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
for more information on these.
Sugar (options):
- `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
negative windowBits implicitly.
- `to` (String) - if equal to 'string', then result will be "binary string"
(each char code [0..255])
##### Example:
```javascript
var pako = require('pako')
, data = Uint8Array([1,2,3,4,5,6,7,8,9]);
console.log(pako.deflate(data));
```
* | deflate ( input , options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
} | deflateRaw(data[, options]) -> Uint8Array|Array|String
- data (Uint8Array|Array|String): input data to compress.
- options (Object): zlib deflate options.
The same as [[deflate]], but creates raw data, without wrapper
(header and adler32 crc).
* | deflateRaw ( input , options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
} | gzip(data[, options]) -> Uint8Array|Array|String
- data (Uint8Array|Array|String): input data to compress.
- options (Object): zlib deflate options.
The same as [[deflate]], but create gzip wrapper instead of
deflate one.
* | gzip ( input , options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
}; | new Inflate(options)
- options (Object): zlib inflate options.
Creates new inflator instance with specified params. Throws exception
on bad params. Supported options:
- `windowBits`
[http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
for more information on these.
Additional options, for internal needs:
- `chunkSize` - size of generated data chunks (16K by default)
- `raw` (Boolean) - do raw inflate
- `to` (String) - if equal to 'string', then result will be converted
from utf8 to utf16 (javascript) string. When string output requested,
chunk length can differ from `chunkSize`, depending on content.
By default, when no options set, autodetect deflate/gzip data format via
wrapper header.
##### Example:
```javascript
var pako = require('pako')
, chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
, chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
var inflate = new pako.Inflate({ level: 3});
inflate.push(chunk1, false);
inflate.push(chunk2, true); // true -> last chunk
if (inflate.err) { throw new Error(inflate.err); }
console.log(inflate.result);
```
* | Inflate ( options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
} while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
return true;
}; | Inflate#push(data[, mode]) -> Boolean
- data (Uint8Array|Array|String): input data
- mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
new output chunks. Returns `true` on success. The last data block must have
mode Z_FINISH (or `true`). That flush internal pending buffers and call
[[Inflate#onEnd]].
On fail call [[Inflate#onEnd]] with error code and return false.
We strongly recommend to use `Uint8Array` on input for best speed (output
format is detected automatically). Also, don't skip last param and always
use the same type in your code (boolean or number). That will improve JS speed.
For regular `Array`-s make sure all elements are [0..255].
##### Example
```javascript
push(chunk, false); // push one of data chunks
...
push(chunk, true); // push last chunk
```
* | Inflate.prototype.push ( data , mode ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
}; | Inflate#onData(chunk) -> Void
- chunk (Uint8Array|Array|String): ouput data. Type of array depends
on js engine support. When string output requested, each chunk
will be string.
By default, stores data blocks in `chunks[]` property and glue
those in `onEnd`. Override this handler, if you need another behaviour.
* | Inflate.prototype.onData ( chunk ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
}; | Inflate#onEnd(status) -> Void
- status (Number): inflate status. 0 (Z_OK) on success,
other if not.
Called once after you tell inflate that input stream complete
or error happenned. By default - join collected chunks,
free memory and fill `results` / `err` properties.
* | Inflate.prototype.onEnd ( status ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
} | inflate(data[, options]) -> Uint8Array|Array|String
- data (Uint8Array|Array|String): input data to decompress.
- options (Object): zlib inflate options.
Decompress `data` with inflate/ungzip and `options`. Autodetect
format via wrapper header by default. That's why we don't provide
separate `ungzip` method.
Supported options are:
- windowBits
[http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
for more information.
Sugar (options):
- `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
negative windowBits implicitly.
- `to` (String) - if equal to 'string', then result will be converted
from utf8 to utf16 (javascript) string. When string output requested,
chunk length can differ from `chunkSize`, depending on content.
##### Example:
```javascript
var pako = require('pako')
, input = pako.deflate([1,2,3,4,5,6,7,8,9])
, output;
try {
output = pako.inflate(input);
} catch (err)
console.log(err);
}
```
* | inflate ( input , options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
} | inflateRaw(data[, options]) -> Uint8Array|Array|String
- data (Uint8Array|Array|String): input data to decompress.
- options (Object): zlib inflate options.
The same as [[inflate]], but creates raw data, without wrapper
(header and adler32 crc).
* | inflateRaw ( input , options ) | javascript | awslabs/datawig | datawig-js/static/js/xlsx_jszip_0.15.5.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/xlsx_jszip_0.15.5.js | Apache-2.0 |
constructor(column) {
this.column = column
this.label_indices = new Object()
this.label_counter = 0
this.index_labels = new Object()
} | Construct a new label encoder for a specific column.
@param {String} column Name of the column to encode | constructor ( column ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/LabelEncoder.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/LabelEncoder.js | Apache-2.0 |
fit(dataset) {
const t0 = performance.now()
const n = dataset.length
console.log('Fitting to ', n, 'rows')
for(var i = 0; i < n; i++) {
const label = dataset[i][this.column]
if (! this.label_indices.hasOwnProperty(label)) {
this.label_indices[label] = this.label_counter
this.index_labels[this.label_counter] = label
this.label_counter++
}
}
const t1 = performance.now()
console.log("LabelEncoder.fit took " + (t1 - t0) + " milliseconds.")
} | Fit to the data.
@param {Array[Object]} dataset Array of Objects, each of the objects must
contain this.column property
@return {void} | fit ( dataset ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/LabelEncoder.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/LabelEncoder.js | Apache-2.0 |
transform(dataset) {
const t0 = performance.now()
const n = dataset.length
const d = this.label_counter
const encoded = new Array(n * d).fill(0)
for(var i = 0; i < n; i++) {
const label = dataset[i][this.column]
if (this.label_indices.hasOwnProperty(label)) {
const index = this.label_indices[label]
encoded[(i*d)+index] = 1
}
}
const t1 = performance.now()
console.log("LabelEncoder.transform took " + (t1 - t0) + " milliseconds.")
return tf.tensor2d(encoded, [n, d])
} | Transform a given dataset.
@param {Array[Object]} dataset Array of Objects, each of the objects must
contain this.column property
@return {tf.tensor2d} 2 dimensional (n by k) tensorflow-js
tensor with n as number of elements in
the dataset and k the number of distinct
labels that are known to the encoder | transform ( dataset ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/LabelEncoder.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/LabelEncoder.js | Apache-2.0 |
static argsort(array, ascending = true) {
let order
if (ascending) {
order = 1
} else {
order = -1
}
return array
.map(function(value, index) { return [value, index] })
.sort(function(vi1, vi2) { return order * (vi1[0] - vi2[0]) })
.map(function(vi) { return vi[1] })
} | Returns sorted indices of input
https://stackoverflow.com/questions/46622486/what-is-the-javascript-equivalent-of-numpy-argsort
@param {Array}
@return {Array} | argsort ( array , ascending = true ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/math.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/math.js | Apache-2.0 |
static shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
} | Shuffles array in place.
https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
@param {Array} a items An array containing the items. | shuffle ( a ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/math.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/math.js | Apache-2.0 |
getTopKMostUncertainSamples(dataset, k) {
const maxScores = this.predict_proba(dataset).max(1).arraySync()
const maxScoreIndices = Math_.argsort(maxScores, true)
const mostUncertainSamples = new Array(k)
let i = 0
for (let idx of maxScoreIndices.slice(0, k)) {
mostUncertainSamples[i] = dataset[idx]
mostUncertainSamples[i]['uncertainty'] = 1 - maxScores[idx]
// mostUncertainSamples[i]['dataset_index'] = idx
i++
}
return mostUncertainSamples
} | Selects at most k samples that have the lagest uncertainty (as measured by uncertainty sampling).
array[obj], int | getTopKMostUncertainSamples ( dataset , k ) | javascript | awslabs/datawig | datawig-js/static/js/datawig/SimpleImputer.js | https://github.com/awslabs/datawig/blob/master/datawig-js/static/js/datawig/SimpleImputer.js | Apache-2.0 |
parsePath (path) {
let hit = this._cache[path];
if (!hit) {
hit = parse$1(path);
if (hit) {
this._cache[path] = hit;
}
}
return hit || []
} | External parse that check for a cache hit first | parsePath ( path ) | javascript | kazupon/vue-i18n | dist/vue-i18n.esm.browser.js | https://github.com/kazupon/vue-i18n/blob/master/dist/vue-i18n.esm.browser.js | MIT |
function formatSubPath (path) {
var trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(path)) { return false }
return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed
}
/**
* Parse a string path into an array of segments
*/
function parse$1 (path) {
var keys = [];
var index = -1;
var mode = BEFORE_PATH;
var subPathDepth = 0;
var c;
var key;
var newChar;
var type;
var transition;
var action;
var typeMap;
var actions = [];
actions[PUSH] = function () {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[APPEND] = function () {
if (key === undefined) {
key = newChar;
} else {
key += newChar;
}
};
actions[INC_SUB_PATH_DEPTH] = function () {
actions[APPEND]();
subPathDepth++;
};
actions[PUSH_SUB_PATH] = function () {
if (subPathDepth > 0) {
subPathDepth--;
mode = IN_SUB_PATH;
actions[APPEND]();
} else {
subPathDepth = 0;
if (key === undefined) { return false }
key = formatSubPath(key);
if (key === false) {
return false
} else {
actions[PUSH]();
}
}
};
function maybeUnescapeQuote () {
var nextChar = path[index + 1];
if ((mode === IN_SINGLE_QUOTE && nextChar === "'") ||
(mode === IN_DOUBLE_QUOTE && nextChar === '"')) {
index++;
newChar = '\\' + nextChar;
actions[APPEND]();
return true
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap['else'] || ERROR;
if (transition === ERROR) {
return // parse error
}
mode = transition[0];
action = actions[transition[1]];
if (action) {
newChar = transition[2];
newChar = newChar === undefined
? c
: newChar;
if (action() === false) {
return
}
}
if (mode === AFTER_PATH) {
return keys
}
}
}
var I18nPath = function I18nPath () {
this._cache = Object.create(null);
};
/**
* External parse that check for a cache hit first
*/
I18nPath.prototype.parsePath = function parsePath (path) {
var hit = this._cache[path];
if (!hit) {
hit = parse$1(path);
if (hit) {
this._cache[path] = hit;
}
}
return hit || []
};
/**
* Get path value from path string
*/
I18nPath.prototype.getPathValue = function getPathValue (obj, path) {
if (!isObject(obj)) { return null }
var paths = this.parsePath(path);
if (paths.length === 0) {
return null
} else {
var length = paths.length;
var last = obj;
var i = 0;
while (i < length) {
var value = last[paths[i]];
if (value === undefined || value === null) {
return null
}
last = value;
i++;
}
return last
}
};
/* */
var htmlTagMatcher = /<\/?[\w\s="/.':;#-\/]+>/;
var linkKeyMatcher = /(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))/g;
var linkKeyPrefixMatcher = /^@(?:\.([a-z]+))?:/;
var bracketsMatcher = /[()]/g;
var defaultModifiers = {
'upper': function (str) { return str.toLocaleUpperCase(); },
'lower': function (str) { return str.toLocaleLowerCase(); },
'capitalize': function (str) { return ("" + (str.charAt(0).toLocaleUpperCase()) + (str.substr(1))); }
};
var defaultFormatter = new BaseFormatter();
var VueI18n = function VueI18n (options) {
var this$1 = this;
if ( options === void 0 ) options = {};
// Auto install if it is not done yet and `window` has `Vue`.
// To allow users to avoid auto-installation in some cases,
// this code should be placed here. See #290
/* istanbul ignore if */
if (!Vue && typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
var locale = options.locale || 'en-US';
var fallbackLocale = options.fallbackLocale === false
? false
: options.fallbackLocale || 'en-US';
var messages = options.messages || {};
var dateTimeFormats = options.dateTimeFormats || {};
var numberFormats = options.numberFormats || {};
this._vm = null;
this._formatter = options.formatter || defaultFormatter;
this._modifiers = options.modifiers || {};
this._missing = options.missing || null;
this._root = options.root || null;
this._sync = options.sync === undefined ? true : !!options.sync;
this._fallbackRoot = options.fallbackRoot === undefined
? true
: !!options.fallbackRoot;
this._formatFallbackMessages = options.formatFallbackMessages === undefined
? false
: !!options.formatFallbackMessages;
this._silentTranslationWarn = options.silentTranslationWarn === undefined
? false
: options.silentTranslationWarn;
this._silentFallbackWarn = options.silentFallbackWarn === undefined
? false
: !!options.silentFallbackWarn;
this._dateTimeFormatters = {};
this._numberFormatters = {};
this._path = new I18nPath();
this._dataListeners = new Set();
this._componentInstanceCreatedListener = options.componentInstanceCreatedListener || null;
this._preserveDirectiveContent = options.preserveDirectiveContent === undefined
? false
: !!options.preserveDirectiveContent;
this.pluralizationRules = options.pluralizationRules || {};
this._warnHtmlInMessage = options.warnHtmlInMessage || 'off';
this._postTranslation = options.postTranslation || null;
this._escapeParameterHtml = options.escapeParameterHtml || false;
/**
* @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
* @param choicesLength {number} an overall amount of available choices
* @returns a final choice index
*/
this.getChoiceIndex = function (choice, choicesLength) {
var thisPrototype = Object.getPrototypeOf(this$1);
if (thisPrototype && thisPrototype.getChoiceIndex) {
var prototypeGetChoiceIndex = (thisPrototype.getChoiceIndex);
return (prototypeGetChoiceIndex).call(this$1, choice, choicesLength)
}
// Default (old) getChoiceIndex implementation - english-compatible
var defaultImpl = function (_choice, _choicesLength) {
_choice = Math.abs(_choice);
if (_choicesLength === 2) {
return _choice
? _choice > 1
? 1
: 0
: 1
}
return _choice ? Math.min(_choice, 2) : 0
};
if (this$1.locale in this$1.pluralizationRules) {
return this$1.pluralizationRules[this$1.locale].apply(this$1, [choice, choicesLength])
} else {
return defaultImpl(choice, choicesLength)
}
};
this._exist = function (message, key) {
if (!message || !key) { return false }
if (!isNull(this$1._path.getPathValue(message, key))) { return true }
// fallback for flat key
if (message[key]) { return true }
return false
};
if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
Object.keys(messages).forEach(function (locale) {
this$1._checkLocaleMessage(locale, this$1._warnHtmlInMessage, messages[locale]);
});
}
this._initVM({
locale: locale,
fallbackLocale: fallbackLocale,
messages: messages,
dateTimeFormats: dateTimeFormats,
numberFormats: numberFormats
});
};
var prototypeAccessors = { vm: { configurable: true },messages: { configurable: true },dateTimeFormats: { configurable: true },numberFormats: { configurable: true },availableLocales: { configurable: true },locale: { configurable: true },fallbackLocale: { configurable: true },formatFallbackMessages: { configurable: true },missing: { configurable: true },formatter: { configurable: true },silentTranslationWarn: { configurable: true },silentFallbackWarn: { configurable: true },preserveDirectiveContent: { configurable: true },warnHtmlInMessage: { configurable: true },postTranslation: { configurable: true } };
VueI18n.prototype._checkLocaleMessage = function _checkLocaleMessage (locale, level, message) {
var paths = [];
var fn = function (level, locale, message, paths) {
if (isPlainObject(message)) {
Object.keys(message).forEach(function (key) {
var val = message[key];
if (isPlainObject(val)) {
paths.push(key);
paths.push('.');
fn(level, locale, val, paths);
paths.pop();
paths.pop();
} else {
paths.push(key);
fn(level, locale, val, paths);
paths.pop();
}
});
} else if (isArray(message)) {
message.forEach(function (item, index) {
if (isPlainObject(item)) {
paths.push(("[" + index + "]"));
paths.push('.');
fn(level, locale, item, paths);
paths.pop();
paths.pop();
} else {
paths.push(("[" + index + "]"));
fn(level, locale, item, paths);
paths.pop();
}
});
} else if (isString(message)) {
var ret = htmlTagMatcher.test(message);
if (ret) {
var msg = "Detected HTML in message '" + message + "' of keypath '" + (paths.join('')) + "' at '" + locale + "'. Consider component interpolation with '<i18n>' to avoid XSS. See https://bit.ly/2ZqJzkp";
if (level === 'warn') {
warn(msg);
} else if (level === 'error') {
error(msg);
}
}
}
};
fn(level, locale, message, paths); | Format a subPath, return its plain form if it is
a literal string or number. Otherwise prepend the
dynamic indicator (*). | formatSubPath ( path ) | javascript | kazupon/vue-i18n | dist/vue-i18n.js | https://github.com/kazupon/vue-i18n/blob/master/dist/vue-i18n.js | MIT |
values = valuesEntries.map(entry => {
const [, vnode] = entry
if (vnode.tag !== undefined) {
return [vnode]
}
}).filter(Boolean) | In this case, we iterate over the VNode list and preserve **only** VNodes with tags and return them, wrapped
in a list.
Rationale: If text nodes are kept, the positional lookup from vue-i18n will fail, rendering the first
child again (i.e `I agree with the, I agree with the`) | (anonymous) | javascript | kazupon/vue-i18n | examples/formatting/custom/src/formatter.js | https://github.com/kazupon/vue-i18n/blob/master/examples/formatting/custom/src/formatter.js | MIT |
export default function defineMixin (bridge: boolean = false) {
function mounted (): void {
if (this !== this.$root && this.$options.__INTLIFY_META__ && this.$el) {
this.$el.setAttribute('data-intlify', this.$options.__INTLIFY_META__)
}
}
return bridge
? { mounted } // delegate `vue-i18n-bridge` mixin implementation
: { // regulary
beforeCreate (): void {
const options: any = this.$options
options.i18n = options.i18n || ((options.__i18nBridge || options.__i18n) ? {} : null)
if (options.i18n) {
if (options.i18n instanceof VueI18n) {
// init locale messages via custom blocks
if ((options.__i18nBridge || options.__i18n)) {
try {
let localeMessages = options.i18n && options.i18n.messages ? options.i18n.messages : {}
const __i18n = options.__i18nBridge || options.__i18n
__i18n.forEach(resource => {
localeMessages = merge(localeMessages, JSON.parse(resource))
})
Object.keys(localeMessages).forEach((locale: Locale) => {
options.i18n.mergeLocaleMessage(locale, localeMessages[locale])
})
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
error(`Cannot parse locale messages via custom blocks.`, e)
}
}
}
this._i18n = options.i18n
this._i18nWatcher = this._i18n.watchI18nData()
} else if (isPlainObject(options.i18n)) {
const rootI18n = this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n
? this.$root.$i18n
: null
// component local i18n
if (rootI18n) {
options.i18n.root = this.$root
options.i18n.formatter = rootI18n.formatter
options.i18n.fallbackLocale = rootI18n.fallbackLocale
options.i18n.formatFallbackMessages = rootI18n.formatFallbackMessages
options.i18n.silentTranslationWarn = rootI18n.silentTranslationWarn
options.i18n.silentFallbackWarn = rootI18n.silentFallbackWarn
options.i18n.pluralizationRules = rootI18n.pluralizationRules
options.i18n.preserveDirectiveContent = rootI18n.preserveDirectiveContent
}
// init locale messages via custom blocks
if ((options.__i18nBridge || options.__i18n)) {
try {
let localeMessages = options.i18n && options.i18n.messages ? options.i18n.messages : {}
const __i18n = options.__i18nBridge || options.__i18n
__i18n.forEach(resource => {
localeMessages = merge(localeMessages, JSON.parse(resource))
})
options.i18n.messages = localeMessages
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
warn(`Cannot parse locale messages via custom blocks.`, e)
}
}
}
const { sharedMessages } = options.i18n
if (sharedMessages && isPlainObject(sharedMessages)) {
options.i18n.messages = merge(options.i18n.messages, sharedMessages)
}
this._i18n = new VueI18n(options.i18n)
this._i18nWatcher = this._i18n.watchI18nData()
if (options.i18n.sync === undefined || !!options.i18n.sync) {
this._localeWatcher = this.$i18n.watchLocale()
}
if (rootI18n) {
rootI18n.onComponentInstanceCreated(this._i18n)
}
} else {
if (process.env.NODE_ENV !== 'production') {
warn(`Cannot be interpreted 'i18n' option.`)
}
}
} else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
// root i18n
this._i18n = this.$root.$i18n
} else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
// parent i18n
this._i18n = options.parent.$i18n
}
},
beforeMount (): void {
const options: any = this.$options
options.i18n = options.i18n || ((options.__i18nBridge || options.__i18n) ? {} : null)
if (options.i18n) {
if (options.i18n instanceof VueI18n) {
// init locale messages via custom blocks
this._i18n.subscribeDataChanging(this)
this._subscribing = true
} else if (isPlainObject(options.i18n)) {
this._i18n.subscribeDataChanging(this)
this._subscribing = true
} else {
if (process.env.NODE_ENV !== 'production') {
warn(`Cannot be interpreted 'i18n' option.`)
}
}
} else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
this._i18n.subscribeDataChanging(this)
this._subscribing = true
} else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
this._i18n.subscribeDataChanging(this)
this._subscribing = true
}
},
mounted,
beforeDestroy (): void {
if (!this._i18n) { return }
const self = this
this.$nextTick(() => {
if (self._subscribing) {
self._i18n.unsubscribeDataChanging(self)
delete self._subscribing
}
if (self._i18nWatcher) {
self._i18nWatcher()
self._i18n.destroyVM()
delete self._i18nWatcher
}
if (self._localeWatcher) {
self._localeWatcher()
delete self._localeWatcher
}
})
}
}
} | Mixin
If `bridge` mode, empty mixin is returned,
else regulary mixin implementation is returned. | defineMixin ( bridge : boolean = false ) | javascript | kazupon/vue-i18n | src/mixin.js | https://github.com/kazupon/vue-i18n/blob/master/src/mixin.js | MIT |
registerRoute(({ event }) => isNav(event), NETWORK_HANDLER); | Adding this before `precacheAndRoute` lets us handle all
the navigation requests even if they are in precache. | (anonymous) | javascript | preactjs/preact-cli | packages/cli/sw/index.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/sw/index.js | MIT |
async function getOutputFile(dir, file) {
if (typeof file !== 'string') {
// @ts-ignore
file = (await readdir(join(dir, 'build'))).find(f => file.test(f));
}
return await readFile(join(dir, 'build', file), 'utf8');
} | Get build output file as utf-8 string
@param {string} dir
@param {RegExp | string} file
@returns {Promise<string>} | getOutputFile ( dir , file ) | javascript | preactjs/preact-cli | packages/cli/tests/build.test.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/tests/build.test.js | MIT |
exports.isPortFree = async function (port) {
try {
await new Promise((resolve, reject) => {
const server = createServer();
server.unref();
server.on('error', reject);
server.listen({ port }, () => {
server.close(resolve);
});
});
return true;
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
return false;
}
}; | Taken from: https://github.com/preactjs/wmr/blob/3401a9bfa6491d25108ad68688c067a7e17d0de5/packages/wmr/src/lib/net-utils.js#L4-Ll4
Check if a port is free
@param {number} port
@returns {Promise<boolean>} | exports.isPortFree ( port ) | javascript | preactjs/preact-cli | packages/cli/src/util.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/util.js | MIT |
async function catchExceptions(err) {
// Webpack Stats Error
if ('moduleName' in err && 'loc' in err) {
error(`${err.moduleName} ${green(err.loc)}\n${err.message}\n\n`);
}
error(err.stack || err.message || err);
} | @param {Error | import('webpack').StatsError} err | catchExceptions ( err ) | javascript | preactjs/preact-cli | packages/cli/src/index.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/index.js | MIT |
async function devBuild(config, env) {
const webpackConfig = await clientConfig(config, env);
await transformConfig(webpackConfig, config, env);
let compiler = webpack(webpackConfig);
return new Promise((res, rej) => {
compiler.hooks.beforeCompile.tap('CliDevPlugin', () => {
if (config['clear']) clear(true);
});
compiler.hooks.done.tap('CliDevPlugin', stats => {
const devServer = webpackConfig.devServer;
const protocol = devServer.https ? 'https' : 'http';
const serverAddr = `${protocol}://${devServer.host}:${bold(
devServer.port
)}`;
const localIpAddr = `${protocol}://${ip.address()}:${bold(
devServer.port
)}`;
if (!stats.hasErrors()) {
process.stdout.write(green('Compiled successfully!\n\n'));
process.stdout.write('You can view the application in browser.\n\n');
process.stdout.write(`${bold('Local:')} ${serverAddr}\n`);
process.stdout.write(`${bold('On Your Network:')} ${localIpAddr}\n`);
}
});
compiler.hooks.failed.tap('CliDevPlugin', rej);
let server = new DevServer(webpackConfig.devServer, compiler);
server.start();
res(server);
});
} | @param {import('../../../types').Env} env | devBuild ( config , env ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/run-webpack.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/run-webpack.js | MIT |
function runCompiler(compiler) {
return new Promise((res, rej) => {
compiler.run((err, stats) => {
if (err) rej(err);
showCompilationIssues(stats);
compiler.close(closeErr => {
if (closeErr) rej(closeErr);
res();
});
});
});
} | @param {import('webpack').Compiler} compiler | runCompiler ( compiler ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/run-webpack.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/run-webpack.js | MIT |
function showCompilationIssues(stats) {
if (stats) {
if (stats.hasWarnings()) {
allFields(stats, 'warnings').forEach(({ message }) => warn(message));
}
if (stats.hasErrors()) {
allFields(stats, 'errors').forEach(err => {
throw err;
});
}
}
} | @param {import('webpack').Stats} stats | showCompilationIssues ( stats ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/run-webpack.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/run-webpack.js | MIT |
get webpack() {
return webpack;
} | Webpack module used to create config.
@readonly
@type {Helpers['webpack']}
@memberof WebpackConfigHelpers | webpack ( ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getLoaders(config) {
return this.getRules(config).map(({ rule, index }) => ({
rule: rule,
ruleIndex: index,
loaders: rule.loaders || rule.use || rule.loader,
}));
} | Returns wrapper around all loaders from config.
@type {Helpers['getLoaders']}
@memberof WebpackConfigHelpers | getLoaders ( config ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getRules(config) {
return [
...(config.module.loaders || []),
...(config.module.rules || []),
].map((rule, index) => ({ index, rule }));
} | Returns wrapper around all rules from config.
@type {Helpers['getRules']}
@memberof WebpackConfigHelpers | getRules ( config ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getPlugins(config) {
return (config.plugins || []).map((plugin, index) => ({ index, plugin }));
} | Returns wrapper around all plugins from config.
@type {Helpers['getPlugins']}
@memberof WebpackConfigHelpers | getPlugins ( config ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getRulesByMatchingFile(config, file) {
let filePath = resolve(this._cwd, file);
return this.getRules(config).filter(
w => w.rule.test && w.rule.test.exec(filePath)
);
} | Returns wrapper around all rules that match provided file.
@type {Helpers['getRulesByMatchingFile']}
@memberof WebpackConfigHelpers | getRulesByMatchingFile ( config , file ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getLoadersByName(config, name) {
return this.getLoaders(config)
.map(({ rule, ruleIndex, loaders }) =>
Array.isArray(loaders)
? loaders.map((loader, loaderIndex) => ({
rule,
ruleIndex,
loader,
loaderIndex,
}))
: [{ rule, ruleIndex, loader: loaders, loaderIndex: -1 }]
)
.reduce((arr, loaders) => arr.concat(loaders), [])
.filter(({ loader }) => {
if (!loader) return false;
if (typeof loader === 'string') return loader.includes(name);
return typeof loader.loader === 'string' &&
loader.loader.includes('proxy-loader')
? loader.options.loader.includes(name)
: loader.loader.includes(name);
});
} | Returns loaders that match provided name.
@example
helpers.getLoadersByName(config, 'less-loader')
@type {Helpers['getLoadersByName']}
@memberof WebpackConfigHelpers | getLoadersByName ( config , name ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getPluginsByName(config, name) {
return this.getPlugins(config).filter(
w =>
w.plugin && w.plugin.constructor && w.plugin.constructor.name === name
);
} | Returns plugins that match provided name.
@example
helpers.getPluginsByName(config, 'HtmlWebpackPlugin')
@type {Helpers['getPluginsByName']}
@memberof WebpackConfigHelpers | getPluginsByName ( config , name ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
getPluginsByType(config, type) {
return this.getPlugins(config).filter(w => w.plugin instanceof type);
} | Returns plugins that match provided type.
@example
helpers.getPluginsByType(config, webpack.optimize.CommonsChunkPlugin)
@type {Helpers['getPluginsByType']}
@memberof WebpackConfigHelpers | getPluginsByType ( config , type ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/transform-config.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/transform-config.js | MIT |
!pages.find(page => page.url === PREACT_FALLBACK_URL) && | We cache a non SSRed page in service worker so that there is
no flash of content when user lands on routes other than `/`.
And we dont have to cache every single html file.
Go easy on network usage of clients. | (anonymous) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/render-html-plugin.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/render-html-plugin.js | MIT |
constructor(options) {
super(options);
} | @param {import('critters').Options} options | constructor ( options ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/critters-plugin.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/critters-plugin.js | MIT |
async getCssAsset(href, style) {
const outputPath = this.options.path;
const publicPath = this.options.publicPath;
// CHECK - the output path
// path on disk (with output.publicPath removed)
let normalizedPath = href.replace(/^\//, '');
const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/'; | Given href, find the corresponding CSS asset | getCssAsset ( href , style ) | javascript | preactjs/preact-cli | packages/cli/src/lib/webpack/critters-plugin.js | https://github.com/preactjs/preact-cli/blob/master/packages/cli/src/lib/webpack/critters-plugin.js | MIT |
exports.installDependencies = async function installDependencies(
cwd,
packageManager
) {
await spawn(packageManager, ['install'], { cwd, stdio: 'inherit' });
}; | @param {string} cwd
@param {'yarn' | 'npm'} packageManager | installDependencies ( cwd , packageManager ) | javascript | preactjs/preact-cli | packages/create-cli/src/util.js | https://github.com/preactjs/preact-cli/blob/master/packages/create-cli/src/util.js | MIT |
function Passwordless() {
this._tokenStore = undefined;
this._userProperty = undefined;
this._deliveryMethods = {};
this._defaultDelivery = undefined;
} | Passwordless is a node.js module for express that allows authentication and
authorization without passwords but simply by sending tokens via email or
other means. It utilizes a very similar mechanism as many sites use for
resetting passwords. The module was inspired by Justin Balthrop's article
"Passwords are Obsolete"
@constructor | Passwordless ( ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.init = function(tokenStore, options) {
options = options || {};
if(!tokenStore) {
throw new Error('tokenStore has to be provided')
}
this._tokenStore = tokenStore;
this._userProperty = (options.userProperty) ? options.userProperty : 'user';
this._allowTokenReuse = options.allowTokenReuse;
this._skipForceSessionSave = (options.skipForceSessionSave) ? true : false;
} | Initializes Passwordless and has to be called before any methods are called
@param {TokenStore} tokenStore - An instance of a TokenStore used to store
and authenticate the generated tokens
@param {Object} [options]
@param {String} [options.userProperty] - Sets the name under which the uid
is stored in the http request object (default: 'user')
@param {Boolean} [options.allowTokenReuse] - Defines wether a token may be
reused by users. Enabling this option is usually required for stateless
operation, but generally not recommended due to the risk that others might
have acquired knowledge about the token while in transit (default: false)
@param {Boolean} [options.skipForceSessionSave] - Some session middleware
(especially cookie-session) does not require (and support) the forced
safe of a session. In this case set this option to 'true' (default: false)
@throws {Error} Will throw an error if called without an instantiated
TokenStore | Passwordless.prototype.init ( tokenStore , options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.acceptToken = function(options) {
var self = this;
options = options || {};
return function(req, res, next) {
if(!self._tokenStore) {
throw new Error('Passwordless is missing a TokenStore. Are you sure you called passwordless.init()?');
}
var tokenField = (options.tokenField) ? options.tokenField : 'token';
var uidField = (options.uidField) ? options.uidField : 'uid';
var token = req.query[tokenField], uid = req.query[uidField];
if(!token && !uid && options.allowPost) {
if(!req.body) {
throw new Error('req.body does not exist: did you require middleware to accept POST data (such as body-parser) before calling acceptToken?')
} else if(req.body[tokenField] && req.body[uidField]) {
token = req.body[tokenField];
uid = req.body[uidField];
}
}
if((options.failureFlash || options.successFlash) && !req.flash) {
throw new Error('To use failureFlash, flash middleware is required such as connect-flash');
}
if(token && uid) {
self._tokenStore.authenticate(token, uid.toString(), function(error, valid, referrer) {
if(valid) {
var success = function() {
req[self._userProperty] = uid;
if(req.session) {
req.session.passwordless = req[self._userProperty];
}
if(options.successFlash) {
req.flash('passwordless-success', options.successFlash);
}
if(options.enableOriginRedirect && referrer) {
// next() will not be called
return self._redirectWithSessionSave(req, res, next, referrer);
}
if(options.successRedirect) {
// next() will not be called, and
// enableOriginRedirect has priority
return self._redirectWithSessionSave(req, res, next, options.successRedirect);
}
next();
}
// Invalidate token, except allowTokenReuse has been set
if(!self._allowTokenReuse) {
self._tokenStore.invalidateUser(uid, function(err) {
if(err) {
next('TokenStore.invalidateUser() error: ' + error);
} else {
success();
}
})
} else {
success();
}
} else if(error) {
next('TokenStore.authenticate() error: ' + error);
} else if(options.failureFlash) {
req.flash('passwordless', options.failureFlash);
next();
} else {
next();
}
});
} else {
next();
}
}
} | Returns express middleware which will look for token / UID query parameters and
authenticate the user if they are provided and valid. A typical URL that is
accepted by acceptToken() does look like this:
http://www.example.com?token=TOKEN&uid=UID
Simply calls the next middleware in case no token / uid has been submitted or if
the supplied token / uid are not valid
@example
app.use(passwordless.sessionSupport());
// Look for tokens in any URL requested from the server
app.use(passwordless.acceptToken());
@param {Object} [options]
@param {String} [options.successRedirect] - If set, the user will be redirected
to the supplied URL in case of a successful authentication. If not set but the
authentication has been successful, the next middleware will be called. This
option is overwritten by option.enableOriginRedirect if set and an origin has
been supplied. It is strongly recommended to set this option to avoid leaking
valid tokens via the HTTP referrer. In case of session-less operation, though,
you might want to ignore this flag for efficient operation (default: null)
@param {String} [options.tokenField] - The query parameter used to submit the
token (default: 'token')
@param {String} [options.uidField] - The query parameter used to submit the
user id (default: 'uid')
@param {Boolean} [options.allowPost] - If set, acceptToken() will also look for
POST parameters to contain the token and uid (default: false)
@param {String} [options.failureFlash] - The error message to be flashed in case
a token and uid were provided but the authentication failed. Using this option
requires flash middleware such as connect-flash. The error message will be stored
as 'passwordless' (example: 'This token is not valid anymore!', default: null)
@param {String} [options.successFlash] - The success message to be flashed in case
the supplied token and uid were accepted. Using this option requires flash middleware
such as connect-flash. The success message will be stored as 'passwordless-success'
(example: 'You are now logged in!', default: null)
@param {Boolean} [options.enableOriginRedirect] - If set to true, the user will
be redirected to the URL he originally requested before he was redirected to the
login page. Requires that the URL was stored in the TokenStore when requesting a
token through requestToken() (default: false)
@return {ExpressMiddleware} Express middleware
@throws {Error} Will throw an error if there is no valid TokenStore, if failureFlash
or successFlash is used without flash middleware or allowPost is used without body
parser middleware | Passwordless.prototype.acceptToken ( options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.restricted = function(options) {
var self = this;
return function(req, res, next) {
if(req[self._userProperty]) {
return next();
}
// not authorized
options = options || {};
if(options.failureRedirect) {
var queryParam = '';
if(options.originField){
var parsedRedirectUrl = url.parse(options.failureRedirect), queryParam = '?';
if(parsedRedirectUrl.query) {
queryParam = '&';
}
queryParam += options.originField + '=' + encodeURIComponent(req.originalUrl);
}
if(options.failureFlash) {
if(!req.flash) {
throw new Error('To use failureFlash, flash middleware is requied such as connect-flash');
} else {
req.flash('passwordless', options.failureFlash);
}
}
self._redirectWithSessionSave(req, res, next, options.failureRedirect + queryParam);
} else if(options.failureFlash) {
throw new Error('failureFlash cannot be used without failureRedirect');
} else if(options.originField) {
throw new Error('originField cannot be used without failureRedirect');
} else {
self._send401(res, 'Provide a token');
}
}
} | Returns express middleware that ensures that only successfully authenticated users
have access to any middleware or responses that follows this middleware. Can either
be used for individual URLs or a certain path and any sub-elements. By default, a
401 error message is returned if the user has no access to the underlying resource.
@example
router.get('/admin', passwordless.restricted({ failureRedirect: '/login' }),
function(req, res) {
res.render('admin', { user: req.user });
});
@param {Object} [options]
@param {String} [options.failureRedirect] - If provided, the user will be redirected
to the given URL in case she is not authenticated. This would typically by a login
page (example: '/login', default: null)
@param {String} [options.failureFlash] - The error message to be flashed in case
the user is not authenticated. Using this option requires flash middleware such as
connect-flash. The message will be stored as 'passwordless'. Can only be used in
combination with failureRedirect (example: 'No access!', default: null)
@param {String} [options.originField] - If set, the originally requested URL will
be passed as query param (with the supplied name) to the redirect URL provided by
failureRedirect. Can only be used in combination with failureRedirect (example:
'origin', default: null)
@return {ExpressMiddleware} Express middleware
@throws {Error} Will throw an error if failureFlash is used without flash middleware,
failureFlash is used without failureRedirect, or originField is used without
failureRedirect | Passwordless.prototype.restricted ( options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.logout = function(options) {
var self = this;
return function(req, res, next) {
if(req.session && req.session.passwordless) {
delete req.session.passwordless;
}
if(req[self._userProperty]) {
self._tokenStore.invalidateUser(req[self._userProperty], function() {
delete req[self._userProperty];
if(options && options.successFlash) {
if(!req.flash) {
return next('To use successFlash, flash middleware is requied such as connect-flash');
} else {
req.flash('passwordless-success', options.successFlash);
}
}
next();
});
} else {
next();
}
}
} | Logs out the current user and invalidates any tokens that are still valid for the user
@example
router.get('/logout', passwordless.logout( {options.successFlash: 'All done!'} ),
function(req, res) {
res.redirect('/');
});
@param {Object} [options]
@param {String} [options.successFlash] - The success message to be flashed in case
has been logged in an the logout proceeded successfully. Using this option requires
flash middleware such as connect-flash. The success message will be stored as
'passwordless-success'. (example: 'You are now logged in!', default: null)
@return {ExpressMiddleware} Express middleware
@throws {Error} Will throw an error if successFlash is used without flash middleware | Passwordless.prototype.logout ( options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.sessionSupport = function() {
var self = this;
return function(req, res, next) {
if(!req.session) {
throw new Error('sessionSupport requires session middleware such as expressSession');
} else if (req.session.passwordless) {
req[self._userProperty] = req.session.passwordless;
}
next();
}
} | By adding this middleware function to a route, Passwordless automatically restores
the logged in user from the session. In 90% of the cases, this is what is required.
However, Passwordless can also work without session support in a stateless mode.
@example
var app = express();
var passwordless = new Passwordless(new DBTokenStore());
app.use(cookieParser());
app.use(expressSession({ secret: '42' }));
app.use(passwordless.sessionSupport());
app.use(passwordless.acceptToken());
@return {ExpressMiddleware} Express middleware
@throws {Error} Will throw an error no session middleware has been supplied | Passwordless.prototype.sessionSupport ( ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.requestToken = function(getUserID, options) {
var self = this;
options = options || {};
return function(req, res, next) {
var sendError = function(statusCode, authenticate) {
if(options.failureRedirect) {
if(options.failureFlash) {
req.flash('passwordless', options.failureFlash);
}
self._redirectWithSessionSave(req, res, next, options.failureRedirect);
} else {
if(statusCode === 401) {
self._send401(res, authenticate)
} else {
res.status(statusCode).send();
}
}
}
if(!self._tokenStore) {
throw new Error('Passwordless is missing a TokenStore. Are you sure you called passwordless.init()?');
}
if(!req.body && !options.allowGet) {
throw new Error('req.body does not exist: did you require middleware to accept POST data (such as body-parser) before calling acceptToken?')
} else if(!self._defaultDelivery && Object.keys(self._deliveryMethods).length === 0) {
throw new Error('passwordless requires at least one delivery method which can be added using passwordless.addDelivery()');
} else if((options.successFlash || options.failureFlash) && !req.flash) {
throw new Error('To use failureFlash or successFlash, flash middleware is required such as connect-flash');
} else if(options.failureFlash && !options.failureRedirect) {
throw new Error('failureFlash cannot be used without failureRedirect');
}
var userField = (options.userField) ? options.userField : 'user';
var deliveryField = (options.deliveryField) ? options.deliveryField : 'delivery';
var originField = (options.originField) ? options.originField : null;
var user, delivery, origin;
if(req.body && req.method === "POST") {
user = req.body[userField];
delivery = req.body[deliveryField];
if(originField) {
origin = req.body[originField];
}
} else if(options.allowGet && req.method === "GET") {
user = req.query[userField];
delivery = req.query[deliveryField];
if(originField) {
origin = req.query[originField];
}
}
var deliveryMethod = self._defaultDelivery;
if(delivery && self._deliveryMethods[delivery]) {
deliveryMethod = self._deliveryMethods[delivery];
}
if(typeof user === 'string' && user.length === 0) {
return sendError(401, 'Provide a valid user');
} else if(!deliveryMethod || !user) {
return sendError(400);
}
getUserID(user, delivery, function(uidError, uid) {
if(uidError) {
next(new Error('Error on the user verification layer: ' + uidError));
} else if(uid) {
var token;
try {
if(deliveryMethod.options.numberToken && deliveryMethod.options.numberToken.max) {
token = self._generateNumberToken(deliveryMethod.options.numberToken.max);
} else {
token = (deliveryMethod.options.tokenAlgorithm || self._generateToken())();
}
} catch(err) {
next(new Error('Error while generating a token: ' + err));
}
var ttl = deliveryMethod.options.ttl || 60 * 60 * 1000;
self._tokenStore.storeOrUpdate(token, uid.toString(), ttl, origin, function(storeError) {
if(storeError) {
next(new Error('Error on the storage layer: ' + storeError));
} else {
deliveryMethod.sendToken(token, uid, user, function(deliveryError) {
if(deliveryError) {
next(new Error('Error on the deliveryMethod delivery layer: ' + deliveryError));
} else {
if(!req.passwordless) {
req.passwordless = {};
}
req.passwordless.uidToAuth = uid;
if(options.successFlash) {
req.flash('passwordless-success', options.successFlash);
}
next();
}
}, req)
}
});
} else {
sendError(401, 'Provide a valid user');
}
}, req)
}
} | Requests a token from Passwordless for a specific user and calls the delivery strategy
to send the token to the user. Sends back a 401 error message if the user is not valid
or a 400 error message if no user information has been transmitted at all. By default,
POST params will be expected
@example
router.post('/sendtoken',
passwordless.requestToken(
function(user, delivery, callback, req) {
// usually you would want something like:
User.find({email: user}, callback(ret) {
if(ret)
callback(null, ret.id)
else
callback(null, null)
})
}),
function(req, res) {
res.render('sent');
});
@param {getUserID} getUserID The function called to resolve the supplied user contact
information (e.g. email) into a proper user ID: function(user, delivery, callback, req)
where user contains the contact details provided, delivery the method used, callback
expects a call in the format callback(error, user), where error is either null or an
error message and user is either null if not user has been found or the user ID. req
contains the Express request object
@param {Object} [options]
@param {String} [options.failureRedirect] - If provided, the user will be redirected
to the given URL in case the user details were not provided or could not be validated
by getUserId. This could typically by a login page (example: '/login', default: null)
@param {String} [options.failureFlash] - The error message to be flashed in case
the user details could not be validated. Using this option requires flash middleware
such as connect-flash. The message will be stored as 'passwordless'. Can only be used
in combination with failureRedirect (example: 'Your user details seem strange',
default: null)
@param {String} [options.successFlash] - The message to be flashed in case the tokens
were send out successfully. Using this option requires flash middleware such as
connect-flash. The message will be stored as 'passwordless-success '.
(example: 'Your token has been send', default: null)
@param {String} [options.userField] - The field which contains the user's contact
detail such as her email address (default: 'user')
@param {String} [options.deliveryField] - The field which contains the name of the
delivery method to be used. Only needed if several strategies have been added with
addDelivery() (default: null)
@param {String} [options.originField] - If set, requestToken() will look for any
URLs in this field that will be stored in the token database so that the user can
be redirected to this URL as soon as she is authenticated. Usually used to redirect
the user to the resource that she originally requested before being redirected to
the login page (default: null)
@param {Boolean} [options.allowGet] - If set, requestToken() will look for GET
parameters instead of POST (default: false)
@return {ExpressMiddleware} Express middleware
@throws {Error} Will throw an error if failureFlash is used without flash middleware,
failureFlash is used without failureRedirect, successFlash is used without flash
middleware, no body parser is used and POST parameters are expected, or if no
delivery method has been added | Passwordless.prototype.requestToken ( getUserID , options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype.addDelivery = function(name, sendToken, options) {
// So that add can be called with (sendToken [, options])
var defaultUsage = false;
if(typeof name === 'function') {
options = sendToken;
sendToken = name;
name = undefined;
defaultUsage = true;
}
options = options || {};
if(typeof sendToken !== 'function' || typeof options !== 'object'
|| (name && typeof name !== 'string')) {
throw new Error('Passwordless.addDelivery called with wrong parameters');
} else if((options.ttl && typeof options.ttl !== 'number') ||
(options.tokenAlgorithm && typeof options.tokenAlgorithm !== 'function') ||
(options.numberToken && (!options.numberToken.max || typeof options.numberToken.max !== 'number'))) {
throw new Error('One of the provided options is of the wrong format');
} else if(options.tokenAlgorithm && options.numberToken) {
throw new Error('options.tokenAlgorithm cannot be used together with options.numberToken');
} else if(this._defaultDelivery) {
throw new Error('Only one default delivery method shall be defined and not be mixed up with named methods. Use named delivery methods instead')
} else if(defaultUsage && Object.keys(this._deliveryMethods).length > 0) {
throw new Error('Default delivery methods and named delivery methods shall not be mixed up');
}
var method = {
sendToken: sendToken,
options: options
};
if(defaultUsage) {
this._defaultDelivery = method;
} else {
if(this._deliveryMethods[name]) {
throw new Error('Only one named delivery method with the same name shall be added')
} else {
this._deliveryMethods[name] = method;
}
}
} | Adds a new delivery method to Passwordless used to transmit tokens to the user. This could,
for example, be an email client or a sms client. If only one method is used, no name has to
provided as it will be the default delivery method. If several methods are used and added,
they will have to be named.
@example
passwordless.init(new MongoStore(pathToMongoDb));
passwordless.addDelivery(
function(tokenToSend, uidToSend, recipient, callback, req) {
// Send out token
smtpServer.send({
text: 'Hello!\nYou can now access your account here: '
+ host + '?token=' + tokenToSend + '&uid=' + encodeURIComponent(uidToSend),
from: yourEmail,
to: recipient,
subject: 'Token for ' + host
}, function(err, message) {
if(err) {
console.log(err);
}
callback(err);
});
});
@param {String} [name] - Name of the strategy. Not needed if only one method is added
@param {sendToken} sendToken - Method that will be called as
function(tokenToSend, uidToSend, recipient, callback, req) to transmit the token to the
user. tokenToSend contains the token, uidToSend the UID that has to be part of the
token URL, recipient contains the target such as an email address or a phone number
depending on the user input, and callback has to be called either with no parameters
or with callback({String}) in case of any issues during delivery
@param {Object} [options]
@param {Number} [options.ttl] - Duration in ms that the token shall be valid
(example: 1000*60*30, default: 1 hour)
@param {function()} [options.tokenAlgorithm] - The algorithm used to generate a token.
Function shall return the token in sync mode (default: Base58 token)
@param {Number} [options.numberToken.max] - Overwrites the default token generator
by a random number generator which generates numbers between 0 and max. Cannot be used
together with options.tokenAlgorithm | Passwordless.prototype.addDelivery ( name , sendToken , options ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype._send401 = function(res, authenticate) {
res.statusCode = 401;
if(authenticate) {
res.setHeader('WWW-Authenticate', authenticate);
}
res.end('Unauthorized');
} | Sends a 401 error message back to the user
@param {Object} res - Node's http res object
@private | Passwordless.prototype._send401 ( res , authenticate ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype._redirectWithSessionSave = function(req, res, next, target) {
if (!req.session || this._skipForceSessionSave) {
return res.redirect(target);
} else {
req.session.save(function(err) {
if (err) {
return next(err);
} else {
res.redirect(target);
}
});
}
}; | Avoids a bug in express that might lead to a redirect
before the session is actually saved
@param {Object} req - Node's http req object
@param {Object} res - Node's http res object
@param {Function} next - Middleware callback
@param {String} target - URL to redirect to
@private | Passwordless.prototype._redirectWithSessionSave ( req , res , next , target ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype._generateToken = function(randomBytes) {
randomBytes = randomBytes || 16;
return function() {
var buf = crypto.randomBytes(randomBytes);
return base58.encode(buf);
}
}; | Generates a random token using Node's crypto rng
@param {Number} randomBytes - Random bytes to be generated
@return {function()} token-generator function
@throws {Error} Will throw an error if there is no sufficient
entropy accumulated
@private | Passwordless.prototype._generateToken ( randomBytes ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
Passwordless.prototype._generateNumberToken = function(max) {
var buf = crypto.randomBytes(4);
return Math.floor(buf.readUInt32BE(0)%max).toString();
}; | Generates a strong random number between 0 and a maximum value. The
maximum value cannot exceed 2^32
@param {Number} max - Maximum number to be generated
@return {Number} Random number between 0 and max
@throws {Error} Will throw an error if there is no sufficient
entropy accumulated
@private | Passwordless.prototype._generateNumberToken ( max ) | javascript | florianheinemann/passwordless | lib/passwordless/passwordless.js | https://github.com/florianheinemann/passwordless/blob/master/lib/passwordless/passwordless.js | MIT |
const stdout = (char) => {
out += String.fromCharCode(char);
if (char === 10) {
console.log(out);
out = "";
}
}; | Process stdout stream
@param {number} char Next char in stream | = | javascript | joye61/pic-smaller | src/engines/GifWasmModule.js | https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js | MIT |
const stderr = (char) => {
err += String.fromCharCode(char);
if (char === 10) {
console.error(err);
err = "";
}
}; | Process stderr stream
@param {number} char Next char in stream | = | javascript | joye61/pic-smaller | src/engines/GifWasmModule.js | https://github.com/joye61/pic-smaller/blob/master/src/engines/GifWasmModule.js | MIT |
pixelbox.tilesheet = function(img) {
return Texture.prototype.setGlobalTilesheet(img);
}; | change default tilesheet used.
@param {Image | Texture | Map} img - tilesheet to use as default.
It can be any renderable thing in Pixelbox | pixelbox.tilesheet ( img ) | javascript | cstoquer/pixelbox | bootstrap.js | https://github.com/cstoquer/pixelbox/blob/master/bootstrap.js | MIT |
function Gamepad() {
this.available = false;
// buttons
this.btn = {};
this.btnp = {};
this.btnr = {};
// axes
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 0;
// trigger analog value
this.lt = 0;
this.rt = 0;
this._setupButtons();
} | @class Gamepad
@classdesc gamepad state
@attribute {boolean} available - is gamepaad available
@property {object} btn - button state
@property {boolean} btn.A - A button
@property {boolean} btn.B - B button
@property {boolean} btn.X - X button
@property {boolean} btn.Y - Y button
@property {boolean} btn.lb - left bumper button
@property {boolean} btn.rb - right bumper button
@property {boolean} btn.lt - left trigger button
@property {boolean} btn.rt - right trigger button
@property {boolean} btn.back - back button
@property {boolean} btn.start - start button
@property {boolean} btn.lp - first axis push button
@property {boolean} btn.rp - second axis push button
@property {boolean} btn.up - directional pad up button
@property {boolean} btn.down - directional pad down button
@property {boolean} btn.left - directional pad left button
@property {boolean} btn.right - directional pad right button
@property {object} btnp - button press. This object has the same structure as `btn` but the value are true only on button press
@property {object} btnr - button release. This object has the same structure as `btn` but the value are true only on button release
@property {number} x - x axe value (first stick horizontal)
@property {number} y - y axe value (first stick vertical)
@property {number} z - z axe value (second stick horizontal)
@property {number} w - w axe value (second stick vertical)
@property {number} lt - left trigger analog value
@property {number} rt - right trigger analog value | Gamepad ( ) | javascript | cstoquer/pixelbox | gamepad/index.js | https://github.com/cstoquer/pixelbox/blob/master/gamepad/index.js | MIT |
function getAnyGamepad() {
// buttons
for (var i = 0; i < MAPPING_BUTTONS.length; i++) {
var key = MAPPING_BUTTONS[i];
ANY_GAMEPADS.btnp[key] = btnp[key] || GAMEPADS[0].btnp[key] || GAMEPADS[1].btnp[key] || GAMEPADS[2].btnp[key] || GAMEPADS[3].btnp[key];
ANY_GAMEPADS.btnr[key] = btnr[key] || GAMEPADS[0].btnr[key] || GAMEPADS[1].btnr[key] || GAMEPADS[2].btnr[key] || GAMEPADS[3].btnr[key];
ANY_GAMEPADS.btn[key] = btn[key] || GAMEPADS[0].btn[key] || GAMEPADS[1].btn[key] || GAMEPADS[2].btn[key] || GAMEPADS[3].btn[key];
}
// forbid up and left or up and down to be set at the same time
if (ANY_GAMEPADS.btn.up && ANY_GAMEPADS.btn.down) ANY_GAMEPADS.btn.down = false;
if (ANY_GAMEPADS.btn.right && ANY_GAMEPADS.btn.left) ANY_GAMEPADS.btn.left = false;
// TODO: axes and triggers
return ANY_GAMEPADS;
}; | Merge states of keyboard and all gamepads and return a global gamepad state.
This is usefull for 1 player games when you don't want to bother with
gamepad configuration.
@todo Only works for gamepad buttons. Analog values (axes and triggers) are not handled
@return {Gamepad} gamepads merged state | getAnyGamepad ( ) | javascript | cstoquer/pixelbox | gamepad/index.js | https://github.com/cstoquer/pixelbox/blob/master/gamepad/index.js | MIT |
exports.mapAnalogStickToDpad = function (deadzone) {
MAP_ANALOG_STICK_TO_DPAD = true;
AXIS_DEADZONE = deadzone === undefined ? 0.3 : deadzone;
}; | Merge gamepad's left analog stick state (x, y axis) with Dpad.
@param {number} deadzone - stick minimum value before considering it as pressed | exports.mapAnalogStickToDpad ( deadzone ) | javascript | cstoquer/pixelbox | gamepad/index.js | https://github.com/cstoquer/pixelbox/blob/master/gamepad/index.js | MIT |
TileMap.prototype.draw = function (px, py, flipH, flipV, flipR) {
this._draw(px, py, flipH, flipV, flipR, pixelbox.$screen);
}; | NOTE: By overwriting draw, we prevent TileMap to create a Texture instance | TileMap.prototype.draw ( px , py , flipH , flipV , flipR ) | javascript | cstoquer/pixelbox | TileMap/webGL.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/webGL.js | MIT |
function Tile(x, y, sprite, flipH, flipV, flipR, flagA, flagB) {
this.x = ~~x;
this.y = ~~y;
this.sprite = ~~sprite;
this.flipH = !!flipH;
this.flipV = !!flipV;
this.flipR = !!flipR;
this.flagA = !!flagA;
this.flagB = !!flagB;
} | @class Tile
@property {number} x - x position in tilemap
@property {number} y - y position in tilemap
@property {number} sprite - sprite index (number between 0 and 255)
@property {boolean} flipH - flip horizontal
@property {boolean} flipV - flip vertical
@property {boolean} flipR - flip rotation
@property {boolean} flagA - user purpose flag A
@property {boolean} flagB - user purpose flag B | Tile ( x , y , sprite , flipH , flipV , flipR , flagA , flagB ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
function TileMap(width, height) {
this._name = '';
this.width = 0;
this.height = 0;
this.items = [];
this.texture = null;
this.tilesheet = null;
this._tilesheetPath = '';
if (width && height) this._init(width, height);
} | @class TileMap
@author Cedric Stoquer
@classdesc
A tilemap is a 2 dimensional array of tiles (`Tile`).
This can be used to reder a level made of tiles, or just to store game data.
A tilemap can be stored as an asset and is usually much smaller than a image because
the only data saved are tile ids (a number between 0 and 255) plus few flags
for how to render the tile (flipping horizontally, vertically, and 90 degree rotation).
For its rendering, a tilemap use one tilesheet, which is an Image containing 256
tiles organized in a 16 x 16 grid (the size of the tilesheet depend of the tile
size you set for your game). The tilesheet can be changed, and the whole map will
be redrawn.
You can create maps from your game code; But usually, you will be using Pixelbox's
tools to create and manage your maps as game assets. A map can then be retrived
by its name with Pixelbox's `getMap` function. The map can then be drawn on screen
(or in another Texture), modified, copied, pasted, resized, etc.
When stored in assets, the map is compressed to Pixelbox format to reduce file size.
@see Tile
@property (string) name - map name
@property {number} width - map width (in tiles)
@property {number} height - map height (in tiles)
@property {Tile[][]} items - 2D array of map items
@property {Texture} texture - generated texture | TileMap ( width , height ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.resize = function (width, height) {
var items = this.items;
var w = Math.min(this.width, width);
var h = Math.min(this.height, height);
this._init(width, height);
for (var x = 0; x < w; x++) {
for (var y = 0; y < h; y++) {
this.items[x][y] = items[x][y];
}}
this.redraw();
return this;
}; | Resize map
@param {number} width - map width
@param {number} heigth - map heigth | TileMap.prototype.resize ( width , height ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.set = function (x, y, sprite, flipH, flipV, flipR, flagA, flagB) {
if (sprite === null || sprite === undefined) return this.remove(x, y);
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return;
var item = this.items[x][y] = new Tile(x, y, sprite, flipH, flipV, flipR, flagA, flagB);
if (this.texture) {
this.texture.ctx.clearRect(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT);
this.texture.sprite(item.sprite, item.x * TILE_WIDTH, item.y * TILE_HEIGHT, item.flipH, item.flipV, item.flipR);
}
return this;
}; | Set a tile in the map, the texture is automatically updated with the tile
@param {number} x - x coordinate of the tile to add
@param {number} y - y coordinate of the tile to add
@param {number} sprite - sprite id of the tile (integer between 0 and 255)
@param {boolean} [flipH] - flip horizontal flag value
@param {boolean} [flipV] - flip vertical flag value
@param {boolean} [flipR] - flip rotation flag value
@param {boolean} [flagA] - user pupose flag A value
@param {boolean} [flagB] - user pupose flag Bvalue | TileMap.prototype.set ( x , y , sprite , flipH , flipV , flipR , flagA , flagB ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.remove = function (x, y) {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return;
this.items[x][y] = null;
if (this.texture) this.texture.ctx.clearRect(x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT);
return this;
}; | Remove a tile from the map by setting the item at the specified coordinate to null.
The internal texture is automatically updated.
@param {number} x - x coordinate of the tile to remove
@param {number} y - y coordinate of the tile to remove
@returns {Map} the map itself | TileMap.prototype.remove ( x , y ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.get = function (x, y) {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return null;
return this.items[x][y];
}; | Retrieve the map item at the specified coordinate.
@param {number} x - x coordinate of the tile to remove
@param {number} y - y coordinate of the tile to remove
@returns {Tile | null} tile value at specified coordinates | TileMap.prototype.get ( x , y ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.redraw = function () {
if (!this.texture) return this;
this.texture.clear();
for (var x = 0; x < this.width; x++) {
for (var y = 0; y < this.height; y++) {
var i = this.items[x][y];
if (i) this.texture.sprite(i.sprite, i.x * TILE_WIDTH, i.y * TILE_HEIGHT, i.flipH, i.flipV, i.flipR);
}}
return this;
}; | Redraw the texture.
@returns {Map} the map itself | TileMap.prototype.redraw ( ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.draw = function (x, y) {
if (!this.texture) this._prepareTexture();
draw(this.texture, x, y);
}; | Draw map on screen at specified position.
Alternatively, a map can be drawn from `Texture.draw(map)`
@param {number} x - x coordinate in pixels
@param {number} y - y coordinate in pixels | TileMap.prototype.draw ( x , y ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.setTilesheet = function (tilesheet) {
this.tilesheet = tilesheet;
this._tilesheetPath = tilesheet && tilesheet.path || '';
if (!this.texture) return this;
this.texture.setTilesheet(tilesheet);
this.redraw();
return this
}; | Set map tilesheet. The map is redrawn with the new tilesheet.
@param {Texture | Image | Sprite | null} tilesheet - the new tilesheet for the map.
If null, use the default tilesheet (assets/tilesheet).
@returns {Map} the map itself | TileMap.prototype.setTilesheet ( tilesheet ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.load = function (obj) {
this.texture = null;
var w = obj.w;
var h = obj.h;
this._init(w, h);
this.name = obj.name || '';
this._setTilesheetPath(obj.sheet);
var arr = decode(obj.data);
for (var x = 0; x < w; x++) {
for (var y = 0; y < h; y++) {
var d = arr[x + y * w];
if (d === null) continue;
var tile = d & 255;
var flipH = (d >> 8 ) & 1;
var flipV = (d >> 9 ) & 1;
var flipR = (d >> 10) & 1;
var flagA = (d >> 11) & 1;
var flagB = (d >> 12) & 1;
this.set(x, y, tile, flipH, flipV, flipR, flagA, flagB);
}}
return this;
}; | Deserialize a JSON object and set the data to this map.
@private
@param {object} obj - Pixelbox formated map data
@returns {Map} the map itself | TileMap.prototype.load ( obj ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.copy = function (x, y, w, h) {
x = x || 0;
y = y || 0;
if (w === undefined || w === null) w = this.width;
if (h === undefined || h === null) h = this.height;
var map = new TileMap(w, h);
map.paste(this, -x, -y);
return map;
}; | Copy this map to a new map. Tile are duplicated.
@param {number} [x] - x offset for the copy
@param {number} [y] - y offset for the copy
@param {number} [w] - width cropping (width of the copy)
@param {number} [h] - height cropping (height of the copy)
@returns {Map} the map copy | TileMap.prototype.copy ( x , y , w , h ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.paste = function (map, x, y, merge) {
x = x || 0;
y = y || 0;
var width = Math.min(map.width, this.width - x);
var height = Math.min(map.height, this.height - y);
var sx = Math.max(0, -x);
var sy = Math.max(0, -y);
for (var i = sx; i < width; i++) {
for (var j = sy; j < height; j++) {
var item = map.items[i][j];
if (!item) {
if (merge) continue;
this.remove(i + x, j + y);
continue;
}
this.set(i + x, j + y, item.sprite, item.flipH, item.flipV, item.flipR, item.flagA, item.flagB);
}
}
return this;
}; | Paste another map data in this map.
@param {Map} map - map to be pasted
@param {number} [x] - x offset of where to paste map
@param {number} [y] - y offset of where to paste map
@param {boolean} [merge] - if set, then null tiles will not overwrite current map tile.
@returns {Map} the map itself | TileMap.prototype.paste ( map , x , y , merge ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.clear = function () {
for (var x = 0; x < this.width; x++) {
for (var y = 0; y < this.height; y++) {
this.items[x][y] = null;
}}
if (this.texture) this.texture.clear();
return this;
}; | Clear the whole map content by setting all its items to null
@returns {Map} the map itself | TileMap.prototype.clear ( ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
TileMap.prototype.find = function (sprite, flagA, flagB) {
if (sprite === null) return this._findNull();
if (flagA === undefined) flagA = null;
if (flagB === undefined) flagB = null;
var result = [];
for (var x = 0; x < this.width; x++) {
for (var y = 0; y < this.height; y++) {
var item = this.items[x][y];
if (!item) continue;
var isSameFlagA = flagA === null || item.flagA === flagA;
var isSameFlagB = flagB === null || item.flagB === flagB;
if (item.sprite === sprite && isSameFlagA && isSameFlagB) result.push(item);
}}
return result;
}; | Find specific tiles in the map
@param {number} [sprite] - sprite id of the tile to find.
Set this parameter to null to find empty tiles.
@param {boolean} [flagA] - filter with flag A value
@param {boolean} [flagB] - filter with flag B value | TileMap.prototype.find ( sprite , flagA , flagB ) | javascript | cstoquer/pixelbox | TileMap/index.js | https://github.com/cstoquer/pixelbox/blob/master/TileMap/index.js | MIT |
function loadData(path, responseType, cb) {
var xobj = new XMLHttpRequest();
xobj.responseType = responseType || 'arraybuffer';
xobj.onreadystatechange = function onXhrStateChange() {
if (~~xobj.readyState !== 4) return;
if (~~xobj.status !== 200 && ~~xobj.status !== 0) {
return cb && cb('xhrError:' + xobj.status);
}
return cb && cb(null, xobj.response);
};
xobj.open('GET', path, true);
xobj.send();
} | @module assetLoader
@desc Loading functions helpers
@author Cedric Stoquer | loadData ( path , responseType , cb ) | javascript | cstoquer/pixelbox | assetLoader/index.js | https://github.com/cstoquer/pixelbox/blob/master/assetLoader/index.js | MIT |
function loadJson(path, cb) {
var xobj = new XMLHttpRequest();
xobj.onreadystatechange = function () {
if (~~xobj.readyState !== 4) return;
if (~~xobj.status !== 200) return cb('xhrError:' + xobj.status);
return cb && cb(null, JSON.parse(xobj.response));
};
xobj.open('GET', path, true);
xobj.send();
} | @function module:loader.loadJson
@desc load a json file
@param {String} path - file path
@param {Function} cb - asynchronous callback function | loadJson ( path , cb ) | javascript | cstoquer/pixelbox | assetLoader/index.js | https://github.com/cstoquer/pixelbox/blob/master/assetLoader/index.js | MIT |
function loadImage(path, cb) {
var img = new Image();
// TODO: remove listeners when load / error
img.onload = function () {
this.onload = null;
this.onerror = null;
cb && cb(null, this);
};
img.onerror = function () {
this.onload = null;
this.onerror = null;
cb && cb('img:' + path);
};
img.src = path;
} | @function module:loader.loadImage
@desc load an image file
@param {String} path - file path
@param {Function} cb - asynchronous callback function | loadImage ( path , cb ) | javascript | cstoquer/pixelbox | assetLoader/index.js | https://github.com/cstoquer/pixelbox/blob/master/assetLoader/index.js | MIT |
function loadSound(path, cb) {
var snd = new Audio();
snd.preload = true;
snd.loop = false;
function onSoundLoad() {
cb && cb(null, snd);
snd.removeEventListener('canplaythrough', onSoundLoad);
snd.removeEventListener('error', onSoundError);
}
function onSoundError() {
cb && cb('snd:load');
snd.removeEventListener('canplaythrough', onSoundLoad);
snd.removeEventListener('error', onSoundError);
}
snd.addEventListener('canplaythrough', onSoundLoad);
snd.addEventListener('error', onSoundError);
snd.src = path;
snd.load();
} | @function module:loader.loadSound
@desc load an image file
@param {String} path - file path
@param {Function} cb - asynchronous callback function | loadSound ( path , cb ) | javascript | cstoquer/pixelbox | assetLoader/index.js | https://github.com/cstoquer/pixelbox/blob/master/assetLoader/index.js | MIT |
function preloadStaticAssets(assetList, cb, onEachLoad) {
var data = assetList.dat;
var imgCount = assetList.img.length;
var count = imgCount + assetList.snd.length;
var root = assetList.root;
var load = 0;
var done = 0;
function storeAsset(path, obj) {
var splitted = path.split('/');
var filename = splitted.pop();
var id = filename.split('.');
id.pop();
id = id.join('.');
var container = data;
for (var i = 0, len = splitted.length; i < len; i++) {
container = container[splitted[i]];
}
container[id] = obj;
splitted.push(id);
obj.name = id;
obj.path = splitted.join('/');
}
function loadAssets() {
var current = load + done;
var percent = current / count;
onEachLoad && onEachLoad(load, current, count, percent);
var path;
var loadFunc;
if (current < imgCount) {
path = assetList.img[current];
loadFunc = loadImage;
} else {
path = assetList.snd[current - imgCount];
loadFunc = loadSound;
}
done += 1;
loadFunc(root + path, function onAssetLoaded(error, img) {
if (!error) storeAsset(path, img);
load += 1;
done -= 1;
if (load + done < count) loadAssets()
else if (done === 0) cb(null, data);
});
}
// loading assets in parallel, with a limit of 5 parallel downloads.
if (count === 0) return cb(null, data);
var parallel = Math.min(5, count - 1);
for (var j = 0; j <= parallel; j++) loadAssets();
// });
} | @function module:loader.preloadStaticAssets
@desc Preload all static assets of the game.
The function first ask the server for the asset list.
Server respond with an object containing the list of images
to load and all data that are put in the www/asset folder.
At this step, if request fail, function send an error.
The function then proceed the loading of image assets.
If an image loading fail, the loading continue, and loading
status is set to 1 (an image load fail).
Images are load by 5 in parallel.
Function end and wil return an object that mix all data and
all assets so that it will have the same structure as the
'assets' folder.
Assets list and data are automaticaly generated by server
Just drop images and json files in the www/asset/ folder
and the server will take care of it !
@param {Function} cb - asynchronous callback function to
call when all is preloaded
@param {Function} onEachLoad - optional callback function called
every time one file is loaded
(for loading progress purpose) | preloadStaticAssets ( assetList , cb , onEachLoad ) | javascript | cstoquer/pixelbox | assetLoader/index.js | https://github.com/cstoquer/pixelbox/blob/master/assetLoader/index.js | MIT |
Texture.prototype.locate = function (i, j) {
this._cursor.i = ~~i;
this._cursor.j = ~~j;
return this;
}; | Set cursor position for the text.
@param {number} i - cursor x position in character size (4 pixels)
@param {number} j - cursor y position in character size (6 pixels)
@returns {Texture} the texture itself | Texture.prototype.locate ( i , j ) | javascript | cstoquer/pixelbox | Texture/textCanvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/textCanvas2D.js | MIT |
Texture.prototype.print = function (str, x, y) {
// string transformation
if (typeof str === 'object') {
try {
str = JSON.stringify(str);
} catch (error) {
str = '[Object]';
}
} else if (typeof str !== 'string') {
str = str.toString();
}
var color = this.palette[this._pen].string;
var charset = CHARSET.getColor(color);
// print at cooordinate
if (x !== undefined) {
x = ~~Math.round(x - this.camera.x);
y = ~~Math.round(y - this.camera.y);
var originX = x;
for (var i = 0; i < str.length; i++) {
var chr = str.charCodeAt(i);
if (chr === 10 || chr === 13) {
y += CHAR_HEIGHT;
x = originX;
continue;
}
chr -= 32;
if (chr < 0 || chr > 255) {
x += CHAR_WIDTH;
continue;
}
var sx = CHAR_WIDTH * (chr % CHAR_PER_LINE);
var sy = CHAR_HEIGHT * ~~(chr / CHAR_PER_LINE);
this.ctx.drawImage(
charset,
sx,
sy,
CHAR_WIDTH, CHAR_HEIGHT,
x, y,
CHAR_WIDTH, CHAR_HEIGHT
);
x += CHAR_WIDTH;
}
return this;
}
// print at cursor
var i = this._cursor.i;
var j = this._cursor.j;
for (var c = 0; c < str.length; c++) {
if (this.width - i * CHAR_WIDTH < CHAR_WIDTH) {
i = 0;
j += 1;
}
if (this.height - j * CHAR_HEIGHT < CHAR_HEIGHT) {
this.textScroll();
j -= 1;
}
var chr = str.charCodeAt(c);
if (chr === 10 || chr === 13) {
i = 0;
j += 1;
continue;
}
chr -= 32;
if (chr < 0 || chr > 255) {
i += 1;
continue;
}
var sx = CHAR_WIDTH * (chr % CHAR_PER_LINE);
var sy = CHAR_HEIGHT * ~~(chr / CHAR_PER_LINE);
this.ctx.drawImage(
charset,
sx,
sy,
CHAR_WIDTH, CHAR_HEIGHT,
i * CHAR_WIDTH,
j * CHAR_HEIGHT,
CHAR_WIDTH, CHAR_HEIGHT
);
i += 1;
}
this._cursor.i = i;
this._cursor.j = j;
return this;
}; | Print text. A position in pixel can be specified. If you do so, the text
will be drawn at specified position plus camera offset. If not, the text is
printed at current cursor position and wil wrap and make screen scroll down
when cursor reach the texture bottom.
@param (string) str - text to be printed
@param (number) [x] - text x position in pixel
@param (number) [y] - text y position in pixel
@returns {Texture} the texture itself | Texture.prototype.print ( str , x , y ) | javascript | cstoquer/pixelbox | Texture/textCanvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/textCanvas2D.js | MIT |
Texture.prototype.println = function (str) {
this.print(str);
this.print('\n');
return this;
}; | Same as print and add a go to the next line.
@param (string) str - text to be printed
@returns {Texture} the texture itself | Texture.prototype.println ( str ) | javascript | cstoquer/pixelbox | Texture/textCanvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/textCanvas2D.js | MIT |
Texture.prototype.resize = function (width, height) {
this.canvas.width = this.width = width;
this.canvas.height = this.height = height;
this.clear();
return this;
}; | Resize texture. The texture is cleared.
@param {number} width - texture new width in pixels
@param {number} height - texture new height in pixels
@returns {Texture} the texture itself | Texture.prototype.resize ( width , height ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.sprite = function (tile, x, y, flipH, flipV, flipR) {
var sx = TILE_WIDTH * (tile % TILES_PER_LINE);
var sy = TILE_HEIGHT * ~~(tile / TILES_PER_LINE);
var ctx = this.ctx;
// add camera and round to the pixel
x = x || 0;
y = y || 0;
x = ~~Math.round(x - this.camera.x);
y = ~~Math.round(y - this.camera.y);
if (!flipH && !flipV && !flipR) {
ctx.drawImage(this.tilesheet, this.ox + sx, this.oy + sy, TILE_WIDTH, TILE_HEIGHT, x, y, TILE_WIDTH, TILE_HEIGHT);
return this;
}
ctx.save();
if (flipH) {
ctx.scale(-1, 1);
x = -x - TILE_WIDTH;
}
if (flipV) {
ctx.scale(1, -1);
y = -y - TILE_HEIGHT;
}
if (flipR) {
ctx.translate(x + TILE_HEIGHT, y);
ctx.rotate(PI2);
} else {
ctx.translate(x, y);
}
ctx.drawImage(this.tilesheet, this.ox + sx, this.oy + sy, TILE_WIDTH, TILE_HEIGHT, 0, 0, TILE_WIDTH, TILE_HEIGHT);
ctx.restore();
return this;
}; | Draw a tile in Texture using the current tilesheet.
@param {number} tile - tile index (number between 0 and 255)
@param {number} [x] - x position in pixels
@param {number} [y] - y position in pixels
@param {boolean} [flipH] - if set, the tile is horizontally flipped
@param {boolean} [flipV] - if set, the tile is vertically flipped
@param {boolean} [flipR] - if set, the tile rotated by 90 degree
@returns {Texture} the texture itself | Texture.prototype.sprite ( tile , x , y , flipH , flipV , flipR ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.draw = function (img, x, y, flipH, flipV, flipR) {
if (!img) {
console.error('Invalid asset');
return this;
}
if (img._isNineSlice) {
img._draw(this, x, y, flipH, flipV);
return this;
}
var hasFlip = flipH || flipV || flipR;
// spritesheet element
if (img._isSprite) {
var sprite = img;
img = sprite.img;
var sx = sprite.x;
var sy = sprite.y;
var sw = sprite.width;
var sh = sprite.height;
// TODO: pivot point
var px = ~~Math.round((x || 0) - this.camera.x);
var py = ~~Math.round((y || 0) - this.camera.y);
if (!hasFlip) {
// fast version
this.ctx.drawImage(img, sx, sy, sw, sh, px, py, sw, sh);
return this;
}
var ctx = this.ctx;
ctx.save();
if (flipR) {
if (flipH) { ctx.scale(-1, 1); px *= -1; px -= sh; }
if (flipV) { ctx.scale(1, -1); py *= -1; py -= sw; }
ctx.translate(px + sh, py);
ctx.rotate(PI2);
} else {
if (flipH) { ctx.scale(-1, 1); px *= -1; px -= sw; }
if (flipV) { ctx.scale(1, -1); py *= -1; py -= sh; }
ctx.translate(px, py);
}
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
ctx.restore();
return this;
}
// Image, Texture or TileMap
if (img._isTileMap) {
if (!img.texture) img._prepareTexture();
img = img.texture.canvas;
}
if (img._isTexture) img = img.canvas;
var px = ~~Math.round((x || 0) - this.camera.x);
var py = ~~Math.round((y || 0) - this.camera.y);
if (!hasFlip) {
// fast version
this.ctx.drawImage(img, px, py);
return this;
}
var ctx = this.ctx;
ctx.save();
if (flipR) {
if (flipH) { ctx.scale(-1, 1); px *= -1; px -= img.height; }
if (flipV) { ctx.scale(1, -1); py *= -1; py -= img.width; }
ctx.translate(px + img.height, py);
ctx.rotate(PI2);
} else {
if (flipH) { ctx.scale(-1, 1); px *= -1; px -= img.width; }
if (flipV) { ctx.scale(1, -1); py *= -1; py -= img.height; }
ctx.translate(px, py);
}
ctx.drawImage(img, 0, 0);
ctx.restore();
return this;
}; | Draw an Image (or anything drawable) in the texture
@param {Image | Canvas | Texture | Map} element - thing to draw in the texture
@param {number} [x] - x coordinate of where to draw the image. The value is offseted by Texture's camera position
@param {number} [y] - y coordinate of where to draw the image. The value is offseted by Texture's camera position
@param {boolean} [flipH] - if set, the image is horizontally flipped
@param {boolean} [flipV] - if set, the image is vertically flipped
@param {boolean} [flipR] - if set, the image rotated by 90 degree
@returns {Texture} the texture itself | Texture.prototype.draw ( img , x , y , flipH , flipV , flipR ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.clear = function () {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
return this;
}; | Clear the whole texture (make it transparent)
@returns {Texture} the texture itself | Texture.prototype.clear ( ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.cls = function () {
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
return this;
}; | Clear texture with current paper color (CLear Screen)
@returns {Texture} the texture itself | Texture.prototype.cls ( ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.pen = function (p) {
this._pen = p % this.palette.length;
this.ctx.strokeStyle = this.palette[this._pen].string;
return this;
}; | Set PEN color index. This color is used when printing text in the texture,
and for outline when drawing shapes.
@param {number} p - pen color index in the palette
@returns {Texture} the texture itself | Texture.prototype.pen ( p ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.paper = function (p) {
this._paper = p % this.palette.length;
this.ctx.fillStyle = this.palette[this._paper].string;
return this;
}; | Set PAPER color index. This color is used for fill when drawing shapes
or when clearing the texture (cls)
@param {number} p - pen color index in the palette
@returns {Texture} the texture itself | Texture.prototype.paper ( p ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.rect = function (x, y, w, h) {
if (w <= 1 || h <= 1) {
var fill = this.ctx.fillStyle;
this.ctx.fillStyle = this.ctx.strokeStyle;
this.ctx.fillRect(~~(x - this.camera.x), ~~(y - this.camera.y), ~~w, ~~h);
this.ctx.fillStyle = fill;
return this;
}
this.ctx.strokeRect(~~(x - this.camera.x) + 0.5, ~~(y - this.camera.y) + 0.5, ~~(w - 1), ~~(h - 1));
return this;
}; | Draw an outlined rectangle, using current PEN color.
Drawing is offset by Texture's camera.
@param {number} x - x coordinate of rectangle upper left corner
@param {number} y - y coordinate of rectangle upper left corner
@param {number} w - rectangle width
@param {number} h - rectangle height
@returns {Texture} the texture itself | Texture.prototype.rect ( x , y , w , h ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
Texture.prototype.rectf = function (x, y, w, h) {
this.ctx.fillRect(~~(x - this.camera.x), ~~(y - this.camera.y), ~~w, ~~h);
return this;
}; | Draw a filled rectangle, using current PAPER color.
Drawing is offset by Texture's camera.
The minimum size of a filled rectangle is 2.
If `w` or `h` is smaller than 2, nothing is drawn.
@param {number} x - x coordinate of rectangle upper left corner
@param {number} y - y coordinate of rectangle upper left corner
@param {number} w - rectangle width
@param {number} h - rectangle height
@returns {Texture} the texture itself | Texture.prototype.rectf ( x , y , w , h ) | javascript | cstoquer/pixelbox | Texture/canvas2D.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/canvas2D.js | MIT |
function Texture(width, height) {
this.width = width;
this.height = height;
this.camera = { x: 0, y: 0 }; // camera offset
this._cursor = { i: 0, j: 0 }; // text cursor
this._paper = 0; // paper color index
this._pen = 1; // pen color index
this._init();
} | @class Texture
@author Cedric Stoquer
@classdesc
Wrap a canvas with functionalities for Pixelbox rendering.
Main screen (accessible on `$screen`) is an instance of that class and most of its methods
are also accessible from the global scope.
@param {number} width - Texture width in pixel
@param {number} height - Texture height in pixel
@property {Canvas} canvas - HTML canvas element
@property {Canvas2DContext} ctx - canvas's context 2D
@property {string[]} palette - Texture's color palette
@property {Texture} tilesheet - Texture's tilesheet | Texture ( width , height ) | javascript | cstoquer/pixelbox | Texture/index.js | https://github.com/cstoquer/pixelbox/blob/master/Texture/index.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.