       cause: error
 
 
-rewriteJavascript = (rootScope, program, go) ->
-  try
-    traverseJavascriptScoped [ rootScope ], rootScope, null, null, program, (globalScope, parent, key, node) ->
-      if node.type is 'Identifier'
-        return if parent.type is 'VariableDeclarator' and key is 'id' # ignore var declarations
-        return if key is 'property' # ignore members
-        return unless identifier = globalScope[node.name]
-
-        # qualify identifier with '_h2o_context_'
-        parent[key] =
-          type: 'MemberExpression'
-          computed: no
-          object:
-            type: 'Identifier'
-            name: identifier.object
-          property:
-            type: 'Identifier'
-            name: identifier.name
-    go null, program
-  catch error
-    go
-      message: 'Error rewriting javascript'
-      cause: error
+createGlobalScope = (rootScope, routines) ->
+  globalScope = {}
+
+  for name, identifier of rootScope
+    globalScope[name] = identifier
+
+  for name of routines
+    globalScope[name] = name: name, object: 'h2o'
+
+  globalScope
+
+rewriteJavascript = (sandbox) ->
+  (rootScope, program, go) ->
+    globalScope = createGlobalScope rootScope, sandbox.routines 
+
+    try
+      traverseJavascriptScoped [ globalScope ], globalScope, null, null, program, (globalScope, parent, key, node) ->
+        if node.type is 'Identifier'
+          return if parent.type is 'VariableDeclarator' and key is 'id' # ignore var declarations
+          return if key is 'property' # ignore members
+          return unless identifier = globalScope[node.name]
+
+          # qualify identifier with '_h2o_context_'
+          parent[key] =
+            type: 'MemberExpression'
+            computed: no
+            object:
+              type: 'Identifier'
+              name: identifier.object
+            property:
+              type: 'Identifier'
+              name: identifier.name
+      go null, program
+    catch error
+      go
+        message: 'Error rewriting javascript'
+        cause: error
 
 generateJavascript = (program, go) ->
   try

executeJavascript = (sandbox) ->
  (closure, go) ->
    try
      go null, closure sandbox.context, sandbox.routines, sandbox.results
    catch error
      go
        message: 'Error executing javascript'

    try
      rootScope = parseDeclarations program.body[0].expression.right.callee.body

      for name of sandbox.context
        rootScope[name] =
          name: name
          object: '_h2o_context_'
