allgreen 0.0.0-stage → 0.1.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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/demo/allgreen/.gitignore +1 -0
  4. package/demo/allgreen/plans/add-to-cart.json +18 -0
  5. package/demo/allgreen/plans/checkout.json +14 -0
  6. package/demo/allgreen/plans/login.json +10 -0
  7. package/demo/allgreen/project.json +8 -0
  8. package/demo/allgreen/secrets.example.json +1 -0
  9. package/demo/site/checkout.html +14 -0
  10. package/demo/site/index.html +11 -0
  11. package/demo/site/login.html +25 -0
  12. package/demo/site/playground.html +194 -0
  13. package/demo/site/shop.html +35 -0
  14. package/demo/site/thanks.html +11 -0
  15. package/dist/cli/format.d.ts +10 -0
  16. package/dist/cli/format.js +142 -0
  17. package/dist/cli/main.d.ts +2 -0
  18. package/dist/cli/main.js +241 -0
  19. package/dist/cli/open-browser.d.ts +2 -0
  20. package/dist/cli/open-browser.js +23 -0
  21. package/dist/core/app-projects.d.ts +45 -0
  22. package/dist/core/app-projects.js +157 -0
  23. package/dist/core/atomic.d.ts +3 -0
  24. package/dist/core/atomic.js +31 -0
  25. package/dist/core/browsers.d.ts +42 -0
  26. package/dist/core/browsers.js +116 -0
  27. package/dist/core/compile.d.ts +22 -0
  28. package/dist/core/compile.js +360 -0
  29. package/dist/core/config.d.ts +31 -0
  30. package/dist/core/config.js +117 -0
  31. package/dist/core/constants.d.ts +8 -0
  32. package/dist/core/constants.js +8 -0
  33. package/dist/core/describe.d.ts +27 -0
  34. package/dist/core/describe.js +118 -0
  35. package/dist/core/devices.d.ts +14 -0
  36. package/dist/core/devices.js +22 -0
  37. package/dist/core/export.d.ts +21 -0
  38. package/dist/core/export.js +151 -0
  39. package/dist/core/failure-texts/de.d.ts +4 -0
  40. package/dist/core/failure-texts/de.js +83 -0
  41. package/dist/core/failure-texts/en.d.ts +4 -0
  42. package/dist/core/failure-texts/en.js +81 -0
  43. package/dist/core/failure-texts/es.d.ts +4 -0
  44. package/dist/core/failure-texts/es.js +80 -0
  45. package/dist/core/failure-texts/fr.d.ts +4 -0
  46. package/dist/core/failure-texts/fr.js +87 -0
  47. package/dist/core/failure-texts/it.d.ts +4 -0
  48. package/dist/core/failure-texts/it.js +82 -0
  49. package/dist/core/failures.d.ts +29 -0
  50. package/dist/core/failures.js +82 -0
  51. package/dist/core/file-keyring.d.ts +6 -0
  52. package/dist/core/file-keyring.js +46 -0
  53. package/dist/core/files.d.ts +16 -0
  54. package/dist/core/files.js +55 -0
  55. package/dist/core/locales.d.ts +8 -0
  56. package/dist/core/locales.js +16 -0
  57. package/dist/core/looks.d.ts +23 -0
  58. package/dist/core/looks.js +70 -0
  59. package/dist/core/mcpb.d.ts +11 -0
  60. package/dist/core/mcpb.js +19 -0
  61. package/dist/core/phrases/common.d.ts +9 -0
  62. package/dist/core/phrases/common.js +5 -0
  63. package/dist/core/phrases/de.d.ts +5 -0
  64. package/dist/core/phrases/de.js +241 -0
  65. package/dist/core/phrases/en.d.ts +5 -0
  66. package/dist/core/phrases/en.js +175 -0
  67. package/dist/core/phrases/es.d.ts +5 -0
  68. package/dist/core/phrases/es.js +208 -0
  69. package/dist/core/phrases/fr.d.ts +5 -0
  70. package/dist/core/phrases/fr.js +207 -0
  71. package/dist/core/phrases/it.d.ts +5 -0
  72. package/dist/core/phrases/it.js +236 -0
  73. package/dist/core/phrases.d.ts +7 -0
  74. package/dist/core/phrases.js +10 -0
  75. package/dist/core/picked.d.ts +6 -0
  76. package/dist/core/picked.js +95 -0
  77. package/dist/core/png.d.ts +5 -0
  78. package/dist/core/png.js +19 -0
  79. package/dist/core/project-files.d.ts +59 -0
  80. package/dist/core/project-files.js +190 -0
  81. package/dist/core/project-write.d.ts +66 -0
  82. package/dist/core/project-write.js +211 -0
  83. package/dist/core/recorded.d.ts +46 -0
  84. package/dist/core/recorded.js +160 -0
  85. package/dist/core/recorder-api.d.ts +7 -0
  86. package/dist/core/recorder-api.js +14 -0
  87. package/dist/core/recorder.d.ts +65 -0
  88. package/dist/core/recorder.js +326 -0
  89. package/dist/core/refs.d.ts +7 -0
  90. package/dist/core/refs.js +25 -0
  91. package/dist/core/results.d.ts +69 -0
  92. package/dist/core/results.js +217 -0
  93. package/dist/core/run-registry.d.ts +63 -0
  94. package/dist/core/run-registry.js +99 -0
  95. package/dist/core/run.d.ts +75 -0
  96. package/dist/core/run.js +229 -0
  97. package/dist/core/runs-history.d.ts +19 -0
  98. package/dist/core/runs-history.js +63 -0
  99. package/dist/core/schema.d.ts +494 -0
  100. package/dist/core/schema.js +401 -0
  101. package/dist/core/secrets.d.ts +21 -0
  102. package/dist/core/secrets.js +52 -0
  103. package/dist/core/step-gate.d.ts +29 -0
  104. package/dist/core/step-gate.js +62 -0
  105. package/dist/core/store.d.ts +56 -0
  106. package/dist/core/store.js +168 -0
  107. package/dist/core/synced.d.ts +13 -0
  108. package/dist/core/synced.js +49 -0
  109. package/dist/core/system-keyring.d.ts +18 -0
  110. package/dist/core/system-keyring.js +83 -0
  111. package/dist/core/zip.d.ts +5 -0
  112. package/dist/core/zip.js +43 -0
  113. package/dist/mcp/app-relay.d.ts +11 -0
  114. package/dist/mcp/app-relay.js +77 -0
  115. package/dist/mcp/connection.d.ts +11 -0
  116. package/dist/mcp/connection.js +44 -0
  117. package/dist/mcp/protocol.d.ts +46 -0
  118. package/dist/mcp/protocol.js +108 -0
  119. package/dist/mcp/server.d.ts +11 -0
  120. package/dist/mcp/server.js +50 -0
  121. package/dist/mcp/tools/app-tools.d.ts +32 -0
  122. package/dist/mcp/tools/app-tools.js +173 -0
  123. package/dist/mcp/tools/context.d.ts +61 -0
  124. package/dist/mcp/tools/context.js +102 -0
  125. package/dist/mcp/tools/get-image.d.ts +3 -0
  126. package/dist/mcp/tools/get-image.js +27 -0
  127. package/dist/mcp/tools/get-run.d.ts +3 -0
  128. package/dist/mcp/tools/get-run.js +71 -0
  129. package/dist/mcp/tools/index.d.ts +13 -0
  130. package/dist/mcp/tools/index.js +25 -0
  131. package/dist/mcp/tools/list-plans.d.ts +3 -0
  132. package/dist/mcp/tools/list-plans.js +30 -0
  133. package/dist/mcp/tools/list-projects.d.ts +3 -0
  134. package/dist/mcp/tools/list-projects.js +26 -0
  135. package/dist/mcp/tools/list-runs.d.ts +3 -0
  136. package/dist/mcp/tools/list-runs.js +9 -0
  137. package/dist/mcp/tools/read-plan.d.ts +3 -0
  138. package/dist/mcp/tools/read-plan.js +22 -0
  139. package/dist/mcp/tools/run-plans.d.ts +3 -0
  140. package/dist/mcp/tools/run-plans.js +12 -0
  141. package/dist/mcp/tools/save-plan.d.ts +3 -0
  142. package/dist/mcp/tools/save-plan.js +41 -0
  143. package/dist/server/app-events.d.ts +28 -0
  144. package/dist/server/app-events.js +59 -0
  145. package/dist/server/app-mcp.d.ts +11 -0
  146. package/dist/server/app-mcp.js +48 -0
  147. package/dist/server/demo-site.d.ts +12 -0
  148. package/dist/server/demo-site.js +34 -0
  149. package/dist/server/reveal.d.ts +4 -0
  150. package/dist/server/reveal.js +26 -0
  151. package/dist/server/routes.d.ts +100 -0
  152. package/dist/server/routes.js +785 -0
  153. package/dist/server/security.d.ts +15 -0
  154. package/dist/server/security.js +39 -0
  155. package/dist/server/server.d.ts +51 -0
  156. package/dist/server/server.js +141 -0
  157. package/dist/server/static.d.ts +10 -0
  158. package/dist/server/static.js +97 -0
  159. package/dist/ui/assets/Toast-D2Sy5v16.js +8 -0
  160. package/dist/ui/assets/index-BYDSHfWD.js +81 -0
  161. package/dist/ui/assets/index-CHbD-LyG.css +2 -0
  162. package/dist/ui/index.html +14 -0
  163. package/package.json +77 -3
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { basename, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
8
+ import { exportProject } from '../core/export.js';
9
+ import { fileKeyring } from '../core/file-keyring.js';
10
+ import { systemKeyring } from '../core/system-keyring.js';
11
+ import { LOCALES } from '../core/locales.js';
12
+ import { initProject, loadProject } from '../core/project-files.js';
13
+ import { playwrightPaths, runProject } from '../core/run.js';
14
+ import { fileStore } from '../core/store.js';
15
+ import { startAppMcp } from '../mcp/app-relay.js';
16
+ import { removeConnection, writeConnection } from '../mcp/connection.js';
17
+ import { startMcp } from '../mcp/server.js';
18
+ import { serveDemoSite } from '../server/demo-site.js';
19
+ import { startServer } from '../server/server.js';
20
+ import { describeError, formatRun } from './format.js';
21
+ import { openBrowser } from './open-browser.js';
22
+ const lang = () => new Option('--lang <locale>', 'language of step phrases and failure messages')
23
+ .choices([...LOCALES])
24
+ .default('en');
25
+ const { version } = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8'));
26
+ const program = new Command('allgreen')
27
+ .description('No-code browser test plans, run with Playwright.')
28
+ .version(version);
29
+ const dir = process.cwd();
30
+ // Commander would exit 1 on usage errors; throw instead so the catch below maps them to 2.
31
+ program.exitOverride().configureOutput({ writeErr: (t) => process.stderr.write(t) });
32
+ program
33
+ .command('init')
34
+ .description('create allgreen/ with an example plan')
35
+ .option('--name <name>', 'project name', basename(dir))
36
+ .option('--url <url>', 'base URL of the site to test', 'http://localhost:3000')
37
+ .action(async (o) => {
38
+ await initProject(dir, { name: o.name, baseUrl: o.url });
39
+ console.log('Created allgreen/. Edit allgreen/plans/example.json, then run: allgreen run');
40
+ });
41
+ program
42
+ .command('run [plans...]')
43
+ .description('run the plans (all, or the named ones) and print a summary; exit 1 if any failed')
44
+ .addOption(lang())
45
+ .action(async (names, o) => {
46
+ const result = await runProject(fileStore(dir), {
47
+ plans: names.length ? names : undefined,
48
+ locale: o.lang,
49
+ });
50
+ const { plans } = await loadProject(dir);
51
+ console.log(formatRun(result, plans, o.lang, Boolean(process.stdout.isTTY && !process.env.NO_COLOR)));
52
+ process.exitCode = result.summary.ok ? 0 : 1;
53
+ });
54
+ program
55
+ .command('export <outDir> [plans...]')
56
+ .description('write the plans as standard Playwright tests')
57
+ .addOption(lang())
58
+ .action(async (outDir, names, o) => {
59
+ const files = await exportProject(dir, outDir, {
60
+ plans: names.length ? names : undefined,
61
+ locale: o.lang,
62
+ });
63
+ console.log(`Exported ${files.length} files to ${outDir}`);
64
+ });
65
+ program
66
+ .command('install-browsers')
67
+ .description('download chromium, firefox and webkit for Allgreen')
68
+ .action(() => new Promise((resolve, reject) => {
69
+ const child = spawn(process.execPath, [playwrightPaths().cli, 'install', 'chromium', 'firefox', 'webkit'], { stdio: 'inherit', windowsHide: true });
70
+ child.on('error', reject);
71
+ child.on('close', (code) => {
72
+ process.exitCode = code === 0 ? 0 : 2;
73
+ resolve();
74
+ });
75
+ }));
76
+ const port = () => new Option('--port <n>', 'port to listen on (another free one if taken)').argParser((v) => {
77
+ if (!/^\d+$/.test(v) || Number(v) > 65535)
78
+ throw new InvalidArgumentError('Not a port number.');
79
+ return Number(v);
80
+ });
81
+ const uiDir = fileURLToPath(new URL('../ui/', import.meta.url));
82
+ /**
83
+ * Closes `server` and exits on Ctrl-C, kill or a closed terminal (and, with `stdin`, when standard input ends: the
84
+ * desktop shell that owns it is gone); a second trigger does not interrupt the close.
85
+ */
86
+ function stopOnSignals(server, stdin = false) {
87
+ let stopping = false;
88
+ const stop = () => {
89
+ if (stopping)
90
+ return;
91
+ stopping = true;
92
+ void server.close().finally(() => process.exit(0));
93
+ };
94
+ // SIGHUP: the terminal closed; a run in its own process group would not get it otherwise
95
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'])
96
+ process.once(signal, stop);
97
+ if (stdin) {
98
+ // the desktop shell must keep stdin piped open: a closed stdin stops the app at once
99
+ process.stdin.on('end', stop).on('close', stop);
100
+ process.stdin.resume();
101
+ }
102
+ }
103
+ program
104
+ .command('ui', { isDefault: true })
105
+ .description('open the visual editor in the browser (the default command)')
106
+ .addOption(port())
107
+ .option('--no-open', 'do not open the browser')
108
+ .action(async (o) => {
109
+ const server = await startServer({ dir, port: o.port, uiDir });
110
+ console.log(`Allgreen is running at ${server.url}\nPress Ctrl-C to stop it.`);
111
+ if (o.open)
112
+ openBrowser(server.url);
113
+ stopOnSignals(server);
114
+ });
115
+ program
116
+ .command('app', { hidden: true })
117
+ .description('serve the editor for the desktop app, with its project list in --data-dir; prints {"url","token"} as one ' +
118
+ 'JSON line on stdout; opens no browser unless --open (the app opens its own window)')
119
+ .requiredOption('--data-dir <dir>', "folder for the app's project list, runs and sessions")
120
+ .addOption(port())
121
+ .option('--open', 'also open the browser')
122
+ .option('--no-open', 'do not open the browser (the default)')
123
+ .addOption(new Option('--dev-keyring', 'keep secrets in a plain file instead of the system keychain').hideHelp())
124
+ // stdout carries the one JSON line only: help and usage errors go to stderr
125
+ .configureOutput({
126
+ writeOut: (t) => process.stderr.write(t),
127
+ writeErr: (t) => process.stderr.write(t),
128
+ })
129
+ .action(async (o) => {
130
+ const dataDir = resolve(o.dataDir);
131
+ await mkdir(dataDir, { recursive: true });
132
+ let keyring;
133
+ if (o.devKeyring === true) {
134
+ console.error('Allgreen development keyring: secrets are stored in a file');
135
+ keyring = fileKeyring(dataDir);
136
+ }
137
+ else {
138
+ try {
139
+ keyring = await systemKeyring();
140
+ }
141
+ catch (e) {
142
+ const { name, code } = e instanceof Error ? e : { name: typeof e, code: undefined };
143
+ // the message is left out: a keychain's own could quote a value
144
+ console.error(code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'
145
+ ? 'The system keychain is only available in the desktop app; use --dev-keyring for development.'
146
+ : `Allgreen could not load the system keychain (${name}${code ? ` ${code}` : ''})`);
147
+ process.exit(2);
148
+ }
149
+ }
150
+ const server = await startServer({
151
+ // this very Node and script: the installed app's own, or the ones a debug build was given
152
+ app: {
153
+ dataDir,
154
+ keyring,
155
+ launch: { node: process.execPath, main: fileURLToPath(import.meta.url) },
156
+ },
157
+ port: o.port,
158
+ uiDir,
159
+ });
160
+ // for `allgreen mcp --app`; written before the app learns the address, removed when the server stops
161
+ // the AI's own token: the file opens the AI's route, not the whole app
162
+ await writeConnection(dataDir, { url: new URL(server.url).origin, token: server.aiToken });
163
+ process.stdout.write(`${JSON.stringify({ url: server.url, token: server.token })}\n`);
164
+ if (o.open === true)
165
+ openBrowser(server.url);
166
+ const close = server.close;
167
+ server.close = () => close().finally(() => removeConnection(dataDir));
168
+ stopOnSignals(server, true);
169
+ });
170
+ program
171
+ .command('mcp')
172
+ .description('serve the project to an AI assistant over MCP (stdio)')
173
+ .option('--app', 'serve the projects of the open desktop app instead (needs --data-dir)')
174
+ .option('--data-dir <dir>', "the desktop app's data folder, as its Connect an AI page shows it")
175
+ .option('--project <dir>', 'project folder the assistant may use (repeatable; default: the current folder)', (v, all) => [...all, v], [])
176
+ // stdout carries JSON-RPC only: help goes to stderr
177
+ .configureOutput({
178
+ writeOut: (t) => process.stderr.write(t),
179
+ writeErr: (t) => process.stderr.write(t),
180
+ })
181
+ .action((o) => {
182
+ if (!o.app)
183
+ return startMcp({ projects: o.project });
184
+ if (!o.dataDir || o.project.length) {
185
+ process.stderr.write("Allgreen: --app needs --data-dir <dir> (see the app's Connect an AI page) and no --project.\n");
186
+ process.exitCode = 1;
187
+ return;
188
+ }
189
+ return startAppMcp({ dataDir: resolve(o.dataDir) });
190
+ });
191
+ program
192
+ .command('demo')
193
+ .description('try Allgreen on a temporary demo project and a local demo site')
194
+ .option('--no-open', 'do not open the browser')
195
+ .action(async (o) => {
196
+ const root = await mkdtemp(join(tmpdir(), 'allgreen-demo-'));
197
+ const demo = fileURLToPath(new URL('../../demo/allgreen/', import.meta.url));
198
+ let site;
199
+ let server;
200
+ let stopping = false;
201
+ const stop = async (code) => {
202
+ if (stopping)
203
+ return; // a second Ctrl-C must not interrupt the cleanup
204
+ stopping = true;
205
+ console.error('Stopping…');
206
+ await Promise.allSettled([site?.close(), server?.close()]);
207
+ await rm(root, { recursive: true, force: true }).catch(() => console.error(`Could not delete the demo copy: remove ${root} yourself.`));
208
+ process.exit(code);
209
+ };
210
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'])
211
+ process.on(signal, () => void stop(0));
212
+ try {
213
+ site = await serveDemoSite();
214
+ const copy = join(root, 'allgreen');
215
+ await cp(demo, copy, { recursive: true, filter: (s) => !s.endsWith('secrets.local.json') });
216
+ await writeFile(join(copy, 'secrets.local.json'), await readFile(join(copy, 'secrets.example.json')), { mode: 0o600 });
217
+ const file = join(copy, 'project.json');
218
+ const project = JSON.parse(await readFile(file, 'utf8'));
219
+ await writeFile(file, JSON.stringify({ ...project, baseUrl: site.url }, null, 2));
220
+ server = await startServer({
221
+ dir: root,
222
+ uiDir,
223
+ });
224
+ }
225
+ catch (e) {
226
+ console.error(describeError(e));
227
+ return void (await stop(2));
228
+ }
229
+ console.log(`Allgreen demo is running at ${server.url}\nDemo site: ${site.url}\n` +
230
+ `This is a demo copy in ${root}; it is deleted when you stop (Ctrl-C).`);
231
+ if (o.open)
232
+ openBrowser(server.url);
233
+ });
234
+ program.parseAsync().catch((e) => {
235
+ if (e instanceof CommanderError && e.exitCode === 0)
236
+ return; // --help, --version
237
+ // Commander already printed its own usage message.
238
+ if (!(e instanceof CommanderError))
239
+ console.error(describeError(e));
240
+ process.exitCode = 2;
241
+ });
@@ -0,0 +1,2 @@
1
+ /** Opens `url` in the default browser; fails silently (the caller prints the address anyway). The URL is never parsed by a shell. */
2
+ export declare function openBrowser(url: string): void;
@@ -0,0 +1,23 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** Opens `url` in the default browser; fails silently (the caller prints the address anyway). The URL is never parsed by a shell. */
3
+ export function openBrowser(url) {
4
+ const [cmd, args] = process.platform === 'darwin'
5
+ ? ['open', [url]]
6
+ : process.platform === 'win32'
7
+ ? ['cmd', ['/c', 'start', '""', url]]
8
+ : ['xdg-open', [url]];
9
+ try {
10
+ // Verbatim on Windows so `""` reaches `start` as its empty title; the URL (hex token, no `&`) needs no escaping.
11
+ const child = spawn(cmd, args, {
12
+ detached: true,
13
+ stdio: 'ignore',
14
+ windowsHide: true,
15
+ windowsVerbatimArguments: true,
16
+ });
17
+ child.on('error', () => { });
18
+ child.unref();
19
+ }
20
+ catch {
21
+ // no opener on this system
22
+ }
23
+ }
@@ -0,0 +1,45 @@
1
+ import type { Locale } from './phrases.js';
2
+ import { type Keyring } from './store.js';
3
+ import { syncedFolder, type SyncEnv } from './synced.js';
4
+ /** The project list refuses a change (not a project, already listed…); the message says why in plain words. */
5
+ export declare class AppProjectError extends Error {
6
+ readonly reason: 'badList' | 'notAProject' | 'notListed' | 'alreadyListed' | 'hasOwnData';
7
+ readonly path: string;
8
+ /** `reason`: why, for a front end to say in its own words; `path`: the file or folder refused. */
9
+ constructor(reason: 'badList' | 'notAProject' | 'notListed' | 'alreadyListed' | 'hasOwnData', path: string, message: string);
10
+ }
11
+ /** A project the app knows: `dir` is its real path. */
12
+ export type AppProject = {
13
+ dir: string;
14
+ name?: string;
15
+ lastOpenedAt?: string;
16
+ };
17
+ export type ProjectListing = AppProject & {
18
+ key: string;
19
+ status: 'ok' | 'missing';
20
+ synced?: ReturnType<typeof syncedFolder>;
21
+ planCount?: number;
22
+ lastRun?: {
23
+ id: string;
24
+ ok: boolean;
25
+ };
26
+ };
27
+ /** The listed projects, most recently opened first; a project whose folder is gone or unreadable is `missing`, never an error. */
28
+ export declare function listProjects(dataDir: string, env?: SyncEnv): Promise<ProjectListing[]>;
29
+ /**
30
+ * Lists `dir` (or just stamps its `lastOpenedAt` when it is listed). With `create`, makes the project first, as
31
+ * `allgreen init` does; without, the folder must already hold `allgreen/project.json`.
32
+ */
33
+ export declare function addProject(dataDir: string, dir: string, opts?: {
34
+ create?: {
35
+ name: string;
36
+ baseUrl: string;
37
+ locale?: Locale;
38
+ };
39
+ }): Promise<AppProject>;
40
+ /** Moves a project's runs, sessions and secrets to `newDir`'s key and points the list at it; refuses if `newDir` already has data. */
41
+ export declare function relocateProject(dataDir: string, oldDir: string, newDir: string, keyring: Keyring): Promise<void>;
42
+ /** Takes `dir` off the list; its runs, sessions and keychain entry go too only with `deleteData`. */
43
+ export declare function removeProject(dataDir: string, dir: string, opts: {
44
+ deleteData: boolean;
45
+ }, keyring: Keyring): Promise<void>;
@@ -0,0 +1,157 @@
1
+ import { mkdir, readFile, realpath, rename, rm, stat } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { writeFileAtomic } from './atomic.js';
4
+ import { initProject } from './project-files.js';
5
+ import { inspectProject } from './project-write.js';
6
+ import { listRuns } from './runs-history.js';
7
+ import { projectKey, SecretsUnavailableError } from './store.js';
8
+ import { syncedFolder } from './synced.js';
9
+ /** A keychain call, its failure replaced by a fixed message: the keychain's own could quote a value. */
10
+ const keychain = (call, reason) => call().catch(() => {
11
+ throw new SecretsUnavailableError(reason);
12
+ });
13
+ /** The project list refuses a change (not a project, already listed…); the message says why in plain words. */
14
+ export class AppProjectError extends Error {
15
+ reason;
16
+ path;
17
+ /** `reason`: why, for a front end to say in its own words; `path`: the file or folder refused. */
18
+ constructor(reason, path, message) {
19
+ super(message);
20
+ this.reason = reason;
21
+ this.path = path;
22
+ this.name = 'AppProjectError';
23
+ }
24
+ }
25
+ const listFile = (dataDir) => join(dataDir, 'projects.json');
26
+ const dataFolder = (dataDir, dir) => join(dataDir, 'projects', projectKey(dir));
27
+ const hasProject = (dir) => stat(join(dir, 'allgreen', 'project.json')).then((s) => s.isFile(), () => false);
28
+ async function readList(dataDir) {
29
+ let text;
30
+ try {
31
+ text = await readFile(listFile(dataDir), 'utf8');
32
+ }
33
+ catch (e) {
34
+ if (e.code === 'ENOENT')
35
+ return [];
36
+ throw e;
37
+ }
38
+ const data = (() => {
39
+ try {
40
+ return JSON.parse(text);
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ })();
46
+ if (!Array.isArray(data?.projects))
47
+ throw new AppProjectError('badList', listFile(dataDir), `${listFile(dataDir)} is not a project list; fix or delete it`);
48
+ return data.projects.filter((p) => typeof p?.dir === 'string');
49
+ }
50
+ async function writeList(dataDir, projects) {
51
+ await mkdir(dataDir, { recursive: true });
52
+ await writeFileAtomic(listFile(dataDir), `${JSON.stringify({ projects }, null, 2)}\n`);
53
+ }
54
+ /** The listed projects, most recently opened first; a project whose folder is gone or unreadable is `missing`, never an error. */
55
+ export async function listProjects(dataDir, env) {
56
+ const projects = await readList(dataDir);
57
+ const listing = await Promise.all(projects.map(async (p) => {
58
+ const base = { ...p, key: projectKey(p.dir) };
59
+ if (!(await hasProject(p.dir)))
60
+ return { ...base, status: 'missing' };
61
+ const synced = syncedFolder(p.dir, env);
62
+ const inspected = await inspectProject(p.dir).catch(() => undefined);
63
+ const planCount = inspected?.plans.filter((x) => !('leftover' in x)).length;
64
+ // the name its settings give now: it may have been renamed since it was listed
65
+ const name = inspected?.project?.name ?? p.name;
66
+ const run = await listRuns({ runsDir: join(dataFolder(dataDir, p.dir), 'runs') })
67
+ .then((runs) => runs.find((r) => r.ok !== undefined))
68
+ .catch(() => undefined);
69
+ return {
70
+ ...base,
71
+ ...(name && { name }),
72
+ status: 'ok',
73
+ ...(synced && { synced }),
74
+ ...(planCount !== undefined && { planCount }),
75
+ ...(run && { lastRun: { id: run.id, ok: run.ok } }),
76
+ };
77
+ }));
78
+ return listing.sort((a, b) => (b.lastOpenedAt ?? '').localeCompare(a.lastOpenedAt ?? ''));
79
+ }
80
+ /**
81
+ * Lists `dir` (or just stamps its `lastOpenedAt` when it is listed). With `create`, makes the project first, as
82
+ * `allgreen init` does; without, the folder must already hold `allgreen/project.json`.
83
+ */
84
+ export async function addProject(dataDir, dir, opts = {}) {
85
+ if (opts.create)
86
+ await initProject(dir, { ...opts.create, secretsFile: false });
87
+ else if (!(await hasProject(dir)))
88
+ throw new AppProjectError('notAProject', dir, `${dir} is not an Allgreen project: it has no allgreen/project.json`);
89
+ const real = await realpath(dir);
90
+ const projects = await readList(dataDir);
91
+ const lastOpenedAt = new Date().toISOString();
92
+ const known = projects.find((p) => p.dir === real);
93
+ const name = opts.create?.name ?? (await inspectProject(real)).project?.name ?? known?.name;
94
+ const entry = { dir: real, ...(name && { name }), lastOpenedAt };
95
+ await writeList(dataDir, [...projects.filter((p) => p !== known), entry]);
96
+ return entry;
97
+ }
98
+ /** Moves a project's runs, sessions and secrets to `newDir`'s key and points the list at it; refuses if `newDir` already has data. */
99
+ export async function relocateProject(dataDir, oldDir, newDir, keyring) {
100
+ if (!(await hasProject(newDir)))
101
+ throw new AppProjectError('notAProject', newDir, `${newDir} is not an Allgreen project: it has no allgreen/project.json`);
102
+ const real = await realpath(newDir);
103
+ const [from, to] = [projectKey(oldDir), projectKey(real)];
104
+ const projects = await readList(dataDir);
105
+ const entry = projects.find((p) => p.dir === oldDir);
106
+ if (!entry)
107
+ throw new AppProjectError('notListed', oldDir, `${oldDir} is not in the project list`);
108
+ if (projects.some((p) => p.dir === real && p !== entry))
109
+ throw new AppProjectError('alreadyListed', real, `${real} is already in the project list`);
110
+ const [target, source] = [dataFolder(dataDir, real), dataFolder(dataDir, oldDir)];
111
+ const secret = from === to ? undefined : await keychain(() => keyring.get(from), 'cannot be read');
112
+ if (from !== to &&
113
+ ((await stat(target).then(() => true, () => false)) ||
114
+ (await keychain(() => keyring.get(to), 'cannot be read')) !== undefined))
115
+ throw new AppProjectError('hasOwnData', real, `${real} already has runs or secrets of its own`);
116
+ const entries = projects.filter((p) => p !== entry);
117
+ const moved = { ...entry, dir: real, lastOpenedAt: new Date().toISOString() };
118
+ if (from === to)
119
+ return writeList(dataDir, [...entries, moved]);
120
+ // Any failure before the list is written leaves the old state whole: copy the secret, move the data, list, then
121
+ // drop the old secret last (a failure there only leaves a harmless stale entry).
122
+ if (secret !== undefined)
123
+ await keychain(() => keyring.set(to, secret), "refused to move the project's secrets");
124
+ try {
125
+ await mkdir(dirname(target), { recursive: true });
126
+ await rename(source, target).catch((e) => {
127
+ if (e.code !== 'ENOENT')
128
+ throw e; // no runs yet
129
+ });
130
+ }
131
+ catch (e) {
132
+ if (secret !== undefined)
133
+ await keyring.delete(to).catch(() => { });
134
+ throw e;
135
+ }
136
+ try {
137
+ await writeList(dataDir, [...entries, moved]);
138
+ }
139
+ catch (e) {
140
+ await rename(target, source).catch(() => { });
141
+ if (secret !== undefined)
142
+ await keyring.delete(to).catch(() => { });
143
+ throw e;
144
+ }
145
+ if (secret !== undefined)
146
+ await keyring.delete(from).catch(() => { });
147
+ }
148
+ /** Takes `dir` off the list; its runs, sessions and keychain entry go too only with `deleteData`. */
149
+ export async function removeProject(dataDir, dir, opts, keyring) {
150
+ const projects = await readList(dataDir);
151
+ // the data first, the list last: a failure leaves the project listed, so removing it again retries
152
+ if (opts.deleteData) {
153
+ await keychain(() => keyring.delete(projectKey(dir)), "refused to delete the project's secrets");
154
+ await rm(dataFolder(dataDir, dir), { recursive: true, force: true });
155
+ }
156
+ await writeList(dataDir, projects.filter((p) => p.dir !== dir));
157
+ }
@@ -0,0 +1,3 @@
1
+ import { rename } from 'node:fs/promises';
2
+ /** Writes `data` (with file `mode` if given) to a temp file next to `path`, then renames it over `path`; the temp file is removed on failure. `renameFn` is a test seam. */
3
+ export declare function writeFileAtomic(path: string, data: string, mode?: number, renameFn?: typeof rename): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { rename, rm, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, join } from 'node:path';
4
+ const RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
5
+ const RENAME_TRIES = 10;
6
+ /** Windows refuses to replace a file another handle (antivirus, indexer, a concurrent read) briefly holds open, so retry with a growing backoff (~0.9 s total). Not gated on win32: elsewhere these codes are rare and the cost is under a second before the same error. */
7
+ async function renameWithRetry(from, to, renameFn) {
8
+ for (let i = 1;; i++) {
9
+ try {
10
+ return await renameFn(from, to);
11
+ }
12
+ catch (e) {
13
+ const code = e.code;
14
+ if (i >= RENAME_TRIES || !code || !RETRY_CODES.has(code))
15
+ throw e;
16
+ await new Promise((r) => setTimeout(r, 20 * i));
17
+ }
18
+ }
19
+ }
20
+ /** Writes `data` (with file `mode` if given) to a temp file next to `path`, then renames it over `path`; the temp file is removed on failure. `renameFn` is a test seam. */
21
+ export async function writeFileAtomic(path, data, mode, renameFn = rename) {
22
+ const tmp = join(dirname(path), `${basename(path)}.${randomBytes(6).toString('hex')}.tmp`);
23
+ try {
24
+ await writeFile(tmp, data, { mode });
25
+ await renameWithRetry(tmp, path, renameFn);
26
+ }
27
+ catch (e) {
28
+ await rm(tmp, { force: true });
29
+ throw e;
30
+ }
31
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * One browser package Playwright needs (a browser, FFmpeg for videos…) and whether it is in the browsers folder;
3
+ * `browser` marks the three the plans run in, not the tools installed with them.
4
+ */
5
+ export type BrowserPackage = {
6
+ name: string;
7
+ dir: string;
8
+ installed: boolean;
9
+ browser?: boolean;
10
+ };
11
+ /** Why an install failed, as far as its output tells. */
12
+ export type BrowserInstallCause = 'network' | 'disk' | 'permission' | 'lock' | 'unknown';
13
+ /** A failed browsers install: the cause, and the last lines of its output (home folder masked as `~`). */
14
+ export declare class BrowserInstallError extends Error {
15
+ readonly cause: BrowserInstallCause;
16
+ readonly tail: string[];
17
+ constructor(cause: BrowserInstallCause, tail: string[]);
18
+ }
19
+ type Opts = {
20
+ env?: NodeJS.ProcessEnv;
21
+ cli?: string;
22
+ signal?: AbortSignal;
23
+ };
24
+ /** The browser packages Playwright needs, with whether each is installed (`<dir>/INSTALLATION_COMPLETE` exists). */
25
+ export declare function browserStatus(opts?: Opts): Promise<BrowserPackage[]>;
26
+ /**
27
+ * Installs the browsers into `PLAYWRIGHT_BROWSERS_PATH` (from `env`; the desktop shell sets it). The app is that folder's
28
+ * only user, so a lock left there is orphaned and removed first. Aborting `signal` stops it. Throws
29
+ * {@link BrowserInstallError} on failure.
30
+ */
31
+ export declare function installBrowsers(opts: Opts & {
32
+ onProgress(p: {
33
+ name: string;
34
+ percent: number;
35
+ }): void;
36
+ }): Promise<void>;
37
+ /** What the server needs of the browsers: tests stand in a fake. */
38
+ export type BrowserTools = {
39
+ status: typeof browserStatus;
40
+ install: typeof installBrowsers;
41
+ };
42
+ export {};
@@ -0,0 +1,116 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { rm } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { killTree, playwrightPaths } from './run.js';
7
+ /** A failed browsers install: the cause, and the last lines of its output (home folder masked as `~`). */
8
+ export class BrowserInstallError extends Error {
9
+ cause;
10
+ tail;
11
+ constructor(cause, tail) {
12
+ super(`Browser install failed (${cause})`);
13
+ this.cause = cause;
14
+ this.tail = tail;
15
+ this.name = 'BrowserInstallError';
16
+ }
17
+ }
18
+ const PACKAGES = ['chromium', 'firefox', 'webkit'];
19
+ const HEADER = /^(?:Downloading )?(.+?) \(playwright (\S+)[^)]*\)/;
20
+ /**
21
+ * Runs the Playwright CLI and gives its output lines; `onLine` sees each as it comes. Aborting `signal` kills it
22
+ * with the processes it started (its download workers).
23
+ */
24
+ function runCli(args, { env = process.env, cli, signal }, onLine) {
25
+ return new Promise((resolve, reject) => {
26
+ const child = spawn(process.execPath, [cli ?? playwrightPaths().cli, ...args], {
27
+ env,
28
+ windowsHide: true,
29
+ stdio: ['ignore', 'pipe', 'pipe'],
30
+ detached: signal !== undefined && process.platform !== 'win32', // its own group, for killTree
31
+ });
32
+ const kill = () => killTree(child);
33
+ if (signal?.aborted)
34
+ kill();
35
+ signal?.addEventListener('abort', kill, { once: true });
36
+ const lines = [];
37
+ let rest = '';
38
+ const feed = (chunk) => {
39
+ const parts = (rest + chunk).split(/\r\n|\r|\n/);
40
+ rest = parts.pop() ?? '';
41
+ for (const l of parts) {
42
+ lines.push(l);
43
+ onLine?.(l);
44
+ }
45
+ };
46
+ for (const s of [child.stdout, child.stderr])
47
+ s.setEncoding('utf8').on('data', feed);
48
+ child.on('error', reject);
49
+ child.on('close', (code) => {
50
+ signal?.removeEventListener('abort', kill);
51
+ if (rest)
52
+ feed('\n');
53
+ resolve({ code, lines });
54
+ });
55
+ });
56
+ }
57
+ /** The browser packages Playwright needs, with whether each is installed (`<dir>/INSTALLATION_COMPLETE` exists). */
58
+ export async function browserStatus(opts = {}) {
59
+ const { code, lines } = await runCli(['install', '--dry-run', ...PACKAGES], opts);
60
+ const packages = [];
61
+ let name;
62
+ let id;
63
+ for (const line of lines) {
64
+ const header = HEADER.exec(line);
65
+ if (header)
66
+ [, name, id] = header;
67
+ const dir = /^\s*Install location:\s*(.+?)\s*$/.exec(line)?.[1];
68
+ if (dir && name) {
69
+ const installed = existsSync(join(dir, 'INSTALLATION_COMPLETE'));
70
+ packages.push({ name, dir, installed, ...(PACKAGES.includes(id ?? '') && { browser: true }) });
71
+ name = undefined;
72
+ }
73
+ }
74
+ if (code !== 0 || !packages.length)
75
+ throw new Error('Could not list the browsers to install');
76
+ return packages;
77
+ }
78
+ const mask = (line) => {
79
+ const home = homedir();
80
+ return home.length > 1 ? line.split(home).join('~') : line;
81
+ };
82
+ function causeOf(text) {
83
+ if (/ENOTFOUND|ECONNRESET|ETIMEDOUT|EAI_AGAIN|getaddrinfo/.test(text))
84
+ return 'network';
85
+ if (/ENOSPC/.test(text))
86
+ return 'disk';
87
+ if (/EACCES|EPERM/.test(text))
88
+ return 'permission';
89
+ if (/Unable to update lock|__dirlock/.test(text))
90
+ return 'lock';
91
+ return 'unknown';
92
+ }
93
+ /**
94
+ * Installs the browsers into `PLAYWRIGHT_BROWSERS_PATH` (from `env`; the desktop shell sets it). The app is that folder's
95
+ * only user, so a lock left there is orphaned and removed first. Aborting `signal` stops it. Throws
96
+ * {@link BrowserInstallError} on failure.
97
+ */
98
+ export async function installBrowsers(opts) {
99
+ const { env = process.env, onProgress } = opts;
100
+ const root = env.PLAYWRIGHT_BROWSERS_PATH;
101
+ if (root)
102
+ await rm(join(root, '__dirlock'), { recursive: true, force: true });
103
+ let name = '';
104
+ const { code, lines } = await runCli(['install', ...PACKAGES], opts, (l) => {
105
+ const header = HEADER.exec(l);
106
+ if (header)
107
+ name = header[1];
108
+ const percent = /(\d{1,3})%/.exec(l)?.[1];
109
+ if (percent && name)
110
+ onProgress({ name, percent: Number(percent) });
111
+ });
112
+ if (code === 0)
113
+ return;
114
+ const tail = lines.slice(-40).map(mask);
115
+ throw new BrowserInstallError(causeOf(lines.join('\n')), tail);
116
+ }