2018-03-20 12:59:29 -04:00
|
|
|
var unzip = require('./unzip');
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
/**
|
2018-02-26 15:42:12 -05:00
|
|
|
* If input a buffer, transforms buffer into a UTF-8 string.
|
2019-03-15 12:23:40 -04:00
|
|
|
* If input is encoded in zip format, the input will be extracted and decoded.
|
2018-02-26 15:42:12 -05:00
|
|
|
* If input is a string, passes that string along to the given callback.
|
2018-05-02 18:17:32 -04:00
|
|
|
* @param {Buffer | string} input Project data
|
2018-05-02 17:10:52 -04:00
|
|
|
* @param {boolean} isSprite Whether the input should be treated as
|
|
|
|
* a sprite (true) or a whole project (false)
|
2018-03-24 11:09:43 -04:00
|
|
|
* @param {Function} callback Error or stringified project data
|
|
|
|
* @return {void}
|
2016-03-18 19:51:40 -04:00
|
|
|
*/
|
2018-05-02 18:17:32 -04:00
|
|
|
module.exports = function (input, isSprite, callback) {
|
2018-02-26 15:42:12 -05:00
|
|
|
if (typeof input === 'string') {
|
|
|
|
// Pass string to callback
|
2018-03-15 18:25:36 -04:00
|
|
|
return callback(null, [input, null]);
|
2018-02-26 15:42:12 -05:00
|
|
|
}
|
|
|
|
|
2016-03-18 19:51:40 -04:00
|
|
|
// Validate input type
|
2018-02-26 15:42:12 -05:00
|
|
|
var typeError = 'Input must be a Buffer or a string.';
|
|
|
|
if (!Buffer.isBuffer(input)) {
|
2018-03-15 18:25:36 -04:00
|
|
|
try {
|
|
|
|
input = new Buffer(input);
|
|
|
|
} catch (e) {
|
|
|
|
return callback(typeError);
|
|
|
|
}
|
2018-02-26 15:42:12 -05:00
|
|
|
}
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
// Determine format
|
|
|
|
// We don't use the file suffix as this is unreliable and mine-type
|
|
|
|
// information is unavailable from Scratch's project CDN. Instead, we look
|
|
|
|
// at the first few bytes from the provided buffer (byte signature).
|
|
|
|
// https://en.wikipedia.org/wiki/List_of_file_signatures
|
|
|
|
var signature = input.slice(0, 3).join(' ');
|
|
|
|
var isLegacy = false;
|
|
|
|
var isZip = false;
|
|
|
|
|
|
|
|
if (signature.indexOf('83 99 114') === 0) isLegacy = true;
|
|
|
|
if (signature.indexOf('80 75') === 0) isZip = true;
|
|
|
|
|
2019-03-15 12:23:40 -04:00
|
|
|
// If not legacy or zip, convert buffer to UTF-8 string and return
|
|
|
|
if (!isZip && !isLegacy) {
|
2018-03-15 18:25:36 -04:00
|
|
|
return callback(null, [input.toString('utf-8'), null]);
|
|
|
|
}
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
// Return error if legacy encoding detected
|
2018-04-05 13:32:06 -04:00
|
|
|
if (isLegacy) return callback('Parser only supports Scratch 2.X and above');
|
2016-03-18 19:51:40 -04:00
|
|
|
|
2019-03-15 12:23:40 -04:00
|
|
|
unzip(input, isSprite, callback);
|
2016-03-18 19:51:40 -04:00
|
|
|
};
|