[gjs/wip/jasper/imports-cleanup: 2/2] jsapi-util: Add the standard CommonJS properties to imported modules



commit b8e7ee91f5a9b9fec11de20e40651ad72c24f2c0
Author: Jasper St. Pierre <jstpierre mecheye net>
Date:   Fri Sep 27 18:03:16 2013 -0400

    jsapi-util: Add the standard CommonJS properties to imported modules
    
    These are currently unused, but our require(); implementation will use
    these when importing modules.
    
    (Philip Chimento: rebased, updated coding style)
    
    [skip ci] Needs work: change the property names to JS atoms

 gjs/module.cpp | 36 +++++++++++++++++++++++++++++++++++-
 1 file changed, 35 insertions(+), 1 deletion(-)
---
diff --git a/gjs/module.cpp b/gjs/module.cpp
index 8861e424..b94efd3f 100644
--- a/gjs/module.cpp
+++ b/gjs/module.cpp
@@ -57,7 +57,23 @@ class GjsModule {
     create(JSContext  *cx,
            const char *name)
     {
-        JSObject *module = JS_NewObject(cx, &GjsModule::klass);
+        JS::RootedObject module(cx, JS_NewObject(cx, &GjsModule::klass));
+        JS::RootedObject exports(cx, JS_NewPlainObject(cx));
+        if (!JS_DefineProperty(cx, module, "exports", exports,
+                               JSPROP_READONLY | JSPROP_PERMANENT))
+            return nullptr;
+
+        JS::RootedValue v_id(cx);
+        if (!gjs_string_from_utf8(cx, name, &v_id))
+            return nullptr;
+
+        JS::RootedObject module_info(cx, JS_NewPlainObject(cx));
+        if (!JS_DefineProperty(cx, module_info, "id", v_id,
+                               JSPROP_READONLY | JSPROP_PERMANENT) ||
+            !JS_DefineProperty(cx, module, "module", module,
+                               JSPROP_READONLY | JSPROP_PERMANENT))
+            return nullptr;
+
         JS_SetPrivate(module, new GjsModule(name));
         return module;
     }
@@ -112,6 +128,24 @@ class GjsModule {
         return true;
     }
 
+    static bool
+    define_module_url(JSContext       *cx,
+                      JS::HandleObject module,
+                      GFile           *file)
+    {
+        JS::RootedObject module_info(cx);
+        if (!gjs_object_require_property(cx, module, "module", "module object",
+                                         &module_info))
+            return false;
+
+        GjsAutoChar url = g_file_get_uri(file);
+        JS::RootedValue v_url(cx);
+        if (!gjs_string_from_utf8(cx, url, &v_url) ||
+            !JS_DefineProperty(cx, module_info, "url", v_url,
+                               JSPROP_READONLY | JSPROP_PERMANENT))
+            return false;
+    }
+
     /* Loads JS code from a file and imports it */
     bool
     import_file_internal(JSContext       *cx,


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]