@spfx-fast/playwright 0.1.0 → 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/README.md +47 -21
- package/agent/PLAYWRIGHT.md +20 -15
- package/bin/spfx-fast-playwright.mjs +23 -13
- package/examples/tenant-crud-validation.recipe.json +11 -0
- package/package.json +2 -2
- package/src/index.d.ts +4 -2
- package/src/index.js +45 -2
- package/src/profile-lock.js +72 -0
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @spfx-fast/playwright
|
|
2
2
|
|
|
3
|
-
|
|
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
4
|
|
|
5
|
-
|
|
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
6
|
|
|
7
7
|
## Install in an SPFx project
|
|
8
8
|
|
|
@@ -10,7 +10,7 @@ The package builds on Playwright's own test runner, locator model, test recorder
|
|
|
10
10
|
npm install --save-dev @spfx-fast/playwright @playwright/test playwright
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
SPFx is not a
|
|
13
|
+
SPFx is not a dependency. Production web parts do not import this package by default.
|
|
14
14
|
|
|
15
15
|
Scaffold a serial Playwright setup with a starter recipe, generated test spec, agent instructions, screenshots, traces, and an ignored auth-state folder:
|
|
16
16
|
|
|
@@ -18,8 +18,7 @@ Scaffold a serial Playwright setup with a starter recipe, generated test spec, a
|
|
|
18
18
|
npx spfx-fast-playwright init
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
The
|
|
22
|
-
The scaffold writes `SPFX-PLAYWRIGHT.md` and appends a link to `AGENTS.md` without replacing existing instructions.
|
|
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.
|
|
23
22
|
|
|
24
23
|
## Record a test with the Playwright recorder
|
|
25
24
|
|
|
@@ -32,48 +31,54 @@ npx spfx-fast-playwright record \
|
|
|
32
31
|
--out tests/e2e/home-page.spec.ts
|
|
33
32
|
```
|
|
34
33
|
|
|
35
|
-
Review
|
|
34
|
+
Review selectors and add business assertions; Codegen records actions only.
|
|
36
35
|
|
|
37
36
|
## Generate a test mechanically from a small recipe
|
|
38
37
|
|
|
39
|
-
Edit `
|
|
38
|
+
Edit the scaffolded `tests/e2e/sharepoint-smoke.recipe.json` for the target site, then:
|
|
40
39
|
|
|
41
40
|
```sh
|
|
42
|
-
npx spfx-fast-playwright validate
|
|
43
|
-
npx spfx-fast-playwright generate
|
|
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
|
|
44
43
|
```
|
|
45
44
|
|
|
46
|
-
|
|
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`:
|
|
47
48
|
|
|
48
49
|
```sh
|
|
49
50
|
SPFX_BASE_URL="https://tenant.sharepoint.com/sites/your-site" npx playwright test
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
Keep state files out of source control. They contain impersonation-capable session data. Use a dedicated least-privilege account and test site.
|
|
53
54
|
|
|
54
55
|
## Run a recipe with a persistent authenticated browser profile
|
|
55
56
|
|
|
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:
|
|
57
58
|
|
|
58
59
|
```sh
|
|
59
|
-
npx spfx-fast-playwright run
|
|
60
|
+
npx spfx-fast-playwright run tests/e2e/sharepoint-smoke.recipe.json \
|
|
60
61
|
--base-url "$SPFX_BASE_URL" \
|
|
61
62
|
--profile-dir "$SPFX_TEST_PROFILE" \
|
|
62
63
|
--artifacts test-results/sharepoint-smoke
|
|
63
64
|
```
|
|
64
65
|
|
|
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.
|
|
66
69
|
|
|
67
70
|
## Recipe actions
|
|
68
71
|
|
|
69
72
|
Recipes are plain JSON so agents can generate them without writing browser plumbing:
|
|
70
73
|
|
|
74
|
+
`navigate` accepts a `query` map. `debugManifestsFile` is limited to local HTTPS hosts for SPFx debug builds.
|
|
75
|
+
|
|
71
76
|
| Action | Purpose |
|
|
72
77
|
| --- | --- |
|
|
73
78
|
| `navigate` | Open a path on the configured site origin |
|
|
74
79
|
| `assertPageReady` | Wait for the document body and SharePoint origin |
|
|
75
80
|
| `assertAuthenticated` | Check the current web's SharePoint REST endpoint without reading user data |
|
|
76
|
-
| `click` | Click a semantic
|
|
81
|
+
| `click` | Click a semantic locator; `confirm: true` accepts an expected browser confirmation |
|
|
77
82
|
| `fill` | Fill an accessible input |
|
|
78
83
|
| `select` | Select an option in a native select |
|
|
79
84
|
| `setChecked` | Set a checkbox or radio state |
|
|
@@ -82,17 +87,38 @@ Recipes are plain JSON so agents can generate them without writing browser plumb
|
|
|
82
87
|
| `assertValue` | Check an input value |
|
|
83
88
|
| `screenshot` | Save a named PNG to the local artifact directory |
|
|
84
89
|
|
|
85
|
-
Prefer
|
|
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.
|
|
86
110
|
|
|
87
111
|
## What this does not do
|
|
88
112
|
|
|
89
|
-
-
|
|
90
|
-
-
|
|
91
|
-
-
|
|
92
|
-
-
|
|
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.
|
|
93
119
|
|
|
94
|
-
|
|
120
|
+
For a full workflow with profile, SharePoint page, image, and OCR guidance, read [the agent browser workflow](../../docs/AGENT-BROWSER-WORKFLOW.md).
|
|
95
121
|
|
|
96
122
|
## Package status
|
|
97
123
|
|
|
98
|
-
This is the
|
|
124
|
+
This is the `0.1.1` companion package. It is framework-agnostic across SPFx projects and ships independently from `@spfx-fast/core`.
|
package/agent/PLAYWRIGHT.md
CHANGED
|
@@ -1,27 +1,32 @@
|
|
|
1
1
|
# SPFx Playwright instructions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
For any SPFx project. This dev tool does not require `@spfx-fast/core`.
|
|
4
4
|
|
|
5
5
|
## Start with the existing project
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- Reuse the project's Playwright version, config, test account, and site.
|
|
8
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,
|
|
10
|
-
-
|
|
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
11
|
|
|
12
12
|
## Generate and run
|
|
13
13
|
|
|
14
|
-
-
|
|
15
|
-
- For
|
|
16
|
-
- Prefer
|
|
17
|
-
- Use `
|
|
18
|
-
-
|
|
19
|
-
-
|
|
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.
|
|
20
23
|
|
|
21
24
|
## Prove and report
|
|
22
25
|
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
-
|
|
26
|
-
-
|
|
27
|
-
-
|
|
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.
|
|
@@ -6,8 +6,9 @@ import { createRequire } from "node:module";
|
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { parseArgs } from "node:util";
|
|
8
8
|
import { generateTestSource, runRecipe, validateBaseUrl, validateRecipe } from "../src/index.js";
|
|
9
|
+
import { acquireProfileLock } from "../src/profile-lock.js";
|
|
9
10
|
|
|
10
|
-
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> Generate a native Playwright test\n run <recipe.json> --base-url <url> --profile-dir <dir> [--artifacts <dir>] [--
|
|
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`;
|
|
11
12
|
|
|
12
13
|
const parsed = parseArgs({
|
|
13
14
|
args: process.argv.slice(2),
|
|
@@ -21,6 +22,8 @@ const parsed = parseArgs({
|
|
|
21
22
|
"timeout-ms": { type: "string" },
|
|
22
23
|
url: { type: "string" },
|
|
23
24
|
headless: { type: "boolean", default: false },
|
|
25
|
+
headed: { type: "boolean", default: false },
|
|
26
|
+
fast: { type: "boolean", default: false },
|
|
24
27
|
force: { type: "boolean", default: false },
|
|
25
28
|
help: { type: "boolean", short: "h", default: false },
|
|
26
29
|
},
|
|
@@ -127,9 +130,12 @@ async function main() {
|
|
|
127
130
|
const requireFromProject = createRequire(pathToFileURL(resolve("package.json")));
|
|
128
131
|
const playwrightEntry = requireFromProject.resolve("playwright");
|
|
129
132
|
const cli = resolve(dirname(playwrightEntry), "cli.js");
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
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(); }
|
|
133
139
|
return;
|
|
134
140
|
}
|
|
135
141
|
if (command === "run") {
|
|
@@ -148,32 +154,36 @@ async function main() {
|
|
|
148
154
|
} catch {}
|
|
149
155
|
await mkdir(artifacts, { recursive: true });
|
|
150
156
|
const { chromium } = await import("playwright");
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
viewport: { width: 1440, height: 900 },
|
|
154
|
-
});
|
|
157
|
+
const releaseProfile = acquireProfileLock(profile);
|
|
158
|
+
let context;
|
|
155
159
|
let page;
|
|
156
160
|
let result;
|
|
157
161
|
let error;
|
|
158
162
|
try {
|
|
163
|
+
context = await chromium.launchPersistentContext(profile, {
|
|
164
|
+
headless: options.headed ? false : true,
|
|
165
|
+
viewport: { width: 1440, height: 900 },
|
|
166
|
+
});
|
|
159
167
|
page = context.pages()[0] ?? await context.newPage();
|
|
160
|
-
await context.tracing.start({ screenshots: true, snapshots: true, sources: false });
|
|
161
|
-
result = await runRecipe(page, recipe, { baseUrl: base.href, screenshotDir: artifacts, timeoutMs });
|
|
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 });
|
|
162
170
|
} catch (cause) {
|
|
163
171
|
error = cause;
|
|
164
172
|
if (page) {
|
|
165
173
|
try { await page.screenshot({ path: resolve(artifacts, "failure.png"), fullPage: true }); } catch {}
|
|
166
174
|
}
|
|
167
175
|
} finally {
|
|
168
|
-
try { await context.tracing.stop({ path: resolve(artifacts, "trace.zip") }); } catch {}
|
|
169
|
-
await context
|
|
176
|
+
if (context && !options.fast) try { await context.tracing.stop({ path: resolve(artifacts, "trace.zip") }); } catch {}
|
|
177
|
+
await context?.close();
|
|
178
|
+
releaseProfile();
|
|
170
179
|
}
|
|
171
180
|
const report = {
|
|
172
181
|
name: recipe.name,
|
|
173
182
|
status: error ? "failed" : "passed",
|
|
174
183
|
stepCount: recipe.steps.length,
|
|
175
184
|
screenshots: error ? ["failure.png"] : result.screenshots.map((file) => file.slice(artifacts.length + 1)),
|
|
176
|
-
trace: "trace.zip",
|
|
185
|
+
trace: options.fast ? null : "trace.zip",
|
|
186
|
+
fastMode: options.fast,
|
|
177
187
|
failedStep: error?.step ?? null,
|
|
178
188
|
error: error ? error.message : null,
|
|
179
189
|
};
|
|
@@ -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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spfx-fast/playwright",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"author": "Vilius Vystartas",
|
|
5
5
|
"description": "Authenticated, recipe-driven Playwright testing helpers for any SharePoint Framework project.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"main": "./src/index.js",
|
|
17
17
|
"types": "./src/index.d.ts",
|
|
18
18
|
"exports": { ".": { "types": "./src/index.d.ts", "import": "./src/index.js" } },
|
|
19
|
-
"bin": { "spfx-fast-playwright": "
|
|
19
|
+
"bin": { "spfx-fast-playwright": "bin/spfx-fast-playwright.mjs" },
|
|
20
20
|
"files": ["src", "bin", "README.md", "LICENSE", "examples", "agent"],
|
|
21
21
|
"peerDependencies": { "@playwright/test": ">=1.50.0 <2", "playwright": ">=1.50.0 <2" },
|
|
22
22
|
"keywords": ["spfx", "sharepoint", "playwright", "e2e", "testing", "agents"]
|
package/src/index.d.ts
CHANGED
|
@@ -8,10 +8,11 @@ export type RecipeLocator =
|
|
|
8
8
|
| { placeholder: string; exact?: boolean };
|
|
9
9
|
|
|
10
10
|
export type RecipeStep =
|
|
11
|
-
| { action: "navigate"; path: string }
|
|
11
|
+
| { action: "navigate"; path: string; query?: Record<string, string> }
|
|
12
12
|
| { action: "assertPageReady" }
|
|
13
13
|
| { action: "assertAuthenticated" }
|
|
14
|
-
| { action: "click"
|
|
14
|
+
| { action: "click"; locator: RecipeLocator; confirm?: true }
|
|
15
|
+
| { action: "assertVisible"; locator: RecipeLocator }
|
|
15
16
|
| { action: "fill"; locator: RecipeLocator; value: string }
|
|
16
17
|
| { action: "select"; locator: RecipeLocator; value: string }
|
|
17
18
|
| { action: "setChecked"; locator: RecipeLocator; checked: boolean }
|
|
@@ -29,5 +30,6 @@ export function runRecipe(page: Page, recipe: SharePointRecipe, options: {
|
|
|
29
30
|
baseUrl: string;
|
|
30
31
|
screenshotDir?: string;
|
|
31
32
|
timeoutMs?: number;
|
|
33
|
+
fast?: boolean;
|
|
32
34
|
}): Promise<{ name: string; steps: number; screenshots: string[] }>;
|
|
33
35
|
export function generateTestSource(recipe: SharePointRecipe): string;
|
package/src/index.js
CHANGED
|
@@ -16,8 +16,28 @@ export function validateRecipe(recipe) {
|
|
|
16
16
|
if (step.action === "navigate" && (typeof step.path !== "string" || !step.path.startsWith("/") || step.path.startsWith("//") || /[?#]/.test(step.path))) {
|
|
17
17
|
throw new TypeError(`Recipe step ${index + 1} needs a same-site path beginning with / and no query or fragment.`);
|
|
18
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
|
+
}
|
|
19
36
|
if (["click", "fill", "select", "setChecked", "assertVisible", "assertText", "assertValue"].includes(step.action)) validateLocator(step.locator, index + 1);
|
|
20
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
|
+
}
|
|
21
41
|
if (step.action === "setChecked" && typeof step.checked !== "boolean") throw new TypeError(`Recipe step ${index + 1} needs a boolean checked value.`);
|
|
22
42
|
if (["assertText", "assertValue"].includes(step.action) && typeof step.expected !== "string") throw new TypeError(`Recipe step ${index + 1} needs expected text.`);
|
|
23
43
|
if (step.action === "screenshot" && (typeof step.name !== "string" || !/^[\w-]+$/.test(step.name))) {
|
|
@@ -60,7 +80,7 @@ function assertSameOrigin(page, base) {
|
|
|
60
80
|
if (current.origin !== base.origin) throw new Error("Navigation left the configured SharePoint origin; check sign-in state and page links.");
|
|
61
81
|
}
|
|
62
82
|
|
|
63
|
-
export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutMs = 15000 } = {}) {
|
|
83
|
+
export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutMs = 15000, fast = false } = {}) {
|
|
64
84
|
validateRecipe(recipe);
|
|
65
85
|
const base = validateBaseUrl(baseUrl);
|
|
66
86
|
const screenshots = [];
|
|
@@ -71,6 +91,7 @@ export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutM
|
|
|
71
91
|
if (step.action === "navigate") {
|
|
72
92
|
const destination = new URL(step.path, base);
|
|
73
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);
|
|
74
95
|
const response = await page.goto(destination.href, { waitUntil: "domcontentloaded", timeout: timeoutMs });
|
|
75
96
|
if (response && response.status() >= 400) throw new Error(`Page returned HTTP ${response.status()}.`);
|
|
76
97
|
assertSameOrigin(page, base);
|
|
@@ -93,7 +114,28 @@ export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutM
|
|
|
93
114
|
}
|
|
94
115
|
assertSameOrigin(page, base);
|
|
95
116
|
} else if (step.action === "click") {
|
|
96
|
-
|
|
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
|
+
}
|
|
97
139
|
assertSameOrigin(page, base);
|
|
98
140
|
} else if (step.action === "fill") {
|
|
99
141
|
await locatorFor(page, step.locator).fill(step.value, { timeout: timeoutMs });
|
|
@@ -121,6 +163,7 @@ export async function runRecipe(page, recipe, { baseUrl, screenshotDir, timeoutM
|
|
|
121
163
|
if (!(step.exact === false ? actual.includes(step.expected) : actual === step.expected)) throw new Error(`Value assertion failed (${step.exact === false ? "contains" : "exact"}).`);
|
|
122
164
|
assertSameOrigin(page, base);
|
|
123
165
|
} else if (step.action === "screenshot") {
|
|
166
|
+
if (fast) continue;
|
|
124
167
|
if (!screenshotDir) throw new Error("Screenshots need an artifact directory.");
|
|
125
168
|
assertSameOrigin(page, base);
|
|
126
169
|
const file = join(screenshotDir, `${step.name}.png`);
|
|
@@ -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
|
+
}
|