Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions apps/daemon/src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ import manifest from '../package.json' with { type: 'json' };
*/
export const VERSION: string = typeof DAEMON_VERSION === 'undefined' ? manifest.version : DAEMON_VERSION;

/**
* The platform the daemon runs on similar to the plugin's naming scheme (e.g. `linux-x64-musl`).
*/
export const TARGET: string = `${process.platform}-${process.arch}${musl() ? '-musl' : ''}`;

/**
* Whether the daemon runs on Linux with musl.
*/
function musl(): boolean {
if (process.platform !== 'linux') {
return false;
}

const { header } = process.report.getReport() as { header: { glibcVersionRuntime?: string } };
return header.glibcVersionRuntime === undefined;
}

// The daemon's version from package.json, defined by build.mjs and vitest.config.ts. Undefined when run through tsx,
// which reads package.json instead.
declare const DAEMON_VERSION: string | undefined;
25 changes: 24 additions & 1 deletion apps/daemon/src/plugins/plugin-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { type DataDirectory, dataDirectory } from '../directories';
import { TARGET } from '../global';
import { PluginStore } from './plugin-store';

// A main module that records what happens to it, with `enabled` for an enable, through a module it and the test share.
Expand Down Expand Up @@ -47,12 +48,14 @@ async function install(
code = tracked(),
dependencies,
elsewise = '^0.1.0',
targets,
version = '1.0.0',
enabled = true,
}: {
code?: string | null;
dependencies?: Record<string, string>;
elsewise?: string;
targets?: string[];
version?: string;
enabled?: boolean;
} = {},
Expand All @@ -65,7 +68,7 @@ async function install(
version,
elsewise,
frontend: {},
...(code !== null && { daemon: { ...(dependencies && { dependencies }) } }),
...(code !== null && { daemon: { ...(dependencies && { dependencies }), ...(targets && { targets }) } }),
};
await fs.writeFile(path.join(folder, 'manifest.json'), JSON.stringify(manifest));
if (code !== null) {
Expand Down Expand Up @@ -220,6 +223,26 @@ describe('enableAll', () => {
expect(events).toEqual([]);
});

test('marks plugin whose targets exclude platform incompatible', async () => {
await install('a', { targets: [TARGET === 'win32-arm64' ? 'win32-x64' : 'win32-arm64'] });
await store.loadAll();

await store.enableAll({});

expect(store.plugins).toMatchObject([{ id: 'a', status: 'incompatible', unsatisfied: { target: TARGET } }]);
expect(events).toEqual([]);
});

test('enables plugin whose targets include platform', async () => {
await install('a', { targets: [TARGET] });
await store.loadAll();

await store.enableAll({});

expect(status('a')).toBe('enabled');
expect(events).toEqual(['enable a']);
});

test('marks plugin whose dependency is missing incompatible', async () => {
await install('b', { dependencies: { a: '^1.0.0' } });
await store.loadAll();
Expand Down
3 changes: 2 additions & 1 deletion apps/daemon/src/plugins/plugin-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { type EnabledSnapshot, type InstalledPlugin, type InvalidPlugin, PluginR
import { readPluginsSync } from '@elsewise/core/node';
import type { Daemon, Disposable, Plugin } from '@elsewise/daemon-plugin';
import type { DataDirectory } from '../directories';
import { VERSION } from '../global';
import { TARGET, VERSION } from '../global';

/**
* The installed plugins, loaded from the data directory, whose daemon parts run in the daemon.
Expand All @@ -15,6 +15,7 @@ import { VERSION } from '../global';
export class PluginStore extends PluginResolver<InstalledPlugin, Daemon, Plugin, EnabledSnapshot> {
protected readonly part = 'daemon';
protected readonly version = VERSION;
protected override readonly target = TARGET;
private readonly data: DataDirectory;

constructor(data: DataDirectory) {
Expand Down
33 changes: 31 additions & 2 deletions packages/core/src/plugins/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,42 @@ export type Part = 'frontend' | 'daemon';

export interface Entry<Installed extends InstalledPlugin, Running> {
plugin: Installed | InvalidPlugin;

state:
| { readonly status: 'disabled' }
| { readonly status: 'failed' }
| { readonly status: 'incompatible'; readonly unsatisfied: Unsatisfied }
| { readonly status: 'enabled'; readonly running?: Running };

/**
* The plugin's queued enable or disable.
*/
pending: Promise<void>;
}

/**
* The host the plugins run in.
*/
export interface Host {
/**
* The plugin part the host runs.
*/
readonly part: Part;

/**
* The host's version. If undefined, every plugin is compatible.
*/
readonly version: string | undefined;

/**
* The platform the daemon runs on (e.g. `linux-x64-musl`). If undefined, the resolver does not validate the target.
*/
readonly target: string | undefined;
}

export type Unsatisfied =
| { readonly elsewise: string }
| { readonly target: string }
| { readonly dependency: string; readonly cause: 'missing' | 'incompatible' }
| { readonly cycle: readonly string[] };

Expand All @@ -31,7 +54,7 @@ export type Unsatisfied =
*/
export function resolve<Installed extends InstalledPlugin, Running>(
entries: ReadonlyMap<string, Entry<Installed, Running>>,
host: { part: Part; version: string | undefined },
host: Host,
): {
graph: DepGraph<undefined>;
unsatisfied: ReadonlyMap<string, Unsatisfied>;
Expand Down Expand Up @@ -66,7 +89,7 @@ export function resolve<Installed extends InstalledPlugin, Running>(
*/
function compatibleGraph<Installed extends InstalledPlugin, Running>(
entries: ReadonlyMap<string, Entry<Installed, Running>>,
{ part, version }: { part: Part; version: string | undefined },
{ part, version, target }: Host,
): {
graph: DepGraph<undefined>;
unsatisfied: ReadonlyMap<string, Unsatisfied>;
Expand All @@ -85,6 +108,12 @@ function compatibleGraph<Installed extends InstalledPlugin, Running>(
continue;
}

const targets: readonly string[] | undefined = manifest.daemon?.targets;
if (target !== undefined && targets !== undefined && !targets.includes(target)) {
unsatisfied.set(id, { target });
continue;
}

for (const [dependency, range] of Object.entries(manifest[part]?.dependencies ?? {})) {
const plugin = entries.get(dependency)?.plugin;
if (plugin === undefined) {
Expand Down
23 changes: 20 additions & 3 deletions packages/core/src/plugins/plugin-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ export abstract class PluginResolver<Installed extends InstalledPlugin, Host, Pl
*/
protected abstract readonly version: string | undefined;

/**
* The platform the daemon runs on (e.g. `linux-x64-musl`). If undefined, the resolver does not validate the target.
*/
protected readonly target: string | undefined = undefined;

get plugins(): readonly PluginSnapshot<Enabled>[] {
return this.snapshot;
}
Expand Down Expand Up @@ -99,7 +104,11 @@ export abstract class PluginResolver<Installed extends InstalledPlugin, Host, Pl
protected abstract installed(id: string): Promise<Installed | InvalidPlugin | undefined>;

private async settle(): Promise<void> {
for (const [id, unsatisfied] of resolve(this.entries, { part: this.part, version: this.version }).unsatisfied) {
for (const [id, unsatisfied] of resolve(this.entries, {
part: this.part,
version: this.version,
target: this.target,
}).unsatisfied) {
const state = this.entries.get(id)?.state;
if (state?.status === 'enabled' && state.running !== undefined) {
await this.disable(id, unsatisfied);
Expand Down Expand Up @@ -144,7 +153,7 @@ export abstract class PluginResolver<Installed extends InstalledPlugin, Host, Pl
* Enables every plugin flagged as enabled.
*/
async enableAll(host: Host): Promise<void> {
const { graph, modified } = resolve(this.entries, { part: this.part, version: this.version });
const { graph, modified } = resolve(this.entries, { part: this.part, version: this.version, target: this.target });
if (modified) {
this.publish();
}
Expand Down Expand Up @@ -179,7 +188,11 @@ export abstract class PluginResolver<Installed extends InstalledPlugin, Host, Pl
return;
}

const { graph, unsatisfied, modified } = resolve(this.entries, { part: this.part, version: this.version });
const { graph, unsatisfied, modified } = resolve(this.entries, {
part: this.part,
version: this.version,
target: this.target,
});
if (modified) {
this.publish();
}
Expand Down Expand Up @@ -283,6 +296,10 @@ export abstract class PluginResolver<Installed extends InstalledPlugin, Host, Pl
return `needs Elsewise ${unsatisfied.elsewise}`;
}

if ('target' in unsatisfied) {
return `does not run on ${unsatisfied.target}`;
}

if ('cycle' in unsatisfied) {
const others = unsatisfied.cycle.filter((id) => id !== manifest.id);
return others.length === 0 ? 'depends on itself' : `is in a dependency cycle with ${others.join(', ')}`;
Expand Down
4 changes: 4 additions & 0 deletions packages/daemon-plugin/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ Run pnpm from the **repo root**: `pnpm --filter @elsewise/daemon-plugin <script>

This is a **source package**: `exports` points straight at `src/` and there is no build step.

`src/build.ts`, exported as `@elsewise/daemon-plugin/build`, is for a plugin's build rather than its runtime:
`linkNodeModules` is a Vite plugin that links a daemon part's `node_modules` into the output folder, for the bundle to
find its dependencies.

## Rules

- **`@elsewise/plugin` is the only dependency.**
Expand Down
3 changes: 2 additions & 1 deletion packages/daemon-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"description": "The API for a plugin's daemon part.",
"sideEffects": false,
"exports": {
".": "./src/index.ts"
".": "./src/index.ts",
"./build": "./src/build.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
Expand Down
40 changes: 40 additions & 0 deletions packages/daemon-plugin/src/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import fs from 'node:fs';
import path from 'node:path';

/**
* A Vite plugin that links the part's `node_modules` into the output folder.
*/
export function linkNodeModules() {
/**
* Represents the `starter/daemon` path.
*/
let root = '';

/**
* Represents the compiled output's path.
*/
let outDir = '';

return {
name: 'elsewise:link-node-modules',
apply: 'build' as const,

configResolved(config: { root: string; build: { outDir: string } }) {
root = config.root;
outDir = path.resolve(config.root, config.build.outDir);
},

writeBundle() {
const modules = path.join(root, 'node_modules');
const link = path.join(outDir, 'node_modules');

if (link === modules || !fs.existsSync(modules)) {
return;
}

fs.rmSync(link, { recursive: true, force: true });
// Uses a junction on Windows as it only lets administrators create symbolic links.
fs.symlinkSync(modules, link, 'junction');
},
};
}
1 change: 1 addition & 0 deletions packages/daemon-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export {
DaemonManifestPart,
DaemonTarget,
type Disposable,
FrontendManifestPart,
Manifest,
Expand Down
1 change: 1 addition & 0 deletions packages/frontend-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export {
DaemonManifestPart,
DaemonTarget,
type Disposable,
FrontendManifestPart,
Manifest,
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { DaemonManifestPart, FrontendManifestPart, Manifest, PluginId } from './manifest';
export { DaemonManifestPart, DaemonTarget, FrontendManifestPart, Manifest, PluginId } from './manifest';
export type { Disposable, PluginInfo } from './plugin';
34 changes: 34 additions & 0 deletions packages/plugin/src/manifest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ const INVALID: [string, unknown][] = [
['has a topic over 50 characters', { ...MINIMAL, topics: ['a'.repeat(51)], frontend: {} }],
['has over 20 topics', { ...MINIMAL, topics: Array.from({ length: 21 }, (_, i) => `topic-${i}`), frontend: {} }],
['has a topic twice', { ...MINIMAL, topics: ['git', 'git'], frontend: {} }],
['has daemon targets that is not an array', { ...MINIMAL, frontend: {}, daemon: { targets: 'linux-x64' } }],
['has no daemon targets in the list', { ...MINIMAL, frontend: {}, daemon: { targets: [] } }],
['has a daemon target twice', { ...MINIMAL, frontend: {}, daemon: { targets: ['linux-x64', 'linux-x64'] } }],
[
'has a daemon target on an unknown architecture',
{ ...MINIMAL, frontend: {}, daemon: { targets: ['linux-riscv64'] } },
],
['has a universal daemon target', { ...MINIMAL, frontend: {}, daemon: { targets: ['universal'] } }],
['has a daemon target in uppercase', { ...MINIMAL, frontend: {}, daemon: { targets: ['Darwin-arm64'] } }],
['has a musl daemon target off Linux', { ...MINIMAL, frontend: {}, daemon: { targets: ['darwin-arm64-musl'] } }],
['has a daemon target with a glibc suffix', { ...MINIMAL, frontend: {}, daemon: { targets: ['linux-x64-gnu'] } }],
];

const RANGES = [
Expand Down Expand Up @@ -93,6 +104,29 @@ describe('Manifest', () => {
});
});

test('keeps daemon targets', () => {
const targets = [
'darwin-arm64',
'darwin-x64',
'linux-arm64',
'linux-arm64-musl',
'linux-x64',
'linux-x64-musl',
'win32-arm64',
'win32-x64',
];

expect(Manifest.parse({ ...MINIMAL, frontend: {}, daemon: { targets } })).toEqual({
...MINIMAL,
frontend: {},
daemon: { main: 'main.js', targets },
});
});

test('drops targets of frontend part', () => {
expect(Manifest.parse({ ...MINIMAL, frontend: { targets: ['linux-x64'] } })).toEqual({ ...MINIMAL, frontend: {} });
});

test('keeps listing metadata', () => {
const listing = {
description: 'Git for Elsewise',
Expand Down
Loading
Loading