@osdlc/wayfinder 0.0.1-stage → 0.7.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/CONTRIBUTING.md +62 -0
  3. package/{LICENSE → LICENSE-APACHE} +1 -11
  4. package/LICENSE-MIT +21 -0
  5. package/README.md +505 -2
  6. package/SECURITY.md +44 -0
  7. package/bin/way.js +18 -0
  8. package/dist/app.d.ts +24 -0
  9. package/dist/app.js +24 -0
  10. package/dist/args.d.ts +44 -0
  11. package/dist/args.js +93 -0
  12. package/dist/cache.d.ts +7 -0
  13. package/dist/cache.js +15 -0
  14. package/dist/catalog.d.ts +38 -0
  15. package/dist/catalog.js +61 -0
  16. package/dist/clean-command.d.ts +43 -0
  17. package/dist/clean-command.js +274 -0
  18. package/dist/cli.d.ts +76 -0
  19. package/dist/cli.js +612 -0
  20. package/dist/config-command.d.ts +52 -0
  21. package/dist/config-command.js +342 -0
  22. package/dist/config.d.ts +367 -0
  23. package/dist/config.js +700 -0
  24. package/dist/devlink.d.ts +14 -0
  25. package/dist/devlink.js +30 -0
  26. package/dist/groups.d.ts +34 -0
  27. package/dist/groups.js +38 -0
  28. package/dist/guide.d.ts +32 -0
  29. package/dist/guide.js +411 -0
  30. package/dist/http.d.ts +22 -0
  31. package/dist/http.js +149 -0
  32. package/dist/origin-owner.d.ts +14 -0
  33. package/dist/origin-owner.js +69 -0
  34. package/dist/page.d.ts +15 -0
  35. package/dist/page.js +58 -0
  36. package/dist/providers-command.d.ts +40 -0
  37. package/dist/providers-command.js +132 -0
  38. package/dist/serve.d.ts +97 -0
  39. package/dist/serve.js +678 -0
  40. package/dist/tools.d.ts +46 -0
  41. package/dist/tools.js +102 -0
  42. package/dist/trust-command.d.ts +33 -0
  43. package/dist/trust-command.js +221 -0
  44. package/dist/trust-store.d.ts +18 -0
  45. package/dist/trust-store.js +46 -0
  46. package/dist/tui.d.ts +178 -0
  47. package/dist/tui.js +846 -0
  48. package/dist/web/main.js +2315 -0
  49. package/dist/web/page.html +110 -0
  50. package/dist/web/styles.css +1514 -0
  51. package/dist/xdg.d.ts +10 -0
  52. package/dist/xdg.js +17 -0
  53. package/package.json +54 -9
