@spfx-fast/playwright 0.0.0-stage → 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +123 -2
- package/agent/PLAYWRIGHT.md +32 -0
- package/bin/spfx-fast-playwright.mjs +201 -0
- package/examples/sharepoint-smoke.recipe.json +9 -0
- package/examples/tenant-crud-validation.recipe.json +11 -0
- package/package.json +21 -4
- package/src/index.d.ts +35 -0
- package/src/index.js +185 -0
- package/src/profile-lock.js +72 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vilius Vystartas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spfx-fast/playwright
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
Playwright helpers for any SPFx project. This dev tool stays out of the web-part bundle and uses the approved signed-in test browser. It does not depend on `@spfx-fast/core` or a UI framework.
|
|
4
|
+
|
|
5
|
+
It adds agent-friendly recipes, same-origin navigation, and authenticated runs with reviewable evidence. Playwright provides the test runner, locators, recorder, traces, and screenshots.
|
|
6
|
+
|
|
7
|
+
## Install in an SPFx project
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-dev @spfx-fast/playwright @playwright/test playwright
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
SPFx is not a dependency. Production web parts do not import this package by default.
|
|
14
|
+
|
|
15
|
+
Scaffold a serial Playwright setup with a starter recipe, generated test spec, agent instructions, screenshots, traces, and an ignored auth-state folder:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx spfx-fast-playwright init
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The config uses storage state only when `SPFX_STORAGE_STATE` is set. Keep it in an ignored folder; never commit it. The scaffold adds `SPFX-PLAYWRIGHT.md` and links it from `AGENTS.md` without replacing existing instructions.
|
|
22
|
+
|
|
23
|
+
## Record a test with the Playwright recorder
|
|
24
|
+
|
|
25
|
+
Use a dedicated signed-in test profile. The command calls Playwright Codegen and writes an ordinary Playwright spec:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npx spfx-fast-playwright record \
|
|
29
|
+
--url "$SPFX_BASE_URL" \
|
|
30
|
+
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
31
|
+
--out tests/e2e/home-page.spec.ts
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Review selectors and add business assertions; Codegen records actions only.
|
|
35
|
+
|
|
36
|
+
## Generate a test mechanically from a small recipe
|
|
37
|
+
|
|
38
|
+
Edit the scaffolded `tests/e2e/sharepoint-smoke.recipe.json` for the target site, then:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
npx spfx-fast-playwright validate tests/e2e/sharepoint-smoke.recipe.json
|
|
42
|
+
npx spfx-fast-playwright generate tests/e2e/sharepoint-smoke.recipe.json --out tests/e2e/sharepoint-smoke.spec.mjs --force
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`init` already creates a spec at that output path; `--force` regenerates it from the edited recipe.
|
|
46
|
+
|
|
47
|
+
The output is a normal Playwright Test spec. Run it with the project's `SPFX_BASE_URL` and `storageState`:
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
SPFX_BASE_URL="https://tenant.sharepoint.com/sites/your-site" npx playwright test
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Keep state files out of source control. They contain impersonation-capable session data. Use a dedicated least-privilege account and test site.
|
|
54
|
+
|
|
55
|
+
## Run a recipe with a persistent authenticated browser profile
|
|
56
|
+
|
|
57
|
+
This path is useful when a team already has a signed-in Playwright profile and does not want to export its storage state:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
npx spfx-fast-playwright run tests/e2e/sharepoint-smoke.recipe.json \
|
|
61
|
+
--base-url "$SPFX_BASE_URL" \
|
|
62
|
+
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
63
|
+
--artifacts test-results/sharepoint-smoke
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Runs headless, enforces the origin, and saves requested screenshots, a trace, and `summary.json`. Use `--headed` to debug. The command locks the profile and releases it after browser exit. It does not sign in, inspect cookies, or copy/remove profile files.
|
|
67
|
+
|
|
68
|
+
Use `--fast` during fix loops: assertions remain, successful screenshots/traces are skipped, and failures capture a screenshot. Run once without it after fixes. Use one job per profile; close any manually opened Chrome first.
|
|
69
|
+
|
|
70
|
+
## Recipe actions
|
|
71
|
+
|
|
72
|
+
Recipes are plain JSON so agents can generate them without writing browser plumbing:
|
|
73
|
+
|
|
74
|
+
`navigate` accepts a `query` map. `debugManifestsFile` is limited to local HTTPS hosts for SPFx debug builds.
|
|
75
|
+
|
|
76
|
+
| Action | Purpose |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| `navigate` | Open a path on the configured site origin |
|
|
79
|
+
| `assertPageReady` | Wait for the document body and SharePoint origin |
|
|
80
|
+
| `assertAuthenticated` | Check the current web's SharePoint REST endpoint without reading user data |
|
|
81
|
+
| `click` | Click a semantic locator; `confirm: true` accepts an expected browser confirmation |
|
|
82
|
+
| `fill` | Fill an accessible input |
|
|
83
|
+
| `select` | Select an option in a native select |
|
|
84
|
+
| `setChecked` | Set a checkbox or radio state |
|
|
85
|
+
| `assertVisible` | Wait for a semantic target to appear |
|
|
86
|
+
| `assertText` | Check exact or contained visible text |
|
|
87
|
+
| `assertValue` | Check an input value |
|
|
88
|
+
| `screenshot` | Save a named PNG to the local artifact directory |
|
|
89
|
+
|
|
90
|
+
Prefer `testId` locators for stable targeting when the app exposes `data-testid`. Use role/label locators when the test is checking accessible interaction, especially for form controls. Use `assertText` to verify user-visible content on the selected element; use a text locator only when the text itself is the only useful target. Recipes do not allow raw JavaScript or arbitrary URLs.
|
|
91
|
+
|
|
92
|
+
For a known browser confirmation, a click can set `"confirm": true`. The runner accepts only a JavaScript `confirm` dialog and fails if no confirmation appears or a different dialog type appears. Use this only for an explicitly approved test action; it does not bypass the confirmation shown to the user.
|
|
93
|
+
|
|
94
|
+
### Validate one Graph list CRUD operation
|
|
95
|
+
|
|
96
|
+
The [tenant CRUD recipe](examples/tenant-crud-validation.recipe.json) clicks the dashboard's **Test list CRUD** button, accepts its explicit warning, and requires the create/read/update/read/delete success message. Copy it from the installed package into the project, then replace the site and page path and configure a test list in the web part:
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
cp node_modules/@spfx-fast/playwright/examples/tenant-crud-validation.recipe.json tests/e2e/tenant-crud-validation.recipe.json
|
|
100
|
+
npx spfx-fast-playwright validate tests/e2e/tenant-crud-validation.recipe.json
|
|
101
|
+
npx spfx-fast-playwright run tests/e2e/tenant-crud-validation.recipe.json \
|
|
102
|
+
--base-url "$SPFX_BASE_URL" \
|
|
103
|
+
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
104
|
+
--artifacts test-results/tenant-crud
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Use a disposable test list and an account approved for Graph `Sites.ReadWrite.All`. The test creates one temporary item and deletes it; inspect the result and remove any item manually if cleanup reports failure. Do not point this recipe at production data.
|
|
108
|
+
|
|
109
|
+
For a known browser confirmation, a click can set `"confirm": true`. The runner accepts only a JavaScript `confirm` dialog and fails if no confirmation appears or a different dialog type appears. Use this only for an explicitly approved test action; it does not bypass the confirmation shown to the user.
|
|
110
|
+
|
|
111
|
+
## What this does not do
|
|
112
|
+
|
|
113
|
+
- No sign-in automation, token extraction, or permission bypass.
|
|
114
|
+
- No content writes unless explicitly added and approved.
|
|
115
|
+
- Screenshots do not prove API success or persistence; assert those separately.
|
|
116
|
+
- Codegen records actions; add meaningful assertions yourself.
|
|
117
|
+
|
|
118
|
+
Artifacts may contain tenant data. Keep results, auth files, and profiles local; review before sharing.
|
|
119
|
+
|
|
120
|
+
For a full workflow with profile, SharePoint page, image, and OCR guidance, read [the agent browser workflow](../../docs/AGENT-BROWSER-WORKFLOW.md).
|
|
121
|
+
|
|
122
|
+
## Package status
|
|
123
|
+
|
|
124
|
+
This is the `0.1.1` companion package. It is framework-agnostic across SPFx projects and ships independently from `@spfx-fast/core`.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# SPFx Playwright instructions
|
|
2
|
+
|
|
3
|
+
For any SPFx project. This dev tool does not require `@spfx-fast/core`.
|
|
4
|
+
|
|
5
|
+
## Start with the existing project
|
|
6
|
+
|
|
7
|
+
- Reuse the project's Playwright version, config, test account, and site.
|
|
8
|
+
- Set `SPFX_BASE_URL` to the SharePoint **web URL**. Set `SPFX_STORAGE_STATE` only to a local ignored file when that project already uses saved state.
|
|
9
|
+
- Never automate sign-in, inspect cookies, copy a daily profile, or commit auth state.
|
|
10
|
+
- Run one job per persistent profile. `run` and `record` lock it; close manually opened browsers first.
|
|
11
|
+
|
|
12
|
+
## Generate and run
|
|
13
|
+
|
|
14
|
+
- Record with `spfx-fast-playwright record`; review selectors and add user-visible assertions.
|
|
15
|
+
- For repeatable checks, validate a JSON recipe, then `generate` or `run` it.
|
|
16
|
+
- Prefer `testId` locators for stable targeting when the app exposes `data-testid`. Use role/label locators when checking accessible interaction, especially for form controls. Use `assertText` to verify user-visible content on the selected element; use text locators only when the text itself is the only useful target. Always use explicit waits; do not use generic `networkidle` on SharePoint.
|
|
17
|
+
- Use `run --fast` during fixes, then run once without it.
|
|
18
|
+
- `assertAuthenticated` checks REST without reading account details.
|
|
19
|
+
- A click may set `confirm: true` to accept exactly one expected JavaScript confirmation; it fails if the dialog is missing or has another type.
|
|
20
|
+
- Keep navigation on the configured origin. Sign-in redirects fail the precondition.
|
|
21
|
+
- Test the real QA page and required data; missing web parts or zero-to-zero comparisons prove nothing.
|
|
22
|
+
- Before tenant deployment, read [the SPFx ALM deployment guide](../../../docs/AGENT-SHAREPOINT-DEPLOYMENT.md). Verify the catalog package state and the manifest component ID; don't choose a web part by a generic name.
|
|
23
|
+
|
|
24
|
+
## Prove and report
|
|
25
|
+
|
|
26
|
+
- Prefer read-only checks. Writes need dedicated records and cleanup; never change production data.
|
|
27
|
+
- The [tenant CRUD recipe](../examples/tenant-crud-validation.recipe.json) is only for a disposable list on a dedicated test page and account.
|
|
28
|
+
- Review generated specs. Inspect `summary.json`, screenshots, and trace after each run.
|
|
29
|
+
- Screenshots show appearance only. Assert API or saved/published state separately.
|
|
30
|
+
- After three failed attempts to reach a control, stop and report the blocker with evidence.
|
|
31
|
+
- Check artifacts for tenant/personal data before sharing.
|
|
32
|
+
- For image overviews, OCR, PDF text, and screenshot diagnostics, see [the browser, image, and OCR workflow](../../../docs/AGENT-BROWSER-WORKFLOW.md). OCR does not prove visual layout or complete text capture.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { generateTestSource, runRecipe, validateBaseUrl, validateRecipe } from "../src/index.js";
|
|
9
|
+
import { acquireProfileLock } from "../src/profile-lock.js";
|
|
10
|
+
|
|
11
|
+
const help = `SPFx Fast Playwright\n\nCommands:\n init [--force] Scaffold config and a smoke recipe\n validate <recipe.json> Validate a recipe\n generate <recipe.json> --out <test.spec.mjs> [--force] Generate a native Playwright test\n run <recipe.json> --base-url <url> --profile-dir <dir> [--artifacts <dir>] [--fast] [--headed]\n record --url <url> --profile-dir <dir> --out <test.spec.ts> Start Playwright Codegen\n\nRuns are headless by default. --fast skips success screenshots and traces; do one full run after fixes.\n`;
|
|
12
|
+
|
|
13
|
+
const parsed = parseArgs({
|
|
14
|
+
args: process.argv.slice(2),
|
|
15
|
+
allowPositionals: true,
|
|
16
|
+
strict: true,
|
|
17
|
+
options: {
|
|
18
|
+
out: { type: "string" },
|
|
19
|
+
"base-url": { type: "string" },
|
|
20
|
+
"profile-dir": { type: "string" },
|
|
21
|
+
artifacts: { type: "string" },
|
|
22
|
+
"timeout-ms": { type: "string" },
|
|
23
|
+
url: { type: "string" },
|
|
24
|
+
headless: { type: "boolean", default: false },
|
|
25
|
+
headed: { type: "boolean", default: false },
|
|
26
|
+
fast: { type: "boolean", default: false },
|
|
27
|
+
force: { type: "boolean", default: false },
|
|
28
|
+
help: { type: "boolean", short: "h", default: false },
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const [command, recipeFile] = parsed.positionals;
|
|
33
|
+
const options = parsed.values;
|
|
34
|
+
|
|
35
|
+
async function readRecipe(file) {
|
|
36
|
+
if (!file) throw new Error("Supply a recipe JSON file.");
|
|
37
|
+
try { return validateRecipe(JSON.parse(await readFile(resolve(file), "utf8"))); }
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error instanceof TypeError) throw error;
|
|
40
|
+
throw new Error("Could not read a valid recipe JSON file.");
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function outputPath(file) {
|
|
45
|
+
if (!file) throw new Error("Supply --out.");
|
|
46
|
+
const target = resolve(file);
|
|
47
|
+
if (!options.force) {
|
|
48
|
+
try { await access(target); throw new Error("Output already exists; pass --force to replace it."); }
|
|
49
|
+
catch (error) { if (error.message.includes("already exists")) throw error; }
|
|
50
|
+
}
|
|
51
|
+
await mkdir(dirname(target), { recursive: true });
|
|
52
|
+
return target;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function requireProfileDirectory(value) {
|
|
56
|
+
if (!value) throw new Error("Supply an existing --profile-dir. The command will not create or copy a signed-in profile.");
|
|
57
|
+
const path = resolve(value);
|
|
58
|
+
let metadata;
|
|
59
|
+
try { metadata = await stat(path); } catch { throw new Error("The supplied profile directory does not exist."); }
|
|
60
|
+
if (!metadata.isDirectory()) throw new Error("The supplied profile path must be a directory.");
|
|
61
|
+
return path;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function main() {
|
|
65
|
+
if (options.help || !command || command === "help") {
|
|
66
|
+
console.log(help);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (command === "init") {
|
|
70
|
+
const agentGuide = await readFile(new URL("../agent/PLAYWRIGHT.md", import.meta.url), "utf8");
|
|
71
|
+
const smokeRecipe = {
|
|
72
|
+
name: "SharePoint page is available to the signed-in user",
|
|
73
|
+
steps: [
|
|
74
|
+
{ action: "navigate", path: "/sites/your-site" },
|
|
75
|
+
{ action: "assertPageReady" },
|
|
76
|
+
{ action: "assertAuthenticated" },
|
|
77
|
+
{ action: "screenshot", name: "sharepoint-page", fullPage: true },
|
|
78
|
+
],
|
|
79
|
+
};
|
|
80
|
+
const files = [
|
|
81
|
+
["playwright.config.ts", `import { defineConfig } from "@playwright/test";\n\nexport default defineConfig({\n testDir: "./tests/e2e",\n fullyParallel: false,\n workers: 1,\n reporter: [["list"], ["html", { open: "never" }]],\n use: {\n baseURL: process.env.SPFX_BASE_URL,\n storageState: process.env.SPFX_STORAGE_STATE || undefined,\n actionTimeout: 15_000,\n navigationTimeout: 45_000,\n screenshot: "only-on-failure",\n trace: "retain-on-failure",\n viewport: { width: 1440, height: 900 },\n },\n});\n`],
|
|
82
|
+
["tests/e2e/sharepoint-smoke.recipe.json", `${JSON.stringify(smokeRecipe, null, 2)}\n`],
|
|
83
|
+
["tests/e2e/sharepoint-smoke.spec.mjs", generateTestSource(smokeRecipe)],
|
|
84
|
+
["playwright/.auth/.gitignore", "*\n!.gitignore\n"],
|
|
85
|
+
["SPFX-PLAYWRIGHT.md", agentGuide],
|
|
86
|
+
];
|
|
87
|
+
if (!options.force) {
|
|
88
|
+
for (const [file] of files) {
|
|
89
|
+
try { await access(resolve(file)); throw new Error(`Refusing to overwrite ${file}; pass --force to replace generated files.`); }
|
|
90
|
+
catch (error) { if (error.message.startsWith("Refusing")) throw error; }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const [file, contents] of files) {
|
|
94
|
+
const target = resolve(file);
|
|
95
|
+
await mkdir(dirname(target), { recursive: true });
|
|
96
|
+
await writeFile(target, contents, "utf8");
|
|
97
|
+
}
|
|
98
|
+
const agentsFile = resolve("AGENTS.md");
|
|
99
|
+
let existingAgents = "";
|
|
100
|
+
try { existingAgents = await readFile(agentsFile, "utf8"); }
|
|
101
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
102
|
+
const marker = "<!-- spfx-fast-playwright:agent-instructions -->";
|
|
103
|
+
if (!existingAgents.includes(marker)) {
|
|
104
|
+
const link = `${marker}\n## SharePoint end-to-end tests\nRead [SPFX-PLAYWRIGHT.md](SPFX-PLAYWRIGHT.md) when creating or running authenticated SharePoint browser tests.\n`;
|
|
105
|
+
const prefix = existingAgents ? `${existingAgents}${existingAgents.endsWith("\n") ? "" : "\n"}\n` : "# Agent instructions\n\n";
|
|
106
|
+
await writeFile(agentsFile, `${prefix}${link}`, "utf8");
|
|
107
|
+
}
|
|
108
|
+
console.log("Created Playwright config, a generated smoke test, agent instructions, and an ignored auth-state folder.");
|
|
109
|
+
console.log("Set SPFX_BASE_URL to the SharePoint web URL. Keep SPFX_STORAGE_STATE private.");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (command === "validate") {
|
|
113
|
+
const recipe = await readRecipe(recipeFile);
|
|
114
|
+
console.log(`Recipe valid: ${recipe.name} (${recipe.steps.length} steps).`);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (command === "generate") {
|
|
118
|
+
const recipe = await readRecipe(recipeFile);
|
|
119
|
+
const target = await outputPath(options.out);
|
|
120
|
+
if (!/\.spec\.(?:mjs|ts)$/.test(target)) throw new Error("Generated tests must end in .spec.mjs or .spec.ts.");
|
|
121
|
+
await writeFile(target, generateTestSource(recipe), "utf8");
|
|
122
|
+
console.log(`Generated native Playwright test: ${target}`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (command === "record") {
|
|
126
|
+
const profile = await requireProfileDirectory(options["profile-dir"]);
|
|
127
|
+
const output = await outputPath(options.out);
|
|
128
|
+
if (!/\.spec\.(?:mjs|ts)$/.test(output)) throw new Error("Recorded tests must end in .spec.mjs or .spec.ts.");
|
|
129
|
+
const url = validateBaseUrl(options.url).href;
|
|
130
|
+
const requireFromProject = createRequire(pathToFileURL(resolve("package.json")));
|
|
131
|
+
const playwrightEntry = requireFromProject.resolve("playwright");
|
|
132
|
+
const cli = resolve(dirname(playwrightEntry), "cli.js");
|
|
133
|
+
const releaseProfile = acquireProfileLock(profile);
|
|
134
|
+
try {
|
|
135
|
+
const result = spawnSync(process.execPath, [cli, "codegen", `--user-data-dir=${profile}`, `--output=${output}`, "--viewport-size=1440,900", url], { stdio: "inherit" });
|
|
136
|
+
if (result.error) throw new Error("Playwright Codegen could not start. Check that Playwright is installed in this project.");
|
|
137
|
+
if (result.status !== 0) process.exitCode = result.status ?? 1;
|
|
138
|
+
} finally { releaseProfile(); }
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (command === "run") {
|
|
142
|
+
const recipe = await readRecipe(recipeFile);
|
|
143
|
+
const base = validateBaseUrl(options["base-url"]);
|
|
144
|
+
const profile = await requireProfileDirectory(options["profile-dir"]);
|
|
145
|
+
const artifactRoot = resolve(options.artifacts ?? "test-results/spfx-fast-playwright");
|
|
146
|
+
const timeoutMs = Number(options["timeout-ms"] ?? 15000);
|
|
147
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new Error("--timeout-ms must be a positive integer.");
|
|
148
|
+
await mkdir(artifactRoot, { recursive: true });
|
|
149
|
+
let artifacts = artifactRoot;
|
|
150
|
+
try {
|
|
151
|
+
if ((await readdir(artifactRoot)).length > 0) {
|
|
152
|
+
artifacts = resolve(artifactRoot, `run-${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`);
|
|
153
|
+
}
|
|
154
|
+
} catch {}
|
|
155
|
+
await mkdir(artifacts, { recursive: true });
|
|
156
|
+
const { chromium } = await import("playwright");
|
|
157
|
+
const releaseProfile = acquireProfileLock(profile);
|
|
158
|
+
let context;
|
|
159
|
+
let page;
|
|
160
|
+
let result;
|
|
161
|
+
let error;
|
|
162
|
+
try {
|
|
163
|
+
context = await chromium.launchPersistentContext(profile, {
|
|
164
|
+
headless: options.headed ? false : true,
|
|
165
|
+
viewport: { width: 1440, height: 900 },
|
|
166
|
+
});
|
|
167
|
+
page = context.pages()[0] ?? await context.newPage();
|
|
168
|
+
if (!options.fast) await context.tracing.start({ screenshots: true, snapshots: true, sources: false });
|
|
169
|
+
result = await runRecipe(page, recipe, { baseUrl: base.href, screenshotDir: artifacts, timeoutMs, fast: options.fast });
|
|
170
|
+
} catch (cause) {
|
|
171
|
+
error = cause;
|
|
172
|
+
if (page) {
|
|
173
|
+
try { await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true }); } catch {}
|
|
174
|
+
}
|
|
175
|
+
} finally {
|
|
176
|
+
if (context && !options.fast) try { await context.tracing.stop({ path: resolve(artifacts, "trace.zip") }); } catch {}
|
|
177
|
+
await context?.close();
|
|
178
|
+
releaseProfile();
|
|
179
|
+
}
|
|
180
|
+
const report = {
|
|
181
|
+
name: recipe.name,
|
|
182
|
+
status: error ? "failed" : "passed",
|
|
183
|
+
stepCount: recipe.steps.length,
|
|
184
|
+
screenshots: error ? ["failure.png"] : result.screenshots.map((file) => file.slice(artifacts.length + 1)),
|
|
185
|
+
trace: options.fast ? null : "trace.zip",
|
|
186
|
+
fastMode: options.fast,
|
|
187
|
+
failedStep: error?.step ?? null,
|
|
188
|
+
error: error ? error.message : null,
|
|
189
|
+
};
|
|
190
|
+
await writeFile(resolve(artifacts, "summary.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
191
|
+
console.log(JSON.stringify({ ...report, artifactDirectory: artifacts }, null, 2));
|
|
192
|
+
if (error) process.exitCode = 1;
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
throw new Error(`Unknown command: ${command}. Use --help.`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
main().catch((error) => {
|
|
199
|
+
console.error(error instanceof Error ? error.message : "Command failed.");
|
|
200
|
+
process.exitCode = 1;
|
|
201
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "SharePoint page is available to the signed-in user",
|
|
3
|
+
"steps": [
|
|
4
|
+
{ "action": "navigate", "path": "/sites/your-site" },
|
|
5
|
+
{ "action": "assertPageReady" },
|
|
6
|
+
{ "action": "assertAuthenticated" },
|
|
7
|
+
{ "action": "screenshot", "name": "sharepoint-page", "fullPage": true }
|
|
8
|
+
]
|
|
9
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "SPFx Fast single-item Graph CRUD validation",
|
|
3
|
+
"steps": [
|
|
4
|
+
{ "action": "navigate", "path": "/sites/your-site/SitePages/tenant-validation.aspx" },
|
|
5
|
+
{ "action": "assertPageReady" },
|
|
6
|
+
{ "action": "assertAuthenticated" },
|
|
7
|
+
{ "action": "assertVisible", "locator": { "testId": "tenant-validation-run-list-crud" } },
|
|
8
|
+
{ "action": "click", "locator": { "testId": "tenant-validation-run-list-crud" }, "confirm": true },
|
|
9
|
+
{ "action": "assertText", "locator": { "testId": "tenant-validation-list-crud-result" }, "expected": "Create, read, update, read, and delete succeeded for one temporary list item.", "exact": false }
|
|
10
|
+
]
|
|
11
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spfx-fast/playwright",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"author": "Vilius Vystartas",
|
|
5
|
+
"description": "Authenticated, recipe-driven Playwright testing helpers for any SharePoint Framework project.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/vystartasv/spfx-fast#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vystartasv/spfx-fast.git",
|
|
11
|
+
"directory": "packages/playwright"
|
|
12
|
+
},
|
|
13
|
+
"bugs": { "url": "https://github.com/vystartasv/spfx-fast/issues" },
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": { "node": ">=18" },
|
|
16
|
+
"main": "./src/index.js",
|
|
17
|
+
"types": "./src/index.d.ts",
|
|
18
|
+
"exports": { ".": { "types": "./src/index.d.ts", "import": "./src/index.js" } },
|
|
19
|
+
"bin": { "spfx-fast-playwright": "bin/spfx-fast-playwright.mjs" },
|
|
20
|
+
"files": ["src", "bin", "README.md", "LICENSE", "examples", "agent"],
|
|
21
|
+
"peerDependencies": { "@playwright/test": ">=1.50.0 <2", "playwright": ">=1.50.0 <2" },
|
|
22
|
+
"keywords": ["spfx", "sharepoint", "playwright", "e2e", "testing", "agents"]
|
|
23
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Page } from "playwright";
|
|
2
|
+
|
|
3
|
+
export type RecipeLocator =
|
|
4
|
+
| { role: string; name: string; exact?: boolean }
|
|
5
|
+
| { text: string; exact?: boolean }
|
|
6
|
+
| { label: string; exact?: boolean }
|
|
7
|
+
| { testId: string }
|
|
8
|
+
| { placeholder: string; exact?: boolean };
|
|
9
|
+
|
|
10
|
+
export type RecipeStep =
|
|
11
|
+
| { action: "navigate"; path: string; query?: Record<string, string> }
|
|
12
|
+
| { action: "assertPageReady" }
|
|
13
|
+
| { action: "assertAuthenticated" }
|
|
14
|
+
| { action: "click"; locator: RecipeLocator; confirm?: true }
|
|
15
|
+
| { action: "assertVisible"; locator: RecipeLocator }
|
|
16
|
+
| { action: "fill"; locator: RecipeLocator; value: string }
|
|
17
|
+
| { action: "select"; locator: RecipeLocator; value: string }
|
|
18
|
+
| { action: "setChecked"; locator: RecipeLocator; checked: boolean }
|
|
19
|
+
| { action: "assertText" | "assertValue"; locator: RecipeLocator; expected: string; exact?: boolean }
|
|
20
|
+
| { action: "screenshot"; name: string; fullPage?: boolean };
|
|
21
|
+
|
|
22
|
+
export interface SharePointRecipe {
|
|
23
|
+
name: string;
|
|
24
|
+
steps: RecipeStep[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function validateRecipe(recipe: unknown): SharePointRecipe;
|
|
28
|
+
export function validateBaseUrl(baseUrl: string): URL;
|
|
29
|
+
export function runRecipe(page: Page, recipe: SharePointRecipe, options: {
|
|
30
|
+
baseUrl: string;
|
|
31
|
+
screenshotDir?: string;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
fast?: boolean;
|
|
34
|
+
}): Promise<{ name: string; steps: number; screenshots: string[] }>;
|
|
35
|
+
export function generateTestSource(recipe: SharePointRecipe): string;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
const actions = new Set(["navigate", "assertPageReady", "assertAuthenticated", "click", "fill", "select", "setChecked", "assertVisible", "assertText", "assertValue", "screenshot"]);
|
|
5
|
+
const locatorKeys = new Set(["role", "text", "label", "testId", "placeholder"]);
|
|
6
|
+
|
|
7
|
+
export function validateRecipe(recipe) {
|
|
8
|
+
if (!recipe || typeof recipe !== "object" || Array.isArray(recipe)) throw new TypeError("Recipe must be a JSON object.");
|
|
9
|
+
if (typeof recipe.name !== "string" || !recipe.name.trim()) throw new TypeError("Recipe needs a non-empty name.");
|
|
10
|
+
if (!Array.isArray(recipe.steps) || recipe.steps.length === 0) throw new TypeError("Recipe needs at least one step.");
|
|
11
|
+
|
|
12
|
+
for (const [index, step] of recipe.steps.entries()) {
|
|
13
|
+
if (!step || typeof step !== "object" || Array.isArray(step) || !actions.has(step.action)) {
|
|
14
|
+
throw new TypeError(`Recipe step ${index + 1} has an unsupported action.`);
|
|
15
|
+
}
|
|
16
|
+
if (step.action === "navigate" && (typeof step.path !== "string" || !step.path.startsWith("/") || step.path.startsWith("//") || /[?#]/.test(step.path))) {
|
|
17
|
+
throw new TypeError(`Recipe step ${index + 1} needs a same-site path beginning with / and no query or fragment.`);
|
|
18
|
+
}
|
|
19
|
+
if (step.action === "navigate" && step.query !== undefined) {
|
|
20
|
+
if (!step.query || typeof step.query !== "object" || Array.isArray(step.query) || Object.keys(step.query).length > 16) {
|
|
21
|
+
throw new TypeError(`Recipe step ${index + 1} query must be an object with at most 16 parameters.`);
|
|
22
|
+
}
|
|
23
|
+
for (const [key, value] of Object.entries(step.query)) {
|
|
24
|
+
if (!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(key) || typeof value !== "string" || value.length > 2048) {
|
|
25
|
+
throw new TypeError(`Recipe step ${index + 1} has an invalid query parameter.`);
|
|
26
|
+
}
|
|
27
|
+
if (key.toLowerCase() === "debugmanifestsfile") {
|
|
28
|
+
let manifest;
|
|
29
|
+
try { manifest = new URL(value); } catch { throw new TypeError("debugManifestsFile must use a local HTTPS URL."); }
|
|
30
|
+
if (manifest.protocol !== "https:" || !["localhost", "127.0.0.1"].includes(manifest.hostname) || manifest.username || manifest.password) {
|
|
31
|
+
throw new TypeError("debugManifestsFile must use a local HTTPS URL.");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (["click", "fill", "select", "setChecked", "assertVisible", "assertText", "assertValue"].includes(step.action)) validateLocator(step.locator, index + 1);
|
|
37
|
+
if (["fill", "select"].includes(step.action) && typeof step.value !== "string") throw new TypeError(`Recipe step ${index + 1} needs a string value.`);
|
|
38
|
+
if (step.confirm !== undefined && (step.action !== "click" || step.confirm !== true)) {
|
|
39
|
+
throw new TypeError(`Recipe step ${index + 1} can only set confirm: true on a click action.`);
|
|
40
|
+
}
|
|
41
|
+
if (step.action === "setChecked" && typeof step.checked !== "boolean") throw new TypeError(`Recipe step ${index + 1} needs a boolean checked value.`);
|
|
42
|
+
if (["assertText", "assertValue"].includes(step.action) && typeof step.expected !== "string") throw new TypeError(`Recipe step ${index + 1} needs expected text.`);
|
|
43
|
+
if (step.action === "screenshot" && (typeof step.name !== "string" || !/^[\w-]+$/.test(step.name))) {
|
|
44
|
+
throw new TypeError(`Recipe step ${index + 1} needs a screenshot name using only letters, numbers, _ or -.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return recipe;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function validateLocator(locator, stepNumber) {
|
|
51
|
+
if (!locator || typeof locator !== "object" || Array.isArray(locator)) throw new TypeError(`Recipe step ${stepNumber} needs a locator.`);
|
|
52
|
+
const keys = Object.keys(locator).filter((key) => locatorKeys.has(key));
|
|
53
|
+
if (keys.length !== 1 || typeof locator[keys[0]] !== "string" || !locator[keys[0]].trim()) {
|
|
54
|
+
throw new TypeError(`Recipe step ${stepNumber} needs exactly one non-empty role, text, label, testId or placeholder locator.`);
|
|
55
|
+
}
|
|
56
|
+
if (keys[0] === "role" && (typeof locator.name !== "string" || !locator.name.trim())) {
|
|
57
|
+
throw new TypeError(`Recipe step ${stepNumber} role locator needs an accessible name.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function validateBaseUrl(baseUrl) {
|
|
62
|
+
let url;
|
|
63
|
+
try { url = new URL(baseUrl); } catch { throw new TypeError("Provide a valid SPFX_BASE_URL."); }
|
|
64
|
+
const secure = url.protocol === "https:" || (url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname));
|
|
65
|
+
if (!secure) throw new TypeError("SPFX_BASE_URL must use HTTPS (HTTP is allowed only for localhost).");
|
|
66
|
+
if (url.username || url.password || url.search || url.hash) throw new TypeError("SPFX_BASE_URL must not contain credentials, query values or a fragment.");
|
|
67
|
+
return url;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function locatorFor(page, locator) {
|
|
71
|
+
if (locator.role) return page.getByRole(locator.role, { name: locator.name, exact: locator.exact ?? true });
|
|
72
|
+
if (locator.text) return page.getByText(locator.text, { exact: locator.exact ?? true });
|
|
73
|
+
if (locator.label) return page.getByLabel(locator.label, { exact: locator.exact ?? true });
|
|
74
|
+
if (locator.testId) return page.getByTestId(locator.testId);
|
|
75
|
+
return page.getByPlaceholder(locator.placeholder, { exact: locator.exact ?? true });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function assertSameOrigin(page, base) {
|
|
79
|
+
const current = new URL(page.url());
|
|
80
|
+
if (current.origin !== base.origin) throw new Error("Navigation left the configured SharePoint origin; check sign-in state and page links.");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutMs = 15000, fast = false } = {}) {
|
|
84
|
+
validateRecipe(recipe);
|
|
85
|
+
const base = validateBaseUrl(baseUrl);
|
|
86
|
+
const screenshots = [];
|
|
87
|
+
if (screenshotDir) await mkdir(screenshotDir, { recursive: true });
|
|
88
|
+
|
|
89
|
+
for (const [index, step] of recipe.steps.entries()) {
|
|
90
|
+
try {
|
|
91
|
+
if (step.action === "navigate") {
|
|
92
|
+
const destination = new URL(step.path, base);
|
|
93
|
+
if (destination.origin !== base.origin) throw new Error("Navigation must stay on the configured SharePoint origin.");
|
|
94
|
+
for (const [key, value] of Object.entries(step.query ?? {})) destination.searchParams.set(key, value);
|
|
95
|
+
const response = await page.goto(destination.href, { waitUntil: "domcontentloaded", timeout: timeoutMs });
|
|
96
|
+
if (response && response.status() >= 400) throw new Error(`Page returned HTTP ${response.status()}.`);
|
|
97
|
+
assertSameOrigin(page, base);
|
|
98
|
+
} else if (step.action === "assertPageReady") {
|
|
99
|
+
await page.waitForLoadState("domcontentloaded", { timeout: timeoutMs });
|
|
100
|
+
await page.locator("body").waitFor({ state: "visible", timeout: timeoutMs });
|
|
101
|
+
assertSameOrigin(page, base);
|
|
102
|
+
} else if (step.action === "assertAuthenticated") {
|
|
103
|
+
const sitePath = base.pathname.replace(/\/$/, "");
|
|
104
|
+
const apiPath = `${sitePath}/_api/web/currentuser?$select=Id`;
|
|
105
|
+
const result = await page.evaluate(async (path) => {
|
|
106
|
+
const response = await fetch(path, {
|
|
107
|
+
credentials: "same-origin",
|
|
108
|
+
headers: { Accept: "application/json;odata=nometadata" },
|
|
109
|
+
});
|
|
110
|
+
return { status: response.status, contentType: response.headers.get("content-type") ?? "" };
|
|
111
|
+
}, apiPath);
|
|
112
|
+
if (result.status < 200 || result.status >= 300 || !result.contentType.toLowerCase().includes("json")) {
|
|
113
|
+
throw new Error(`Signed-in SharePoint REST check failed (HTTP ${result.status}).`);
|
|
114
|
+
}
|
|
115
|
+
assertSameOrigin(page, base);
|
|
116
|
+
} else if (step.action === "click") {
|
|
117
|
+
if (step.confirm) {
|
|
118
|
+
let dialogSeen = false;
|
|
119
|
+
let dialogError;
|
|
120
|
+
let dialogHandling = Promise.resolve();
|
|
121
|
+
const handleDialog = (dialog) => {
|
|
122
|
+
dialogSeen = true;
|
|
123
|
+
dialogHandling = dialog.type() === "confirm"
|
|
124
|
+
? dialog.accept().catch(() => { dialogError = "The browser confirmation could not be accepted."; })
|
|
125
|
+
: dialog.dismiss().then(() => { dialogError = "Expected a browser confirmation dialog."; });
|
|
126
|
+
};
|
|
127
|
+
page.once("dialog", handleDialog);
|
|
128
|
+
try {
|
|
129
|
+
await locatorFor(page, step.locator).click({ timeout: timeoutMs });
|
|
130
|
+
await dialogHandling;
|
|
131
|
+
if (!dialogSeen) throw new Error("Expected a browser confirmation dialog, but none appeared.");
|
|
132
|
+
if (dialogError) throw new Error(dialogError);
|
|
133
|
+
} finally {
|
|
134
|
+
page.off("dialog", handleDialog);
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
await locatorFor(page, step.locator).click({ timeout: timeoutMs });
|
|
138
|
+
}
|
|
139
|
+
assertSameOrigin(page, base);
|
|
140
|
+
} else if (step.action === "fill") {
|
|
141
|
+
await locatorFor(page, step.locator).fill(step.value, { timeout: timeoutMs });
|
|
142
|
+
assertSameOrigin(page, base);
|
|
143
|
+
} else if (step.action === "select") {
|
|
144
|
+
await locatorFor(page, step.locator).selectOption(step.value, { timeout: timeoutMs });
|
|
145
|
+
assertSameOrigin(page, base);
|
|
146
|
+
} else if (step.action === "setChecked") {
|
|
147
|
+
await locatorFor(page, step.locator).setChecked(step.checked, { timeout: timeoutMs });
|
|
148
|
+
assertSameOrigin(page, base);
|
|
149
|
+
} else if (step.action === "assertVisible") {
|
|
150
|
+
await locatorFor(page, step.locator).waitFor({ state: "visible", timeout: timeoutMs });
|
|
151
|
+
assertSameOrigin(page, base);
|
|
152
|
+
} else if (step.action === "assertText") {
|
|
153
|
+
const target = locatorFor(page, step.locator);
|
|
154
|
+
await target.waitFor({ state: "visible", timeout: timeoutMs });
|
|
155
|
+
const actual = (await target.innerText()).replace(/\s+/g, " ").trim();
|
|
156
|
+
const expected = step.expected.replace(/\s+/g, " ").trim();
|
|
157
|
+
if (!(step.exact ? actual === expected : actual.includes(expected))) throw new Error(`Text assertion failed (${step.exact ? "exact" : "contains"}).`);
|
|
158
|
+
assertSameOrigin(page, base);
|
|
159
|
+
} else if (step.action === "assertValue") {
|
|
160
|
+
const target = locatorFor(page, step.locator);
|
|
161
|
+
await target.waitFor({ state: "visible", timeout: timeoutMs });
|
|
162
|
+
const actual = await target.inputValue();
|
|
163
|
+
if (!(step.exact === false ? actual.includes(step.expected) : actual === step.expected)) throw new Error(`Value assertion failed (${step.exact === false ? "contains" : "exact"}).`);
|
|
164
|
+
assertSameOrigin(page, base);
|
|
165
|
+
} else if (step.action === "screenshot") {
|
|
166
|
+
if (fast) continue;
|
|
167
|
+
if (!screenshotDir) throw new Error("Screenshots need an artifact directory.");
|
|
168
|
+
assertSameOrigin(page, base);
|
|
169
|
+
const file = join(screenshotDir, `${step.name}.png`);
|
|
170
|
+
await page.screenshot({ path: file, fullPage: step.fullPage ?? false });
|
|
171
|
+
screenshots.push(file);
|
|
172
|
+
}
|
|
173
|
+
} catch (cause) {
|
|
174
|
+
const error = new Error(`Recipe step ${index + 1} (${step.action}) failed.`, { cause });
|
|
175
|
+
error.step = index + 1;
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return { name: recipe.name, steps: recipe.steps.length, screenshots };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function generateTestSource(recipe) {
|
|
183
|
+
validateRecipe(recipe);
|
|
184
|
+
return `import { test } from "@playwright/test";\nimport { runRecipe } from "@spfx-fast/playwright";\n\nconst recipe = ${JSON.stringify(recipe, null, 2)};\n\ntest(recipe.name, async ({ page }, testInfo) => {\n const baseUrl = process.env.SPFX_BASE_URL;\n if (!baseUrl) throw new Error("Set SPFX_BASE_URL to the SharePoint site under test.");\n await runRecipe(page, recipe, {\n baseUrl,\n screenshotDir: testInfo.outputPath("spfx-fast-screenshots"),\n });\n});\n`;
|
|
185
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { hostname, tmpdir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { mkdirSync, readFileSync, readlinkSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
|
|
6
|
+
function processExists(pid) {
|
|
7
|
+
try { process.kill(pid, 0); return true; }
|
|
8
|
+
catch (error) { return error?.code === "EPERM"; }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function assertProfileFree(profileDir) {
|
|
12
|
+
if (process.platform === "win32") return;
|
|
13
|
+
let value;
|
|
14
|
+
try { value = readlinkSync(join(profileDir, "SingletonLock")); }
|
|
15
|
+
catch { return; }
|
|
16
|
+
const separator = value.lastIndexOf("-");
|
|
17
|
+
const ownerHost = value.slice(0, separator);
|
|
18
|
+
const ownerPid = Number(value.slice(separator + 1));
|
|
19
|
+
if (ownerHost === hostname() && Number.isInteger(ownerPid) && processExists(ownerPid)) {
|
|
20
|
+
throw new Error("The supplied browser profile is already open. Close that browser before running Playwright.");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Serialize SPFx Fast jobs using one persistent browser profile. Never removes Chrome profile files. */
|
|
25
|
+
export function acquireProfileLock(profileDirectory) {
|
|
26
|
+
const profileDir = resolve(profileDirectory);
|
|
27
|
+
assertProfileFree(profileDir);
|
|
28
|
+
const hash = createHash("sha256").update(profileDir).digest("hex").slice(0, 24);
|
|
29
|
+
const lockDir = join(tmpdir(), `spfx-fast-playwright-${hash}.lock`);
|
|
30
|
+
const owner = JSON.stringify({ host: hostname(), pid: process.pid });
|
|
31
|
+
try {
|
|
32
|
+
mkdirSync(lockDir);
|
|
33
|
+
writeFileSync(join(lockDir, "owner.json"), owner, { flag: "wx", mode: 0o600 });
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (error?.code === "EEXIST") {
|
|
36
|
+
let previous;
|
|
37
|
+
try { previous = JSON.parse(readFileSync(join(lockDir, "owner.json"), "utf8")); }
|
|
38
|
+
catch { throw new Error("A Playwright job may be starting with this browser profile; retry after it finishes."); }
|
|
39
|
+
if (previous.host !== hostname() || processExists(Number(previous.pid))) {
|
|
40
|
+
throw new Error("Another SPFx Fast Playwright job is using this browser profile.");
|
|
41
|
+
}
|
|
42
|
+
const staleDir = `${lockDir}.stale-${process.pid}-${Date.now()}`;
|
|
43
|
+
try { renameSync(lockDir, staleDir); }
|
|
44
|
+
catch (renameError) {
|
|
45
|
+
if (renameError?.code === "ENOENT") return acquireProfileLock(profileDir);
|
|
46
|
+
throw new Error("A Playwright job may be opening this browser profile; retry after it finishes.");
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
if (readFileSync(join(staleDir, "owner.json"), "utf8") !== JSON.stringify(previous)) {
|
|
50
|
+
try { renameSync(staleDir, lockDir); } catch { /* Another run already restored or replaced the lock. */ }
|
|
51
|
+
throw new Error("The browser-profile lock changed while checking it; retry after the active job finishes.");
|
|
52
|
+
}
|
|
53
|
+
} catch (verifyError) {
|
|
54
|
+
if (verifyError instanceof Error && verifyError.message.startsWith("The browser-profile lock changed")) throw verifyError;
|
|
55
|
+
throw new Error("Could not verify the browser-profile lock owner; retry after the active job finishes.");
|
|
56
|
+
}
|
|
57
|
+
rmSync(staleDir, { recursive: true, force: true });
|
|
58
|
+
return acquireProfileLock(profileDir);
|
|
59
|
+
}
|
|
60
|
+
rmSync(lockDir, { recursive: true, force: true });
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
let released = false;
|
|
64
|
+
return () => {
|
|
65
|
+
if (released) return;
|
|
66
|
+
released = true;
|
|
67
|
+
try {
|
|
68
|
+
const current = readFileSync(join(lockDir, "owner.json"), "utf8");
|
|
69
|
+
if (current === owner) rmSync(lockDir, { recursive: true, force: true });
|
|
70
|
+
} catch { /* The lock was already released or replaced. */ }
|
|
71
|
+
};
|
|
72
|
+
}
|