@codifycli/plugin-test 1.1.0-beta6 → 1.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.
@@ -0,0 +1,97 @@
1
+ // Same as TerminalLines in the Codify CLI (src/plugins/terminal-lines.ts): keep them in sync
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ /**
4
+ * Longest line in progress kept (a progress bar that never prints a newline). It may grow to twice this before it is
5
+ * cut, so a flood of small chunks without newlines doesn't copy the whole line for every chunk.
6
+ */
7
+ const MAX_PARTIAL_LENGTH = 4096;
8
+ // An escape sequence cut off at the end of a chunk (`ESC`, `ESC[1`, an unfinished `ESC]` title): kept for the next chunk
9
+ // eslint-disable-next-line no-control-regex
10
+ const INCOMPLETE_ESCAPE = /\u001B(?:\[[\d;?]*|\][^\u0007\u001B]{0,256})?$/;
11
+ // Text drawn somewhere else on the screen between saving and restoring the cursor (`ESC 7` … `ESC 8`, `ESC[s` … `ESC[u`):
12
+ // apt's progress bar on the last row. It isn't part of the output's lines
13
+ // eslint-disable-next-line no-control-regex
14
+ const DRAWN_ELSEWHERE = /\u001B7[\s\S]*?\u001B8|\u001B\[s[\s\S]*?\u001B\[u/g;
15
+ // A cursor save without its restore yet (the rest is in the next chunk)
16
+ // eslint-disable-next-line no-control-regex
17
+ const UNFINISHED_DRAWN_ELSEWHERE = /(?:\u001B7|\u001B\[s)(?![\s\S]*(?:\u001B8|\u001B\[u))[\s\S]*$/;
18
+ /** Longest unfinished cursor save kept for the next chunk */
19
+ const MAX_PENDING_LENGTH = 1024;
20
+ // Cursor to the start of the line (`ESC[G`, `ESC[0G`, `ESC[1G`): progress bars redraw the line with it instead of \r
21
+ // eslint-disable-next-line no-control-regex
22
+ const CURSOR_TO_LINE_START = /\u001B\[[01]?G/g;
23
+ // A line that only holds spinner frames (npm's `⠼ ⠴ ⠦`, `| / - \`)
24
+ const SPINNER_LINE = /^[⠀-⣿|/\\-]+$/;
25
+ /**
26
+ * Turns command output (chunks as they come from a terminal) into the lines a terminal would end up showing:
27
+ * - a line redrawn with `\r` or cursor-to-line-start (spinners, progress bars) keeps only its final state
28
+ * - spinner-only and blank lines are dropped, escape codes (colors) removed
29
+ * - an escape sequence split between two chunks is put back together
30
+ * - text drawn elsewhere on the screen (apt's progress bar on the last row, between a cursor save and restore) is dropped
31
+ *
32
+ * Only the new chunk is processed: a chunk costs its own size, however long the line in progress is.
33
+ */
34
+ export class TerminalLines {
35
+ partial = '';
36
+ pendingEscape = '';
37
+ /** Adds a chunk of output and returns the lines it completed */
38
+ push(chunk) {
39
+ let raw = (this.pendingEscape + chunk).replaceAll(DRAWN_ELSEWHERE, '');
40
+ const incomplete = UNFINISHED_DRAWN_ELSEWHERE.exec(raw) ?? INCOMPLETE_ESCAPE.exec(raw);
41
+ this.pendingEscape = incomplete && incomplete[0].length <= MAX_PENDING_LENGTH ? incomplete[0] : '';
42
+ if (incomplete) {
43
+ raw = raw.slice(0, incomplete.index);
44
+ }
45
+ // \r\n line endings: the \r stays at the end of the line, where cleanLine ignores it
46
+ const parts = stripVTControlCharacters(raw.replaceAll(CURSOR_TO_LINE_START, '\r')).split('\n');
47
+ if (parts.length === 1) {
48
+ this.partial += parts[0];
49
+ if (this.partial.length > MAX_PARTIAL_LENGTH * 2) {
50
+ this.partial = this.partial.slice(-MAX_PARTIAL_LENGTH);
51
+ }
52
+ return [];
53
+ }
54
+ const lines = [];
55
+ const add = (text) => {
56
+ const line = cleanLine(text);
57
+ if (line) {
58
+ lines.push(line);
59
+ }
60
+ };
61
+ add(this.partial + parts[0]);
62
+ for (let i = 1; i < parts.length - 1; i++) {
63
+ add(parts[i]);
64
+ }
65
+ this.partial = parts.at(-1);
66
+ if (this.partial.length > MAX_PARTIAL_LENGTH * 2) {
67
+ this.partial = this.partial.slice(-MAX_PARTIAL_LENGTH);
68
+ }
69
+ return lines;
70
+ }
71
+ /** The line in progress, as a terminal shows it ('' if there is nothing to show) */
72
+ current() {
73
+ return cleanLine(this.partial.slice(-MAX_PARTIAL_LENGTH));
74
+ }
75
+ /** Ends the line in progress (the command finished): returns it, or '' */
76
+ flush() {
77
+ const line = this.current();
78
+ this.partial = '';
79
+ this.pendingEscape = '';
80
+ return line;
81
+ }
82
+ }
83
+ /**
84
+ * What a terminal shows of a line: the text after the last carriage return (progress bars redraw the line), or ''
85
+ * when nothing is left to show (blank, or only spinner frames).
86
+ */
87
+ function cleanLine(line) {
88
+ const segments = line.split('\r');
89
+ for (let i = segments.length - 1; i >= 0; i--) {
90
+ const segment = segments[i].trimEnd();
91
+ if (segment.trim()) {
92
+ return SPINNER_LINE.test(segment.trim()) ? '' : segment;
93
+ }
94
+ }
95
+ return '';
96
+ }
97
+ //# sourceMappingURL=terminal-lines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal-lines.js","sourceRoot":"","sources":["../src/terminal-lines.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAErD;;;GAGG;AACH,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,yHAAyH;AACzH,4CAA4C;AAC5C,MAAM,iBAAiB,GAAG,gDAAgD,CAAC;AAE3E,0HAA0H;AAC1H,0EAA0E;AAC1E,4CAA4C;AAC5C,MAAM,eAAe,GAAG,oDAAoD,CAAC;AAE7E,wEAAwE;AACxE,4CAA4C;AAC5C,MAAM,0BAA0B,GAAG,+DAA+D,CAAC;AAEnG,6DAA6D;AAC7D,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEhC,qHAAqH;AACrH,4CAA4C;AAC5C,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;AAE/C,mEAAmE;AACnE,MAAM,YAAY,GAAG,eAAe,CAAC;AAErC;;;;;;;;GAQG;AACH,MAAM,OAAO,aAAa;IAChB,OAAO,GAAG,EAAE,CAAC;IACb,aAAa,GAAG,EAAE,CAAC;IAE3B,gEAAgE;IAChE,IAAI,CAAC,KAAa;QAChB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,EAAE,EAAE,CAAC;YACnB,OAAO,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC"}
@@ -21,7 +21,7 @@ export const TestUtils = {
21
21
  resolve(response.data);
22
22
  }
23
23
  else {
24
- reject(new Error(String(response.data)));
24
+ reject(toError(response.data));
25
25
  }
26
26
  }
27
27
  });
@@ -120,4 +120,17 @@ export const TestUtils = {
120
120
  return os.platform() === 'linux';
121
121
  },
122
122
  };
123
+ /**
124
+ * Errors from plugins: plugin-core >= 2.0 sends `{ errorType, message, data? }` (PluginErrorData), shown as
125
+ * `[errorType] message` with the data (ex: the plan of an apply validation error) under `Details:`, and kept on the
126
+ * error (`errorType`, `data`). Older plugins send a string, used as is.
127
+ */
128
+ function toError(data) {
129
+ if (data && typeof data === 'object' && typeof data.message === 'string') {
130
+ const { data: errorData, errorType, message } = data;
131
+ const details = errorData === null || errorData === undefined ? '' : `\nDetails: ${JSON.stringify(errorData, null, 2)}`;
132
+ return Object.assign(new Error(`[${errorType ?? 'error'}] ${message}${details}`), { data: errorData, errorType });
133
+ }
134
+ return new Error(String(data));
135
+ }
123
136
  //# sourceMappingURL=test-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"test-utils.js","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,gBAAgB,EAAgB,aAAa,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAE5G,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM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SAAS,OAAO,CAAC,IAAa;IAC5B,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAQ,IAA8B,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACpG,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,IAA+D,CAAC;QAChH,MAAM,OAAO,GAAG,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QACxH,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,SAAS,IAAI,OAAO,KAAK,OAAO,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,CAAC;IACpH,CAAC;IAED,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACjC,CAAC"}
package/dist/utils.d.ts CHANGED
@@ -1,6 +1,14 @@
1
- import { ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
1
+ import { LinuxDistro, ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
2
2
  export declare function splitUserConfig<T extends StringIndexedObject>(config: ResourceConfig & T): {
3
3
  parameters: T;
4
4
  coreParameters: ResourceConfig;
5
5
  };
6
+ /**
7
+ * Whether a config applies to this machine, like the CLI's os and distro filters: `os` must include the current OS,
8
+ * and on Linux `distro` must match the current distribution (`debian-based` / `rpm-based` match their families).
9
+ * `distro` is ignored on other OSes and when the distribution is unknown.
10
+ */
11
+ export declare function appliesToCurrentPlatform(config: Pick<ResourceConfig, 'distro' | 'os'>): boolean;
12
+ export declare function getLinuxDistro(): LinuxDistro | undefined;
13
+ export declare function distroMatches(filter: LinuxDistro, current: LinuxDistro): boolean;
6
14
  export declare function getPlatformOs(): ResourceOs;
package/dist/utils.js CHANGED
@@ -1,5 +1,22 @@
1
- import { ResourceOs } from '@codifycli/schemas';
1
+ import { LinuxDistro, ResourceOs } from '@codifycli/schemas';
2
+ import fs from 'node:fs';
2
3
  import os from 'node:os';
4
+ const DEBIAN_BASED_DISTROS = [
5
+ LinuxDistro.DEBIAN,
6
+ LinuxDistro.UBUNTU,
7
+ LinuxDistro.MINT,
8
+ LinuxDistro.POP_OS,
9
+ LinuxDistro.ELEMENTARY_OS,
10
+ LinuxDistro.KALI,
11
+ ];
12
+ const RPM_BASED_DISTROS = [
13
+ LinuxDistro.FEDORA,
14
+ LinuxDistro.CENTOS,
15
+ LinuxDistro.RHEL,
16
+ LinuxDistro.AMAZON_LINUX,
17
+ LinuxDistro.OPENSUSE,
18
+ LinuxDistro.SUSE,
19
+ ];
3
20
  export function splitUserConfig(config) {
4
21
  const coreParameters = {
5
22
  type: config.type,
@@ -15,6 +32,48 @@ export function splitUserConfig(config) {
15
32
  coreParameters,
16
33
  };
17
34
  }
35
+ /**
36
+ * Whether a config applies to this machine, like the CLI's os and distro filters: `os` must include the current OS,
37
+ * and on Linux `distro` must match the current distribution (`debian-based` / `rpm-based` match their families).
38
+ * `distro` is ignored on other OSes and when the distribution is unknown.
39
+ */
40
+ export function appliesToCurrentPlatform(config) {
41
+ if (config.os && config.os.length > 0 && !config.os.includes(getPlatformOs())) {
42
+ return false;
43
+ }
44
+ if (!config.distro || config.distro.length === 0 || os.platform() !== 'linux') {
45
+ return true;
46
+ }
47
+ const current = getLinuxDistro();
48
+ return !current || config.distro.some((d) => distroMatches(d, current));
49
+ }
50
+ export function getLinuxDistro() {
51
+ for (const candidate of ['/etc/os-release', '/usr/lib/os-release']) {
52
+ let osRelease;
53
+ try {
54
+ osRelease = fs.readFileSync(candidate, 'utf8');
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ for (const line of osRelease.split('\n')) {
60
+ if (line.startsWith('ID=')) {
61
+ const distroId = line.slice(3).trim().replaceAll('"', '');
62
+ return Object.values(LinuxDistro).includes(distroId) ? distroId : undefined;
63
+ }
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+ export function distroMatches(filter, current) {
69
+ if (filter === LinuxDistro.DEBIAN_BASED) {
70
+ return DEBIAN_BASED_DISTROS.includes(current);
71
+ }
72
+ if (filter === LinuxDistro.RPM_BASED) {
73
+ return RPM_BASED_DISTROS.includes(current);
74
+ }
75
+ return filter === current;
76
+ }
18
77
  export function getPlatformOs() {
19
78
  const currOs = os.platform();
20
79
  switch (currOs) {
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,UAAU,EAAuB,MAAM,oBAAoB,CAAC;AACrF,OAAO,EAAE,MAAM,SAAS,CAAC;AAEzB,MAAM,UAAU,eAAe,CAC7B,MAA0B;IAE1B,MAAM,cAAc,GAAG;QACrB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5D,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpD,CAAC;IAEF,6DAA6D;IAC7D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,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O,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,MAAM,MAAM,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;IAC7B,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,OAAO,UAAU,CAAC,KAAK,CAAC;QAC1B,CAAC;QAED,KAAK,OAAO,CAAC,CAAC,CAAC;YACb,OAAO,UAAU,CAAC,KAAK,CAAC;QAC1B,CAAC;QAED,KAAK,OAAO,CAAC,CAAC,CAAC;YACb,OAAO,UAAU,CAAC,OAAO,CAAC;QAC5B,CAAC;QAED,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,IAAI,KAAK,CAAC,mBAAmB,MAAM,EAAE,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codifycli/plugin-test",
3
- "version": "1.1.0-beta6",
3
+ "version": "1.2.0",
4
4
  "description": "Testing framework for Codify plugins with complete lifecycle testing, IPC communication, and cross-platform support",
5
5
  "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -27,25 +27,25 @@
27
27
  "prepublishOnly": "tsc"
28
28
  },
29
29
  "dependencies": {
30
- "@codifycli/schemas": "1.1.0-beta4",
30
+ "@codifycli/schemas": "1.8.1",
31
+ "node-pty": "1.2.0-beta.15",
31
32
  "ajv": "^8.18.0",
32
33
  "ajv-formats": "^3.0.1",
33
- "lodash.matches": "^4.6.0",
34
+ "chalk": "^5.4.1",
34
35
  "lodash.differencewith": "4.5.0",
36
+ "lodash.matches": "^4.6.0",
35
37
  "lodash.unionby": "^4.8.0",
36
38
  "nanoid": "^5.0.9",
37
- "chalk": "^5.4.1",
38
- "@homebridge/node-pty-prebuilt-multiarch": "^0.13.1",
39
39
  "strip-ansi": "^7.1.2"
40
40
  },
41
41
  "devDependencies": {
42
- "@codifycli/plugin-core": "1.1.0-beta12",
42
+ "@codifycli/plugin-core": "2.3.0",
43
43
  "@oclif/prettier-config": "^0.2.1",
44
44
  "@types/debug": "^4.1.12",
45
- "@types/node": "^22",
46
- "@types/lodash.matches": "^4.6.9",
47
45
  "@types/lodash.differencewith": "^4.5.9",
46
+ "@types/lodash.matches": "^4.6.9",
48
47
  "@types/lodash.unionby": "^4.8.9",
48
+ "@types/node": "^22",
49
49
  "eslint": "^8.51.0",
50
50
  "eslint-config-oclif": "^5",
51
51
  "eslint-config-oclif-typescript": "^3",
@@ -7,8 +7,8 @@ import {
7
7
  ImportRequestData,
8
8
  ImportResponseData,
9
9
  InitializeResponseData,
10
- IpcMessageSchema,
11
10
  IpcMessageV2,
11
+ IpcMessageV2Schema,
12
12
  MessageCmd,
13
13
  PlanRequestData,
14
14
  PlanResponseData,
@@ -21,13 +21,19 @@ import { ChildProcess, fork } from 'node:child_process';
21
21
  import path from 'node:path';
22
22
 
23
23
  import { spawnSafe } from './spawn.js';
24
+ import { TerminalLines } from './terminal-lines.js';
24
25
  import { TestUtils } from './test-utils.js';
25
26
 
26
27
  const ajv = new Ajv.default({
27
28
  strict: true
28
29
  });
29
30
 
30
- const ipcMessageValidator = ajv.compile(IpcMessageSchema);
31
+ const ipcMessageValidator = ajv.compile<IpcMessageV2>(IpcMessageV2Schema);
32
+
33
+ /** Plugin → CLI, no reply: `{ data }`, the plugin's stdout (plugin-core >= 2.3.0 sends it over IPC, in order with the other messages) */
34
+ export const OUTPUT_MESSAGE_CMD = 'output';
35
+ /** Plugin → CLI, no reply: `{ id, exitCode }` (plugin-core >= 2.2.0) */
36
+ export const COMMAND_FINISHED_MESSAGE_CMD = 'command_finished';
31
37
  const commandRequestValidator = ajv.compile(CommandRequestDataSchema);
32
38
 
33
39
  export class PluginProcess {
@@ -58,7 +64,11 @@ export class PluginProcess {
58
64
  )
59
65
 
60
66
  this.childProcess.stderr?.pipe(process.stderr);
61
- this.childProcess.stdout?.pipe(process.stdout);
67
+ // Command output (older plugins write it to stdout): printed as the lines a terminal would end up showing, so
68
+ // spinners and progress bars don't flood the test logs with a line per redraw
69
+ this.childProcess.stdout?.setEncoding('utf8');
70
+ this.childProcess.stdout?.on('data', (data: string) => this.printOutput(data));
71
+ this.childProcess.on('exit', () => this.printLastLine());
62
72
 
63
73
  this.handleIncomingRequests(this.childProcess);
64
74
  }
@@ -111,6 +121,23 @@ export class PluginProcess {
111
121
  });
112
122
  }
113
123
 
124
+ private readonly output = new TerminalLines();
125
+
126
+ private printOutput(data: string): void {
127
+ const lines = this.output.push(data);
128
+ if (lines.length > 0) {
129
+ process.stdout.write(lines.map((line) => `${line}\n`).join(''));
130
+ }
131
+ }
132
+
133
+ /** The last line of a command when it doesn't end with a newline (a prompt, a progress bar) */
134
+ private printLastLine(): void {
135
+ const line = this.output.flush();
136
+ if (line) {
137
+ process.stdout.write(`${line}\n`);
138
+ }
139
+ }
140
+
114
141
  kill() {
115
142
  this.childProcess.kill();
116
143
  }
@@ -122,6 +149,21 @@ export class PluginProcess {
122
149
  throw new Error(`Invalid message from plugin. ${JSON.stringify(message, null, 2)}`);
123
150
  }
124
151
 
152
+ // The plugin's command output (plugin-core >= 2.3.0). command_started is ignored
153
+ if (message.cmd === OUTPUT_MESSAGE_CMD) {
154
+ const { data } = message.data as { data?: unknown };
155
+ if (typeof data === 'string') {
156
+ this.printOutput(data);
157
+ }
158
+
159
+ return;
160
+ }
161
+
162
+ if (message.cmd === COMMAND_FINISHED_MESSAGE_CMD) {
163
+ this.printLastLine();
164
+ return;
165
+ }
166
+
125
167
  if (message.cmd === MessageCmd.COMMAND_REQUEST) {
126
168
  const { data, requestId } = message;
127
169
  if (!commandRequestValidator(data)) {
@@ -8,7 +8,7 @@ import chalk from 'chalk';
8
8
  import unionBy from 'lodash.unionby';
9
9
 
10
10
  import { PluginProcess } from './plugin-process.js';
11
- import { getPlatformOs, splitUserConfig } from './utils.js';
11
+ import { appliesToCurrentPlatform, splitUserConfig } from './utils.js';
12
12
 
13
13
  export interface FullTestOptions {
14
14
  skipUninstall?: boolean,
@@ -33,7 +33,8 @@ export class PluginTester {
33
33
  configs: ResourceConfig[],
34
34
  options?: FullTestOptions,
35
35
  ): Promise<void> {
36
- configs = configs.filter((c) => !c.os || c.os.includes(getPlatformOs()));
36
+ configs = configs.filter((c) => appliesToCurrentPlatform(c));
37
+ const modifiedConfigs = options?.testModify?.modifiedConfigs.filter((c) => appliesToCurrentPlatform(c));
37
38
  const ids = configs
38
39
  .map((c) => `${c.type}${c.name ? `.${c.name}` : ''}`)
39
40
  .join(', ')
@@ -45,47 +46,61 @@ export class PluginTester {
45
46
  await this.ensurePrerequisites(pluginPath, options.prerequisites);
46
47
  }
47
48
 
48
- const plugin = new PluginProcess(pluginPath);
49
-
49
+ // Uninstall also runs when a phase fails, so a failed test doesn't leave resources installed for the next one
50
+ let failed = false;
50
51
  try {
51
- await this.initializeAndValidate(plugin, configs);
52
-
53
- await this.validateExampleAndDefaultConfigs(plugin, configs);
52
+ const plugin = new PluginProcess(pluginPath);
54
53
 
55
- console.info(chalk.cyan('Testing plan...'))
56
- const plans = await this.planConfigs(plugin, configs);
54
+ try {
55
+ const resourceTypes = await this.initializeAndValidate(plugin, configs);
57
56
 
58
- if (options?.validatePlan) {
59
- await options.validatePlan(plans);
60
- }
57
+ await this.validateExampleAndDefaultConfigs(plugin, configs, resourceTypes);
61
58
 
62
- console.info(chalk.cyan('Testing apply...'))
63
- await this.applyPlans(plugin, plans);
59
+ console.info(chalk.cyan('Testing plan...'))
60
+ const plans = await this.planConfigs(plugin, configs);
64
61
 
65
- if (options?.validateApply) {
66
- await options.validateApply(plans);
67
- }
68
- } finally {
69
- plugin.kill();
70
- }
62
+ if (options?.validatePlan) {
63
+ await options.validatePlan(plans);
64
+ }
71
65
 
72
- if (!options?.skipImport) {
73
- await this.runImportPhase(pluginPath, configs, options?.validateImport);
74
- }
66
+ console.info(chalk.cyan('Testing apply...'))
67
+ await this.applyPlans(plugin, plans);
75
68
 
76
- if (options?.testModify) {
77
- await this.runModifyPhase(pluginPath, options.testModify);
78
- }
69
+ if (options?.validateApply) {
70
+ await options.validateApply(plans);
71
+ }
72
+ } finally {
73
+ plugin.kill();
74
+ }
75
+
76
+ if (!options?.skipImport) {
77
+ await this.runImportPhase(pluginPath, configs, options?.validateImport);
78
+ }
79
79
 
80
- if (!skipUninstall) {
81
- // We need to add unique names to multiple configs with the same type or else it breaks the unionBy below.
82
- const configsWithNames = this.addNamesToConfigs(configs);
83
- const modifiedConfigs = this.addNamesToConfigs(options?.testModify?.modifiedConfigs ?? [])
80
+ if (options?.testModify && modifiedConfigs) {
81
+ await this.runModifyPhase(pluginPath, { ...options.testModify, modifiedConfigs });
82
+ }
83
+ } catch (error) {
84
+ failed = true;
85
+ throw error;
86
+ } finally {
87
+ if (!skipUninstall) {
88
+ // We need to add unique names to multiple configs with the same type or else it breaks the unionBy below.
89
+ const configsWithNames = this.addNamesToConfigs(configs);
90
+ const modifiedConfigsWithNames = this.addNamesToConfigs(modifiedConfigs ?? [])
84
91
 
85
- const id = (config: ResourceConfig) => config.type + (config.name ? `.${config.name}` : '')
92
+ const id = (config: ResourceConfig) => config.type + (config.name ? `.${config.name}` : '')
86
93
 
87
- const configsToDestroy = unionBy(modifiedConfigs, configsWithNames, id);
88
- await this.uninstall(pluginPath, configsToDestroy.toReversed(), options);
94
+ const configsToDestroy = unionBy(modifiedConfigsWithNames, configsWithNames, id);
95
+ try {
96
+ // validateDestroy only checks a test that succeeded
97
+ await this.uninstall(pluginPath, configsToDestroy.toReversed(), failed ? undefined : options);
98
+ } catch (error) {
99
+ // Don't hide the error that failed the test
100
+ if (!failed) throw error;
101
+ console.error(chalk.red(`Uninstall after the failed test also failed: ${error}`));
102
+ }
103
+ }
89
104
  }
90
105
  }
91
106
 
@@ -145,7 +160,7 @@ export class PluginTester {
145
160
  }
146
161
 
147
162
  private static async ensurePrerequisites(pluginPath: string, prerequisites: ResourceConfig[]): Promise<void> {
148
- prerequisites = prerequisites.filter((c) => !c.os || c.os.includes(getPlatformOs()));
163
+ prerequisites = prerequisites.filter((c) => appliesToCurrentPlatform(c));
149
164
  if (prerequisites.length === 0) return;
150
165
 
151
166
  const ids = prerequisites.map((c) => `${c.type}${c.name ? `.${c.name}` : ''}`).join(', ');
@@ -197,7 +212,8 @@ export class PluginTester {
197
212
  }
198
213
  }
199
214
 
200
- private static async initializeAndValidate(plugin: PluginProcess, configs: ResourceConfig[]): Promise<void> {
215
+ /** Returns the resource types of the plugin */
216
+ private static async initializeAndValidate(plugin: PluginProcess, configs: ResourceConfig[]): Promise<Set<string>> {
201
217
  console.info(chalk.cyan('Testing initialization...'))
202
218
  const initializeResult = await plugin.initialize();
203
219
 
@@ -224,11 +240,14 @@ export class PluginTester {
224
240
  }));
225
241
  throw new Error(`The following configs did not validate:\n ${JSON.stringify(invalidWithConfigs, null, 2)}`)
226
242
  }
243
+
244
+ return new Set(initializeResult.resourceDefinitions.map((rd) => rd.type));
227
245
  }
228
246
 
229
247
  private static async validateExampleAndDefaultConfigs(
230
248
  plugin: PluginProcess,
231
249
  configs: ResourceConfig[],
250
+ resourceTypes: Set<string>,
232
251
  ): Promise<void> {
233
252
  console.info(chalk.cyan('Validating examples and default config...'))
234
253
  const uniqueTypes = [...new Set(configs.map((c) => c.type))];
@@ -246,6 +265,13 @@ export class PluginTester {
246
265
  for (const [label, exampleConfigList] of exampleEntries) {
247
266
  for (const [idx, exampleConfig] of exampleConfigList.entries()) {
248
267
  const configLabel = `resource '${type}' ${label}[${idx}]`;
268
+ // Examples can include resources of other plugins (ex: installing a prerequisite): only this plugin can
269
+ // validate its own
270
+ if (!resourceTypes.has(exampleConfig.type as string)) {
271
+ console.info(chalk.gray(`Skipping ${configLabel}: '${exampleConfig.type}' is not a resource of this plugin`));
272
+ continue;
273
+ }
274
+
249
275
  await this.validateSingleExampleConfig(plugin, configLabel, exampleConfig, errors);
250
276
  }
251
277
  }
@@ -376,19 +402,16 @@ ${JSON.stringify(modifyPlans, null, 2)}`)
376
402
  }
377
403
  }
378
404
 
405
+ /** Copies of the configs, with names added when there are several of a type (the caller's configs are kept) */
379
406
  private static addNamesToConfigs(configs: ResourceConfig[]): ResourceConfig[] {
380
407
  const configsWithNames = new Array<ResourceConfig>();
381
408
 
382
409
  const typeSet = new Set(configs.map((c) => c.type));
383
410
  for (const type of typeSet) {
384
411
  const sameTypeConfigs = configs.filter((c) => c.type === type);
385
- if (sameTypeConfigs.length > 1) {
386
- sameTypeConfigs.forEach((c, idx) => {
387
- c.name = c.name ?? idx.toString()
388
- });
389
- }
390
-
391
- configsWithNames.push(...sameTypeConfigs);
412
+ configsWithNames.push(...sameTypeConfigs.map((c, idx) => (
413
+ sameTypeConfigs.length > 1 ? { ...c, name: c.name ?? idx.toString() } : { ...c }
414
+ )));
392
415
  }
393
416
 
394
417
  return configsWithNames;