Skip to content

Commit

Permalink
Progress on automatic config
Browse files Browse the repository at this point in the history
  • Loading branch information
julienmalard committed Nov 10, 2024
1 parent ac172f6 commit 280a158
Show file tree
Hide file tree
Showing 12 changed files with 767 additions and 411 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,6 @@ node_modules/

# JS
node_modules
dist
dist

.orbiter
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"@constl/orbit-db-types": "^2.0.6",
"@constl/utils-tests": "^1.6.2",
"@eslint/js": "^9.14.0",
"@types/lodash-es": "^4.17.12",
"@types/mocha": "^10.0.9",
"@types/yargs": "^17.0.33",
"aegir": "^44.1.4",
Expand Down Expand Up @@ -66,7 +67,9 @@
"@constl/utils-ipa": "^1.0.3",
"@orbitdb/core": "^2.4.3",
"chalk": "^5.3.0",
"change-case": "^5.4.4",
"deepcopy": "^2.1.0",
"lodash-es": "^4.17.21",
"log-update": "^6.1.0",
"ora": "^8.1.1",
"semaphore-async-await": "^1.5.1",
Expand Down
22 changes: 18 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 18 additions & 16 deletions src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ import {
} from "@constl/ipa";

import { createOrbiter } from "@/orbiter.js";
const MACHINE_PREFIX = "MACHINE MESSAGE:"
const MACHINE_PREFIX = "MACHINE MESSAGE:";

const baseDir = url.fileURLToPath(new URL("..", import.meta.url));
const packageJsonFile = path.join(baseDir, "./package.json");
const packageJson = JSON.parse(fs.readFileSync(packageJsonFile, "utf8"));

const sendMachineMessage = ({ message }: { message: {type: string} }) => {
const sendMachineMessage = ({ message }: { message: { type: string } }) => {
console.log(MACHINE_PREFIX + JSON.stringify(message));
};

Expand All @@ -37,18 +37,19 @@ const followConnections = async ({ ipa }: { ipa: Constellation }) => {

const fFinale = () => {
const nIpfsConnections = connexions.sfip.length;
const nConstellationConnections = connexions.constellation.filter((c) => c.infoMembre.idCompte !== connexions.monId && !c.vuÀ).length;
const nConstellationConnections = connexions.constellation.filter(
(c) => c.infoMembre.idCompte !== connexions.monId && !c.vuÀ,
).length;

logUpdate(
chalk.yellow(
// eslint-disable-next-line no-irregular-whitespace
`Network connections: ${nIpfsConnections}\nConstellation nodes online: ${nConstellationConnections}`,
),
);
};

const forgetMyId = await ipa.suivreIdCompte({
f: id => connexions.monId = id,
f: (id) => (connexions.monId = id),
});
const forgetIpfsConnections = await ipa.réseau.suivreConnexionsPostesSFIP({
f: (x) => {
Expand All @@ -62,7 +63,7 @@ const followConnections = async ({ ipa }: { ipa: Constellation }) => {
connexions.constellation = x;
fFinale();
},
}); // TODO: check specifically for Orbiter instances on the Constellation network
}); // TODO: check specifically for Orbiter instances on the Constellation network
return async () => {
await Promise.all([
forgetMyId(),
Expand All @@ -86,7 +87,8 @@ yargs(hideBin(process.argv))
})
.option("machine", {
alias: "m",
describe: "Machine communication mode (useful for programmatic access).",
describe:
"Machine communication mode (useful for programmatic access).",
type: "boolean",
});
},
Expand All @@ -98,17 +100,19 @@ yargs(hideBin(process.argv))
if (argv.machine) {
sendMachineMessage({ message: { type: "STARTING ORBITER" } });
} else {
wheel = ora(chalk.yellow(`Initialising Orbiter`)); // .start()
wheel = ora(chalk.yellow(`Initialising Orbiter`)); // .start()
}

const constellation = créerConstellation({
dossier: argv.dir || '.orbiter',
})
dossier: argv.dir || ".orbiter",
});

