From 6ee59cd46e5735a0c10fdad039d1f6f6950ad32f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Lehni?= Date: Fri, 10 Mar 2017 23:56:06 +0100 Subject: [PATCH] Prevent leakage of bundled Acorn into window.acorn And fix Acorn loading under load.js --- src/core/PaperScript.js | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/core/PaperScript.js b/src/core/PaperScript.js index 9f95fe53..b27e341d 100644 --- a/src/core/PaperScript.js +++ b/src/core/PaperScript.js @@ -15,18 +15,31 @@ * @namespace */ Base.exports.PaperScript = function() { - // Locally turn of exports and define for inlined acorn. - // Just declaring the local vars is enough, as they will be undefined. - var exports, define, - acorn = this.acorn; - // Try importing an outside version of acorn first, and fall back on the - // internal v0.5, which is kept at that version of small size, for now. - if (typeof require !== 'undefined') { + // `this` == global scope, as the function is called with `.call(this);` + var global = this, + // See if there is a global Acorn in the browser already. + acorn = global.acorn; + // Also try importing an outside version of Acorn, and fall back on the + // internal v0.5.0, which is kept at that version of small size, for now. + if (!acorn && typeof require !== 'undefined') { try { acorn = require('acorn'); } catch(e) {} } + // If no Acorn was found, load the bundled version. if (!acorn) { -/*#*/ include('../../node_modules/acorn/acorn.min.js', { exports: false }); - acorn = this.acorn; + // Provide our own local exports and module object so that Acorn gets + // assigned to it and ends up in the local acorn object. + var exports, module; + acorn = exports = module = {}; +/*#*/ include('../../node_modules/acorn/acorn.js', { exports: false }); + // Clear object again if it wasn't loaded here; for load.js, see below. + if (!acorn.version) + acorn = null; + } + + function parse(code, options) { + // NOTE: When using load.js, Acorn will end up in global.acorn and will + // not be immediately available, so we need to check for it here again: + return (acorn || global.acorn).parse(code, options); } // Operators to overload @@ -96,10 +109,6 @@ Base.exports.PaperScript = function() { // AST Helpers - function parse(code, options) { - return acorn.parse(code, options); - } - /** * Compiles PaperScript code into JavaScript code. *