package/dist/http.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * A fetch-style server on `node:http`: the handler takes a web `Request` and
3
+ * returns a `Response`, and the body streams out chunk by chunk. Runs under
4
+ * Node and Bun.
5
+ */
6
+ import { createServer } from 'node:http';
7
+ /** How long `stop` waits for busy connections before closing them. */
8
+ const STOP_GRACE_MS = 1000;
9
+ function toRequest(req, origin, body) {
10
+ const headers = new Headers();
11
+ for (const [name, value] of Object.entries(req.headers)) {
12
+ if (value === undefined)
13
+ continue;
14
+ for (const v of Array.isArray(value) ? value : [value])
15
+ headers.append(name, v);
16
+ }
17
+ return new Request(new URL(req.url ?? '/', origin), {
18
+ method: req.method ?? 'GET',
19
+ headers,
20
+ ...(body !== null ? { body: new Uint8Array(body) } : {}),
21
+ });
22
+ }
23
+ /** The largest request body read; every route takes a small JSON body. */
24
+ export const MAX_BODY_BYTES = 1024 * 1024;
25
+ class BodyTooLarge extends Error {
26
+ }
27
+ function readBody(req) {
28
+ if (req.method === 'GET' || req.method === 'HEAD')
29
+ return Promise.resolve(null);
30
+ return new Promise((resolve, reject) => {
31
+ const chunks = [];
32
+ let size = 0;
33
+ req.on('data', (c) => {
34
+ size += c.length;
35
+ if (size > MAX_BODY_BYTES) {
36
+ req.removeAllListeners('data');
37
+ reject(new BodyTooLarge());
38
+ return;
39
+ }
40
+ chunks.push(c);
41
+ });
42
+ req.on('end', () => resolve(Buffer.concat(chunks)));
43
+ req.on('error', reject);
44
+ });
45
+ }
46
+ /**
47
+ * Write `response` out. Each chunk is written, and drained when the socket is
48
+ * full, before the next is read. A client that disconnects cancels the body.
49
+ */
50
+ async function writeResponse(res, response) {
51
+ const headers = {};
52
+ response.headers.forEach((value, name) => {
53
+ headers[name] = value;
54
+ });
55
+ res.writeHead(response.status, headers);
56
+ if (response.body === null) {
57
+ res.end();
58
+ return;
59
+ }
60
+ const reader = response.body.getReader();
61
+ let closed = false;
62
+ let wake = () => { };
63
+ const onClose = () => {
64
+ if (res.writableFinished)
65
+ return;
66
+ closed = true;
67
+ wake();
68
+ void reader.cancel().catch(() => { });
69
+ };
70
+ res.once('close', onClose);
71
+ try {
72
+ for (;;) {
73
+ const { done, value } = await reader.read();
74
+ if (done || closed)
75
+ break;
76
+ if (!res.write(value)) {
77
+ await new Promise((resolve) => {
78
+ wake = resolve;
79
+ res.once('drain', resolve);
80
+ });
81
+ res.off('drain', wake);
82
+ if (closed)
83
+ break;
84
+ }
85
+ }
86
+ }
87
+ finally {
88
+ res.off('close', onClose);
89
+ }
90
+ if (!closed)
91
+ res.end();
92
+ }
93
+ /** Bind `hostname:port` and answer every request with `fetch`. */
94
+ export function serveFetch(options) {
95
+ let handle;
96
+ let stopping = false;
97
+ const server = createServer((req, res) => {
98
+ // A response that finishes while stopping leaves an idle keep-alive
99
+ // connection that would hold `close` open.
100
+ res.on('finish', () => {
101
+ if (stopping)
102
+ setImmediate(() => server.closeIdleConnections());
103
+ });
104
+ void (async () => {
105
+ try {
106
+ const body = await readBody(req);
107
+ const origin = `http://${req.headers.host ?? `${options.hostname}:${handle.port}`}`;
108
+ await writeResponse(res, await options.fetch(toRequest(req, origin, body), handle));
109
+ }
110
+ catch (err) {
111
+ if (res.headersSent) {
112
+ // A body is part-sent under a success status: cut it off rather
113
+ // than append an error to it.
114
+ res.destroy();
115
+ }
116
+ else if (err instanceof BodyTooLarge) {
117
+ res.writeHead(413, { 'content-type': 'text/plain', connection: 'close' });
118
+ res.end('request body too large');
119
+ // Stop reading the rest once the answer is out.
120
+ res.once('finish', () => req.destroy());
121
+ }
122
+ else {
123
+ res.writeHead(500, { 'content-type': 'text/plain' });
124
+ res.end(err instanceof Error ? err.message : String(err));
125
+ }
126
+ }
127
+ })();
128
+ });
129
+ return new Promise((resolve, reject) => {
130
+ server.once('error', reject);
131
+ server.listen(options.port, options.hostname, () => {
132
+ server.off('error', reject);
133
+ const port = server.address().port;
134
+ handle = {
135
+ port,
136
+ stop: () => new Promise((done) => {
137
+ stopping = true;
138
+ const force = setTimeout(() => server.closeAllConnections(), STOP_GRACE_MS);
139
+ server.close(() => {
140
+ clearTimeout(force);
141
+ done();
142
+ });
143
+ server.closeIdleConnections();
144
+ }),
145
+ };
146
+ resolve(handle);
147
+ });
148
+ });
149
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The git-backed `ownerOf` handed to `@osdlc/trust-repo`, which knows no git.
3
+ * Without it `trust.owners` never matches.
4
+ */
5
+ /**
6
+ * `root`'s `origin` remote owner, or null when there is none we can read.
7
+ * Git runs in `root` with the caller's git location and config variables
8
+ * removed, so they cannot point it at another repository. Git still searches
9
+ * upward from `root`, so a directory without its own `.git` inside a
10
+ * repository gets that repository's owner. A remote that is neither a URL nor
11
+ * scp-style is a local path (`owner/repo` is one) and has no owner. A host
12
+ * hosted-git-info does not know (a self-hosted server) has no owner either.
13
+ */
14
+ export declare function originOwner(root: string): string | null;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The git-backed `ownerOf` handed to `@osdlc/trust-repo`, which knows no git.
3
+ * Without it `trust.owners` never matches.
4
+ */
5
+ import { Git, parseGitUrl } from '@osdlc/typed-git';
6
+ /**
7
+ * Git variables the caller's environment must not apply to the owner lookup:
8
+ * they point git at another repository or add config that rewrites the
9
+ * remote. Git itself exports `GIT_DIR`, `GIT_INDEX_FILE`, `GIT_COMMON_DIR`
10
+ * and `GIT_CONFIG_PARAMETERS` (from `-c`) to hooks and aliases, so they leak
11
+ * into a tool by accident. `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM` and
12
+ * `GIT_CONFIG_NOSYSTEM` are kept on purpose: they are deliberate user setup,
13
+ * like `~/.gitconfig`, whose `insteadOf` rules still apply.
14
+ */
15
+ const GIT_LOCATION_VARS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR'];
16
+ const GIT_CONFIG_VAR = /^GIT_CONFIG(?:$|_COUNT$|_PARAMETERS$|_KEY_\d+$|_VALUE_\d+$)/;
17
+ /**
18
+ * Run `fn` with the git variables listed above removed from `process.env`,
19
+ * then put them back. The typed git client's `env` option is add-only, and an
20
+ * empty `GIT_DIR` is an error, so the variables are removed around one call.
21
+ * `fn` must be synchronous: the process environment is shared, so an await
22
+ * inside would let other code see the change.
23
+ */
24
+ function withoutGitOverrides(fn) {
25
+ const saved = new Map();
26
+ for (const [name, value] of Object.entries(process.env)) {
27
+ if (value === undefined)
28
+ continue;
29
+ if (GIT_LOCATION_VARS.includes(name) || GIT_CONFIG_VAR.test(name))
30
+ saved.set(name, value);
31
+ }
32
+ for (const name of saved.keys())
33
+ delete process.env[name];
34
+ try {
35
+ return fn();
36
+ }
37
+ finally {
38
+ for (const [name, value] of saved)
39
+ process.env[name] = value;
40
+ }
41
+ }
42
+ /** A remote git reads as a URL (`scheme://...`) or as scp-style (`[user@]host:path`). */
43
+ const URL_REMOTE = /^[a-z][a-z0-9+.-]*:\/\//i;
44
+ const SCP_REMOTE = /^(?:[^@/:\s]+@)?[^@/:\s]+:(?!\/\/)/;
45
+ /**
46
+ * hosted-git-info shortcuts (`github:owner/repo`). Git reads these as scp-style
47
+ * ssh to a host called `github`, so they have no owner here.
48
+ */
49
+ const SHORTCUT_REMOTE = /^(?:github|gitlab|bitbucket|gist|sourcehut):/;
50
+ /**
51
+ * `root`'s `origin` remote owner, or null when there is none we can read.
52
+ * Git runs in `root` with the caller's git location and config variables
53
+ * removed, so they cannot point it at another repository. Git still searches
54
+ * upward from `root`, so a directory without its own `.git` inside a
55
+ * repository gets that repository's owner. A remote that is neither a URL nor
56
+ * scp-style is a local path (`owner/repo` is one) and has no owner. A host
57
+ * hosted-git-info does not know (a self-hosted server) has no owner either.
58
+ */
59
+ export function originOwner(root) {
60
+ const res = withoutGitOverrides(() => new Git(root).try.remoteGetUrl('origin'));
61
+ if (!res.ok || res.value === null)
62
+ return null;
63
+ if (SHORTCUT_REMOTE.test(res.value))
64
+ return null;
65
+ if (!URL_REMOTE.test(res.value) && !SCP_REMOTE.test(res.value))
66
+ return null;
67
+ const info = parseGitUrl(res.value);
68
+ return info?.user && info.project ? info.user : null;
69
+ }
package/dist/page.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The page builder: assemble `web/` into one self-contained HTML response.
3
+ *
4
+ * The web view is authored as parts (a skeleton, a stylesheet, TypeScript
5
+ * modules) and served as one document, with no request beyond the catalog
6
+ * API. The installed package reads the script the build bundled into
7
+ * `dist/web/main.js`. A checkout running the source bundles it per request,
8
+ * so an edit is a browser reload, not a restart.
9
+ */
10
+ /**
11
+ * @param sessionToken handed to the page so its fetches can authenticate. It
12
+ * is JSON-encoded into an inline script rather than put in a URL or a cookie:
13
+ * the page keeps it in module state only.
14
+ */
15
+ export declare function buildPage(sessionToken: string): Promise<string>;
package/dist/page.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The page builder: assemble `web/` into one self-contained HTML response.
3
+ *
4
+ * The web view is authored as parts (a skeleton, a stylesheet, TypeScript
5
+ * modules) and served as one document, with no request beyond the catalog
6
+ * API. The installed package reads the script the build bundled into
7
+ * `dist/web/main.js`. A checkout running the source bundles it per request,
8
+ * so an edit is a browser reload, not a restart.
9
+ */
10
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
11
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
12
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
13
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
14
+ });
15
+ }
16
+ return path;
17
+ };
18
+ import { existsSync } from 'node:fs';
19
+ import { readFile } from 'node:fs/promises';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { APP } from "./app.js";
22
+ const DIR = new URL('./web/', import.meta.url);
23
+ const path = (name) => fileURLToPath(new URL(name, DIR));
24
+ /**
25
+ * @param sessionToken handed to the page so its fetches can authenticate. It
26
+ * is JSON-encoded into an inline script rather than put in a URL or a cookie:
27
+ * the page keeps it in module state only.
28
+ */
29
+ export async function buildPage(sessionToken) {
30
+ const [skeleton, styles, script] = await Promise.all([
31
+ readFile(path('page.html'), 'utf8'),
32
+ readFile(path('styles.css'), 'utf8'),
33
+ buildScript(),
34
+ ]);
35
+ // `<\/` keeps a token that somehow contained "</script>" from closing the
36
+ // tag early; JSON.stringify handles the rest.
37
+ const token = JSON.stringify(sessionToken).replaceAll('</', '<\\/');
38
+ return skeleton
39
+ .replace('<!-- @STYLE@ -->', `<style>\n${styles}</style>`)
40
+ .replace('<!-- @TOKEN@ -->', `<script>window.__WAYFINDER_TOKEN__ = ${token};</script>`)
41
+ .replace('<!-- @SCRIPT@ -->', `<script type="module">\n${script.replaceAll('</script>', '<\\/script>')}</script>`);
42
+ }
43
+ async function buildScript() {
44
+ const built = path('main.js');
45
+ if (existsSync(built))
46
+ return readFile(built, 'utf8');
47
+ try {
48
+ // A checkout: the bundler is a dev dependency, reached only from source.
49
+ const bundler = '../scripts/web-bundle.mjs';
50
+ const { bundleWeb } = (await import(__rewriteRelativeImportExtension(bundler)));
51
+ return await bundleWeb(path('main.ts'));
52
+ }
53
+ catch (err) {
54
+ // Fail loudly in the page rather than serve a stale or empty script.
55
+ const detail = err instanceof Error ? err.message : String(err);
56
+ return `document.body.innerHTML = "<pre></pre>";document.querySelector("pre").textContent = ${JSON.stringify(`${APP}: the page script failed to build\n\n${detail}`)};`;
57
+ }
58
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `way providers`: every registered tool, built-in or loaded from a module,
3
+ * with its roles, its runner kind, its binary and whether that binary is on
4
+ * the PATH. Reads files only; runs nothing.
5
+ */
6
+ import { type CliIo } from '@osdlc/cli-tool';
7
+ import type { Project, RoleName, ToolDef } from '@osdlc/system-model/detect';
8
+ import { type LoadedConfig } from './config.ts';
9
+ import type { LoadedTool } from './tools.ts';
10
+ export interface ProvidersCommandIO extends CliIo {
11
+ env?: Record<string, string | undefined>;
12
+ home?: string;
13
+ /** The configured `allowExec`, with wayfinder's default; `main` supplies it. */
14
+ configuredAllowExec: (cfg: LoadedConfig) => boolean;
15
+ /** Load the tool modules and build the project; `main` supplies it. */
16
+ load: (cfg: LoadedConfig, modules: readonly string[], projectAllowed: boolean) => Promise<{
17
+ project: Project;
18
+ tools: LoadedTool[];
19
+ warnings: string[];
20
+ } | {
21
+ error: string;
22
+ }>;
23
+ }
24
+ /** One row of the listing, as `--json` prints it. */
25
+ export interface ProviderRow {
26
+ id: string;
27
+ roles: RoleName[];
28
+ /** The runner role's kind; null for a tool with no runner. */
29
+ kind: 'parse' | 'exec' | null;
30
+ binary: string | null;
31
+ /** Whether `binary` is on the PATH; null when the tool names none. */
32
+ onPath: boolean | null;
33
+ source: 'built-in' | 'custom';
34
+ /** The module a custom tool came from. */
35
+ module?: string;
36
+ }
37
+ /** One row per registered tool, in registry order. */
38
+ export declare function providerRows(tools: readonly ToolDef[], custom: readonly LoadedTool[], env: Record<string, string | undefined>): ProviderRow[];
39
+ /** `way providers …`. Returns the exit code. */
40
+ export declare function runProvidersCommand(root: string, argv: string[], io: ProvidersCommandIO): Promise<number>;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `way providers`: every registered tool, built-in or loaded from a module,
3
+ * with its roles, its runner kind, its binary and whether that binary is on
4
+ * the PATH. Reads files only; runs nothing.
5
+ */
6
+ import { accessSync, constants, statSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { delimiter, join } from 'node:path';
9
+ import { EXIT } from '@osdlc/cli-tool';
10
+ import { policyExecGate } from '@osdlc/trust-repo';
11
+ import { APP, BIN } from "./app.js";
12
+ import { ConfigError, loadConfig, trustPolicyFromConfig, trustPolicyOptions, } from "./config.js";
13
+ import { appTrustStore } from "./trust-store.js";
14
+ const ROLE_ORDER = ['runner', 'packageManager', 'toolManager', 'hookManager'];
15
+ function usage() {
16
+ return `${BIN} providers — the tools ${APP} knows, built-in and your own
17
+
18
+ usage: ${BIN} providers [options]
19
+
20
+ --config MODULE also load the tools a module exports; repeatable
21
+ --json the same rows as a JSON array
22
+ -C, --dir PATH the project whose config to read (default: cwd)
23
+ -h, --help this text
24
+
25
+ A custom tool comes from --config, from "tools" in the user config, or from
26
+ "tools" in the project file when the repository is trusted and execution is
27
+ allowed. kind is the runner
28
+ role's: parse reads files, exec runs the repository's tools and needs trust.
29
+ `;
30
+ }
31
+ function onPath(binary, env) {
32
+ for (const dir of (env['PATH'] ?? '').split(delimiter)) {
33
+ if (dir === '')
34
+ continue;
35
+ try {
36
+ const file = join(dir, binary);
37
+ if (!statSync(file).isFile())
38
+ continue;
39
+ accessSync(file, constants.X_OK);
40
+ return true;
41
+ }
42
+ catch {
43
+ // Not here.
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+ /** One row per registered tool, in registry order. */
49
+ export function providerRows(tools, custom, env) {
50
+ return tools.map((t) => {
51
+ const from = custom.find((c) => c.def === t);
52
+ return {
53
+ id: t.id,
54
+ roles: ROLE_ORDER.filter((r) => t.roles[r] !== undefined),
55
+ kind: t.roles.runner?.kind ?? null,
56
+ binary: t.binary ?? null,
57
+ onPath: t.binary === undefined ? null : onPath(t.binary, env),
58
+ source: from === undefined ? 'built-in' : 'custom',
59
+ ...(from !== undefined ? { module: from.module } : {}),
60
+ };
61
+ });
62
+ }
63
+ function table(rows) {
64
+ const cells = rows.map((r) => [
65
+ r.id,
66
+ r.roles.join(',') || '-',
67
+ r.kind ?? '-',
68
+ r.binary ?? '-',
69
+ r.onPath === null ? '-' : r.onPath ? 'yes' : 'no',
70
+ r.source === 'custom' && r.module !== undefined ? `custom ${r.module}` : r.source,
71
+ ]);
72
+ const head = ['tool', 'roles', 'kind', 'binary', 'on PATH', 'source'];
73
+ const widths = head.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i].length)));
74
+ const fmt = (c) => c
75
+ .map((v, i) => (i === c.length - 1 ? v : v.padEnd(widths[i])))
76
+ .join(' ')
77
+ .trimEnd();
78
+ return [fmt(head), ...cells.map(fmt)].join('\n') + '\n';
79
+ }
80
+ /** `way providers …`. Returns the exit code. */
81
+ export async function runProvidersCommand(root, argv, io) {
82
+ const env = io.env ?? process.env;
83
+ const home = io.home ?? homedir();
84
+ let json = false;
85
+ const modules = [];
86
+ for (let i = 0; i < argv.length; i++) {
87
+ const arg = argv[i];
88
+ if (arg === '-h' || arg === '--help') {
89
+ io.stdout(usage());
90
+ return EXIT.ok;
91
+ }
92
+ else if (arg === '--json')
93
+ json = true;
94
+ else if (arg === '--config' || arg.startsWith('--config=')) {
95
+ const value = arg === '--config' ? argv[++i] : arg.slice('--config='.length);
96
+ if (value === undefined || value === '') {
97
+ io.stderr(`${APP}: --config needs a module path\n\n${usage()}`);
98
+ return EXIT.usage;
99
+ }
100
+ modules.push(value);
101
+ }
102
+ else {
103
+ io.stderr(`${APP}: unknown option: ${arg}\n\n${usage()}`);
104
+ return EXIT.usage;
105
+ }
106
+ }
107
+ let cfg;
108
+ try {
109
+ cfg = await loadConfig(root, env, home);
110
+ }
111
+ catch (err) {
112
+ if (err instanceof ConfigError) {
113
+ io.stderr(`${APP}: ${err.message}\n`);
114
+ return EXIT.error;
115
+ }
116
+ throw err;
117
+ }
118
+ for (const warning of cfg.warnings)
119
+ io.stderr(`warning: ${warning}\n`);
120
+ // The same gate `way` applies: project modules need trust and execution allowed.
121
+ const gate = await policyExecGate(appTrustStore({ env, home }), trustPolicyFromConfig(cfg.effective), { root, configured: io.configuredAllowExec(cfg) }, trustPolicyOptions(home));
122
+ const built = await io.load(cfg, modules, gate.trusted && gate.allowExec);
123
+ if ('error' in built) {
124
+ io.stderr(`${APP}: ${built.error}\n`);
125
+ return EXIT.error;
126
+ }
127
+ for (const warning of built.warnings)
128
+ io.stderr(`warning: ${warning}\n`);
129
+ const rows = providerRows(built.project.tools, built.tools, env);
130
+ io.stdout(json ? `${JSON.stringify(rows, null, 2)}\n` : table(rows));
131
+ return EXIT.ok;
132
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The web view — the same catalog as a page you can search in a browser.
3
+ *
4
+ * A SERVER rather than a generated file, because a file would be a snapshot:
5
+ * add a task and the page is wrong with no signal that it is. Every
6
+ * `/api/catalog` request re-probes, and the page re-fetches on focus and on a
7
+ * slow poll, so what is on screen is what the repository currently has.
8
+ *
9
+ * Loopback is not by itself a boundary, so every route is behind a token.
10
+ *
11
+ * Other local users on this machine can reach 127.0.0.1, and can read a
12
+ * process's argv and environment for as long as it runs. So the session token
13
+ * never appears in a URL or an argv. What does appear in a URL is the boot
14
+ * token, which is single-use and expires in a minute; burning it on first use
15
+ * bounds the window to the moment between opening the browser and the page
16
+ * loading.
17
+ *
18
+ * Any website the user visits can also issue cross-origin requests to
19
+ * 127.0.0.1. A cookie would ride along on those — that is CSRF — while a
20
+ * request header does not, and the token header is a non-simple header, so a
21
+ * cross-origin fetch must first pass a CORS preflight this server never
22
+ * answers. Hence header auth, and hence the boot token is accepted on the page
23
+ * routes only, never on the API.
24
+ *
25
+ * `/api/run` hands this server's own terminal to a task and exits. It takes a
26
+ * task id and nothing else — see the note on the route.
27
+ *
28
+ * `/api/trust` POST permits this repository's code to run from now on, so it is
29
+ * gated a third time, beyond the method and the token: the grant must be
30
+ * APPLICABLE — the same condition that decides whether the page may offer the
31
+ * button at all. Without it a grant would override `--no-exec` or write the
32
+ * store under `--exec`. DELETE revokes and carries no such gate.
33
+ */
34
+ import { type Catalog, type Project, type RunnerCacheState } from '@osdlc/system-model/detect';
35
+ import { type WayOptions } from './catalog.ts';
36
+ import { type FetchServer } from './http.ts';
37
+ export interface ServeOptions {
38
+ /** The registered tools, built-ins plus any loaded. */
39
+ project: Project;
40
+ /**
41
+ * The project file names tools that were not loaded because the repository is untrusted or execution is off.
42
+ * A grant from the page does not load them; the response says so.
43
+ */
44
+ projectToolsPending?: boolean | undefined;
45
+ root: string;
46
+ collectOptions: WayOptions;
47
+ port?: number | undefined;
48
+ open?: boolean | undefined;
49
+ /** `runners.order` from config; applied to every collected catalog. */
50
+ runnerOrder?: string[] | undefined;
51
+ /**
52
+ * Which `collectOptions` keys came from a command-line flag rather than the
53
+ * config file. Saving a setting re-derives the config's slice of the collect
54
+ * options in the running process; a key named here is left alone, because a
55
+ * flag is the user's most recent explicit instruction about it and a write
56
+ * to some other setting must not revoke it.
57
+ *
58
+ * Only the keys `collectOptionsFromConfig` produces are meaningful:
59
+ * `exclude`, `discovery`, `excludePaths`.
60
+ */
61
+ pinnedByFlag?: readonly string[] | undefined;
62
+ /**
63
+ * The trust store's environment and home, threaded from the CLI. Injectable
64
+ * for the reason every sibling in this lane is: a test that let them default
65
+ * would grant trust in the developer's own `~/.local/state/wayfinder/`. Nothing but
66
+ * a test ever passes them.
67
+ */
68
+ env?: Record<string, string | undefined> | undefined;
69
+ home?: string | undefined;
70
+ }
71
+ /** What the page is served: a catalog, and where each runner's rows came from. */
72
+ export interface CatalogSnapshot {
73
+ catalog: Catalog;
74
+ /** One entry per selected runner. All "fresh" after a real probe. */
75
+ cache: RunnerCacheState[];
76
+ }
77
+ /**
78
+ * Bind the port and return the server's handle, without printing or opening anything.
79
+ *
80
+ * Split out of {@link serve} because `serve` never returns — it is the process's
81
+ * last statement — and a function that never returns cannot be tested. The
82
+ * mutating endpoint is the one part of this file that must not regress silently,
83
+ * so it needs a caller that can bind an ephemeral port, drive real requests and
84
+ * stop again.
85
+ *
86
+ * The catalog source comes back with the handle because it is the server's, not
87
+ * a second one: the startup banner must report the probe the page will see.
88
+ */
89
+ export declare function startServer(options: ServeOptions): Promise<{
90
+ server: FetchServer;
91
+ catalog: (force: boolean) => Promise<CatalogSnapshot>;
92
+ /** The one-shot token that signs a browser in; spent on first use. */
93
+ bootToken: string;
94
+ /** Starts the boot token's expiry window — call when the URL is handed over. */
95
+ armBoot: () => void;
96
+ }>;
97
+ export declare function serve(options: ServeOptions): Promise<number>;