await createOrbiter({
const { config } = await createOrbiter({
constellation,
});

console.log(config);

process.stdin.on("data", async () => {
if (argv.machine) {
sendMachineMessage({ message: { type: "Closing Orbiter" } });
Expand All @@ -133,7 +137,7 @@ yargs(hideBin(process.argv))
});
} else {
wheel!.succeed(
chalk.yellow("Orbiter is running. Press any key to close."),
chalk.yellow("Orbiter is running. Press `enter` to close."),
);
oublierConnexions = await followConnections({ ipa: constellation });
}
Expand All @@ -151,7 +155,5 @@ yargs(hideBin(process.argv))
)
.demandCommand()
.help("help", "Get command line help")
.epilog(
"Source code and bug reports: https://github.com/riffcc/orbiter",
)
.parse();
.epilog("Source code and bug reports: https://github.com/riffcc/orbiter")
.parse();
106 changes: 106 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import {
ConfigMode,
VariableIds,
possiblyIncompleteOrbiterConfigSchema,
type OrbiterConfig,
type PossiblyIncompleteOrbiterConfig,
} from "./types";

import {constantCase} from 'change-case';
import {
isBrowser,
isElectronRenderer,
isReactNative,
isWebWorker,
} from "wherearewe";
import Ajv from "ajv/dist/jtd";

import { CONFIG_FILE_NAME } from "./consts.js";

const ajv = new Ajv();
const validateConfig = ajv.compile(possiblyIncompleteOrbiterConfigSchema);

export const getConfig = async ({
dir,
}: {
dir: string;
}): Promise<PossiblyIncompleteOrbiterConfig> => {
if (isBrowser || isElectronRenderer || isReactNative || isWebWorker) {
throw new Error(
"The `getConfig` function is only available in Node and Electron main environments.",
);
}
const { existsSync, readFileSync } = await import("fs");
const { join } = await import("path");
const configFilePath = join(dir, CONFIG_FILE_NAME);
if (existsSync(configFilePath)) {
const data = readFileSync(configFilePath);
try {
const jsonConfig = JSON.parse(new TextDecoder().decode(data)) as unknown;
if (validateConfig(jsonConfig)) {
return jsonConfig;
} else {
return {};
}
} catch {
return {};
}
}
return {};
};

export const saveConfig = async ({
dir,
config,
mode = "vite",
}: {
dir: string;
config: OrbiterConfig;
mode: ConfigMode;
}) => {
const configFileText = exportConfig({ config, mode });
if (isBrowser || isElectronRenderer || isReactNative || isWebWorker) {
throw new Error(
"The `saveConfig` function is only available in Node and Electron main environments.",
);
}
const { writeFileSync } = await import("fs");
const { join } = await import("path");
const configFilePath = join(dir, CONFIG_FILE_NAME);
writeFileSync(configFilePath, configFileText);
};

export const exportConfig = ({
config,
mode = "vite",
}: {
config: OrbiterConfig;
mode: ConfigMode;
}): string => {
if (mode === "vite") return exportViteConfig({ config });
else throw new Error(`Unknown exportation mode ${mode}.`);
};

export const exportViteConfig = ({
config,
}: {
config: OrbiterConfig;
}): string => {
const { siteId, swarmId, variableIds } = config;
let envFileText = '# The address below should be regenerated for each Orbiter site. If you are setting up an independent site, erase the value below and run the site in development mode (`pnpm dev`) to automatically regenerate. \n' +
'VITE_SITE_ID=' + siteId +
'\n';
const variableIdsList = Object.keys(variableIds).map(
k => `VITE_${constantCase(k)}_ID=${variableIds[k as keyof VariableIds]}`,
);

envFileText +=
'# These should ideally stay the same for all Orbiter site. Changing these will create a parallel network and thereby keep your lens from syncing and interacting with the main network.\n' +
'VITE_SWARM_ID=' + swarmId +
'\n' +
'\n' +
variableIdsList.join('\n') +
'\n'
;
return envFileText;
};
54 changes: 28 additions & 26 deletions src/consts.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
export const TRUSTED_SITES_TABLE_KEY = 'trustedSites';
export const TRUSTED_SITES_SITE_ID_COL = 'siteId';
export const TRUSTED_SITES_NAME_COL = 'siteName';
export const TRUSTED_SITES_TABLE_KEY = "trustedSites";
export const TRUSTED_SITES_SITE_ID_COL = "siteId";
export const TRUSTED_SITES_NAME_COL = "siteName";

export const FEATURED_RELEASES_TABLE_KEY = 'featuredReleases';
export const FEATURED_RELEASES_RELEASE_ID_COLUMN = 'releaseId';
export const FEATURED_RELEASES_START_TIME_COLUMN = 'startTime';
export const FEATURED_RELEASES_END_TIME_COLUMN = 'endTime';
export const FEATURED_RELEASES_TABLE_KEY = "featuredReleases";
export const FEATURED_RELEASES_RELEASE_ID_COLUMN = "releaseId";
export const FEATURED_RELEASES_START_TIME_COLUMN = "startTime";
export const FEATURED_RELEASES_END_TIME_COLUMN = "endTime";

export const BLOCKED_RELEASES_TABLE_KEY = 'blockedReleases';
export const BLOCKED_RELEASES_RELEASE_ID_COLUMN = 'releaseId';
export const BLOCKED_RELEASES_TABLE_KEY = "blockedReleases";
export const BLOCKED_RELEASES_RELEASE_ID_COLUMN = "releaseId";

export const RELEASES_FILE_COLUMN = 'file';
export const RELEASES_AUTHOR_COLUMN = 'author';
export const RELEASES_NAME_COLUMN = 'contentName';
export const RELEASES_METADATA_COLUMN = 'metadata';
export const RELEASES_THUMBNAIL_COLUMN = 'thumbnail';
export const RELEASES_CATEGORY_COLUMN = 'category';
export const RELEASES_STATUS_COLUMN = 'status';
export const RELEASES_COVER_COLUMN = 'cover';
export const RELEASES_FILE_COLUMN = "file";
export const RELEASES_AUTHOR_COLUMN = "author";
export const RELEASES_NAME_COLUMN = "contentName";
export const RELEASES_METADATA_COLUMN = "metadata";
export const RELEASES_THUMBNAIL_COLUMN = "thumbnail";
export const RELEASES_CATEGORY_COLUMN = "category";
export const RELEASES_STATUS_COLUMN = "status";
export const RELEASES_COVER_COLUMN = "cover";

export const COLLECTIONS_RELEASES_COLUMN = 'releases';
export const COLLECTIONS_AUTHOR_COLUMN = 'author';
export const COLLECTIONS_NAME_COLUMN = 'contentName';
export const COLLECTIONS_METADATA_COLUMN = 'metadata';
export const COLLECTIONS_THUMBNAIL_COLUMN = 'thumbnail';
export const COLLECTIONS_CATEGORY_COLUMN = 'category';
export const COLLECTIONS_STATUS_COLUMN = 'status';
export const COLLECTIONS_RELEASES_COLUMN = "releases";
export const COLLECTIONS_AUTHOR_COLUMN = "author";
export const COLLECTIONS_NAME_COLUMN = "contentName";
export const COLLECTIONS_METADATA_COLUMN = "metadata";
export const COLLECTIONS_THUMBNAIL_COLUMN = "thumbnail";
export const COLLECTIONS_CATEGORY_COLUMN = "category";
export const COLLECTIONS_STATUS_COLUMN = "status";

export const RELEASES_DB_TABLE_KEY = 'releases';
export const COLLECTIONS_DB_TABLE_KEY = 'collections';
export const RELEASES_DB_TABLE_KEY = "releases";
export const COLLECTIONS_DB_TABLE_KEY = "collections";

export const CONFIG_FILE_NAME = ".orbiter-config.json";
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { Orbiter } from "./orbiter.js";
export { version } from "./version.js";
export { version } from "./version.js";
export * as types from "./types.js";
export * as consts from "./consts.js";
export * as consts from "./consts.js";
Loading

0 comments on commit 280a158

Please sign in to comment.