Fix a bug affecting relative path resolution, change _req() to _require(), add abilit...
authorNick Downing <nick@ndcode.org>
Mon, 29 Oct 2018 10:12:57 +0000 (21:12 +1100)
committerNick Downing <nick@ndcode.org>
Tue, 30 Oct 2018 07:54:35 +0000 (18:54 +1100)
js_template.js

index 1fb8a9d..5dfcb1b 100644 (file)
@@ -13,16 +13,29 @@ let fs_stat = util.promisify(fs.stat)
 let fs_writeFile = util.promisify(fs.writeFile)
 
 let build_cache = new BuildCache()
-let js_template = async (root, dirname, pathname) => {
+let js_template = async (root, dirname, pathname, args) => {
   while (pathname.charAt(0) === '/') {
-    dir = root
+    dirname = root
     pathname = pathname.slice(1)
   }
   pathname = path.posix.resolve(dirname, pathname)
-  dirname = path.posix.dirname(pathname)
   return build_cache.get(
     pathname,
     async result => {
+      dirname = path.posix.dirname(pathname)
+
+      let arg_names = ['_require', '_html_escape']
+      let arg_values = [
+        async pathname => js_template(root, dirname, pathname, args),
+        html_escape
+      ]
+      if (args !== undefined)
+        for (let i in args)
+          if (Object.prototype.hasOwnProperty.call(args, i)) {
+            arg_names.push(i)
+            arg_values.push(args[i])
+          }
+
       let stats = await fs_stat(pathname)
 
       let js_pathname = path.posix.resolve(
@@ -48,9 +61,8 @@ let js_template = async (root, dirname, pathname) => {
             transform.transform(
               visitors,
               acorn.parse(
-                'module.exports = async (_req, _html_escape) => {' +
-                text +
-                '}')
+                `module.exports = async (${arg_names.join(', ')}) => {${text}}`
+              )
             ),
             {} //indent: ''}
           ),
@@ -60,10 +72,9 @@ let js_template = async (root, dirname, pathname) => {
       else
         console.log('reloading', js_pathname)
 
-      result.value = await (require(js_pathname))(
-        async pathname => js_template(root, dirname, pathname),
-        html_escape
-      )
+      let full_js_pathname = require.resolve(js_pathname)
+      delete require.cache[full_js_pathname]
+      result.value = await (require(full_js_pathname)).apply(null, arg_values)
     }
   )
 }