Page MenuHomeSealhub

module.mjs
No OneTemporary

Authored By
Unknown
Size
7 KB
Referenced Files
None
Subscribers
None

module.mjs

import { OUTPUT_DIR } from "./config.mjs";
import { v4 as uuidv4 } from "uuid";
import { toKebabCase } from "js-convert-case";
import chalk from "chalk";
export const Registry = new (class {
modules = [];
register(module) {
this.modules.push(module);
}
findByNpmName(npmName) {
return (
this.modules.find((module) => module.getPrintName() == npmName) ||
this.modules.find(
(module) => module.getPrintName() == `@sealcode/${npmName}`,
) ||
this.modules.find(
(module) => module.getPrintName() == toKebabCase(npmName),
)
);
}
async findAllThatDependOn(npmName) {
return (
await Promise.all(
this.modules
.filter((module) => module.npmName !== npmName)
.map(async (module) => [
await module.dependenciesInclude(npmName),
module,
]),
)
)
.filter(([match]) => match)
.map(([, module]) => module);
}
getGraph() {
let ret = "digraph {";
for (const module of this.modules) {
ret += `"${module.getPrintName()}" -> { ${module
.getLinkedModules()
.map((module) => `"${module.getPrintName()}"`)
.join(" ")} }`;
ret += "\n";
}
ret += "}";
return ret;
}
// returns objects sorted by dependencies — those without dependencies come first
async sortTopologically(elements, read_repository_name) {
const repos = elements.map(read_repository_name);
if (elements.length == 1) {
return elements;
}
let edges = "";
for (const x of repos) {
for (const y of repos) {
if (x == y) {
continue;
}
const repo_x = this.findByNpmName(x);
const repo_y = this.findByNpmName(y);
if (await repo_x.dependenciesInclude(repo_y.npmName)) {
edges += `${y} ${x}\n`;
}
}
}
const sorted = (await $`echo ${edges} | tsort`).stdout
.split("\n")
.slice(0, -1); /* remove last empty element*/
return sorted.map((e) =>
elements.find((s) => read_repository_name(s) == e),
);
}
})();
export class Module {
constructor({ npmName, dirname, repo, dependsOn }) {
this.npmName = npmName;
this.dirname = dirname;
this.repo = repo;
this.dependsOn = dependsOn;
Registry.register(this);
}
getPrintName() {
return this.npmName || this.dirname;
}
async clone() {
console.log("Cloning", this.repo);
if (fs.existsSync(this.getAbsolutePath())) {
console.log("\t already exists");
return;
}
await $`git clone ${this.repo} ${this.getAbsolutePath()}`;
console.log("\t done");
}
async runCommand(command, args) {
await $`cd ${this.getAbsolutePath()} && fnm use --install-if-missing --version-file-strategy recursive && ${command} ${args}`;
}
async runNpmScript(script) {
const command_string = this.getPackageJson().scripts[script];
if (!command_string) {
return null;
}
return this.runCommand("npm", ["run", script]);
}
async getDependencies() {
return (await this.getPackageJson()).dependencies || {};
}
getLinkedModules() {
return (this.dependsOn || []).map((name) => Registry.findByNpmName(name));
}
async dependenciesInclude(npmName) {
console.log(
"Checking if dependencies of",
this.npmName,
"include",
npmName,
);
const dependencies = await this.getDependencies();
return Object.keys(dependencies).includes(npmName);
}
async install(ignoreScripts = false) {
await this.runCommand("npm", [
"install",
...(ignoreScripts ? ["--ignore-scripts"] : []),
]);
}
getPackageJson() {
return JSON.parse(
fs.readFileSync(`${this.getAbsolutePath()}/package.json`),
);
}
async build() {
for (const script of ["build", "build-types", "build-declarations"]) {
try {
await this.runNpmScript(script);
} catch (e) {
console.error(
chalk.red(
`There has been an error trying to build ${this.getPrintName()}`,
),
);
console.error(`Try running:`);
console.error(
chalk.yellow(` cd ${this.getAbsolutePath()} && npm run ${script}`),
);
console.error(`to see what needs fixing`);
process.exit(1);
}
}
console.log("Finished build");
}
getAbsolutePath() {
return `${process.cwd()}/${OUTPUT_DIR}/${this.getDirname()}`;
}
getDirname() {
return this.dirname || this.npmName.split("/").at(-1);
}
async linkDeps() {
for (const npmName of this.dependsOn || []) {
await $`rm -rf ${`${this.getAbsolutePath()}/node_modules/${npmName}`}`;
const dep = Registry.findByNpmName(npmName);
if (!dep) {
console.warn("Didn't find", npmName);
continue;
}
await $`ln -s ${dep.getAbsolutePath()} ${`${this.getAbsolutePath()}/node_modules/${dep.npmName}`}`;
}
}
async cleanupArcanistBranches() {
const temp_branch = uuidv4();
await this.runCommand("bash", [
"-c",
`git checkout -b ${temp_branch} && git branch | cut -c3- | grep arcpatch- | xargs -n1 git branch -D && (git checkout main || git checkout master) && git branch -D ${temp_branch} `,
]);
}
async applyRevision(revision_id) {
try {
await this.runCommand("arc", ["patch", revision_id]);
} catch (e) {
console.error(e.stderr);
if (
e.stderr.includes(
"Arc was unable to automagically make a name for this patch",
)
) {
await this.cleanupArcanistBranches();
return this.applyRevision(revision_id);
} else {
throw e;
}
}
await this.install(true);
await this.linkDeps();
}
static playgroundFork(name, url) {
return new Module({
dirname: name,
repo: url,
dependsOn: [
"@sealcode/jdd",
"@sealcode/monaco-wrapper",
"@sealcode/jdd-editor",
"@sealcode/add-to-head",
"@sealcode/ansi-html-stream",
"@sealcode/file-manager",
"sealious",
"@sealcode/simplemde",
"@sealcode/sealgen",
"koa-responsive-image-router",
],
});
}
}
export class KoaModule extends Module {
constructor() {
super({
npmName: "@types/koa",
dirname: `${process.cwd()}/${OUTPUT_DIR}/sealious-playground/node_modules/@types/koa`,
});
}
clone() {
// not cloning as it will be installed in playground's node modules and we will use that
}
install() {}
build() {}
getPackageJson() {
return { scripts: [], dependencies: [] };
}
async linkDeps() {
const playground = Registry.modules.find(
(e) => e.dirname == "sealious-playground",
);
for (const module of Registry.modules) {
if (module == playground) {
continue; // not removing from playground - this is where the only instance of this dep should live
}
const koa_dir = `${module.getAbsolutePath()}/node_modules/@types/koa`;
const real_koa_dir = `${playground.getAbsolutePath()}/node_modules/@types/koa`;
if (fs.existsSync(koa_dir)) {
await $`rm -rf ${koa_dir}`;
await $`ln -s ${real_koa_dir} ${koa_dir}`;
}
}
}
}

File Metadata

Mime Type
application/javascript
Expires
Sat, Nov 28, 04:12 (14 h, 57 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1190351
Default Alt Text
module.mjs (7 KB)

Event Timeline