Debian Codegraph @

rhino/src/org/mozilla/javascript/commonjs/module/Require.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.commonjs.module;
6
7 import java.io.File;
8 import java.net.URI;
9 import java.net.URISyntaxException;
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.concurrent.ConcurrentHashMap;
13
14 import org.mozilla.javascript.BaseFunction;
15 import org.mozilla.javascript.Context;
16 import org.mozilla.javascript.Script;
17 import org.mozilla.javascript.ScriptRuntime;
18 import org.mozilla.javascript.Scriptable;
19 import org.mozilla.javascript.ScriptableObject;
20
21 /**
22 * Implements the require() function as defined by
23 * <a href="http://wiki.commonjs.org/wiki/Modules/1.1">Common JS modules</a>.
24 * <h1>Thread safety</h1>
25 * You will ordinarily create one instance of require() for every top-level
26 * scope. This ordinarily means one instance per program execution, except if
27 * you use shared top-level scopes and installing most objects into them.
28 * Module loading is thread safe, so using a single require() in a shared
29 * top-level scope is also safe.
30 * <h1>Creation</h1>
31 * If you need to create many otherwise identical require() functions for
32 * different scopes, you might want to use {@link RequireBuilder} for
33 * convenience.
34 * <h1>Making it available</h1>
35 * In order to make the require() function available to your JavaScript
36 * program, you need to invoke either {@link #install(Scriptable)} or
37 * {@link #requireMain(Context, String)}.
38 * @author Attila Szegedi
39 * @version $Id: Require.java,v 1.4 2011/04/07 20:26:11 hannes%helma.at Exp $
40 */
41 public class Require extends BaseFunction
42 {
43 private static final long serialVersionUID = 1L;
44
45 private final ModuleScriptProvider moduleScriptProvider;
46 private final Scriptable nativeScope;
47 private final Scriptable paths;
48 private final boolean sandboxed;
49 private final Script preExec;
50 private final Script postExec;
51 private String mainModuleId = null;
52 private Scriptable mainExports;
53
54 // Modules that completed loading; visible to all threads
55 private final Map<String, Scriptable> exportedModuleInterfaces =
56 new ConcurrentHashMap<String, Scriptable>();
57 private final Object loadLock = new Object();
58 // Modules currently being loaded on the thread. Used to resolve circular
59 // dependencies while loading.
60 private static final ThreadLocal<Map<String, Scriptable>>
61 loadingModuleInterfaces = new ThreadLocal<Map<String,Scriptable>>();
62
63 /**
64 * Creates a new instance of the require() function. Upon constructing it,
65 * you will either want to install it in the global (or some other) scope
66 * using {@link #install(Scriptable)}, or alternatively, you can load the
67 * program's main module using {@link #requireMain(Context, String)} and
68 * then act on the main module's exports.
69 * @param cx the current context
70 * @param nativeScope a scope that provides the standard native JavaScript
71 * objects.
72 * @param moduleScriptProvider a provider for module scripts
73 * @param preExec an optional script that is executed in every module's
74 * scope before its module script is run.
75 * @param postExec an optional script that is executed in every module's
76 * scope after its module script is run.
77 * @param sandboxed if set to true, the require function will be sandboxed.
78 * This means that it doesn't have the "paths" property, and also that the
79 * modules it loads don't export the "module.uri" property.
80 */
81 public Require(Context cx, Scriptable nativeScope,
82 ModuleScriptProvider moduleScriptProvider, Script preExec,
83 Script postExec, boolean sandboxed) {
84 this.moduleScriptProvider = moduleScriptProvider;
85 this.nativeScope = nativeScope;
86 this.sandboxed = sandboxed;
87 this.preExec = preExec;
88 this.postExec = postExec;
89 setPrototype(ScriptableObject.getFunctionPrototype(nativeScope));
90 if(!sandboxed) {
91 paths = cx.newArray(nativeScope, 0);
92 defineReadOnlyProperty(this, "paths", paths);
93 }
94 else {
95 paths = null;
96 }
97 }
98
99 /**
100 * Calling this method establishes a module as being the main module of the
101 * program to which this require() instance belongs. The module will be
102 * loaded as if require()'d and its "module" property will be set as the
103 * "main" property of this require() instance. You have to call this method
104 * before the module has been loaded (that is, the call to this method must
105 * be the first to require the module and thus trigger its loading). Note
106 * that the main module will execute in its own scope and not in the global
107 * scope. Since all other modules see the global scope, executing the main
108 * module in the global scope would open it for tampering by other modules.
109 * @param cx the current context
110 * @param mainModuleId the ID of the main module
111 * @return the "exports" property of the main module
112 * @throws IllegalStateException if the main module is already loaded when
113 * required, or if this require() instance already has a different main
114 * module set.
115 */
116 public Scriptable requireMain(Context cx, String mainModuleId) {
117 if(this.mainModuleId != null) {
118 if (!this.mainModuleId.equals(mainModuleId)) {
119 throw new IllegalStateException("Main module already set to " +
120 this.mainModuleId);
121 }
122 return mainExports;
123 }
124
125 ModuleScript moduleScript;
126 try {
127 // try to get the module script to see if it is on the module path
128 moduleScript = moduleScriptProvider.getModuleScript(
129 cx, mainModuleId, null, null, paths);
130 } catch (RuntimeException x) {
131 throw x;
132 } catch (Exception x) {
133 throw new RuntimeException(x);
134 }
135
136 if (moduleScript != null) {
137 mainExports = getExportedModuleInterface(cx, mainModuleId,
138 null, null, true);
139 } else if (!sandboxed) {
140
141 URI mainUri = null;
142
143 // try to resolve to an absolute URI or file path
144 try {
145 mainUri = new URI(mainModuleId);
146 } catch (URISyntaxException usx) {
147 // fall through
148 }
149
150 // if not an absolute uri resolve to a file path
151 if (mainUri == null || !mainUri.isAbsolute()) {
152 File file = new File(mainModuleId);
153 if (!file.isFile()) {
154 throw ScriptRuntime.throwError(cx, nativeScope,
155 "Module \"" + mainModuleId + "\" not found.");
156 }
157 mainUri = file.toURI();
158 }
159 mainExports = getExportedModuleInterface(cx, mainUri.toString(),
160 mainUri, null, true);
161 }
162
163 this.mainModuleId = mainModuleId;
164 return mainExports;
165 }
166
167 /**
168 * Binds this instance of require() into the specified scope under the
169 * property name "require".
170 * @param scope the scope where the require() function is to be installed.
171 */
172 public void install(Scriptable scope) {
173 ScriptableObject.putProperty(scope, "require", this);
174 }
175
176 @Override
177 public Object call(Context cx, Scriptable scope, Scriptable thisObj,
178 Object[] args)
179 {
180 if(args == null || args.length < 1) {
181 throw ScriptRuntime.throwError(cx, scope,
182 "require() needs one argument");
183 }
184
185 String id = (String)Context.jsToJava(args[0], String.class);
186 URI uri = null;
187 URI base = null;
188 if (id.startsWith("./") || id.startsWith("../")) {
189 if (!(thisObj instanceof ModuleScope)) {
190 throw ScriptRuntime.throwError(cx, scope,
191 "Can't resolve relative module ID \"" + id +
192 "\" when require() is used outside of a module");
193 }
194
195 ModuleScope moduleScope = (ModuleScope) thisObj;
196 base = moduleScope.getBase();
197 URI current = moduleScope.getUri();
198 uri = current.resolve(id);
199
200 if (base == null) {
201 // calling module is absolute, resolve to absolute URI
202 // (but without file extension)
203 id = uri.toString();
204 } else {
205 // try to convert to a relative URI rooted on base
206 id = base.relativize(current).resolve(id).toString();
207 if (id.charAt(0) == '.') {
208 // resulting URI is not contained in base,
209 // throw error or make absolute depending on sandbox flag.
210 if (sandboxed) {
211 throw ScriptRuntime.throwError(cx, scope,
212 "Module \"" + id + "\" is not contained in sandbox.");
213 } else {
214 id = uri.toString();
215 }
216 }
217 }
218 }
219 return getExportedModuleInterface(cx, id, uri, base, false);
220 }
221
222 @Override
223 public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
224 throw ScriptRuntime.throwError(cx, scope,
225 "require() can not be invoked as a constructor");
226 }
227
228 private Scriptable getExportedModuleInterface(Context cx, String id,
229 URI uri, URI base, boolean isMain)
230 {
231 // Check if the requested module is already completely loaded
232 Scriptable exports = exportedModuleInterfaces.get(id);
233 if(exports != null) {
234 if(isMain) {
235 throw new IllegalStateException(
236 "Attempt to set main module after it was loaded");
237 }
238 return exports;
239 }
240 // Check if it is currently being loaded on the current thread
241 // (supporting circular dependencies).
242 Map<String, Scriptable> threadLoadingModules =
243 loadingModuleInterfaces.get();
244 if(threadLoadingModules != null) {
245 exports = threadLoadingModules.get(id);
246 if(exports != null) {
247 return exports;
248 }
249 }
250 // The requested module is neither already loaded, nor is it being
251 // loaded on the current thread. End of fast path. We must synchronize
252 // now, as we have to guarantee that at most one thread can load
253 // modules at any one time. Otherwise, two threads could end up
254 // attempting to load two circularly dependent modules in opposite
255 // order, which would lead to either unacceptable non-determinism or
256 // deadlock, depending on whether we underprotected or overprotected it
257 // with locks.
258 synchronized(loadLock) {
259 // Recheck if it is already loaded - other thread might've
260 // completed loading it just as we entered the synchronized block.
261 exports = exportedModuleInterfaces.get(id);
262 if(exports != null) {
263 return exports;
264 }
265 // Nope, still not loaded; we're loading it then.
266 final ModuleScript moduleScript = getModule(cx, id, uri, base);
267 if (sandboxed && !moduleScript.isSandboxed()) {
268 throw ScriptRuntime.throwError(cx, nativeScope, "Module \""
269 + id + "\" is not contained in sandbox.");
270 }
271 exports = cx.newObject(nativeScope);
272 // Are we the outermost locked invocation on this thread?
273 final boolean outermostLocked = threadLoadingModules == null;
274 if(outermostLocked) {
275 threadLoadingModules = new HashMap<String, Scriptable>();
276 loadingModuleInterfaces.set(threadLoadingModules);
277 }
278 // Must make the module exports available immediately on the
279 // current thread, to satisfy the CommonJS Modules/1.1 requirement
280 // that "If there is a dependency cycle, the foreign module may not
281 // have finished executing at the time it is required by one of its
282 // transitive dependencies; in this case, the object returned by
283 // "require" must contain at least the exports that the foreign
284 // module has prepared before the call to require that led to the
285 // current module's execution."
286 threadLoadingModules.put(id, exports);
287 try {
288 // Support non-standard Node.js feature to allow modules to
289 // replace the exports object by setting module.exports.
290 Scriptable newExports = executeModuleScript(cx, id, exports,
291 moduleScript, isMain);
292 if (exports != newExports) {
293 threadLoadingModules.put(id, newExports);
294 exports = newExports;
295 }
296 }
297 catch(RuntimeException e) {
298 // Throw loaded module away if there was an exception
299 threadLoadingModules.remove(id);
300 throw e;
301 }
302 finally {
303 if(outermostLocked) {
304 // Make loaded modules visible to other threads only after
305 // the topmost triggering load has completed. This strategy
306 // (compared to the one where we'd make each module
307 // globally available as soon as it loads) prevents other
308 // threads from observing a partially loaded circular
309 // dependency of a module that completed loading.
310 exportedModuleInterfaces.putAll(threadLoadingModules);
311 loadingModuleInterfaces.set(null);
312 }
313 }
314 }
315 return exports;
316 }
317
318 private Scriptable executeModuleScript(Context cx, String id,
319 Scriptable exports, ModuleScript moduleScript, boolean isMain)
320 {
321 final ScriptableObject moduleObject = (ScriptableObject)cx.newObject(
322 nativeScope);
323 URI uri = moduleScript.getUri();
324 URI base = moduleScript.getBase();
325 defineReadOnlyProperty(moduleObject, "id", id);
326 if(!sandboxed) {
327 defineReadOnlyProperty(moduleObject, "uri", uri.toString());
328 }
329 final Scriptable executionScope = new ModuleScope(nativeScope, uri, base);
330 // Set this so it can access the global JS environment objects.
331 // This means we're currently using the "MGN" approach (ModuleScript
332 // with Global Natives) as specified here:
333 // <http://wiki.commonjs.org/wiki/Modules/ProposalForNativeExtension>
334 executionScope.put("exports", executionScope, exports);
335 executionScope.put("module", executionScope, moduleObject);
336 moduleObject.put("exports", moduleObject, exports);
337 install(executionScope);
338 if(isMain) {
339 defineReadOnlyProperty(this, "main", moduleObject);
340 }
341 executeOptionalScript(preExec, cx, executionScope);
342 moduleScript.getScript().exec(cx, executionScope);
343 executeOptionalScript(postExec, cx, executionScope);
344 return ScriptRuntime.toObject(cx, nativeScope,
345 ScriptableObject.getProperty(moduleObject, "exports"));
346 }
347
348 private static void executeOptionalScript(Script script, Context cx,
349 Scriptable executionScope)
350 {
351 if(script != null) {
352 script.exec(cx, executionScope);
353 }
354 }
355
356 private static void defineReadOnlyProperty(ScriptableObject obj,
357 String name, Object value) {
358 ScriptableObject.putProperty(obj, name, value);
359 obj.setAttributes(name, ScriptableObject.READONLY |
360 ScriptableObject.PERMANENT);
361 }
362
363 private ModuleScript getModule(Context cx, String id, URI uri, URI base) {
364 try {
365 final ModuleScript moduleScript =
366 moduleScriptProvider.getModuleScript(cx, id, uri, base, paths);
367 if (moduleScript == null) {
368 throw ScriptRuntime.throwError(cx, nativeScope, "Module \""
369 + id + "\" not found.");
370 }
371 return moduleScript;
372 }
373 catch(RuntimeException e) {
374 throw e;
375 }
376 catch(Exception e) {
377 throw Context.throwAsScriptRuntimeEx(e);
378 }
379 }
380
381 @Override
382 public String getFunctionName() {
383 return "require";
384 }
385
386 @Override
387 public int getArity() {
388 return 1;
389 }
390
391 @Override
392 public int getLength() {
393 return 1;
394 }
395 }