@unframework.dev/testing 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 (133) hide show
  1. package/README.md +536 -2
  2. package/dist/browser/axe.js +34 -0
  3. package/dist/browser/behaviour.js +59 -0
  4. package/dist/browser/capabilities.js +58 -0
  5. package/dist/browser/clock.d.ts +17 -0
  6. package/dist/browser/clock.js +69 -0
  7. package/dist/browser/console.d.ts +27 -0
  8. package/dist/browser/console.js +142 -0
  9. package/dist/browser/determinism.js +108 -0
  10. package/dist/browser/element-timeout.js +28 -0
  11. package/dist/browser/events.js +68 -0
  12. package/dist/browser/geometry.js +135 -0
  13. package/dist/browser/keys.js +62 -0
  14. package/dist/browser/matchers.d.ts +39 -0
  15. package/dist/browser/matchers.js +78 -0
  16. package/dist/browser/navigation.js +38 -0
  17. package/dist/browser/parity.d.ts +10 -0
  18. package/dist/browser/parity.js +93 -0
  19. package/dist/browser/spec.d.ts +25 -0
  20. package/dist/browser/spec.js +38 -0
  21. package/dist/browser/target.d.ts +16 -0
  22. package/dist/browser/target.js +27 -0
  23. package/dist/browser/text-runs.js +68 -0
  24. package/dist/browser/thrown.js +71 -0
  25. package/dist/browser/trace.d.ts +21 -0
  26. package/dist/browser/trace.js +73 -0
  27. package/dist/browser/user.d.ts +45 -0
  28. package/dist/browser/user.js +184 -0
  29. package/dist/browser/view.d.ts +114 -0
  30. package/dist/browser/view.js +282 -0
  31. package/dist/browser/visual.d.ts +20 -0
  32. package/dist/browser/visual.js +36 -0
  33. package/dist/cli.d.ts +23 -0
  34. package/dist/cli.js +90 -0
  35. package/dist/commands.d.ts +107 -0
  36. package/dist/config/broadcast.js +29 -0
  37. package/dist/config/cases.d.ts +28 -0
  38. package/dist/config/cases.js +94 -0
  39. package/dist/config/index.d.ts +82 -0
  40. package/dist/config/index.js +295 -0
  41. package/dist/config/project-vite.d.ts +40 -0
  42. package/dist/config/project-vite.js +152 -0
  43. package/dist/diff.d.ts +14 -0
  44. package/dist/diff.js +92 -0
  45. package/dist/dom/serialize.js +236 -0
  46. package/dist/errors.d.ts +13 -0
  47. package/dist/errors.js +38 -0
  48. package/dist/harness.d.ts +189 -0
  49. package/dist/harness.js +53 -0
  50. package/dist/index.d.ts +16 -0
  51. package/dist/index.js +12 -0
  52. package/dist/internal.d.ts +8 -0
  53. package/dist/internal.js +6 -0
  54. package/dist/layers.d.ts +183 -0
  55. package/dist/layers.js +241 -0
  56. package/dist/node/browser.d.ts +33 -0
  57. package/dist/node/browser.js +64 -0
  58. package/dist/node/commands.d.ts +137 -0
  59. package/dist/node/commands.js +139 -0
  60. package/dist/node/context.d.ts +28 -0
  61. package/dist/node/context.js +55 -0
  62. package/dist/node/events.d.ts +25 -0
  63. package/dist/node/events.js +50 -0
  64. package/dist/node/finished.d.ts +12 -0
  65. package/dist/node/finished.js +28 -0
  66. package/dist/node/index.d.ts +21 -0
  67. package/dist/node/index.js +20 -0
  68. package/dist/node/matrix.d.ts +219 -0
  69. package/dist/node/matrix.js +309 -0
  70. package/dist/node/mode.d.ts +103 -0
  71. package/dist/node/mode.js +204 -0
  72. package/dist/node/names.d.ts +4 -0
  73. package/dist/node/names.js +5 -0
  74. package/dist/node/policy.d.ts +44 -0
  75. package/dist/node/policy.js +140 -0
  76. package/dist/node/reporter.d.ts +101 -0
  77. package/dist/node/reporter.js +251 -0
  78. package/dist/node/summary.d.ts +99 -0
  79. package/dist/node/summary.js +352 -0
  80. package/dist/node/thrown.js +78 -0
  81. package/dist/node/viewport.d.ts +7 -0
  82. package/dist/node/viewport.js +8 -0
  83. package/dist/node/visual.d.ts +85 -0
  84. package/dist/node/visual.js +373 -0
  85. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/protocol.d.ts +23930 -0
  86. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/structs.d.ts +22 -0
  87. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/types.d.ts +22221 -0
  88. package/dist/normalize/display.js +309 -0
  89. package/dist/normalize/index.d.ts +34 -0
  90. package/dist/normalize/index.js +38 -0
  91. package/dist/normalize/pipeline.d.ts +19 -0
  92. package/dist/normalize/pipeline.js +45 -0
  93. package/dist/normalize/print.js +103 -0
  94. package/dist/normalize/rules/angular-hosts.js +53 -0
  95. package/dist/normalize/rules/aria-hosts.js +48 -0
  96. package/dist/normalize/rules/comments.js +16 -0
  97. package/dist/normalize/rules/control-values.js +65 -0
  98. package/dist/normalize/rules/engine-aliases.js +34 -0
  99. package/dist/normalize/rules/framework-attributes.js +85 -0
  100. package/dist/normalize/rules/generated-ids.js +64 -0
  101. package/dist/normalize/rules/ordering.js +39 -0
  102. package/dist/normalize/rules/qwik-styles.js +21 -0
  103. package/dist/normalize/rules/qwik-templates.js +20 -0
  104. package/dist/normalize/rules/values.js +125 -0
  105. package/dist/normalize/rules/whitespace.js +381 -0
  106. package/dist/normalize/style.js +121 -0
  107. package/dist/normalize/targets.d.ts +8 -0
  108. package/dist/normalize/targets.js +17 -0
  109. package/dist/normalize/tree.d.ts +1 -0
  110. package/dist/normalize/tree.js +151 -0
  111. package/dist/setup.d.ts +1 -0
  112. package/dist/setup.js +149 -0
  113. package/dist/ssr/index.d.ts +10 -0
  114. package/dist/ssr/index.js +103 -0
  115. package/dist/ssr/spec.d.ts +1 -0
  116. package/dist/ssr/spec.js +7 -0
  117. package/dist/targets/angular.d.ts +1 -0
  118. package/dist/targets/angular.js +5 -0
  119. package/dist/targets/astro.d.ts +1 -0
  120. package/dist/targets/astro.js +5 -0
  121. package/dist/targets/qwik.d.ts +1 -0
  122. package/dist/targets/qwik.js +5 -0
  123. package/dist/targets/react.d.ts +1 -0
  124. package/dist/targets/react.js +5 -0
  125. package/dist/targets/solid.d.ts +1 -0
  126. package/dist/targets/solid.js +5 -0
  127. package/dist/targets/svelte.d.ts +1 -0
  128. package/dist/targets/svelte.js +5 -0
  129. package/dist/targets/vue.d.ts +1 -0
  130. package/dist/targets/vue.js +5 -0
  131. package/dist/visual-types.d.ts +92 -0
  132. package/dist/visual-types.js +24 -0
  133. package/package.json +146 -3
