@procedures/mark 0.0.0-stage → 0.2.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 (91) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +21 -0
  3. package/README.md +799 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/args.d.ts +77 -0
  6. package/dist/args.d.ts.map +1 -0
  7. package/dist/args.js +351 -0
  8. package/dist/args.js.map +1 -0
  9. package/dist/ask.d.ts +48 -0
  10. package/dist/ask.d.ts.map +1 -0
  11. package/dist/ask.js +91 -0
  12. package/dist/ask.js.map +1 -0
  13. package/dist/bin.d.ts +9 -0
  14. package/dist/bin.d.ts.map +1 -0
  15. package/dist/bin.js +10 -0
  16. package/dist/bin.js.map +1 -0
  17. package/dist/cli.d.ts +61 -0
  18. package/dist/cli.d.ts.map +1 -0
  19. package/dist/cli.js +535 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/client-mode.d.ts +21 -0
  22. package/dist/client-mode.d.ts.map +1 -0
  23. package/dist/client-mode.js +75 -0
  24. package/dist/client-mode.js.map +1 -0
  25. package/dist/ecosystem.d.ts +67 -0
  26. package/dist/ecosystem.d.ts.map +1 -0
  27. package/dist/ecosystem.js +212 -0
  28. package/dist/ecosystem.js.map +1 -0
  29. package/dist/failure.d.ts +16 -0
  30. package/dist/failure.d.ts.map +1 -0
  31. package/dist/failure.js +47 -0
  32. package/dist/failure.js.map +1 -0
  33. package/dist/format.d.ts +30 -0
  34. package/dist/format.d.ts.map +1 -0
  35. package/dist/format.js +125 -0
  36. package/dist/format.js.map +1 -0
  37. package/dist/index.d.ts +13 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +13 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/lockfile.d.ts +26 -0
  42. package/dist/lockfile.d.ts.map +1 -0
  43. package/dist/lockfile.js +68 -0
  44. package/dist/lockfile.js.map +1 -0
  45. package/dist/manifest-build.d.ts +7 -0
  46. package/dist/manifest-build.d.ts.map +1 -0
  47. package/dist/manifest-build.js +11 -0
  48. package/dist/manifest-build.js.map +1 -0
  49. package/dist/manifest.d.ts +57 -0
  50. package/dist/manifest.d.ts.map +1 -0
  51. package/dist/manifest.js +140 -0
  52. package/dist/manifest.js.map +1 -0
  53. package/dist/manifest.json +20960 -0
  54. package/dist/parse.d.ts +143 -0
  55. package/dist/parse.d.ts.map +1 -0
  56. package/dist/parse.js +509 -0
  57. package/dist/parse.js.map +1 -0
  58. package/dist/print.d.ts +42 -0
  59. package/dist/print.d.ts.map +1 -0
  60. package/dist/print.js +80 -0
  61. package/dist/print.js.map +1 -0
  62. package/dist/prompts.d.ts +58 -0
  63. package/dist/prompts.d.ts.map +1 -0
  64. package/dist/prompts.js +124 -0
  65. package/dist/prompts.js.map +1 -0
  66. package/dist/repl.d.ts +34 -0
  67. package/dist/repl.d.ts.map +1 -0
  68. package/dist/repl.js +101 -0
  69. package/dist/repl.js.map +1 -0
  70. package/dist/server-mode.d.ts +37 -0
  71. package/dist/server-mode.d.ts.map +1 -0
  72. package/dist/server-mode.js +167 -0
  73. package/dist/server-mode.js.map +1 -0
  74. package/package.json +97 -3
  75. package/src/args.ts +440 -0
  76. package/src/ask.ts +119 -0
  77. package/src/bin.ts +11 -0
  78. package/src/cli.ts +600 -0
  79. package/src/client-mode.ts +90 -0
  80. package/src/ecosystem.ts +260 -0
  81. package/src/failure.ts +47 -0
  82. package/src/format.ts +177 -0
  83. package/src/index.ts +31 -0
  84. package/src/lockfile.ts +85 -0
  85. package/src/manifest-build.ts +12 -0
  86. package/src/manifest.ts +162 -0
  87. package/src/parse.ts +670 -0
  88. package/src/print.ts +108 -0
  89. package/src/prompts.ts +181 -0
  90. package/src/repl.ts +121 -0
  91. package/src/server-mode.ts +205 -0
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Workspace-based Procedure Discovery
3
+ *
4
+ * Dynamically discovers and loads procedures from the packages of the
5
+ * monorepo this CLI lives in. This enables the CLI to automatically find
6
+ * all available procedures without hardcoding imports.
7
+ *
8
+ * Discovery flow:
9
+ * 1. Walk up from this module to the folder that holds pnpm-workspace.yaml
10
+ * 2. For each packages/* folder, read its package.json
11
+ * 3. If it has client.procedures, dynamically import it
12
+ * 4. The register.js entry of each package registers its procedures in PROCEDURE_REGISTRY
13
+ */
14
+
15
+ import * as fs from "node:fs";
16
+ import * as path from "node:path";
17
+ import { fileURLToPath, pathToFileURL } from "node:url";
18
+ import {
19
+ PROCEDURE_REGISTRY,
20
+ allCoreProcedures,
21
+ clientModule,
22
+ createRegistry,
23
+ defineModule,
24
+ pathToKey,
25
+ registerModules,
26
+ type AnyProcedure,
27
+ type ProcedureModule,
28
+ type ProcedureRegistry,
29
+ } from "@procedures/client";
30
+
31
+ // =============================================================================
32
+ // Types
33
+ // =============================================================================
34
+
35
+ interface PackageJson {
36
+ name: string;
37
+ client?: {
38
+ procedures?: string;
39
+ };
40
+ exports?: Record<string, unknown>;
41
+ }
42
+
43
+ interface DiscoveredPackage {
44
+ name: string;
45
+ path: string;
46
+ proceduresPath: string;
47
+ /** The file of the side-effect-free `./module` entry, when the package has one (roadmap 3.1) */
48
+ modulePath?: string | undefined;
49
+ }
50
+
51
+ /** The file of the `./module` export of a package, relative to the package folder. */
52
+ function moduleEntryOf(packageJson: PackageJson): string | undefined {
53
+ const entry = packageJson.exports?.["./module"];
54
+ if (typeof entry === "string") return entry;
55
+ if (entry && typeof entry === "object") {
56
+ const target = (entry as { import?: unknown; default?: unknown }).import ?? (entry as { default?: unknown }).default;
57
+ return typeof target === "string" ? target : undefined;
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ // =============================================================================
63
+ // Discovery
64
+ // =============================================================================
65
+
66
+ /**
67
+ * Read and parse JSON file
68
+ */
69
+ function readJson<T>(filePath: string): T | null {
70
+ try {
71
+ const content = fs.readFileSync(filePath, "utf-8");
72
+ return JSON.parse(content) as T;
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Find the workspace root: the nearest folder above this module that holds pnpm-workspace.yaml
80
+ */
81
+ export function findWorkspaceRoot(): string | null {
82
+ let dir = path.dirname(fileURLToPath(import.meta.url));
83
+ for (;;) {
84
+ if (fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) {
85
+ return dir;
86
+ }
87
+ const parent = path.dirname(dir);
88
+ if (parent === dir) {
89
+ return null;
90
+ }
91
+ dir = parent;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Discover workspace packages that declare client.procedures
97
+ */
98
+ export function discoverFromEcosystem(root: string | null = findWorkspaceRoot()): DiscoveredPackage[] {
99
+ const discovered: DiscoveredPackage[] = [];
100
+
101
+ if (!root) {
102
+ // Not running from inside the monorepo, nothing to discover
103
+ return discovered;
104
+ }
105
+
106
+ const packagesDir = path.join(root, "packages");
107
+ const entries = fs.readdirSync(packagesDir, { withFileTypes: true });
108
+ for (const entry of entries) {
109
+ if (!entry.isDirectory()) {
110
+ continue;
111
+ }
112
+ const packageDir = path.join(packagesDir, entry.name);
113
+ const packageJson = readJson<PackageJson>(path.join(packageDir, "package.json"));
114
+
115
+ if (packageJson?.client?.procedures) {
116
+ discovered.push({
117
+ name: packageJson.name,
118
+ path: packageDir,
119
+ proceduresPath: packageJson.client.procedures,
120
+ modulePath: moduleEntryOf(packageJson),
121
+ });
122
+ }
123
+ }
124
+
125
+ return discovered;
126
+ }
127
+
128
+ /**
129
+ * This function registers all core procedures of `@procedures/client` in the global registry: the
130
+ * control flow and `procedure.*` of `clientModule`, and the math, string, array, object, comparison
131
+ * and type procedures (`client.add` and the others). An import registers none of them
132
+ * (ARCHITECTURE-PROPOSALS-2026-10, P9). (Docs review DOC-6: before, `mark client add` was an
133
+ * unknown command.) A procedure that is registered already stays.
134
+ */
135
+ export function registerCoreProcedures(): number {
136
+ let added = 0;
137
+ for (const procedure of [...clientModule.procedures, ...allCoreProcedures]) {
138
+ if (!PROCEDURE_REGISTRY.has(procedure.path)) {
139
+ PROCEDURE_REGISTRY.register(procedure);
140
+ added++;
141
+ }
142
+ }
143
+ return added;
144
+ }
145
+
146
+ /**
147
+ * Dynamically load procedures from discovered packages.
148
+ *
149
+ * A package that fails to load gives one warning line on stderr, also without `verbose`: before,
150
+ * its commands were missing with no message (deep dive CLI-18). A package that is not built yet
151
+ * (no procedures file) is reported only with `verbose`. `warn: false` turns the warnings off (the
152
+ * build of mark writes the manifest while other packages can still be in their build).
153
+ */
154
+ export async function loadEcosystemProcedures(verbose = false, warn = true): Promise<string[]> {
155
+ registerCoreProcedures();
156
+ const discovered = discoverFromEcosystem();
157
+ const loaded: string[] = [];
158
+
159
+ for (const pkg of discovered) {
160
+ // Build the full path to the procedures file
161
+ const proceduresFullPath = path.join(pkg.path, pkg.proceduresPath);
162
+
163
+ // Check if file exists
164
+ if (!fs.existsSync(proceduresFullPath)) {
165
+ if (verbose) {
166
+ console.warn(`Procedures file not found (build the package): ${proceduresFullPath}`);
167
+ }
168
+ continue;
169
+ }
170
+
171
+ try {
172
+ // Dynamic import - the module will self-register procedures. pathToFileURL escapes
173
+ // "#", "%" and spaces in the path (before, a string join broke such paths).
174
+ await import(pathToFileURL(proceduresFullPath).href);
175
+
176
+ loaded.push(pkg.name);
177
+
178
+ if (verbose) {
179
+ console.log(`Loaded procedures from: ${pkg.name}`);
180
+ }
181
+ } catch (error) {
182
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
183
+ if (warn) {
184
+ console.warn(`mark: the procedures of ${pkg.name} did not load: ${message}`);
185
+ }
186
+ if (verbose && error instanceof Error && error.stack) {
187
+ console.warn(error.stack);
188
+ }
189
+ }
190
+ }
191
+
192
+ return loaded;
193
+ }
194
+
195
+ /**
196
+ * Get list of ecosystem packages that have procedures
197
+ */
198
+ export function listEcosystemProcedurePackages(): Array<{ name: string; path: string }> {
199
+ return discoverFromEcosystem().map((pkg) => ({
200
+ name: pkg.name,
201
+ path: pkg.path,
202
+ }));
203
+ }
204
+
205
+ /** The core procedures that `mark` serves: all of them, also the ones that the core import does not register. */
206
+ const allCoreModule: ProcedureModule = defineModule("@procedures/client (all core procedures)", allCoreProcedures);
207
+
208
+ /** The registry of `mark` and the names of the packages that it holds. */
209
+ export interface EcosystemRegistry {
210
+ registry: ProcedureRegistry;
211
+ loaded: string[];
212
+ }
213
+
214
+ /**
215
+ * The module of a package: its `./module` entry (it registers nothing), or else the procedures
216
+ * that importing its procedures file adds to the global registry (a package of the old kind).
217
+ */
218
+ async function moduleOfPackage(pkg: DiscoveredPackage): Promise<ProcedureModule | undefined> {
219
+ if (pkg.modulePath) {
220
+ const file = path.join(pkg.path, pkg.modulePath);
221
+ if (fs.existsSync(file)) {
222
+ const exports = (await import(pathToFileURL(file).href)) as { default?: ProcedureModule };
223
+ if (exports.default && Array.isArray(exports.default.procedures)) return exports.default;
224
+ }
225
+ }
226
+ const proceduresFile = path.join(pkg.path, pkg.proceduresPath);
227
+ if (!fs.existsSync(proceduresFile)) return undefined;
228
+ const before = new Set(PROCEDURE_REGISTRY.getAll().map((procedure) => pathToKey(procedure.path)));
229
+ await import(pathToFileURL(proceduresFile).href);
230
+ const added: AnyProcedure[] = PROCEDURE_REGISTRY.getAll().filter((procedure) => !before.has(pathToKey(procedure.path)));
231
+ return { name: pkg.name, procedures: added };
232
+ }
233
+
234
+ /**
235
+ * The registry of `mark` (roadmap 3.1): a registry of its own, built from the module of each
236
+ * workspace package that declares `client.procedures`, with all the core procedures. The global
237
+ * registry does not change for a package with a module entry. A package that fails to load gives
238
+ * one warning line on stderr, as with `loadEcosystemProcedures()`.
239
+ */
240
+ export async function loadEcosystemRegistry(verbose = false, warn = true): Promise<EcosystemRegistry> {
241
+ const registry = createRegistry(allCoreModule);
242
+ const loaded: string[] = [];
243
+ for (const pkg of discoverFromEcosystem()) {
244
+ try {
245
+ const module = await moduleOfPackage(pkg);
246
+ if (!module) {
247
+ if (verbose) console.warn(`Procedures file not found (build the package): ${path.join(pkg.path, pkg.proceduresPath)}`);
248
+ continue;
249
+ }
250
+ registerModules(registry, [module]);
251
+ loaded.push(pkg.name);
252
+ if (verbose) console.log(`Loaded procedures from: ${pkg.name}`);
253
+ } catch (error) {
254
+ const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
255
+ if (warn) console.warn(`mark: the procedures of ${pkg.name} did not load: ${message}`);
256
+ if (verbose && error instanceof Error && error.stack) console.warn(error.stack);
257
+ }
258
+ }
259
+ return { registry, loaded };
260
+ }
package/src/failure.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Procedure-level failure
3
+ *
4
+ * A procedure reports a failure in one of three ways, and `mark` exits with code 1 for each:
5
+ *
6
+ * 1. It throws an error. This is the usual way.
7
+ * 2. It returns an object with `success: false`. Use this when the result has more to show,
8
+ * for example the list of problems of `lib audit`.
9
+ * 3. It returns an object with a numeric `exitCode` that is not 0. Use this for a procedure that
10
+ * runs an external command (`vitest run`, `shell run`), so the caller sees the command's result.
11
+ *
12
+ * For a streaming procedure, each item is examined: one failed item makes the command fail.
13
+ */
14
+
15
+ /** A short description of the failure that a result reports, or undefined when it reports none */
16
+ export function failureOf(result: unknown): string | undefined {
17
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
18
+ return undefined;
19
+ }
20
+ const record = result as Record<string, unknown>;
21
+ const exitCode = record["exitCode"];
22
+ if (typeof exitCode === "number" && exitCode !== 0) {
23
+ return `exit code ${exitCode}`;
24
+ }
25
+ if (record["success"] === false) {
26
+ return firstText(record["error"]) ?? firstText(record["errors"]) ?? firstText(record["message"]) ?? "success: false";
27
+ }
28
+ return undefined;
29
+ }
30
+
31
+ /** The first text of a value: a string, the message of an error object, or the first of a list */
32
+ function firstText(value: unknown): string | undefined {
33
+ if (typeof value === "string" && value.length > 0) {
34
+ return value;
35
+ }
36
+ if (Array.isArray(value)) {
37
+ for (const item of value) {
38
+ const text = firstText(item);
39
+ if (text) return text;
40
+ }
41
+ return undefined;
42
+ }
43
+ if (value && typeof value === "object" && typeof (value as { message?: unknown }).message === "string") {
44
+ return (value as { message: string }).message;
45
+ }
46
+ return undefined;
47
+ }
package/src/format.ts ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Output Formatting
3
+ *
4
+ * Formats procedure results for CLI output based on metadata hints.
5
+ */
6
+
7
+ export type OutputFormat = "text" | "json" | "table" | "streaming";
8
+
9
+ /**
10
+ * Print interface (used by formatOutput)
11
+ */
12
+ export interface Print {
13
+ info: (message: string) => void;
14
+ error: (message: string) => void;
15
+ success: (message: string) => void;
16
+ warning: (message: string) => void;
17
+ table: (data: string[][], options?: { format?: string }) => void;
18
+ spin: (message: string) => Spinner;
19
+ }
20
+
21
+ export interface Spinner {
22
+ stop: () => void;
23
+ succeed: (message?: string) => void;
24
+ fail: (message?: string) => void;
25
+ text: string;
26
+ }
27
+
28
+ /**
29
+ * Format and print the result based on output format hint
30
+ */
31
+ export function formatOutput(
32
+ print: Print,
33
+ result: unknown,
34
+ format: OutputFormat = "text"
35
+ ): void {
36
+ if (result === undefined || result === null) {
37
+ return;
38
+ }
39
+
40
+ switch (format) {
41
+ case "json":
42
+ print.info(JSON.stringify(result, null, 2));
43
+ break;
44
+
45
+ case "table":
46
+ formatTable(print, result);
47
+ break;
48
+
49
+ case "text":
50
+ case "streaming":
51
+ default:
52
+ formatText(print, result);
53
+ break;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Format as text - handles common result shapes
59
+ */
60
+ function formatText(print: Print, result: unknown): void {
61
+ // String output
62
+ if (typeof result === "string") {
63
+ print.info(result);
64
+ return;
65
+ }
66
+
67
+ // Result with output field (common pattern)
68
+ if (isObjectWithOutput(result)) {
69
+ print.info(result.output);
70
+ return;
71
+ }
72
+
73
+ // Result with message field
74
+ if (isObjectWithMessage(result)) {
75
+ if (result.success === false) {
76
+ print.error(result.message);
77
+ } else {
78
+ print.success(result.message);
79
+ }
80
+ return;
81
+ }
82
+
83
+ // Result with error field
84
+ if (isObjectWithError(result)) {
85
+ print.error(result.error);
86
+ return;
87
+ }
88
+
89
+ // Array of items
90
+ if (Array.isArray(result)) {
91
+ for (const item of result) {
92
+ formatText(print, item);
93
+ }
94
+ return;
95
+ }
96
+
97
+ // Fallback to JSON
98
+ print.info(JSON.stringify(result, null, 2));
99
+ }
100
+
101
+ /**
102
+ * Format as table - handles arrays of objects
103
+ */
104
+ function formatTable(print: Print, result: unknown): void {
105
+ // Result with rows/headers
106
+ if (isTableResult(result)) {
107
+ const headers = result.headers ?? Object.keys(result.rows[0] ?? {});
108
+ const data: string[][] = [headers];
109
+
110
+ for (const row of result.rows) {
111
+ if (Array.isArray(row)) {
112
+ data.push(row.map(String));
113
+ } else if (typeof row === "object" && row !== null) {
114
+ data.push(headers.map((h) => String((row as Record<string, unknown>)[h] ?? "")));
115
+ }
116
+ }
117
+
118
+ print.table(data);
119
+ return;
120
+ }
121
+
122
+ // Plain array of objects
123
+ if (Array.isArray(result) && result.length > 0 && typeof result[0] === "object") {
124
+ const headers = Object.keys(result[0] as object);
125
+ const data: string[][] = [headers];
126
+
127
+ for (const row of result) {
128
+ if (typeof row === "object" && row !== null) {
129
+ data.push(headers.map((h) => String((row as Record<string, unknown>)[h] ?? "")));
130
+ }
131
+ }
132
+
133
+ print.table(data);
134
+ return;
135
+ }
136
+
137
+ // Fallback to text
138
+ formatText(print, result);
139
+ }
140
+
141
+ // Type guards
142
+
143
+ function isObjectWithOutput(val: unknown): val is { output: string } {
144
+ return (
145
+ typeof val === "object" &&
146
+ val !== null &&
147
+ "output" in val &&
148
+ typeof (val as { output: unknown }).output === "string"
149
+ );
150
+ }
151
+
152
+ function isObjectWithMessage(val: unknown): val is { message: string; success?: boolean } {
153
+ return (
154
+ typeof val === "object" &&
155
+ val !== null &&
156
+ "message" in val &&
157
+ typeof (val as { message: unknown }).message === "string"
158
+ );
159
+ }
160
+
161
+ function isObjectWithError(val: unknown): val is { error: string } {
162
+ return (
163
+ typeof val === "object" &&
164
+ val !== null &&
165
+ "error" in val &&
166
+ typeof (val as { error: unknown }).error === "string"
167
+ );
168
+ }
169
+
170
+ function isTableResult(val: unknown): val is { rows: unknown[]; headers?: string[] } {
171
+ return (
172
+ typeof val === "object" &&
173
+ val !== null &&
174
+ "rows" in val &&
175
+ Array.isArray((val as { rows: unknown }).rows)
176
+ );
177
+ }
package/src/index.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Mark CLI
3
+ *
4
+ * A generic CLI that reflects registered procedures from client packages.
5
+ * Importing this module runs nothing: the `mark` bin (`dist/bin.js`) runs the CLI.
6
+ */
7
+
8
+ export { run, main, executeArgs, initCli, type CliContext } from "./cli.js";
9
+ export { parseCommandLine, parseLeadingGlobals, type ParsedCommandLine, type Globals } from "./args.js";
10
+ export { failureOf } from "./failure.js";
11
+ export {
12
+ parseFromSchema,
13
+ generateHelp,
14
+ extractSchemaFields,
15
+ convertValue,
16
+ type CLIMeta,
17
+ type FieldType,
18
+ type SchemaFieldInfo,
19
+ } from "./parse.js";
20
+ export { formatOutput, type OutputFormat } from "./format.js";
21
+ export {
22
+ readLockfile,
23
+ writeLockfile,
24
+ removeLockfile,
25
+ isServerAlive,
26
+ getLockfilePath,
27
+ getLockfileDir,
28
+ getLogPath,
29
+ rotateLogFile,
30
+ type LockfileData,
31
+ } from "./lockfile.js";
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Lockfiles of the CLI server: `mark` uses the shared module of `client-server`, so `mark` and the
3
+ * `server.*` procedures read and write the same files the same way (deep dive CLI-4). This module
4
+ * adds what only `mark` needs: the log file and the build id.
5
+ */
6
+
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import {
11
+ checkServer,
12
+ findServer,
13
+ getMarkDir,
14
+ getServersDir,
15
+ readAllLockfiles,
16
+ readLockfileForPort,
17
+ removeLockfileForPort,
18
+ writeLockfile as writeSharedLockfile,
19
+ type LockfileData,
20
+ } from "@procedures/peer/lockfile";
21
+
22
+ export type { LockfileData };
23
+ export { checkServer, findServer, readAllLockfiles, readLockfileForPort, removeLockfileForPort };
24
+
25
+ const LOG_PATH = path.join(getMarkDir(), "server.log");
26
+ const LOG_PREV_PATH = path.join(getMarkDir(), "server.log.1");
27
+
28
+ /**
29
+ * The build of this `mark`: its file and the time of its last build. A warm server runs only the
30
+ * commands of the same build (deep dive CLI-14): after `pnpm build`, or from another checkout,
31
+ * the CLI runs the command itself.
32
+ */
33
+ export function currentBuild(): string {
34
+ const file = fileURLToPath(import.meta.url);
35
+ try {
36
+ return `${file}@${fs.statSync(file).mtimeMs}`;
37
+ } catch {
38
+ return file;
39
+ }
40
+ }
41
+
42
+ export async function writeLockfile(data: LockfileData): Promise<void> {
43
+ writeSharedLockfile(data);
44
+ }
45
+
46
+ /** The first lockfile whose server answers as its peer (any folder, any build). */
47
+ export async function readLockfile(): Promise<LockfileData | null> {
48
+ for (const data of readAllLockfiles()) {
49
+ if (await isServerAlive(data)) return data;
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** True when the lockfile's server answers as its peer. A dead server's lockfile is removed. */
55
+ export async function isServerAlive(lockfile: LockfileData): Promise<boolean> {
56
+ const state = await checkServer(lockfile);
57
+ if (state === "dead") removeLockfileForPort(lockfile.port);
58
+ return state === "alive";
59
+ }
60
+
61
+ /** This function removes the lockfile of the default port (3000). */
62
+ export async function removeLockfile(): Promise<void> {
63
+ removeLockfileForPort(3000);
64
+ }
65
+
66
+ export function getLockfileDir(): string {
67
+ return getMarkDir();
68
+ }
69
+
70
+ export function getLockfilePath(): string {
71
+ return getServersDir();
72
+ }
73
+
74
+ export function getLogPath(): string {
75
+ return LOG_PATH;
76
+ }
77
+
78
+ export async function rotateLogFile(): Promise<void> {
79
+ try {
80
+ fs.mkdirSync(getMarkDir(), { recursive: true });
81
+ if (fs.existsSync(LOG_PATH)) fs.renameSync(LOG_PATH, LOG_PREV_PATH);
82
+ } catch {
83
+ // Ignore rotation errors
84
+ }
85
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The build of mark runs this module after `tsc -b`: it builds the registry of the workspace
3
+ * (the module of each package, roadmap 3.1) and writes `dist/manifest.json` (see manifest.ts).
4
+ * mark depends on each package that has procedures, so they are built before it.
5
+ */
6
+
7
+ import { loadEcosystemRegistry } from "./ecosystem.js";
8
+ import { manifestPath, writeManifest } from "./manifest.js";
9
+
10
+ const { registry, loaded } = await loadEcosystemRegistry(false, false);
11
+ const manifest = await writeManifest(registry.getAll());
12
+ console.log(`mark: ${manifestPath()} has ${manifest.commands.length} commands from ${loaded.length} packages`);