-
-
Save caridy/c906097b44acb6c24e104d3ad19c22f4 to your computer and use it in GitHub Desktop.
a tiny userland registry, using a "parse" and "link" primitive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {b} from "./b.js"; | |
import $ from "jquery"; | |
export function a() { | |
// ... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {a} from "./a.js"; | |
import $ from "jquery"; | |
export function b() { | |
// ... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TinyLittleRegistry { | |
constructor(realm, jquery) { | |
this.#realm = realm; | |
this.#jquery = jquery; | |
this.links = { | |
"a": { | |
"./b.js": "b", | |
}, | |
"b": { | |
"./a.js": a | |
}, | |
}; | |
} | |
@lazy records() { | |
return Promise.all([fetch("a.js"), fetch("b.js")]) | |
.then(sources => sources.map(s => this.#realm.parseModule(s))); | |
} | |
@lazy async graph() { | |
const { a, b } = await this.records(); | |
const { jquery } = this; | |
return { a, b, jquery }; | |
} | |
getDependencyOf(referrer, specifier) { | |
const modules = await this.#registry.graph(); | |
const name = Object.keys(modules).findIndex(name => modules[name] === referrer); | |
if (!name) { | |
// must be a top level | |
return module[specifier]; | |
} | |
const depName = this.link[name][specifier]; | |
return depName ? modules[depName] : Promise.resolve(new ReferenceError(`unrecognized module: ${depName} from referrer ${name}`)); | |
} | |
getTopLevelModule(name) { | |
return this.#registry.graph().then(graph => graph[name]); | |
} | |
} | |
import * as jquery from "jquery"; | |
class TinyLittleRealm extends Realm { | |
constructor() { | |
super(); | |
this.#registry = new TinyLittleRegistry(this, jquery); | |
} | |
[Realm.import](name, referrer) { | |
if (!referrer) { | |
return this.#registry.getTopLevelModule(name); | |
} | |
return this.#registry.getDependencyOf(referrer, 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