Merge pull request #956 from kchadha/validate-sb2

Validate sb2
This commit is contained in:
kchadha 2018-03-02 10:28:53 -05:00 committed by GitHub
commit a0c7d9aeb3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 8 deletions

View file

@ -55,6 +55,7 @@
"promise": "8.0.1",
"scratch-audio": "latest",
"scratch-blocks": "latest",
"scratch-parser": "latest",
"scratch-render": "latest",
"scratch-storage": "^0.4.0",
"script-loader": "0.7.2",

View file

@ -9,6 +9,8 @@ const sb2 = require('./serialization/sb2');
const sb3 = require('./serialization/sb3');
const StringUtil = require('./util/string-util');
const formatMessage = require('format-message');
const validate = require('scratch-parser');
const Variable = require('./engine/variable');
const {loadCostume} = require('./import/load-costume.js');
@ -226,26 +228,36 @@ class VirtualMachine extends EventEmitter {
// Validate & parse
if (typeof json !== 'string' && typeof json !== 'object') {
log.error('Failed to parse project. Invalid type supplied to fromJSON.');
return;
throw new Error('Failed to parse project. Invalid type supplied to fromJSON.');
}
// Attempt to parse JSON if string is supplied
if (typeof json === 'string') json = JSON.parse(json);
// Establish version, deserialize, and load into runtime
// @todo Support Scratch 1.4
// @todo This is an extremely naïve / dangerous way of determining version.
// See `scratch-parser` for a more sophisticated validation
// methodology that should be adapted for use here
let deserializer;
if ((typeof json.meta !== 'undefined') && (typeof json.meta.semver !== 'undefined')) {
let validatedProject;
const possibleSb3 = typeof json === 'string' ? JSON.parse(json) : json;
if ((typeof possibleSb3.meta !== 'undefined') && (typeof possibleSb3.meta.semver !== 'undefined')) {
deserializer = sb3;
validatedProject = possibleSb3;
} else {
// scratch-parser expects a json string or a buffer
const possibleSb2 = typeof json === 'object' ? JSON.stringify(json) : json;
validate(possibleSb2, (err, project) => {
if (err) {
throw new Error(
`The given project could not be validated, parsing failed with error: ${JSON.stringify(err)}`);
} else {
deserializer = sb2;
validatedProject = project;
}
});
}
return deserializer.deserialize(json, this.runtime)
return deserializer.deserialize(validatedProject, this.runtime)
.then(({targets, extensions}) =>
this.installTargets(targets, extensions, true));
}