@@ -0,0 +1,94 @@
1
+ import { COLOR_SCHEMES } from "../harness.js";
2
+ import { KEBAB_CASE } from "../node/names.js";
3
+ import { existsSync, globSync, readFileSync, readdirSync } from "node:fs";
4
+ import { dirname, join, relative, resolve, sep } from "node:path";
5
+ import { TARGET_NAMES } from "@unframework.dev/compiler";
6
+ //#region src/config/cases.ts
7
+ /** What a test file never lies in: installed packages and build output. */
8
+ const EXCLUDED = ["**/node_modules/**", "**/dist/**"];
9
+ /** The keys of a project's `case.json`: the public ones (ADR-0085). */
10
+ const CASE_KEYS = /* @__PURE__ */ new Set([
11
+ "description",
12
+ "main",
13
+ "ssr",
14
+ "axe",
15
+ "colorScheme",
16
+ "reference"
17
+ ]);
18
+ /**
19
+ * Every case under the root, sorted by id. Throws, naming the fix, on a directory with two test
20
+ * files, a case with no main source, a test file at the root itself and a malformed `case.json`:
21
+ * a case that cannot be told apart would have nowhere to go in the run.
22
+ */
23
+ function discoverCases(options) {
24
+ const files = globSync([...options.include], {
25
+ cwd: options.root,
26
+ exclude: [...EXCLUDED]
27
+ }).toSorted();
28
+ const byDirectory = /* @__PURE__ */ new Map();
29
+ for (const file of files) {
30
+ const absolute = resolve(options.root, file);
31
+ const directory = dirname(absolute);
32
+ byDirectory.set(directory, [...byDirectory.get(directory) ?? [], absolute]);
33
+ }
34
+ const cases = [];
35
+ for (const [dir, specs] of byDirectory) {
36
+ const id = relative(options.root, dir).split(sep).join("/");
37
+ if (!id) throw new Error(`[uf] ${relative(options.root, specs[0])} is at the project's root: a case is a directory, so move the test file into a directory of its own, such as test/<name>/.`);
38
+ if (specs.length > 1) throw new Error(`[uf] Case ${id} holds ${specs.length} test files (${specs.map((spec) => relative(dir, spec)).join(", ")}): a case is a directory with one test file, so give each its own directory.`);
39
+ const config = readCaseConfig(id, join(dir, "case.json"));
40
+ cases.push({
41
+ id,
42
+ dir,
43
+ spec: specs[0],
44
+ source: mainSource(id, dir, config.main),
45
+ config
46
+ });
47
+ }
48
+ return cases.toSorted((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
49
+ }
50
+ /**
51
+ * A case's main source: `main`, relative to the case's directory, or the directory's only
52
+ * `.uf.tsx`.
53
+ */
54
+ function mainSource(id, dir, main) {
55
+ if (main !== void 0) {
56
+ const source = resolve(dir, main);
57
+ if (!main.endsWith(".uf.tsx") || !existsSync(source)) throw new Error(`[uf] Case ${id}: case.json's "main" names ${JSON.stringify(main)}, which is no .uf.tsx file relative to the case's directory. Point it at the component the test mounts, such as "../../src/Button.uf.tsx".`);
58
+ return source;
59
+ }
60
+ const inputs = readdirSync(dir).filter((file) => file.endsWith(".uf.tsx"));
61
+ if (inputs.length === 1) return join(dir, inputs[0]);
62
+ throw new Error(inputs.length ? `[uf] Case ${id} holds ${inputs.join(", ")}: name the one the test mounts in case.json, "main": "${inputs[0]}".` : `[uf] Case ${id} has no main source: add a .uf.tsx beside its test, or name the component in case.json, "main": "../../src/Button.uf.tsx".`);
63
+ }
64
+ /** A case's `case.json`, checked: `{}` when it has none. */
65
+ function readCaseConfig(id, file) {
66
+ if (!existsSync(file)) return {};
67
+ let config;
68
+ try {
69
+ config = JSON.parse(readFileSync(file, "utf8"));
70
+ } catch (error) {
71
+ throw new Error(`[uf] Case ${id}: case.json is not JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
72
+ }
73
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new Error(`[uf] Case ${id}: case.json must hold an object.`);
74
+ const record = config;
75
+ const problems = [];
76
+ for (const key of Object.keys(record)) if (!CASE_KEYS.has(key)) problems.push(`unknown key "${key}" (it takes ${[...CASE_KEYS].join(", ")})`);
77
+ if (record.description !== void 0 && typeof record.description !== "string") problems.push(`"description" must be a string`);
78
+ if (record.main !== void 0 && typeof record.main !== "string") problems.push(`"main" must be the path of a .uf.tsx file, relative to the case`);
79
+ if (record.reference !== void 0 && !TARGET_NAMES.includes(record.reference)) problems.push(`"reference" must name a target: ${TARGET_NAMES.join(", ")}`);
80
+ if (record.colorScheme !== void 0 && !COLOR_SCHEMES.includes(record.colorScheme)) problems.push(`"colorScheme" must be one of ${COLOR_SCHEMES.map((s) => `"${s}"`).join(", ")}`);
81
+ if (record.axe !== void 0 && (!Array.isArray(record.axe) || record.axe.some((rule) => typeof rule !== "string"))) problems.push(`"axe" must be a list of axe rule ids`);
82
+ if (record.ssr !== void 0) {
83
+ if (typeof record.ssr !== "object" || record.ssr === null || Array.isArray(record.ssr)) problems.push(`"ssr" must map scenario names to { "props": {…} }`);
84
+ else for (const [scenario, value] of Object.entries(record.ssr)) {
85
+ if (!KEBAB_CASE.test(scenario)) problems.push(`SSR scenario "${scenario}", which is not kebab-case`);
86
+ const props = value?.props;
87
+ if (typeof value !== "object" || value === null || Array.isArray(value) || props !== void 0 && (typeof props !== "object" || props === null || Array.isArray(props))) problems.push(`SSR scenario "${scenario}" must be { "props": {…} }`);
88
+ }
89
+ }
90
+ if (problems.length) throw new Error(`[uf] Case ${id}: case.json has ${problems.join("; ")}.`);
91
+ return record;
92
+ }
93
+ //#endregion
94
+ export { EXCLUDED, discoverCases, readCaseConfig };
@@ -0,0 +1,82 @@
1
+ import { PixelMode } from "../harness.js";
2
+ import { DiscoverOptions, ProjectCase, discoverCases } from "./cases.js";
3
+ import { OWNED_KEYS, OWNED_SERVER_KEYS, PASS_THROUGH_DECLARATIONS, ProjectPlugins, ProjectVite, passThroughDeclarations, projectPlugins, withProjectVite } from "./project-vite.js";
4
+ import { TargetName } from "@unframework.dev/compiler";
5
+ import { ViteUserConfig } from "vitest/config";
6
+ import { Toolchain } from "@unframework.dev/codegen";
7
+ //#region src/config/index.d.ts
8
+ /** The options of {@link defineTestConfig}. */
9
+ export interface TestConfigOptions {
10
+ /** The targets to test: `unframework.config.ts`'s `targets` by default. */
11
+ targets?: readonly TargetName[];
12
+ /** Globs of test files, relative to the root: `["**\/*.test.ts"]` by default. */
13
+ include?: readonly string[];
14
+ /**
15
+ * The target that writes the shared expectations, which every other target must match: `vue`
16
+ * when the project tests it, the first target otherwise. It always joins the run.
17
+ */
18
+ reference?: TargetName;
19
+ /**
20
+ * What pixels compare with: `live`, every target against the reference's capture in the same
21
+ * run, by default, in CI too; or `baseline`, committed baselines, which only the baseline image
22
+ * writes.
23
+ */
24
+ pixels?: PixelMode;
25
+ /**
26
+ * Where a target's compiler stack resolves from, such as Angular's: `package.resolveFrom` in
27
+ * `unframework.config.ts` by default, then the root.
28
+ */
29
+ toolchainDirs?: Partial<Record<TargetName, string>>;
30
+ /** The project's root, where `unframework.config.ts` lies: the working directory by default. */
31
+ root?: string;
32
+ }
33
+ /** The test files a project's run finds by default. */
34
+ export declare const DEFAULT_INCLUDE: readonly string[];
35
+ /**
36
+ * This package's modules, wherever a project installs it: the server render comparison imports
37
+ * each case's main source, which must go through the project's Vite pipeline.
38
+ */
39
+ export declare const TESTING_PACKAGE: RegExp;
40
+ /**
41
+ * The target packages' modules, wherever a project installs them: a server renderer imports its
42
+ * framework, which must be the copy the component the project's Vite pipeline compiles imports.
43
+ */
44
+ export declare const TARGET_PACKAGES: RegExp;
45
+ /**
46
+ * The Vitest configuration of a project's tests: one `browser:<target>` project in Chromium and
47
+ * one `ssr:<target>` project per target, with the reference ordered first. `UF_TARGETS` narrows
48
+ * the targets (`unframework test --target`), and `UF_UPDATE=1` writes the expectations
49
+ * (`--update`). Throws, naming the fix, on an invalid configuration, an unknown target, a case it
50
+ * cannot tell apart and a toolchain that cannot load: a check that cannot start fails.
51
+ */
52
+ export declare function defineTestConfig(options?: TestConfigOptions): Promise<ViteUserConfig>;
53
+ /**
54
+ * The targets `UF_TARGETS` selects (`unframework test --target`), every one of the project's when
55
+ * it is unset. A name outside the project's targets throws, so a typo never tests nothing.
56
+ */
57
+ export declare function selectedTargets(value: string | undefined, targets: readonly TargetName[]): TargetName[];
58
+ /**
59
+ * The targets a run tests, in the project's order: the selected ones, and the reference and every
60
+ * target a case names as its own, which write the expectations and the live captures the others
61
+ * compare with (ADR-0057), so they always join.
62
+ */
63
+ export declare function runTargets(targets: readonly TargetName[], selected: readonly TargetName[], writers: readonly TargetName[]): TargetName[];
64
+ /**
65
+ * Where a target's compiler stack resolves from: `toolchainDirs`, relative to the root, then
66
+ * `package.resolveFrom`, which `resolveConfig` has made absolute, then the root (A9).
67
+ */
68
+ export declare function toolchainDirOf(target: TargetName, root: string, toolchainDirs: TestConfigOptions["toolchainDirs"], resolveFrom: string | Partial<Record<TargetName, string>> | undefined): string;
69
+ /**
70
+ * Loads a target's toolchain, refusing one of another name. It loads from this package, which
71
+ * depends on every target, so a project need not install the target packages itself: the
72
+ * preview (`@unframework.dev/visual`) builds its servers from it too.
73
+ */
74
+ export declare function loadToolchain(target: TargetName): Promise<Toolchain>;
75
+ /**
76
+ * The file of a toolchain's browser mount adapter (`toolchain.client`), resolved from this
77
+ * package, which depends on the target: a Vite server outside the test projects imports it by
78
+ * path, since the project need not install the target package (pnpm keeps it out of reach).
79
+ */
80
+ export declare function toolchainClientFile(toolchain: Toolchain): string;
81
+ //#endregion
82
+ export { type DiscoverOptions, OWNED_KEYS, OWNED_SERVER_KEYS, PASS_THROUGH_DECLARATIONS, type ProjectCase, type ProjectPlugins, type ProjectVite, discoverCases, passThroughDeclarations, projectPlugins, withProjectVite };
@@ -0,0 +1,295 @@
1
+ import { caseReferences } from "../harness.js";
2
+ import { recordCompiledModule } from "../node/events.js";
3
+ import { createHarnessRun, groupOrder, resolveHarnessMode } from "../node/mode.js";
4
+ import { parityBrowser } from "../node/browser.js";
5
+ import { ufMapStack } from "../node/thrown.js";
6
+ import { noErrorBroadcast } from "./broadcast.js";
7
+ import { EXCLUDED, discoverCases } from "./cases.js";
8
+ import { OWNED_KEYS, OWNED_SERVER_KEYS, PASS_THROUGH_DECLARATIONS, passThroughDeclarations, projectPlugins, withProjectVite } from "./project-vite.js";
9
+ import { realpathSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ import { TARGET_NAMES, builtinTargets, loadConfig, resolveConfig } from "@unframework.dev/compiler";
12
+ import { fileURLToPath } from "node:url";
13
+ import { mergeConfig } from "vitest/config";
14
+ //#region src/config/index.ts
15
+ /** The test files a project's run finds by default. */
16
+ const DEFAULT_INCLUDE = ["**/*.test.ts"];
17
+ /**
18
+ * This package's modules, wherever a project installs it: the server render comparison imports
19
+ * each case's main source, which must go through the project's Vite pipeline.
20
+ */
21
+ const TESTING_PACKAGE = /[\\/]node_modules[\\/]@unframework\.dev[\\/]testing[\\/]/;
22
+ /**
23
+ * The target packages' modules, wherever a project installs them: a server renderer imports its
24
+ * framework, which must be the copy the component the project's Vite pipeline compiles imports.
25
+ */
26
+ const TARGET_PACKAGES = /[\\/]node_modules[\\/]@unframework\.dev[\\/]target-[a-z]+[\\/]/;
27
+ /** How long a test runs at most: a cold browser project's first mount compiles its framework. */
28
+ const TEST_TIMEOUT = 6e4;
29
+ /**
30
+ * The Vitest configuration of a project's tests: one `browser:<target>` project in Chromium and
31
+ * one `ssr:<target>` project per target, with the reference ordered first. `UF_TARGETS` narrows
32
+ * the targets (`unframework test --target`), and `UF_UPDATE=1` writes the expectations
33
+ * (`--update`). Throws, naming the fix, on an invalid configuration, an unknown target, a case it
34
+ * cannot tell apart and a toolchain that cannot load: a check that cannot start fails.
35
+ */
36
+ async function defineTestConfig(options = {}) {
37
+ const root = realpathSync(options.root ?? process.cwd());
38
+ const config = await projectConfig(root);
39
+ const targets = options.targets ?? config.targets;
40
+ checkTargets("targets", targets, TARGET_NAMES);
41
+ const reference = options.reference ?? (targets.includes("vue") ? "vue" : targets[0]);
42
+ if (reference === void 0) throw new Error("[uf] defineTestConfig: the project has no target.");
43
+ checkTargets("reference", [reference], targets);
44
+ const mode = resolveHarnessMode({
45
+ env: process.env,
46
+ platform: process.platform,
47
+ argv: process.env.UF_TEST_CLI === "1" ? [] : process.argv,
48
+ project: { pixels: options.pixels ?? "live" }
49
+ });
50
+ if (mode.browser !== "chromium") throw new Error(`[uf] A project's tests run in Chromium alone: UF_BROWSER=${mode.browser} cannot apply.`);
51
+ const include = options.include ?? DEFAULT_INCLUDE;
52
+ const cases = discoverCases({
53
+ root,
54
+ include
55
+ });
56
+ if (!cases.length) throw new Error(`[uf] No test file under ${root} matches ${include.join(", ")}: a case is a directory with one test file, such as test/button/button.test.ts.`);
57
+ const harness = createHarnessRun({
58
+ root,
59
+ casesDir: root,
60
+ reference,
61
+ mode,
62
+ quarantine: [],
63
+ cases: Object.fromEntries(cases.map((info) => [info.id, info.config])),
64
+ updateCommand: "unframework test --update",
65
+ liveFonts: config.liveFonts
66
+ });
67
+ const named = caseReferences(harness);
68
+ checkTargets("a case's reference", named, targets);
69
+ const run = runTargets(targets, selectedTargets(process.env.UF_TARGETS, targets), [reference, ...named]);
70
+ const setup = {
71
+ root,
72
+ harness,
73
+ mode,
74
+ cases,
75
+ targets: run,
76
+ toolchainDir: (target) => toolchainDirOf(target, root, options.toolchainDirs, config.package?.resolveFrom),
77
+ vite: config.vite,
78
+ declarations: passThroughDeclarations(root)
79
+ };
80
+ return { test: { projects: await Promise.all(run.flatMap((target) => [browserProject(setup, target), ssrProject(setup, target)])) } };
81
+ }
82
+ /** The project's `unframework.config.ts`, resolved, or an error that lists its diagnostics. */
83
+ async function projectConfig(root) {
84
+ const loaded = await loadConfig(root);
85
+ const resolved = loaded.raw === void 0 ? {
86
+ config: void 0,
87
+ diagnostics: []
88
+ } : await resolveConfig(loaded.raw, loaded);
89
+ const diagnostics = [...loaded.diagnostics, ...resolved.diagnostics];
90
+ if (!resolved.config || diagnostics.some((each) => each.severity === "error")) throw new Error(`[uf] ${loaded.file ?? "unframework.config.ts"} is invalid:\n ${diagnostics.map((each) => `${each.code} ${each.message}`).join("\n ")}`);
91
+ return resolved.config;
92
+ }
93
+ /** Throws unless every name is one of `allowed`. */
94
+ function checkTargets(what, names, allowed) {
95
+ const unknown = names.filter((name) => !allowed.includes(name));
96
+ if (unknown.length) throw new Error(`[uf] defineTestConfig: ${what} names ${unknown.join(", ")}, which ${unknown.length > 1 ? "are" : "is"} not among ${allowed === TARGET_NAMES ? "the targets" : "the project's targets"} (${allowed.join(", ")}).`);
97
+ }
98
+ /**
99
+ * The targets `UF_TARGETS` selects (`unframework test --target`), every one of the project's when
100
+ * it is unset. A name outside the project's targets throws, so a typo never tests nothing.
101
+ */
102
+ function selectedTargets(value, targets) {
103
+ if (!value?.trim()) return [...targets];
104
+ const requested = value.split(",").map((name) => name.trim()).filter(Boolean);
105
+ const unknown = requested.filter((name) => !targets.includes(name));
106
+ if (unknown.length) throw new Error(`[uf] UF_TARGETS names ${unknown.join(", ")}, which ${unknown.length > 1 ? "are" : "is"} not among the project's targets (${targets.join(", ")}).`);
107
+ return targets.filter((name) => requested.includes(name));
108
+ }
109
+ /**
110
+ * The targets a run tests, in the project's order: the selected ones, and the reference and every
111
+ * target a case names as its own, which write the expectations and the live captures the others
112
+ * compare with (ADR-0057), so they always join.
113
+ */
114
+ function runTargets(targets, selected, writers) {
115
+ return targets.filter((name) => selected.includes(name) || writers.includes(name));
116
+ }
117
+ /**
118
+ * Where a target's compiler stack resolves from: `toolchainDirs`, relative to the root, then
119
+ * `package.resolveFrom`, which `resolveConfig` has made absolute, then the root (A9).
120
+ */
121
+ function toolchainDirOf(target, root, toolchainDirs, resolveFrom) {
122
+ const own = toolchainDirs?.[target];
123
+ if (own !== void 0) return resolve(root, own);
124
+ return (typeof resolveFrom === "string" ? resolveFrom : resolveFrom?.[target]) ?? root;
125
+ }
126
+ function group(setup, kind, target) {
127
+ return groupOrder(kind, target, setup.mode, setup.harness.reference, caseReferences(setup.harness), setup.targets);
128
+ }
129
+ /** Each target's toolchain, loaded when its projects are built, so a run loads only its own. */
130
+ const TOOLCHAINS = {
131
+ react: () => import("@unframework.dev/target-react/toolchain"),
132
+ vue: () => import("@unframework.dev/target-vue/toolchain"),
133
+ svelte: () => import("@unframework.dev/target-svelte/toolchain"),
134
+ solid: () => import("@unframework.dev/target-solid/toolchain"),
135
+ angular: () => import("@unframework.dev/target-angular/toolchain"),
136
+ qwik: () => import("@unframework.dev/target-qwik/toolchain"),
137
+ astro: () => import("@unframework.dev/target-astro/toolchain")
138
+ };
139
+ /**
140
+ * Loads a target's toolchain, refusing one of another name. It loads from this package, which
141
+ * depends on every target, so a project need not install the target packages itself: the
142
+ * preview (`@unframework.dev/visual`) builds its servers from it too.
143
+ */
144
+ async function loadToolchain(target) {
145
+ let module;
146
+ try {
147
+ module = await TOOLCHAINS[target]();
148
+ } catch (error) {
149
+ throw new Error(`[uf] The ${target} toolchain (@unframework.dev/target-${target}/toolchain) could not be loaded: install the ${target} framework and its Vite plugin.`, { cause: error });
150
+ }
151
+ const toolchain = module.toolchain ?? module.default;
152
+ if (!toolchain || toolchain.name !== target) throw new Error(`[uf] @unframework.dev/target-${target}/toolchain must export \`toolchain\` with name "${target}".`);
153
+ return toolchain;
154
+ }
155
+ async function unpluginOf(target) {
156
+ const { default: unframework } = await import("@unframework.dev/unplugin/vite");
157
+ return unframework({
158
+ target,
159
+ onCompile: (event) => recordCompiledModule(event)
160
+ });
161
+ }
162
+ /**
163
+ * Where a target's toolchain runs the project's tests: Angular's ngtsc compiles with the
164
+ * pass-through declarations, and a server of the toolchain's own (Astro's render server) loads
165
+ * the project's plugins for the same target and kind of server (ADR-0104).
166
+ */
167
+ function toolchainContext(setup, target, mode) {
168
+ return {
169
+ toolchainDir: setup.toolchainDir(target),
170
+ root: setup.root,
171
+ declarations: setup.declarations,
172
+ plugins: projectPlugins(setup.vite, {
173
+ target,
174
+ mode
175
+ })
176
+ };
177
+ }
178
+ /**
179
+ * A project's `test` options: the defaults, then the toolchain's own, then the options this
180
+ * configuration owns. A toolchain that sets an owned option throws, as in the harness; setup files
181
+ * add up, this configuration's first.
182
+ */
183
+ function projectTest(target, fragment, defaults, owned) {
184
+ const toolchain = fragment ?? {};
185
+ const taken = Object.keys(toolchain).filter((key) => key !== "setupFiles" && key in owned);
186
+ if (taken.length) throw new Error(`[uf] The ${target} toolchain's Vite configuration sets ${taken.map((key) => `test.${key}`).join(", ")}, which defineTestConfig owns.`);
187
+ const setupFiles = [owned.setupFiles ?? [], toolchain.setupFiles ?? []].flat();
188
+ return {
189
+ ...defaults,
190
+ ...toolchain,
191
+ ...owned,
192
+ ...setupFiles.length ? { setupFiles } : {}
193
+ };
194
+ }
195
+ function resolveModule(specifier) {
196
+ return fileURLToPath(import.meta.resolve(specifier));
197
+ }
198
+ /**
199
+ * The file of a toolchain's browser mount adapter (`toolchain.client`), resolved from this
200
+ * package, which depends on the target: a Vite server outside the test projects imports it by
201
+ * path, since the project need not install the target package (pnpm keeps it out of reach).
202
+ */
203
+ function toolchainClientFile(toolchain) {
204
+ return resolveModule(toolchain.client);
205
+ }
206
+ async function browserProject(setup, target) {
207
+ const name = `browser:${target}`;
208
+ const toolchain = await loadToolchain(target);
209
+ const context = toolchainContext(setup, target, "browser");
210
+ const fragment = await toolchain.vite("browser", context);
211
+ return {
212
+ ...await withProjectVite(mergeConfig({
213
+ root: setup.root,
214
+ plugins: [...await unpluginOf(target), noErrorBroadcast()],
215
+ optimizeDeps: {
216
+ include: ["@unframework.dev/testing > axe-core", "@unframework.dev/testing > parse5"],
217
+ exclude: ["@unframework.dev/testing", "@unframework.dev/target-qwik"]
218
+ }
219
+ }, fragment), setup.vite, {
220
+ target,
221
+ mode: "browser"
222
+ }),
223
+ extends: false,
224
+ test: projectTest(target, fragment.test, {
225
+ testTimeout: TEST_TIMEOUT,
226
+ expect: {
227
+ poll: { timeout: 5e3 },
228
+ requireAssertions: true
229
+ }
230
+ }, {
231
+ name,
232
+ root: setup.root,
233
+ include: setup.cases.map((info) => info.spec),
234
+ exclude: [...EXCLUDED],
235
+ setupFiles: [resolveModule("@unframework.dev/testing/setup"), resolveModule(`@unframework.dev/testing/${target}`)],
236
+ provide: {
237
+ target,
238
+ ufHarness: setup.harness,
239
+ ufCapabilities: builtinTargets[target].capabilities,
240
+ ufNoOutput: {}
241
+ },
242
+ sequence: { groupOrder: group(setup, "browser", target) },
243
+ browser: {
244
+ ...parityBrowser({
245
+ name,
246
+ commands: {
247
+ ...toolchain.browserCommands?.(context),
248
+ ufMapStack
249
+ }
250
+ }),
251
+ screenshotDirectory: join(setup.root, ".reports", "failures")
252
+ }
253
+ })
254
+ };
255
+ }
256
+ async function ssrProject(setup, target) {
257
+ const toolchain = await loadToolchain(target);
258
+ const fragment = await toolchain.vite("ssr", toolchainContext(setup, target, "ssr"));
259
+ const config = await withProjectVite(mergeConfig({
260
+ root: setup.root,
261
+ plugins: await unpluginOf(target)
262
+ }, fragment), setup.vite, {
263
+ target,
264
+ mode: "ssr"
265
+ });
266
+ const cases = setup.cases.map((info) => ({
267
+ id: info.id,
268
+ dir: info.dir,
269
+ source: info.source
270
+ }));
271
+ return {
272
+ ...config,
273
+ extends: false,
274
+ test: projectTest(target, fragment.test, {
275
+ environment: "node",
276
+ pool: "forks",
277
+ testTimeout: TEST_TIMEOUT
278
+ }, {
279
+ name: `ssr:${target}`,
280
+ root: setup.root,
281
+ include: [resolveModule("@unframework.dev/testing/ssr/spec")],
282
+ exclude: [],
283
+ server: { deps: { inline: [TESTING_PACKAGE, TARGET_PACKAGES] } },
284
+ provide: {
285
+ target,
286
+ ufHarness: setup.harness,
287
+ ufServer: toolchain.server,
288
+ ufSsrCases: cases
289
+ },
290
+ sequence: { groupOrder: group(setup, "ssr", target) }
291
+ })
292
+ };
293
+ }
294
+ //#endregion
295
+ export { DEFAULT_INCLUDE, OWNED_KEYS, OWNED_SERVER_KEYS, PASS_THROUGH_DECLARATIONS, TARGET_PACKAGES, TESTING_PACKAGE, defineTestConfig, discoverCases, loadToolchain, passThroughDeclarations, projectPlugins, runTargets, selectedTargets, toolchainClientFile, toolchainDirOf, withProjectVite };
@@ -0,0 +1,40 @@
1
+ import { UnframeworkConfig, ViteContext } from "@unframework.dev/compiler";
2
+ import { ToolchainContext } from "@unframework.dev/codegen";
3
+ //#region src/config/project-vite.d.ts
4
+ /** The project's `vite` function, as `unframework.config.ts` gives it. */
5
+ export type ProjectVite = UnframeworkConfig["vite"];
6
+ /** What `ToolchainContext.plugins` takes: a function that makes a fresh set of Vite plugins. */
7
+ export type ProjectPlugins = NonNullable<ToolchainContext["plugins"]>;
8
+ /**
9
+ * The keys every server sets for itself, which the project's config may not set: its root, its
10
+ * caches, its Vitest options, and the preview's refusal to load a Vite config of its own or to
11
+ * listen beyond this machine (ADR-0088).
12
+ */
13
+ export declare const OWNED_KEYS: readonly string[];
14
+ /**
15
+ * The `server` keys every server sets for itself: the preview listens on `127.0.0.1` alone, and an
16
+ * HMR server of its own (`server.hmr`) would open a WebSocket server that listens beyond it.
17
+ */
18
+ export declare const OWNED_SERVER_KEYS: readonly string[];
19
+ /**
20
+ * A server's config with the project's merged in (ADR-0104): the project's plugins first, before
21
+ * the unframework plugin, and every other key merged after the server's own with Vite's
22
+ * `mergeConfig`, so a list such as `optimizeDeps.include` adds to the server's.
23
+ */
24
+ export declare function withProjectVite<T extends object>(config: T, vite: ProjectVite, context: ViteContext): Promise<T>;
25
+ /**
26
+ * The project's plugins for one server, as `ToolchainContext.plugins` takes them: each call makes
27
+ * a fresh set for a server of the toolchain's own, such as Astro's render server, which takes
28
+ * the plugins alone.
29
+ */
30
+ export declare function projectPlugins(vite: ProjectVite, context: ViteContext): ProjectPlugins;
31
+ /** The declaration file's contents: one wildcard module for each pass-through prefix. */
32
+ export declare const PASS_THROUGH_DECLARATIONS: string;
33
+ /**
34
+ * The declarations every toolchain reads beside the outputs (`ToolchainContext.declarations`):
35
+ * one file, written under the root's `node_modules/.cache/unframework/`, since the packages ship
36
+ * `dist` alone. It is written only when it differs, through a rename, so runs that share a root
37
+ * never read half of it.
38
+ */
39
+ export declare function passThroughDeclarations(root: string): string[];
40
+ //#endregion
@@ -0,0 +1,152 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { DEFAULT_PASS_THROUGH } from "@unframework.dev/compiler";
4
+ import { mergeConfig } from "vitest/config";
5
+ //#region src/config/project-vite.ts
6
+ /**
7
+ * The keys every server sets for itself, which the project's config may not set: its root, its
8
+ * caches, its Vitest options, and the preview's refusal to load a Vite config of its own or to
9
+ * listen beyond this machine (ADR-0088).
10
+ */
11
+ const OWNED_KEYS = [
12
+ "root",
13
+ "base",
14
+ "cacheDir",
15
+ "test",
16
+ "configFile",
17
+ "envDir"
18
+ ];
19
+ /**
20
+ * The `server` keys every server sets for itself: the preview listens on `127.0.0.1` alone, and an
21
+ * HMR server of its own (`server.hmr`) would open a WebSocket server that listens beyond it.
22
+ */
23
+ const OWNED_SERVER_KEYS = [
24
+ "host",
25
+ "port",
26
+ "strictPort",
27
+ "hmr"
28
+ ];
29
+ /** Where every message about the field points. */
30
+ const FIELD = "vite in unframework.config.ts";
31
+ /**
32
+ * Calls the project's `vite` for one server, and checks what it gives. Throws, naming the field
33
+ * and the reason, when it throws, a promise it gives rejects, it gives something that is no
34
+ * config or no plugin, or it sets a key the server owns: a check that cannot start fails, and
35
+ * says why.
36
+ */
37
+ async function serverConfig(vite, context) {
38
+ if (!vite) return {
39
+ plugins: [],
40
+ rest: {}
41
+ };
42
+ let made;
43
+ try {
44
+ made = await vite(context);
45
+ } catch (error) {
46
+ throw failed("threw", error);
47
+ }
48
+ if (typeof made !== "object" || made === null || Array.isArray(made)) throw new Error(`[uf] ${FIELD} gave ${describeValue(made)}, which is no Vite config: return an object, such as \`{ plugins: [engine()] }\`.`);
49
+ const { plugins, ...rest } = made;
50
+ const owned = OWNED_KEYS.filter((key) => key in rest);
51
+ const server = rest.server;
52
+ if ("server" in rest && (typeof server !== "object" || server === null || Array.isArray(server))) throw new Error(`[uf] ${FIELD} gives \`server\` as ${describeValue(server)}, which is no object: give the server keys it may set, such as \`{ fs: { allow: [".."] } }\`.`);
53
+ if (server) {
54
+ const keys = Object.keys(server);
55
+ owned.push(...OWNED_SERVER_KEYS.filter((key) => keys.includes(key)).map((key) => `server.${key}`));
56
+ }
57
+ if (owned.length) throw new Error(`[uf] ${FIELD} sets ${owned.map((key) => `\`${key}\``).join(", ")}, which the ${context.mode} server for ${context.target} sets itself: leave ${owned.length > 1 ? "them" : "it"} out.`);
58
+ return {
59
+ plugins: await flattenPlugins(plugins),
60
+ rest
61
+ };
62
+ }
63
+ /**
64
+ * A server's config with the project's merged in (ADR-0104): the project's plugins first, before
65
+ * the unframework plugin, and every other key merged after the server's own with Vite's
66
+ * `mergeConfig`, so a list such as `optimizeDeps.include` adds to the server's.
67
+ */
68
+ async function withProjectVite(config, vite, context) {
69
+ const project = await serverConfig(vite, context);
70
+ const own = config.plugins;
71
+ return {
72
+ ...mergeConfig(config, project.rest),
73
+ plugins: [...project.plugins, ...Array.isArray(own) ? own : []]
74
+ };
75
+ }
76
+ /**
77
+ * The project's plugins for one server, as `ToolchainContext.plugins` takes them: each call makes
78
+ * a fresh set for a server of the toolchain's own, such as Astro's render server, which takes
79
+ * the plugins alone.
80
+ */
81
+ function projectPlugins(vite, context) {
82
+ return async () => (await serverConfig(vite, context)).plugins;
83
+ }
84
+ /** A plugin option in any shape Vite's `plugins` takes, flattened: read as `unknown`, since the project's code gives it. */
85
+ async function flattenPlugins(option) {
86
+ let value;
87
+ try {
88
+ value = await option;
89
+ } catch (error) {
90
+ throw failed("gave a promise that rejected", error);
91
+ }
92
+ if (value === false || value === null || value === void 0) return [];
93
+ if (Array.isArray(value)) return (await Promise.all(value.map((each) => flattenPlugins(each)))).flat();
94
+ if (typeof value !== "object" || typeof value.name !== "string") throw new Error(`[uf] ${FIELD} gave ${describeValue(value)} among its plugins, which is no Vite plugin: a plugin is an object with a name.`);
95
+ return [value];
96
+ }
97
+ /**
98
+ * The error of a function or a promise of the field's that failed. The CLI prints a message
99
+ * alone, so the reason is in it, as well as in `cause`.
100
+ */
101
+ function failed(what, error) {
102
+ const reason = error instanceof Error ? String(error.message) || "an error with no message" : describeValue(error);
103
+ return new Error(`[uf] ${FIELD} ${what}: ${reason}`, { cause: error });
104
+ }
105
+ /** A value as a message names it, whatever it is. */
106
+ function describeValue(value) {
107
+ switch (typeof value) {
108
+ case "string": return JSON.stringify(value);
109
+ case "object":
110
+ if (value === null) return "null";
111
+ if (Array.isArray(value)) return "a list";
112
+ return "name" in value ? "an object whose name is no string" : "an object without a name";
113
+ case "function": return "a function";
114
+ case "symbol": return value.toString();
115
+ case "number":
116
+ case "bigint":
117
+ case "boolean": return `${value}`;
118
+ default: return "undefined";
119
+ }
120
+ }
121
+ /** The declaration file's contents: one wildcard module for each pass-through prefix. */
122
+ const PASS_THROUGH_DECLARATIONS = [
123
+ "// Written by @unframework.dev/testing (ADR-0104): Angular's compile in `unframework test`,",
124
+ "// `visual` and `preview` takes any module that passes through as written. The project's own",
125
+ "// source check (tsconfig.uf.json) reads the real types.",
126
+ ...DEFAULT_PASS_THROUGH.map((prefix) => `declare module "${prefix}*";`),
127
+ ""
128
+ ].join("\n");
129
+ /**
130
+ * The declarations every toolchain reads beside the outputs (`ToolchainContext.declarations`):
131
+ * one file, written under the root's `node_modules/.cache/unframework/`, since the packages ship
132
+ * `dist` alone. It is written only when it differs, through a rename, so runs that share a root
133
+ * never read half of it.
134
+ */
135
+ function passThroughDeclarations(root) {
136
+ const file = join(root, "node_modules", ".cache", "unframework", "pass-through.d.ts");
137
+ let current;
138
+ try {
139
+ current = readFileSync(file, "utf8");
140
+ } catch {
141
+ current = void 0;
142
+ }
143
+ if (current !== PASS_THROUGH_DECLARATIONS) {
144
+ mkdirSync(dirname(file), { recursive: true });
145
+ const temporary = `${file}.${process.pid}.tmp`;
146
+ writeFileSync(temporary, PASS_THROUGH_DECLARATIONS);
147
+ renameSync(temporary, file);
148
+ }
149
+ return [file];
150
+ }
151
+ //#endregion
152
+ export { OWNED_KEYS, OWNED_SERVER_KEYS, PASS_THROUGH_DECLARATIONS, passThroughDeclarations, projectPlugins, withProjectVite };