@x-tech-laboratories/x-app 0.133.0 → 0.134.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,12 +5,14 @@
5
5
  Code the X-apps share, published as one npm package, `@x-tech-laboratories/x-app`, with a subpath per module. It was X-Libs (`@x-tech-laboratories/x-libs`) until 0.97.0, the last release under that name;
6
6
  an app moves over by changing the package name in its imports and its `x-libs-*` commands to `x-app-*`.
7
7
 
8
- The host agent's side, `agent/*` and `durations`, is also its own package, `@x-tech-laboratories/x-app-agent` in
9
- `packages/agent`, released at the same version as X-App, so an app's agent installs on each host with sshpk and
10
- parse-duration alone in place of the whole of X-App, React and Fastify included. Its modules keep the same names
11
- (`@x-tech-laboratories/x-app-agent/session`), and X-App's own `agent/*` and `durations` re-export them, so an app's
12
- server and pages import them from either. An app packages its agent from a folder with its own `package.json` that
13
- depends on the agent package alone.
8
+ The host agent's side is also its own package, `@x-tech-laboratories/x-app-agent` in `packages/agent`, released at
9
+ the same version as X-App, so an app's agent installs on each host with a handful of small packages in place of the
10
+ whole of X-App, React and Fastify included. It holds `agent/*` and `durations`, and the helpers an engine running on a
11
+ host needs as well, such as X-Monitor's agent running its own monitors: `cron`, `log`, `plugins`, `plugin_folder`,
12
+ `config_watch`, `sql` and `python_text`, and the server's side of agent connections, `server/agents/hub`,
13
+ `connection` and `agent`, which need nothing but Node (the Fastify route, `server/agents/route`, stays in X-App). Its modules keep the same names (`@x-tech-laboratories/x-app-agent/session`),
14
+ and X-App's own paths re-export them, so an app's server and pages import them from either. An app packages its agent
15
+ from a folder with its own `package.json` that depends on the agent package alone.
14
16
 
15
17
  ## Modules
16
18
 
@@ -1,15 +1 @@
1
- export interface ConfigWatchOptions {
2
- path: string;
3
- loaded_digest: () => string | null;
4
- reload: () => Promise<unknown>;
5
- interval_in_milliseconds?: number;
6
- on_error?: (error: unknown) => void;
7
- }
8
- export interface ConfigWatch {
9
- check(): Promise<boolean>;
10
- stop(): void;
11
- }
12
- export declare const config_poll_in_milliseconds = 3000;
13
- export declare function config_fingerprint(path: string): Promise<string | null>;
14
- export declare function file_digest(path: string): Promise<string | null>;
15
- export declare function watch_config(options: ConfigWatchOptions, start_timer?: boolean): ConfigWatch;
1
+ export * from "@x-tech-laboratories/x-app-agent/config_watch";
@@ -1,75 +1,2 @@
1
- // Reloads a config file when it changes. Every few seconds it reads a fingerprint of what the path points at (the real
2
- // path through any symlink, its inode, change time and size), so a re-pointed symlink or a replaced file counts as a
3
- // change; it waits one more check for the fingerprint to hold still, and reloads only when the content's hash differs
4
- // from what was last loaded.
5
- // ── Imports ──────────────────────────────────────────────────────────────────
6
- import { createHash } from "node:crypto";
7
- import { readFile, realpath, stat } from "node:fs/promises";
8
- // ── Settings ─────────────────────────────────────────────────────────────────
9
- export const config_poll_in_milliseconds = 3000;
10
- // ── Reading the file ─────────────────────────────────────────────────────────
11
- // What the path points at and when it last changed, or null when it cannot be read.
12
- export async function config_fingerprint(path) {
13
- try {
14
- const real = await realpath(path);
15
- const info = await stat(real, { bigint: true });
16
- return JSON.stringify([real, String(info.ino), String(info.mtimeNs), String(info.size)]);
17
- }
18
- catch {
19
- return null;
20
- }
21
- }
22
- // The sha256 of the file's content in hex, or null when it cannot be read.
23
- export async function file_digest(path) {
24
- try {
25
- return createHash("sha256").update(await readFile(path)).digest("hex");
26
- }
27
- catch {
28
- return null;
29
- }
30
- }
31
- // ── Watching ─────────────────────────────────────────────────────────────────
32
- // Starts checking on a timer; `check` can also be called by hand, as a test does.
33
- export function watch_config(options, start_timer = true) {
34
- let seen = null;
35
- let pending = null;
36
- let timer;
37
- let stopped = false;
38
- const check = async () => {
39
- const current = await config_fingerprint(options.path);
40
- if (current === null || current === seen) {
41
- pending = null;
42
- return false;
43
- }
44
- if (current !== pending) {
45
- pending = current;
46
- return false;
47
- }
48
- seen = current;
49
- pending = null;
50
- if ((await file_digest(options.path)) === options.loaded_digest())
51
- return false;
52
- try {
53
- await options.reload();
54
- }
55
- catch (error) {
56
- options.on_error?.(error);
57
- }
58
- return true;
59
- };
60
- const schedule = () => {
61
- if (stopped)
62
- return;
63
- timer = setTimeout(() => void check().finally(schedule), options.interval_in_milliseconds ?? config_poll_in_milliseconds);
64
- timer.unref?.();
65
- };
66
- if (start_timer)
67
- schedule();
68
- return {
69
- check,
70
- stop: () => {
71
- stopped = true;
72
- clearTimeout(timer);
73
- },
74
- };
75
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/config_watch";
package/dist/cron.d.ts CHANGED
@@ -1,34 +1 @@
1
- export declare class CronSchedule {
2
- readonly expression: string;
3
- readonly minutes: ReadonlySet<number>;
4
- readonly hours: ReadonlySet<number>;
5
- readonly days: ReadonlySet<number>;
6
- readonly months: ReadonlySet<number>;
7
- readonly weekdays: ReadonlySet<number>;
8
- readonly any_day: boolean;
9
- readonly any_weekday: boolean;
10
- private constructor();
11
- static parse(expression: string): CronSchedule;
12
- matches_day(day: Date): boolean;
13
- next_after(moment: Date): Date | null;
14
- }
15
- export type IntervalUnit = "minutes" | "hours" | "days";
16
- export type RunSchedule = {
17
- kind: "every";
18
- every: number;
19
- unit: IntervalUnit;
20
- } | {
21
- kind: "at";
22
- time: string;
23
- weekdays: number[];
24
- };
25
- export interface ScheduleLimits {
26
- min_minutes?: number;
27
- }
28
- export declare function checked_schedule(given: unknown, limits?: ScheduleLimits): RunSchedule;
29
- export declare function describe_schedule(schedule: RunSchedule): string;
30
- export declare function schedule_cron(schedule: Extract<RunSchedule, {
31
- kind: "at";
32
- }>): CronSchedule;
33
- export declare function next_due(schedule: RunSchedule, since: number): number;
34
- export declare function is_due(schedule: RunSchedule, since: number, now: number): boolean;
1
+ export * from "@x-tech-laboratories/x-app-agent/cron";
package/dist/cron.js CHANGED
@@ -1,187 +1,2 @@
1
- // Five-field cron expressions read in local time: minute, hour, day of month, month, day of week, with the @daily
2
- // style aliases and month and weekday names. On them, the simpler schedules a user picks for recurring work: every so
3
- // many minutes, hours or days after it last ran, or at a time on chosen weekdays, due once however often it was missed.
4
- // ── Expressions ──────────────────────────────────────────────────────────────
5
- const aliases = {
6
- "@hourly": "0 * * * *",
7
- "@daily": "0 0 * * *",
8
- "@midnight": "0 0 * * *",
9
- "@weekly": "0 0 * * 0",
10
- "@monthly": "0 0 1 * *",
11
- "@yearly": "0 0 1 1 *",
12
- "@annually": "0 0 1 1 *",
13
- };
14
- const month_names = Object.fromEntries(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].map((name, index) => [name, index + 1]));
15
- const weekday_names = Object.fromEntries(["sun", "mon", "tue", "wed", "thu", "fri", "sat"].map((name, index) => [name, index]));
16
- // Long enough to reach a 29 February across a century year that skips its leap day.
17
- const search_days = 366 * 9;
18
- function field_value(text, names, label) {
19
- const lowered = text.toLowerCase();
20
- if (Object.hasOwn(names, lowered))
21
- return names[lowered];
22
- if (!/^\d+$/.test(text))
23
- throw new Error(`${label} has an unrecognised value '${text}'`);
24
- return Number(text);
25
- }
26
- // Expands one field, such as "*/15", "1-5" or "mon,wed", into the values it allows.
27
- function parse_field(text, low, high, label, names = {}) {
28
- const values = new Set();
29
- for (const part of text.split(",")) {
30
- const slash = part.indexOf("/");
31
- const base = slash === -1 ? part : part.slice(0, slash);
32
- const step_text = slash === -1 ? "" : part.slice(slash + 1);
33
- let step = 1;
34
- if (step_text) {
35
- if (!/^\d+$/.test(step_text) || Number(step_text) === 0)
36
- throw new Error(`${label} has a bad step '${step_text}'`);
37
- step = Number(step_text);
38
- }
39
- let start;
40
- let end;
41
- if (base === "*") {
42
- start = low;
43
- end = high;
44
- }
45
- else if (base.includes("-")) {
46
- const dash = base.indexOf("-");
47
- start = field_value(base.slice(0, dash), names, label);
48
- end = field_value(base.slice(dash + 1), names, label);
49
- }
50
- else {
51
- start = field_value(base, names, label);
52
- // A lone value with a step, as in "5/10", runs from that value to the end of the range.
53
- end = step_text ? high : start;
54
- }
55
- if (!(low <= start && start <= high && low <= end && end <= high) || start > end)
56
- throw new Error(`${label} value '${base}' is outside ${low}-${high}`);
57
- for (let value = start; value <= end; value += step)
58
- values.add(value);
59
- }
60
- return values;
61
- }
62
- export class CronSchedule {
63
- expression;
64
- minutes;
65
- hours;
66
- days;
67
- months;
68
- weekdays;
69
- any_day;
70
- any_weekday;
71
- constructor(expression, fields) {
72
- const [minute, hour, day, month, weekday] = fields;
73
- this.expression = expression;
74
- this.minutes = parse_field(minute, 0, 59, "minute");
75
- this.hours = parse_field(hour, 0, 23, "hour");
76
- this.days = parse_field(day, 1, 31, "day of month");
77
- this.months = parse_field(month, 1, 12, "month", month_names);
78
- // Cron allows 7 as a second name for Sunday.
79
- this.weekdays = new Set([...parse_field(weekday, 0, 7, "day of week", weekday_names)].map((value) => (value === 7 ? 0 : value)));
80
- this.any_day = day.startsWith("*");
81
- this.any_weekday = weekday.startsWith("*");
82
- }
83
- // Reads an expression such as "30 2 * * *" or "@daily", throwing when it is malformed or never matches.
84
- static parse(expression) {
85
- const text = String(expression).trim();
86
- const fields = (aliases[text.toLowerCase()] ?? text).split(/\s+/).filter((field) => field !== "");
87
- if (fields.length !== 5)
88
- throw new Error(`cron expression '${text}' needs five fields: minute hour day-of-month month day-of-week`);
89
- const schedule = new CronSchedule(text, fields);
90
- if (schedule.next_after(new Date(2000, 0, 1)) === null)
91
- throw new Error(`cron expression '${text}' never matches a real date`);
92
- return schedule;
93
- }
94
- // Whether it runs on this date; a restricted day of month and day of week match either, as cron does.
95
- matches_day(day) {
96
- if (!this.months.has(day.getMonth() + 1))
97
- return false;
98
- const weekday = day.getDay();
99
- if (this.any_day && this.any_weekday)
100
- return true;
101
- if (this.any_day)
102
- return this.weekdays.has(weekday);
103
- if (this.any_weekday)
104
- return this.days.has(day.getDate());
105
- return this.days.has(day.getDate()) || this.weekdays.has(weekday);
106
- }
107
- // The first run strictly after `moment`, in local time, or null when there is none.
108
- next_after(moment) {
109
- const start = new Date(moment.getFullYear(), moment.getMonth(), moment.getDate(), moment.getHours(), moment.getMinutes() + 1);
110
- const hours = [...this.hours].sort((a, b) => a - b);
111
- const minutes = [...this.minutes].sort((a, b) => a - b);
112
- let day = new Date(start.getFullYear(), start.getMonth(), start.getDate());
113
- for (let step = 0; step < search_days; step++) {
114
- if (this.matches_day(day)) {
115
- for (const hour of hours) {
116
- for (const minute of minutes) {
117
- const candidate = new Date(day.getFullYear(), day.getMonth(), day.getDate(), hour, minute);
118
- if (candidate >= start)
119
- return candidate;
120
- }
121
- }
122
- }
123
- day = new Date(day.getFullYear(), day.getMonth(), day.getDate() + 1);
124
- }
125
- return null;
126
- }
127
- }
128
- const unit_ms = { minutes: 60_000, hours: 3_600_000, days: 86_400_000 };
129
- const weekday_words = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
130
- // The schedule given, checked, or a plain reason it is not one.
131
- export function checked_schedule(given, limits = {}) {
132
- const value = (given ?? {});
133
- if (value.kind === "every") {
134
- const every = Number(value.every);
135
- const unit = String(value.unit);
136
- const min_minutes = limits.min_minutes ?? 1;
137
- if (!Object.hasOwn(unit_ms, unit))
138
- throw new Error('A schedule\'s unit is "minutes", "hours" or "days".');
139
- if (!Number.isInteger(every) || every < 1)
140
- throw new Error("A schedule runs every whole number of minutes, hours or days, one or more.");
141
- if (unit === "minutes" && every < min_minutes)
142
- throw new Error(`A schedule runs at most every ${min_minutes} minutes.`);
143
- return { kind: "every", every, unit };
144
- }
145
- if (value.kind === "at") {
146
- const time = String(value.time ?? "");
147
- const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(time);
148
- if (!match)
149
- throw new Error("A schedule's time is a 24-hour time such as 07:30.");
150
- const weekdays = Array.isArray(value.weekdays) ? [...new Set(value.weekdays.map(Number))].filter((day) => Number.isInteger(day) && day >= 0 && day <= 6).sort((a, b) => a - b) : [];
151
- if (weekdays.length === 0)
152
- throw new Error("A schedule at a time runs on one weekday or more, 0 being Sunday.");
153
- return { kind: "at", time: `${match[1].padStart(2, "0")}:${match[2]}`, weekdays };
154
- }
155
- throw new Error('A schedule is { kind: "every", every, unit } or { kind: "at", time, weekdays }.');
156
- }
157
- function word_list(words) {
158
- return words.length <= 1 ? (words[0] ?? "") : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
159
- }
160
- // The schedule in plain words, such as "every 2 hours" or "at 07:30 on Monday and Friday".
161
- export function describe_schedule(schedule) {
162
- if (schedule.kind === "every")
163
- return schedule.every === 1 ? `every ${schedule.unit.slice(0, -1)}` : `every ${schedule.every} ${schedule.unit}`;
164
- const days = schedule.weekdays.length === 7
165
- ? "every day"
166
- : schedule.weekdays.length === 5 && schedule.weekdays.every((day) => day >= 1 && day <= 5)
167
- ? "on weekdays"
168
- : `on ${word_list(schedule.weekdays.map((day) => weekday_words[day]))}`;
169
- return `at ${schedule.time} ${days}`;
170
- }
171
- // An "at" schedule as the cron expression naming the same moments.
172
- export function schedule_cron(schedule) {
173
- const [hours, minutes] = schedule.time.split(":").map(Number);
174
- return CronSchedule.parse(`${minutes} ${hours} * * ${schedule.weekdays.join(",")}`);
175
- }
176
- // When the work falls due next, given when it last ran or was made.
177
- export function next_due(schedule, since) {
178
- if (schedule.kind === "every")
179
- return since + schedule.every * unit_ms[schedule.unit];
180
- return schedule_cron(schedule).next_after(new Date(since))?.getTime() ?? since + unit_ms.days;
181
- }
182
- // Whether the work is due now, given when it last ran or was made: once, however many times it was missed.
183
- export function is_due(schedule, since, now) {
184
- if (schedule.kind === "every")
185
- return now - since >= schedule.every * unit_ms[schedule.unit];
186
- return next_due(schedule, since) <= now;
187
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/cron";
package/dist/log.d.ts CHANGED
@@ -1,30 +1 @@
1
- export type Level = "critical" | "error" | "warn" | "info" | "debug";
2
- export declare const levels: Level[];
3
- export declare const default_level: Level;
4
- export interface LevelSpec {
5
- default: Level;
6
- scopes: Record<string, Level>;
7
- }
8
- export declare function parse_level_spec(spec: string | undefined, fallback?: Level): LevelSpec;
9
- export declare function level_for(spec: LevelSpec, scope: string): Level;
10
- export declare function is_enabled(spec: LevelSpec, scope: string, level: Level): boolean;
11
- export interface LogRecord {
12
- at: number;
13
- level: Level;
14
- scope: string;
15
- message: string;
16
- data?: unknown;
17
- }
18
- export type LogSink = (record: LogRecord) => void;
19
- export declare function format_record(record: LogRecord): string;
20
- export interface Logger {
21
- critical(message: string, data?: unknown): void;
22
- error(message: string, data?: unknown): void;
23
- warn(message: string, data?: unknown): void;
24
- info(message: string, data?: unknown): void;
25
- debug(message: string, data?: unknown): void;
26
- enabled(level: Level): boolean;
27
- child(scope: string): Logger;
28
- }
29
- export type SpecSource = LevelSpec | (() => LevelSpec);
30
- export declare function create_logger(scope: string, spec: SpecSource, sink: LogSink): Logger;
1
+ export * from "@x-tech-laboratories/x-app-agent/log";
package/dist/log.js CHANGED
@@ -1,85 +1,2 @@
1
- // Logging by scope and level, such as "warn,play:debug", where a mistake in the setting never silences logging.
2
- const level_order = { critical: 0, error: 1, warn: 2, info: 3, debug: 4 };
3
- export const levels = Object.keys(level_order);
4
- const level_aliases = {
5
- crit: "critical", critical: "critical",
6
- err: "error", error: "error",
7
- warn: "warn", warning: "warn",
8
- info: "info",
9
- debug: "debug", verbose: "debug", trace: "debug",
10
- };
11
- export const default_level = "info";
12
- // ── Parsing ──────────────────────────────────────────────────────────────────
13
- // A bare level sets the default and "scope:level" one scope; entries it cannot read are skipped.
14
- export function parse_level_spec(spec, fallback = default_level) {
15
- const parsed = { default: fallback, scopes: {} };
16
- if (!spec)
17
- return parsed;
18
- for (const raw_part of spec.split(",")) {
19
- const part = raw_part.trim().toLowerCase();
20
- if (part === "")
21
- continue;
22
- // Scopes hold colons of their own, so the level follows the last one.
23
- const colon = part.lastIndexOf(":");
24
- if (colon === -1) {
25
- const level = level_aliases[part];
26
- if (level)
27
- parsed.default = level;
28
- continue;
29
- }
30
- const scope = part.slice(0, colon).trim();
31
- const level = level_aliases[part.slice(colon + 1).trim()];
32
- if (!level || scope === "")
33
- continue;
34
- if (scope === "*")
35
- parsed.default = level;
36
- else
37
- parsed.scopes[scope] = level;
38
- }
39
- return parsed;
40
- }
41
- // A scope without its own level takes its nearest dotted parent's, so "x.core" covers "x.core.db", then the default.
42
- export function level_for(spec, scope) {
43
- for (let name = scope; name !== ""; name = name.includes(".") ? name.slice(0, name.lastIndexOf(".")) : "") {
44
- const level = spec.scopes[name];
45
- if (level !== undefined)
46
- return level;
47
- }
48
- return spec.default;
49
- }
50
- export function is_enabled(spec, scope, level) {
51
- return level_order[level] <= level_order[level_for(spec, scope)];
52
- }
53
- const two_digits = (count) => String(count).padStart(2, "0");
54
- // A line in fixed columns, such as "10:33:35.123 WARN play message {"detail":1}".
55
- export function format_record(record) {
56
- const date = new Date(record.at);
57
- const time = `${two_digits(date.getHours())}:${two_digits(date.getMinutes())}:${two_digits(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
58
- let line = `${time} ${record.level.toUpperCase().padEnd(8)} ${record.scope.padEnd(9)} ${record.message}`;
59
- if (record.data !== undefined) {
60
- try {
61
- line += ` ${JSON.stringify(record.data)}`;
62
- }
63
- catch {
64
- line += " [unserializable]";
65
- }
66
- }
67
- return line;
68
- }
69
- const resolve_spec = (source) => typeof source === "function" ? source() : source;
70
- export function create_logger(scope, spec, sink) {
71
- const emit = (level, message, data) => {
72
- if (!is_enabled(resolve_spec(spec), scope, level))
73
- return;
74
- sink({ at: Date.now(), level, scope, message, data });
75
- };
76
- return {
77
- critical: (message, data) => emit("critical", message, data),
78
- error: (message, data) => emit("error", message, data),
79
- warn: (message, data) => emit("warn", message, data),
80
- info: (message, data) => emit("info", message, data),
81
- debug: (message, data) => emit("debug", message, data),
82
- enabled: (level) => is_enabled(resolve_spec(spec), scope, level),
83
- child: (child_scope) => create_logger(`${scope}:${child_scope}`, spec, sink),
84
- };
85
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/log";
@@ -1,24 +1 @@
1
- import type { Plugin, PluginApi } from "./plugins.ts";
2
- export interface PluginEntry {
3
- name: string;
4
- path: string;
5
- file: string;
6
- }
7
- export interface PluginProblem {
8
- name: string;
9
- problem: string;
10
- }
11
- export declare function plugin_entries(folder: string, side: string): {
12
- entries: PluginEntry[];
13
- problems: PluginProblem[];
14
- };
15
- export declare function inside(root: string, path: string): string | undefined;
16
- export declare function plugin_index(folder: string, side: string): {
17
- entries: string[];
18
- problems: PluginProblem[];
19
- };
20
- export declare function read_plugin_file(folder: string, path: string, side?: string): string;
21
- export declare function load_plugin_folder<Api extends PluginApi = PluginApi>(folder: string, side: string): Promise<{
22
- plugins: Plugin<Api>[];
23
- problems: PluginProblem[];
24
- }>;
1
+ export * from "@x-tech-laboratories/x-app-agent/plugin_folder";
@@ -1,107 +1,2 @@
1
- // Plugins kept in a folder on disk: each in a subfolder whose package.json names, under "x-plugin", its built entry for each side of the app, such as { "server": "dist/server.js", "web": "dist/web.js" }.
2
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
4
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
5
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
6
- });
7
- }
8
- return path;
9
- };
10
- import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
11
- import { join, relative, resolve, sep } from "node:path";
12
- import { pathToFileURL } from "node:url";
13
- // The entries for one side, such as "server", "agent", "main" or "web"; a subfolder without one is skipped, a broken one is a problem.
14
- export function plugin_entries(folder, side) {
15
- const entries = [];
16
- const problems = [];
17
- if (!existsSync(folder))
18
- return { entries, problems };
19
- for (const item of readdirSync(folder, { withFileTypes: true })) {
20
- if (!item.isDirectory() || item.name.startsWith("."))
21
- continue;
22
- const root = join(folder, item.name);
23
- try {
24
- const entry = entry_in(root, side);
25
- if (entry)
26
- entries.push({ name: item.name, ...entry });
27
- }
28
- catch (error) {
29
- problems.push({ name: item.name, problem: error instanceof Error ? error.message : String(error) });
30
- }
31
- }
32
- return { entries, problems };
33
- }
34
- function entry_in(root, side) {
35
- const manifest_file = join(root, "package.json");
36
- if (!existsSync(manifest_file))
37
- throw new Error("It has no package.json.");
38
- const manifest = JSON.parse(readFileSync(manifest_file, "utf8"));
39
- const sides = manifest && typeof manifest === "object" ? manifest["x-plugin"] : undefined;
40
- if (!sides || typeof sides !== "object")
41
- throw new Error('Its package.json has no "x-plugin" entries.');
42
- const path = sides[side];
43
- if (path === undefined)
44
- return undefined;
45
- if (typeof path !== "string")
46
- throw new Error(`Its ${side} entry is not a path.`);
47
- const file = inside(root, path);
48
- if (!file)
49
- throw new Error(`Its ${side} entry ${path} is outside its folder.`);
50
- if (!existsSync(file))
51
- throw new Error(`Its ${side} entry ${path} is missing; is it built?`);
52
- return { path: relative(realpathSync(root), file).split(sep).join("/"), file };
53
- }
54
- // The file at path under root, or nothing when it, or a link it goes through, leads outside root.
55
- export function inside(root, path) {
56
- if (!existsSync(root))
57
- return undefined;
58
- const real_root = realpathSync(root);
59
- const file = resolve(real_root, path);
60
- const real_file = existsSync(file) ? realpathSync(file) : file;
61
- return real_file.startsWith(real_root + sep) ? real_file : undefined;
62
- }
63
- // The page's list of a folder's entries for one side, as URLs relative to the list, with a problem per broken subfolder.
64
- export function plugin_index(folder, side) {
65
- const { entries, problems } = plugin_entries(folder, side);
66
- return { entries: entries.map((entry) => `${encodeURIComponent(entry.name)}/${entry.path.split("/").map(encodeURIComponent).join("/")}`), problems };
67
- }
68
- // A file the page asks for by its path under the list: "index.json" is plugin_index as JSON, anything else is read from
69
- // its plugin's own subfolder, and "" when it is not there or leads outside it. For a desktop page reaching the folder over IPC.
70
- export function read_plugin_file(folder, path, side = "web") {
71
- if (path === "index.json")
72
- return JSON.stringify(plugin_index(folder, side));
73
- const [name = "", ...rest] = path.split("/").map((part) => {
74
- try {
75
- return decodeURIComponent(part);
76
- }
77
- catch {
78
- return "";
79
- }
80
- });
81
- const root = name && !name.startsWith(".") ? inside(folder, name) : undefined;
82
- const file = root && inside(root, rest.join("/"));
83
- try {
84
- return file && existsSync(file) ? readFileSync(file, "utf8") : "";
85
- }
86
- catch {
87
- return "";
88
- }
89
- }
90
- // Imports each entry for the side; its default export, or an export named plugin, is the plugin.
91
- export async function load_plugin_folder(folder, side) {
92
- const { entries, problems } = plugin_entries(folder, side);
93
- const plugins = [];
94
- for (const entry of entries) {
95
- try {
96
- const module = (await import(__rewriteRelativeImportExtension(pathToFileURL(entry.file).href)));
97
- const plugin = module.default ?? module.plugin;
98
- if (!plugin || typeof plugin.start !== "function")
99
- throw new Error(`Its ${side} entry exports no plugin.`);
100
- plugins.push(plugin);
101
- }
102
- catch (error) {
103
- problems.push({ name: entry.name, problem: error instanceof Error ? error.message : String(error) });
104
- }
105
- }
106
- return { plugins, problems };
107
- }
1
+ // Moved to @x-tech-laboratories/x-app-agent, which a host agent installs without the rest of X-App.
2
+ export * from "@x-tech-laboratories/x-app-agent/plugin_folder";