Skip to content

Instantly share code, notes, and snippets.

@dherman
Last active February 3, 2017 17:44
Show Gist options
  • Save dherman/c2559e9c176db9770c595574788ede99 to your computer and use it in GitHub Desktop.
Save dherman/c2559e9c176db9770c595574788ede99 to your computer and use it in GitHub Desktop.
a tiny userland registry, using a "parse" and "link" primitive
import {b} from "./b.js";
import $ from "jquery";
export function a() {
// ...
}
import {a} from "./a.js";
import $ from "jquery";
export function b() {
// ...
}
class TinyLittleRegistry {
constructor(realm, jquery) {
this.#realm = realm;
this.#jquery = jquery;
}
@lazy records() {
return Promise.all([fetch("a.js"), fetch("b.js")])
.then(sources => sources.map(s => this.#realm.parseModule(s)));
}
@lazy async graph() {
let { a, b } = await this.records();
a.link({
"./b.js": b,
"jquery": this.#jquery
});
b.link({
"./a.js": a,
"jquery": this.#jquery
});
return { a, b };
}
}
import * as jquery from "jquery";
class TinyLittleRealm extends Realm {
constructor() {
super();
this.#registry = new TinyLittleRegistry(this, jquery);
}
[Realm.import](name, referrer) {
if (["a", "b"].indexOf(name) < 0) {
throw new ReferenceError("unrecognized module: " + name);
}
return this.#registry.graph().then(graph => graph[name]);
}
}
let realm = new TinyLittleRealm();
realm.eval("import('a')").then(m => m.a());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment