@x-tech-laboratories/x-app 0.133.0 → 0.135.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
 
@@ -25,7 +27,7 @@ depends on the agent package alone.
25
27
  | `app/window_size` | `fit_window_size(work_area)`: a first window of most of the screen's free area, between 960×640 and 1800×1200 and never past the screen; hand it to `run_desktop` as `default_size`. |
26
28
  | `app/seed` | A development database of an app's example data, made by its own calls: `seed_app_database(app, { file, reset, seed })` opens a fresh file with the app's schema and hands `seed` the app's calls, refusing a file already there without `reset` (which takes its `-wal` and `-shm` too) and the desktop app's real database in `~/.config/<id>` (`real_database_path`) whatever path leads there; `run_seed(app, seed)` is the seed script's whole command line, `<file> [--reset]`, read by `seed_target`. |
27
29
  | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, the theme kept in this browser or, for an app with `synced_theme`, in its synced setting, the sidebar's dragged width remembered on this device (`default_sidebar_width`) unless the chrome's `sidebar_width` holds it, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync, Backups and Import and export, the settings as a file) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools`, a `side_pane`, a `contained` window where only the page scrolls with a `main_class` for its box, `around`, which wraps the page, such as in the app's own context or with dialogs over any page, and `bare` for the page alone with no sidebar or header, such as a strip embedded in another program. `settings_categories(props)` adds the app's own Settings categories after General, for settings no one page owns. A page's `children` fold open under its row in the sidebar (`#/diet/foods`, the title "Foods · Diet", the first shown when none is named, a single child leaving the page one row); its `use_items` hook gives rows worked out as the page runs, such as each paired device, folding open under it onto `#/devices/<id>` with the title "Pixel · Devices", and its `title(parts)` names the window for its route, such as "Job 12"; and `phone_services` loads the app's own work on the phone only there, such as reminders handed to Android, told of every write, every change from another device and each return to the app; an older version's backup schedule in the page's storage moves into the setting. In a browser, Settings ends with Users and Tokens (`users_settings`) for an admin of the server, with the app's `role_text`; an app's own `use_chrome` sidebar, such as a tree, sits under the pages' rows. |
28
- | `app/web/page_dashboards` | A page's own dashboards: a page declares `dashboard: { data_sources, ready_cards, initial, place }` and the base app draws `Dashboards` on its main route, above its view or in its place, each person's kept per page under the account preference `dashboards`, which every app's server allows and cleans with `clean_page_dashboards`, or on the device where no one signs in; the tabs' menu adds, renames, duplicates, resets and deletes them. |
30
+ | `app/web/page_dashboards` | A page's own dashboards: a page declares `dashboard: { data_sources, ready_cards, initial, place }` and the base app draws `Dashboards` on its main route, above its view, below it (`place: "below"`), where the view draws `PageDashboardsHere` (`"inline"`, such as under its heading) or in its place (`"only"`), each person's kept per page under the account preference `dashboards`, which every app's server allows and cleans with `clean_page_dashboards`, or on the device where no one signs in; the tabs' menu adds, renames, duplicates, resets and deletes them. |
29
31
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/electron_builder`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. The page presets stand in for Capacitor where the app has none installed (`config/capacitor`'s `capacitor_stand_in`), so a web and desktop app needs no phone packages, and the dev server proxies `/api/`, leaving the page's own `api.ts` to Vite. `electron_builder_config({ id, name, app_id, comment, categories, link_scheme })` is the desktop app's AppImage and Flatpak bundle for electron-builder, the Flatpak keeping its data in `~/.config/<id>` as the other builds do, and reaching what else `flatpak_permissions` names, such as `--system-talk-name=org.bluez`. |
30
32
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
31
33
  | `idle_watch` | `step_idle_watch`: time away from the computer while something runs, such as a timer: each look at the idle seconds (the desktop's `get_idle_seconds`) moves the watch on, and once someone comes back it hands back the stretch away (`AwaySpan`) when it passed the threshold, a long gap between looks, as when the computer slept, counting as time away from the last look; `fresh_idle_watch` to start. |
@@ -1,14 +1,17 @@
1
1
  import "@x-tech-laboratories/halon/halon-tokens.css";
2
2
  import "@x-tech-laboratories/halon/halon.css";
3
3
  import type { App } from "../define.ts";
4
- import { type AppPages } from "./settings_page.tsx";
4
+ import type { AccountPrefsClient } from "../../web/react/account_prefs.ts";
5
+ import { type AppPage, type AppPages } from "./settings_page.tsx";
5
6
  export type { AppChrome, AppPage, AppPages, AppSubpage, PageSettingsProps } from "./settings_page.tsx";
6
7
  export type { PageDashboard } from "./page_dashboards.tsx";
8
+ export { PageDashboardsHere } from "./page_dashboards.tsx";
7
9
  export declare const default_sidebar_width: {
8
10
  default_width: number;
9
11
  min: number;
10
12
  max: number;
11
13
  };
14
+ export declare function with_dashboards(shown: AppPage, rest: string[], app_id: string, client: AccountPrefsClient | null): React.ReactNode;
12
15
  export declare function AppView({ pages }: {
13
16
  pages: AppPages;
14
17
  }): import("react").JSX.Element;
@@ -18,8 +18,9 @@ import { apply_theme_colors, local_theme_storage, pinned_theme_choice, read_serv
18
18
  import { phone_outside_fetch } from "../outside_fetch.js";
19
19
  import { desktop_api, is_android, is_desktop, web_api } from "./hosts.js";
20
20
  import { calls, data_watch, page, set_page_api, set_page_reach, use_data, use_settings } from "./page.js";
21
- import { PageDashboardsView } from "./page_dashboards.js";
21
+ import { PageDashboardsProvider, PageDashboardsView } from "./page_dashboards.js";
22
22
  import { SettingsView } from "./settings_page.js";
23
+ export { PageDashboardsHere } from "./page_dashboards.js";
23
24
  // ── Pages ────────────────────────────────────────────────────────────────────
24
25
  // Relative, so a server behind a proxy under a folder keeps it.
25
26
  const accounts = create_accounts_client({ base: "api" });
@@ -100,14 +101,19 @@ function use_default_page(pages) {
100
101
  return null;
101
102
  return pages.pages.some((each) => each.id === chosen.data) ? String(chosen.data) : fallback;
102
103
  }
104
+ // A page's view with its dashboards above it, below it, where it puts them or in its place, on its main route.
103
105
  // A page's view with its dashboards above it, or in its place, on its main route.
104
- function with_dashboards(shown, rest, app_id, client) {
106
+ export function with_dashboards(shown, rest, app_id, client) {
105
107
  if (!shown.dashboard || rest.length > 0)
106
108
  return shown.view(rest);
107
- const dashboards = _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client });
109
+ const dashboards = _jsx("div", { className: "page", children: _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client }) });
110
+ if (shown.dashboard.place === "inline")
111
+ return _jsx(PageDashboardsProvider, { dashboards: _jsx(PageDashboardsView, { app_id: app_id, page_id: shown.id, dashboard: shown.dashboard, client: client }), children: shown.view(rest) });
108
112
  if (shown.dashboard.place === "only")
109
- return _jsx("div", { className: "page", children: dashboards });
110
- return _jsxs(_Fragment, { children: [_jsx("div", { className: "page", children: dashboards }), shown.view(rest)] });
113
+ return dashboards;
114
+ if (shown.dashboard.place === "below")
115
+ return _jsxs(_Fragment, { children: [shown.view(rest), dashboards] });
116
+ return _jsxs(_Fragment, { children: [dashboards, shown.view(rest)] });
111
117
  }
112
118
  function Pages({ pages, account }) {
113
119
  const default_page = use_default_page(pages);
@@ -1,3 +1,4 @@
1
+ import { type ReactNode } from "react";
1
2
  import { type Dashboard } from "../../dashboard.ts";
2
3
  import type { AccountPrefsClient } from "../../web/react/account_prefs.ts";
3
4
  import { type DataSource, type ReadyCardKind } from "../../web/react/dashboard.tsx";
@@ -5,10 +6,15 @@ export interface PageDashboard {
5
6
  data_sources: DataSource[];
6
7
  ready_cards?: ReadyCardKind[];
7
8
  initial?: () => Dashboard;
8
- place?: "above" | "only";
9
+ place?: "above" | "below" | "inline" | "only";
9
10
  refresh_in_milliseconds?: number;
10
11
  }
11
12
  export declare const page_dashboards_pref = "dashboards";
13
+ export declare function PageDashboardsProvider({ dashboards, children }: {
14
+ dashboards: ReactNode;
15
+ children: ReactNode;
16
+ }): import("react").JSX.Element;
17
+ export declare function PageDashboardsHere(): import("react").JSX.Element;
12
18
  interface PageDashboardsProps {
13
19
  app_id: string;
14
20
  page_id: string;
@@ -1,8 +1,9 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
2
  // A page's own dashboards, as the base app draws them above the page: the app declares the data its cards may chart,
3
3
  // its ready-made cards and the dashboard each person starts with, and every person arranges their own, kept with their
4
4
  // account or, with no one signed in, on this device. The tabs' menu adds, renames, duplicates, resets and deletes them.
5
5
  // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { createContext, useContext } from "react";
6
7
  import { clean_page_dashboards } from "../../dashboard.js";
7
8
  import { use_account_pref } from "../../web/react/account_prefs.js";
8
9
  import { Dashboards } from "../../web/react/dashboard.js";
@@ -12,6 +13,16 @@ import { toast } from "../../web/react/toasts.js";
12
13
  import { data_watch } from "./page.js";
13
14
  // The account preference every page's dashboards are kept under, which the base app's server allows.
14
15
  export const page_dashboards_pref = "dashboards";
16
+ // ── Placing ──────────────────────────────────────────────────────────────────
17
+ const PlacedDashboards = createContext(null);
18
+ // Hands a page's dashboards to the `PageDashboardsHere` its view draws, for a page whose dashboards go "inline".
19
+ export function PageDashboardsProvider({ dashboards, children }) {
20
+ return _jsx(PlacedDashboards.Provider, { value: dashboards, children: children });
21
+ }
22
+ // Where a page that places its dashboards "inline" draws them in its view; nothing on any other page or route.
23
+ export function PageDashboardsHere() {
24
+ return _jsx(_Fragment, { children: useContext(PlacedDashboards) });
25
+ }
15
26
  // ── Keeping ──────────────────────────────────────────────────────────────────
16
27
  const no_dashboards = {};
17
28
  const is_page_dashboards = (value) => typeof value === "object" && value !== null && JSON.stringify(clean_page_dashboards(value)) === JSON.stringify(value);
@@ -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";