@plune-ai/cairn 0.9.0 → 0.11.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.
- package/README.md +84 -8
- package/dist/agent/check-docs.d.ts +25 -0
- package/dist/agent/check-docs.d.ts.map +1 -0
- package/dist/agent/check-docs.js +57 -0
- package/dist/agent/check-docs.js.map +1 -0
- package/dist/agent/collect-docs.d.ts +94 -0
- package/dist/agent/collect-docs.d.ts.map +1 -0
- package/dist/agent/collect-docs.js +326 -0
- package/dist/agent/collect-docs.js.map +1 -0
- package/dist/agent/graph.d.ts +39 -2
- package/dist/agent/graph.d.ts.map +1 -1
- package/dist/agent/graph.js +113 -4
- package/dist/agent/graph.js.map +1 -1
- package/dist/agent/index.d.ts +14 -0
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +114 -10
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/overlays.d.ts +88 -0
- package/dist/agent/overlays.d.ts.map +1 -0
- package/dist/agent/overlays.js +447 -0
- package/dist/agent/overlays.js.map +1 -0
- package/dist/agent/repair-loop.d.ts +8 -1
- package/dist/agent/repair-loop.d.ts.map +1 -1
- package/dist/agent/repair-loop.js +18 -3
- package/dist/agent/repair-loop.js.map +1 -1
- package/dist/analyze/index.d.ts +1 -1
- package/dist/analyze/index.d.ts.map +1 -1
- package/dist/analyze/index.js +3 -2
- package/dist/analyze/index.js.map +1 -1
- package/dist/api/adversarial.d.ts +1 -1
- package/dist/api/adversarial.js +1 -1
- package/dist/api/collection.d.ts +20 -0
- package/dist/api/collection.d.ts.map +1 -0
- package/dist/api/collection.js +357 -0
- package/dist/api/collection.js.map +1 -0
- package/dist/api/derived.d.ts +179 -0
- package/dist/api/derived.d.ts.map +1 -0
- package/dist/api/derived.js +852 -0
- package/dist/api/derived.js.map +1 -0
- package/dist/api/discover.d.ts +66 -0
- package/dist/api/discover.d.ts.map +1 -0
- package/dist/api/discover.js +125 -0
- package/dist/api/discover.js.map +1 -0
- package/dist/api/flows.d.ts +194 -0
- package/dist/api/flows.d.ts.map +1 -0
- package/dist/api/flows.js +663 -0
- package/dist/api/flows.js.map +1 -0
- package/dist/api/guard.d.ts +19 -0
- package/dist/api/guard.d.ts.map +1 -1
- package/dist/api/guard.js +18 -4
- package/dist/api/guard.js.map +1 -1
- package/dist/api/openapi.d.ts +17 -1
- package/dist/api/openapi.d.ts.map +1 -1
- package/dist/api/openapi.js +64 -3
- package/dist/api/openapi.js.map +1 -1
- package/dist/api/runner.d.ts.map +1 -1
- package/dist/api/runner.js +18 -14
- package/dist/api/runner.js.map +1 -1
- package/dist/api/two-actor.d.ts +165 -0
- package/dist/api/two-actor.d.ts.map +1 -0
- package/dist/api/two-actor.js +627 -0
- package/dist/api/two-actor.js.map +1 -0
- package/dist/artifacts/contract.d.ts +1 -1
- package/dist/artifacts/contract.d.ts.map +1 -1
- package/dist/artifacts/index.d.ts +5 -0
- package/dist/artifacts/index.d.ts.map +1 -1
- package/dist/artifacts/index.js +14 -10
- package/dist/artifacts/index.js.map +1 -1
- package/dist/artifacts/report.d.ts +29 -2
- package/dist/artifacts/report.d.ts.map +1 -1
- package/dist/artifacts/report.js +65 -1
- package/dist/artifacts/report.js.map +1 -1
- package/dist/artifacts/testcase-md.d.ts +18 -0
- package/dist/artifacts/testcase-md.d.ts.map +1 -1
- package/dist/artifacts/testcase-md.js +15 -1
- package/dist/artifacts/testcase-md.js.map +1 -1
- package/dist/browser/api-traffic.d.ts +85 -0
- package/dist/browser/api-traffic.d.ts.map +1 -0
- package/dist/browser/api-traffic.js +283 -0
- package/dist/browser/api-traffic.js.map +1 -0
- package/dist/browser/backends/playwright-cli.d.ts.map +1 -1
- package/dist/browser/backends/playwright-cli.js +3 -0
- package/dist/browser/backends/playwright-cli.js.map +1 -1
- package/dist/browser/backends/playwright-lib.d.ts +84 -1
- package/dist/browser/backends/playwright-lib.d.ts.map +1 -1
- package/dist/browser/backends/playwright-lib.js +677 -32
- package/dist/browser/backends/playwright-lib.js.map +1 -1
- package/dist/browser/click-effect.d.ts +84 -0
- package/dist/browser/click-effect.d.ts.map +1 -0
- package/dist/browser/click-effect.js +235 -0
- package/dist/browser/click-effect.js.map +1 -0
- package/dist/browser/gateway.d.ts +9 -1
- package/dist/browser/gateway.d.ts.map +1 -1
- package/dist/browser/index.d.ts +3 -0
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/index.js +5 -0
- package/dist/browser/index.js.map +1 -1
- package/dist/browser/types.d.ts +196 -1
- package/dist/browser/types.d.ts.map +1 -1
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +123 -5
- package/dist/cli/index.js.map +1 -1
- package/dist/codegen/index.d.ts +10 -1
- package/dist/codegen/index.d.ts.map +1 -1
- package/dist/codegen/index.js +28 -7
- package/dist/codegen/index.js.map +1 -1
- package/dist/codegen/lint.d.ts +32 -1
- package/dist/codegen/lint.d.ts.map +1 -1
- package/dist/codegen/lint.js +286 -1
- package/dist/codegen/lint.js.map +1 -1
- package/dist/codegen/mailbox.d.ts +19 -0
- package/dist/codegen/mailbox.d.ts.map +1 -0
- package/dist/codegen/mailbox.js +78 -0
- package/dist/codegen/mailbox.js.map +1 -0
- package/dist/codegen/schema.d.ts.map +1 -1
- package/dist/codegen/schema.js +3 -2
- package/dist/codegen/schema.js.map +1 -1
- package/dist/config/profiles.d.ts +2 -0
- package/dist/config/profiles.d.ts.map +1 -1
- package/dist/config/profiles.js +2 -0
- package/dist/config/profiles.js.map +1 -1
- package/dist/core/modalities/api.d.ts.map +1 -1
- package/dist/core/modalities/api.js +265 -29
- package/dist/core/modalities/api.js.map +1 -1
- package/dist/core/modalities/check-docs.d.ts +3 -0
- package/dist/core/modalities/check-docs.d.ts.map +1 -0
- package/dist/core/modalities/check-docs.js +64 -0
- package/dist/core/modalities/check-docs.js.map +1 -0
- package/dist/core/modalities/collect-docs.d.ts +3 -0
- package/dist/core/modalities/collect-docs.d.ts.map +1 -0
- package/dist/core/modalities/collect-docs.js +48 -0
- package/dist/core/modalities/collect-docs.js.map +1 -0
- package/dist/core/modalities/explore.d.ts.map +1 -1
- package/dist/core/modalities/explore.js +2 -0
- package/dist/core/modalities/explore.js.map +1 -1
- package/dist/core/modalities/mcp-test.d.ts +3 -0
- package/dist/core/modalities/mcp-test.d.ts.map +1 -0
- package/dist/core/modalities/mcp-test.js +26 -0
- package/dist/core/modalities/mcp-test.js.map +1 -0
- package/dist/core/registry.d.ts.map +1 -1
- package/dist/core/registry.js +11 -3
- package/dist/core/registry.js.map +1 -1
- package/dist/decider/uses/repair-triage.d.ts +9 -0
- package/dist/decider/uses/repair-triage.d.ts.map +1 -1
- package/dist/decider/uses/repair-triage.js +20 -3
- package/dist/decider/uses/repair-triage.js.map +1 -1
- package/dist/design/critique.d.ts +1 -1
- package/dist/design/index.d.ts +7 -1
- package/dist/design/index.d.ts.map +1 -1
- package/dist/design/index.js +20 -2
- package/dist/design/index.js.map +1 -1
- package/dist/design/schema.d.ts +9 -3
- package/dist/design/schema.d.ts.map +1 -1
- package/dist/design/schema.js +4 -1
- package/dist/design/schema.js.map +1 -1
- package/dist/documentarian/check.d.ts +91 -0
- package/dist/documentarian/check.d.ts.map +1 -0
- package/dist/documentarian/check.js +230 -0
- package/dist/documentarian/check.js.map +1 -0
- package/dist/documentarian/docs.d.ts +103 -0
- package/dist/documentarian/docs.d.ts.map +1 -0
- package/dist/documentarian/docs.js +243 -0
- package/dist/documentarian/docs.js.map +1 -0
- package/dist/documentarian/index.d.ts +2 -0
- package/dist/documentarian/index.d.ts.map +1 -1
- package/dist/documentarian/index.js +5 -4
- package/dist/documentarian/index.js.map +1 -1
- package/dist/environment/apply.js +1 -1
- package/dist/environment/apply.js.map +1 -1
- package/dist/flow/crawl.d.ts +4 -0
- package/dist/flow/crawl.d.ts.map +1 -1
- package/dist/flow/crawl.js +9 -2
- package/dist/flow/crawl.js.map +1 -1
- package/dist/fs/inside-dir.d.ts +8 -0
- package/dist/fs/inside-dir.d.ts.map +1 -0
- package/dist/fs/inside-dir.js +15 -0
- package/dist/fs/inside-dir.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/index.d.ts +1 -1
- package/dist/llm/index.d.ts.map +1 -1
- package/dist/llm/index.js +1 -1
- package/dist/llm/index.js.map +1 -1
- package/dist/llm/structured.d.ts +19 -0
- package/dist/llm/structured.d.ts.map +1 -1
- package/dist/llm/structured.js +61 -0
- package/dist/llm/structured.js.map +1 -1
- package/dist/mailbox/doctor.d.ts +10 -0
- package/dist/mailbox/doctor.d.ts.map +1 -0
- package/dist/mailbox/doctor.js +33 -0
- package/dist/mailbox/doctor.js.map +1 -0
- package/dist/mailbox/rule.d.ts +34 -0
- package/dist/mailbox/rule.d.ts.map +1 -0
- package/dist/mailbox/rule.js +47 -0
- package/dist/mailbox/rule.js.map +1 -0
- package/dist/mailbox/session.d.ts +5 -0
- package/dist/mailbox/session.d.ts.map +1 -1
- package/dist/mailbox/session.js +8 -0
- package/dist/mailbox/session.js.map +1 -1
- package/dist/mcp/server.d.ts +15 -5
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +75 -27
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/tools.d.ts +194 -82
- package/dist/mcp/tools.d.ts.map +1 -1
- package/dist/mcp/tools.js +82 -8
- package/dist/mcp/tools.js.map +1 -1
- package/dist/mcp-test/adversarial.d.ts +80 -0
- package/dist/mcp-test/adversarial.d.ts.map +1 -0
- package/dist/mcp-test/adversarial.js +99 -0
- package/dist/mcp-test/adversarial.js.map +1 -0
- package/dist/mcp-test/advice.d.ts +20 -0
- package/dist/mcp-test/advice.d.ts.map +1 -0
- package/dist/mcp-test/advice.js +22 -0
- package/dist/mcp-test/advice.js.map +1 -0
- package/dist/mcp-test/call.d.ts +76 -0
- package/dist/mcp-test/call.d.ts.map +1 -0
- package/dist/mcp-test/call.js +105 -0
- package/dist/mcp-test/call.js.map +1 -0
- package/dist/mcp-test/cases.d.ts +154 -0
- package/dist/mcp-test/cases.d.ts.map +1 -0
- package/dist/mcp-test/cases.js +643 -0
- package/dist/mcp-test/cases.js.map +1 -0
- package/dist/mcp-test/connect.d.ts +70 -0
- package/dist/mcp-test/connect.d.ts.map +1 -0
- package/dist/mcp-test/connect.js +426 -0
- package/dist/mcp-test/connect.js.map +1 -0
- package/dist/mcp-test/coverage.d.ts +61 -0
- package/dist/mcp-test/coverage.d.ts.map +1 -0
- package/dist/mcp-test/coverage.js +76 -0
- package/dist/mcp-test/coverage.js.map +1 -0
- package/dist/mcp-test/discover.d.ts +40 -0
- package/dist/mcp-test/discover.d.ts.map +1 -0
- package/dist/mcp-test/discover.js +149 -0
- package/dist/mcp-test/discover.js.map +1 -0
- package/dist/mcp-test/guard.d.ts +161 -0
- package/dist/mcp-test/guard.d.ts.map +1 -0
- package/dist/mcp-test/guard.js +363 -0
- package/dist/mcp-test/guard.js.map +1 -0
- package/dist/mcp-test/model.d.ts +89 -0
- package/dist/mcp-test/model.d.ts.map +1 -0
- package/dist/mcp-test/model.js +88 -0
- package/dist/mcp-test/model.js.map +1 -0
- package/dist/mcp-test/payloads.d.ts +20 -0
- package/dist/mcp-test/payloads.d.ts.map +1 -0
- package/dist/mcp-test/payloads.js +20 -0
- package/dist/mcp-test/payloads.js.map +1 -0
- package/dist/mcp-test/report.d.ts +55 -0
- package/dist/mcp-test/report.d.ts.map +1 -0
- package/dist/mcp-test/report.js +157 -0
- package/dist/mcp-test/report.js.map +1 -0
- package/dist/mcp-test/run.d.ts +68 -0
- package/dist/mcp-test/run.d.ts.map +1 -0
- package/dist/mcp-test/run.js +467 -0
- package/dist/mcp-test/run.js.map +1 -0
- package/dist/mcp-test/runner.d.ts +133 -0
- package/dist/mcp-test/runner.d.ts.map +1 -0
- package/dist/mcp-test/runner.js +412 -0
- package/dist/mcp-test/runner.js.map +1 -0
- package/dist/mcp-test/schema.d.ts +103 -0
- package/dist/mcp-test/schema.d.ts.map +1 -0
- package/dist/mcp-test/schema.js +513 -0
- package/dist/mcp-test/schema.js.map +1 -0
- package/dist/mcp-test/secrets.d.ts +25 -0
- package/dist/mcp-test/secrets.d.ts.map +1 -0
- package/dist/mcp-test/secrets.js +67 -0
- package/dist/mcp-test/secrets.js.map +1 -0
- package/dist/observe/index.d.ts +3 -1
- package/dist/observe/index.d.ts.map +1 -1
- package/dist/observe/index.js +1 -0
- package/dist/observe/index.js.map +1 -1
- package/dist/observe/locator-hints.d.ts +18 -0
- package/dist/observe/locator-hints.d.ts.map +1 -0
- package/dist/observe/locator-hints.js +36 -0
- package/dist/observe/locator-hints.js.map +1 -0
- package/dist/observe/overlays.d.ts +135 -0
- package/dist/observe/overlays.d.ts.map +1 -0
- package/dist/observe/overlays.js +242 -0
- package/dist/observe/overlays.js.map +1 -0
- package/dist/observe/parse-aria.d.ts +7 -1
- package/dist/observe/parse-aria.d.ts.map +1 -1
- package/dist/observe/parse-aria.js +79 -4
- package/dist/observe/parse-aria.js.map +1 -1
- package/dist/probe/index.d.ts +3 -1
- package/dist/probe/index.d.ts.map +1 -1
- package/dist/probe/index.js +3 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/project/index.d.ts +2 -0
- package/dist/project/index.d.ts.map +1 -1
- package/dist/project/index.js +10 -2
- package/dist/project/index.js.map +1 -1
- package/dist/prompts/local/describe-screen.d.ts +7 -0
- package/dist/prompts/local/describe-screen.d.ts.map +1 -0
- package/dist/prompts/local/describe-screen.js +29 -0
- package/dist/prompts/local/describe-screen.js.map +1 -0
- package/dist/prompts/local/index.d.ts.map +1 -1
- package/dist/prompts/local/index.js +7 -0
- package/dist/prompts/local/index.js.map +1 -1
- package/dist/prompts/local/name-overlays.d.ts +6 -0
- package/dist/prompts/local/name-overlays.d.ts.map +1 -0
- package/dist/prompts/local/name-overlays.js +16 -0
- package/dist/prompts/local/name-overlays.js.map +1 -0
- package/dist/prompts/local/qa-api-flows.d.ts +8 -0
- package/dist/prompts/local/qa-api-flows.d.ts.map +1 -0
- package/dist/prompts/local/qa-api-flows.js +19 -0
- package/dist/prompts/local/qa-api-flows.js.map +1 -0
- package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
- package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
- package/dist/prompts/local/qa-playwright-ts-writer.js +5 -1
- package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.js +2 -0
- package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
- package/dist/session/index.d.ts.map +1 -1
- package/dist/session/index.js +24 -2
- package/dist/session/index.js.map +1 -1
- package/dist/validate/index.d.ts +11 -0
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +21 -0
- package/dist/validate/index.js.map +1 -1
- package/dist/validate/runner.d.ts +15 -1
- package/dist/validate/runner.d.ts.map +1 -1
- package/dist/validate/runner.js +158 -25
- package/dist/validate/runner.js.map +1 -1
- package/dist/validate/write-guard.d.ts +24 -0
- package/dist/validate/write-guard.d.ts.map +1 -0
- package/dist/validate/write-guard.js +210 -0
- package/dist/validate/write-guard.js.map +1 -0
- package/dist/view/index.d.ts +9 -0
- package/dist/view/index.d.ts.map +1 -0
- package/dist/view/index.js +126 -0
- package/dist/view/index.js.map +1 -0
- package/package.json +3 -2
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #230 — saved API flows: a named chain of requests (its steps, the values it returns, and the cleanup that deletes
|
|
3
|
+
* what it created), kept in a JSON file and turned into a Playwright fixture for UI tests. A UI test then gets its
|
|
4
|
+
* data or its session through the API instead of twenty UI steps, and the cleanup runs after the test whatever its
|
|
5
|
+
* result (a fixture's teardown runs after a failed test, and the cleanup sits in a `finally`).
|
|
6
|
+
*
|
|
7
|
+
* A flow comes from a hand-written file or from `cairn api --scenarios --save-flows` (the create step of a scenario
|
|
8
|
+
* chain, the id its delete needs, and the delete as cleanup). Nothing here sends a request: the fixture does, in the
|
|
9
|
+
* user's own test run, and a flow that changes data refuses to run against an address no flag allowed — the same
|
|
10
|
+
* read-only default as `cairn api --base-url` (#196).
|
|
11
|
+
*/
|
|
12
|
+
import { readFile } from "node:fs/promises";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { collectSecrets, READ_ONLY_METHODS, SENSITIVE } from "./guard.js";
|
|
15
|
+
/** The fixture module's file name, beside the specs that import it (`import { test, expect } from './api-flows.fixture'`). */
|
|
16
|
+
export const FLOW_FIXTURE_FILE = "api-flows.fixture.ts";
|
|
17
|
+
const METHODS = ["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"];
|
|
18
|
+
/** `{{name}}`, `{{env.NAME}}` or `{{uid}}` inside any string of a step. */
|
|
19
|
+
const TEMPLATE = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
20
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
21
|
+
/** Body / form / query keys (and header names) whose literal value would be a secret written into the file. */
|
|
22
|
+
const SECRET_KEY = /pass(?:w|phrase|code)|pwd|secret|token|credential|api[-_]?key|auth(?!or(?!i[sz]))/i;
|
|
23
|
+
/** Short words that name a secret only as a whole word of a key (`pass`, `userPass`, `db_pass`), not inside `compass`. */
|
|
24
|
+
const SECRET_WORDS = new Set(["pass", "passwd", "pw", "creds"]);
|
|
25
|
+
const isSecretKey = (key) => SECRET_KEY.test(key) || key.split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/).some((w) => SECRET_WORDS.has(w.toLowerCase()));
|
|
26
|
+
/** A header whose name says it carries a credential (`Authorization`, `Cookie`, `X-Api-Key`, `X-Auth-Token`, …). */
|
|
27
|
+
export const isCredentialHeader = (name) => SENSITIVE.test(name) || isSecretKey(name);
|
|
28
|
+
/** The only shape a secret may take in the file: `{{env.NAME}}`, after an optional `Bearer `/`Basic `/`Token ` scheme. */
|
|
29
|
+
const ENV_ONLY = /^(?:(?:Bearer|Basic|Token) )?\{\{\s*env\.[A-Za-z_][A-Za-z0-9_]*\s*\}\}$/i;
|
|
30
|
+
/** Names the Playwright test fixtures and options already use — a flow named so would shadow one. */
|
|
31
|
+
const PLAYWRIGHT_NAMES = new Set([
|
|
32
|
+
"page", "context", "browser", "browserName", "request", "playwright", "baseURL", "storageState", "headless", "channel",
|
|
33
|
+
"launchOptions", "connectOptions", "viewport", "video", "trace", "screenshot", "testIdAttribute", "extraHTTPHeaders",
|
|
34
|
+
"httpCredentials", "ignoreHTTPSErrors", "locale", "timezoneId", "geolocation", "permissions", "offline", "colorScheme",
|
|
35
|
+
"userAgent", "javaScriptEnabled", "bypassCSP", "proxy", "actionTimeout", "navigationTimeout", "contextOptions",
|
|
36
|
+
"serviceWorkers", "acceptDownloads", "deviceScaleFactor", "hasTouch", "isMobile", "test", "expect", "use",
|
|
37
|
+
]);
|
|
38
|
+
/** A JSON pointer into the response body, written `/id` or as in OpenAPI links, `$response.body#/id`. */
|
|
39
|
+
const PointerSchema = z
|
|
40
|
+
.string()
|
|
41
|
+
.transform((s) => s.replace(/^\$response\.body#/, ""))
|
|
42
|
+
.refine((s) => s.startsWith("/"), "a capture is a JSON pointer into the response body, e.g. /id or $response.body#/id");
|
|
43
|
+
const StepSchema = z
|
|
44
|
+
.strictObject({
|
|
45
|
+
name: z.string().optional(),
|
|
46
|
+
method: z
|
|
47
|
+
.string()
|
|
48
|
+
.transform((s) => s.toUpperCase())
|
|
49
|
+
.pipe(z.enum(METHODS)),
|
|
50
|
+
path: z
|
|
51
|
+
.string()
|
|
52
|
+
.regex(/^\/(?!\/)/, "a path starts with a single '/' and is relative to the base URL")
|
|
53
|
+
.refine((s) => !s.includes("?") && !s.includes("#"), "a path has no '?' or '#': query parameters go in \"query\""),
|
|
54
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
55
|
+
query: z.record(z.string(), z.string()).optional(),
|
|
56
|
+
body: z.unknown().optional(),
|
|
57
|
+
form: z.record(z.string(), z.string()).optional(),
|
|
58
|
+
/** Statuses that count as success; default any 2xx or 3xx (redirects are not followed). */
|
|
59
|
+
expect: z.union([z.number().int(), z.array(z.number().int()).min(1)]).optional(),
|
|
60
|
+
/** Values to keep from the JSON answer, by name, for later steps, the cleanup and `returns`. */
|
|
61
|
+
capture: z.record(z.string().regex(IDENT, "a captured name is an identifier"), PointerSchema).optional(),
|
|
62
|
+
})
|
|
63
|
+
.refine((s) => s.body === undefined || s.form === undefined, "a step sends a JSON body or a form, not both");
|
|
64
|
+
const FlowSchema = z.strictObject({
|
|
65
|
+
name: z.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/, "a flow name is a TypeScript identifier (it becomes the fixture's name)"),
|
|
66
|
+
/** `data` (default): creates or reads data and returns values; `signin`: its cookies become the tests' storageState. */
|
|
67
|
+
kind: z.enum(["data", "signin"]).default("data"),
|
|
68
|
+
description: z.string().default(""),
|
|
69
|
+
steps: z.array(StepSchema).min(1),
|
|
70
|
+
returns: z.array(z.string()).default([]),
|
|
71
|
+
cleanup: z.array(StepSchema).default([]),
|
|
72
|
+
});
|
|
73
|
+
const FlowFileSchema = z.strictObject({
|
|
74
|
+
version: z.literal(1),
|
|
75
|
+
/** Where the API lives; the fixture falls back to it when API_BASE_URL is not set. */
|
|
76
|
+
baseUrl: z.url({ protocol: /^https?$/ }).optional(),
|
|
77
|
+
/** Headers on every request, e.g. `"Authorization": "Bearer {{env.API_TOKEN}}"`. */
|
|
78
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
79
|
+
flows: z.array(FlowSchema),
|
|
80
|
+
});
|
|
81
|
+
/**
|
|
82
|
+
* A flow changes data when it is not a sign-in and any of its steps or cleanup steps is not GET/HEAD/OPTIONS. A
|
|
83
|
+
* sign-in flow may send one such request — the login itself — and nothing else that changes data (checked on read).
|
|
84
|
+
*/
|
|
85
|
+
export function flowChangesData(flow) {
|
|
86
|
+
return flow.kind === "data" && [...flow.steps, ...flow.cleanup].some((s) => !READ_ONLY_METHODS.has(s.method));
|
|
87
|
+
}
|
|
88
|
+
/** The `{{…}}` names a step sends: its path, headers, query, body and form. Its `name` is only a label. */
|
|
89
|
+
export function stepTemplateNames(step) {
|
|
90
|
+
return templateNames([step.path, step.headers, step.query, step.body, step.form]);
|
|
91
|
+
}
|
|
92
|
+
/** Every `{{…}}` name in a value (strings, arrays and objects, keys left alone). */
|
|
93
|
+
export function templateNames(value) {
|
|
94
|
+
if (typeof value === "string")
|
|
95
|
+
return [...value.matchAll(TEMPLATE)].map((m) => m[1]);
|
|
96
|
+
if (Array.isArray(value))
|
|
97
|
+
return value.flatMap(templateNames);
|
|
98
|
+
if (value && typeof value === "object")
|
|
99
|
+
return Object.values(value).flatMap(templateNames);
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
/** #253: every `{{…}}` name in a key of a value. A key goes out as written, so a template there is filled by nothing. */
|
|
103
|
+
function keyTemplates(value) {
|
|
104
|
+
if (Array.isArray(value))
|
|
105
|
+
return value.flatMap(keyTemplates);
|
|
106
|
+
if (!value || typeof value !== "object")
|
|
107
|
+
return [];
|
|
108
|
+
return Object.entries(value).flatMap(([k, v]) => [...templateNames(k), ...keyTemplates(v)]);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* #253: a JSON answer with every number kept as the text the server wrote, where JSON.parse would make a double of
|
|
112
|
+
* it. Only numbers outside strings are matched: a string is matched first, whole, and left as it is.
|
|
113
|
+
*/
|
|
114
|
+
export const numbersAsWritten = (text) => JSON.parse(text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (t) => (t.startsWith('"') ? t : `"${t}"`)));
|
|
115
|
+
/** A number's text as its sign, its digits with no zero at either end and its exponent: `3.50`, `35e-1` → `35e-1`. */
|
|
116
|
+
const digitsOf = (n) => {
|
|
117
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(n);
|
|
118
|
+
if (!m)
|
|
119
|
+
return n; // Infinity
|
|
120
|
+
const all = `${m[2]}${m[3] ?? ""}`.replace(/^0+/, "");
|
|
121
|
+
const digits = all.replace(/0+$/, "");
|
|
122
|
+
return digits ? `${m[1]}${digits}e${Number(m[4] ?? 0) - (m[3] ?? "").length + all.length - digits.length}` : "0";
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* #251, #253: whether a captured number `v` may go into a request. Not a whole number past 2^53, which JSON.parse may
|
|
126
|
+
* have rounded to another record's id, and only the number the server wrote (`written`, from {@link numbersAsWritten}):
|
|
127
|
+
* `1e400` reads as Infinity, `9007199254740991.4` and `3.0000000000000000001` read as safe integers.
|
|
128
|
+
*/
|
|
129
|
+
export const isExactNumber = (v, written) => !(Number.isInteger(v) && !Number.isSafeInteger(v)) && digitsOf(String(v)) === digitsOf(written);
|
|
130
|
+
/**
|
|
131
|
+
* #250: what a run's output must not repeat: the value of every `{{env.NAME}}` the file names, as written and as it goes
|
|
132
|
+
* on the wire (encoded in a path, a query or a form, escaped in a JSON body). What is worth masking is decided as for a
|
|
133
|
+
* credential header's value: too short or too common a value would mangle the text, and is left alone.
|
|
134
|
+
*/
|
|
135
|
+
export function flowEnvSecrets(file, env = process.env) {
|
|
136
|
+
const values = templateNames(file).flatMap((n) => (n.startsWith("env.") ? (env[n.slice(4)] ?? []) : []));
|
|
137
|
+
const forms = (s) => [s, new URLSearchParams({ s }).toString().slice(2), JSON.stringify(s).slice(1, -1)];
|
|
138
|
+
return [...new Set(values.flatMap((v) => collectSecrets({ Authorization: v }).flatMap(forms)))];
|
|
139
|
+
}
|
|
140
|
+
/** Body / form / query fields that hold a literal secret, as `key` paths. */
|
|
141
|
+
function literalSecrets(value, at = "") {
|
|
142
|
+
if (Array.isArray(value))
|
|
143
|
+
return value.flatMap((v, i) => literalSecrets(v, `${at}[${i}]`));
|
|
144
|
+
if (!value || typeof value !== "object")
|
|
145
|
+
return [];
|
|
146
|
+
return Object.entries(value).flatMap(([k, v]) => {
|
|
147
|
+
const here = at ? `${at}.${k}` : k;
|
|
148
|
+
if (typeof v === "string" && isSecretKey(k) && v !== "" && !ENV_ONLY.test(v))
|
|
149
|
+
return [here];
|
|
150
|
+
return literalSecrets(v, here);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/** #233: the same rule for any header map Cairn reads from a file — a secret only as `{{env.NAME}}`. */
|
|
154
|
+
export function secretHeaderProblems(headers, where) {
|
|
155
|
+
const errors = [];
|
|
156
|
+
checkHeaders(headers, where, errors);
|
|
157
|
+
return errors;
|
|
158
|
+
}
|
|
159
|
+
function checkHeaders(headers, where, errors) {
|
|
160
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
161
|
+
if ((SENSITIVE.test(name) || isSecretKey(name)) && !ENV_ONLY.test(value)) {
|
|
162
|
+
errors.push(`${where}: header "${name}" holds a secret — write it as {{env.NAME}} (after an optional Bearer/Basic/Token) and set NAME in the environment`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** A flow's exported type name: `project` → `ProjectFlow`. Two flows must not share one (`a` and `A`). */
|
|
167
|
+
const typeNameOf = (flow) => `${flow.charAt(0).toUpperCase()}${flow.slice(1).replace(/^\$/, "")}Flow`;
|
|
168
|
+
/** The cross-field rules zod cannot express: names, templates, returns, cleanup and secrets. */
|
|
169
|
+
function checkFlowFile(file) {
|
|
170
|
+
const errors = [];
|
|
171
|
+
checkHeaders(file.headers, "headers", errors);
|
|
172
|
+
for (const n of templateNames(file.headers)) {
|
|
173
|
+
if (n !== "uid" && !/^env\.[A-Za-z_][A-Za-z0-9_]*$/.test(n))
|
|
174
|
+
errors.push(`headers: {{${n}}} — file headers may use only {{env.NAME}} and {{uid}}`);
|
|
175
|
+
}
|
|
176
|
+
for (const n of keyTemplates(file.headers))
|
|
177
|
+
errors.push(`headers: {{${n}}} is in a key; only values are filled, so write the key as it goes out`);
|
|
178
|
+
const seen = new Set();
|
|
179
|
+
const typeNames = new Map();
|
|
180
|
+
for (const flow of file.flows) {
|
|
181
|
+
const at = `flow "${flow.name}"`;
|
|
182
|
+
if (seen.has(flow.name))
|
|
183
|
+
errors.push(`${at}: the name is used twice`);
|
|
184
|
+
else {
|
|
185
|
+
const other = typeNames.get(typeNameOf(flow.name));
|
|
186
|
+
if (other !== undefined)
|
|
187
|
+
errors.push(`${at}: its type ${typeNameOf(flow.name)} is also flow "${other}"'s — rename one of them`);
|
|
188
|
+
else
|
|
189
|
+
typeNames.set(typeNameOf(flow.name), flow.name);
|
|
190
|
+
}
|
|
191
|
+
seen.add(flow.name);
|
|
192
|
+
if (PLAYWRIGHT_NAMES.has(flow.name))
|
|
193
|
+
errors.push(`${at}: "${flow.name}" is a Playwright fixture or option name — pick another`);
|
|
194
|
+
const known = new Set(["uid"]);
|
|
195
|
+
const checkStep = (step, where) => {
|
|
196
|
+
checkHeaders(step.headers, where, errors);
|
|
197
|
+
for (const key of [...literalSecrets(step.body), ...literalSecrets(step.form), ...literalSecrets(step.query)]) {
|
|
198
|
+
errors.push(`${where}: "${key}" holds a secret — write it as {{env.NAME}} and set NAME in the environment`);
|
|
199
|
+
}
|
|
200
|
+
for (const n of keyTemplates([step.headers, step.query, step.body, step.form])) {
|
|
201
|
+
errors.push(`${where}: {{${n}}} is in a key; only values are filled, so write the key as it goes out`);
|
|
202
|
+
}
|
|
203
|
+
for (const n of stepTemplateNames(step)) {
|
|
204
|
+
if (/^env\.[A-Za-z_][A-Za-z0-9_]*$/.test(n) || known.has(n))
|
|
205
|
+
continue;
|
|
206
|
+
errors.push(`${where}: {{${n}}} names no value captured before it (nor env.NAME or uid)`);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
flow.steps.forEach((step, i) => {
|
|
210
|
+
checkStep(step, `${at} step ${i + 1}`);
|
|
211
|
+
for (const name of Object.keys(step.capture ?? {})) {
|
|
212
|
+
if (name === "uid" || name === "env")
|
|
213
|
+
errors.push(`${at} step ${i + 1}: "${name}" cannot be a captured name`);
|
|
214
|
+
known.add(name);
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
flow.cleanup.forEach((step, i) => {
|
|
218
|
+
checkStep(step, `${at} cleanup ${i + 1}`);
|
|
219
|
+
if (step.capture)
|
|
220
|
+
errors.push(`${at} cleanup ${i + 1}: a cleanup step captures nothing`);
|
|
221
|
+
});
|
|
222
|
+
for (const r of flow.returns) {
|
|
223
|
+
if (r === "uid" || !known.has(r))
|
|
224
|
+
errors.push(`${at}: "${flow.name}" returns "${r}", which no step captures`);
|
|
225
|
+
}
|
|
226
|
+
if (flow.kind === "signin") {
|
|
227
|
+
if (flow.returns.length)
|
|
228
|
+
errors.push(`${at}: a sign-in flow returns its session (storageState), not values`);
|
|
229
|
+
if (flow.cleanup.length)
|
|
230
|
+
errors.push(`${at}: a sign-in flow has no cleanup`);
|
|
231
|
+
if (flow.steps.filter((s) => !READ_ONLY_METHODS.has(s.method)).length > 1) {
|
|
232
|
+
errors.push(`${at}: a sign-in flow sends one request that changes data (the login) — its other steps are GET/HEAD/OPTIONS; put the rest in a data flow`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
else if (flowChangesData(flow) && flow.cleanup.length === 0) {
|
|
236
|
+
errors.push(`${at}: "${flow.name}" changes data but has no cleanup — add the steps that delete what it creates`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (file.flows.filter((f) => f.kind === "signin").length > 1) {
|
|
240
|
+
errors.push("a file has at most one sign-in flow: it sets the tests' storageState, and there is only one");
|
|
241
|
+
}
|
|
242
|
+
return errors;
|
|
243
|
+
}
|
|
244
|
+
/** Read and check a flow file's text. Throws one error listing every problem found. */
|
|
245
|
+
export function parseApiFlows(text, source = "the API flow file") {
|
|
246
|
+
let raw;
|
|
247
|
+
try {
|
|
248
|
+
raw = JSON.parse(text);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
// The parser quotes the text around the error, and nothing has checked yet that this text holds no secret.
|
|
252
|
+
throw new Error(`${source} is not valid JSON.`);
|
|
253
|
+
}
|
|
254
|
+
const parsed = FlowFileSchema.safeParse(raw);
|
|
255
|
+
const problems = parsed.success
|
|
256
|
+
? checkFlowFile(parsed.data)
|
|
257
|
+
: parsed.error.issues.map((i) => `${i.path.map((p) => (typeof p === "number" ? `[${p}]` : `.${String(p)}`)).join("").replace(/^\./, "") || "(file)"}: ${i.message}`);
|
|
258
|
+
if (problems.length || !parsed.success) {
|
|
259
|
+
throw new Error(`${source} is not a valid API flow file:\n${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
260
|
+
}
|
|
261
|
+
return parsed.data;
|
|
262
|
+
}
|
|
263
|
+
/** Read a flow file from disk (see {@link parseApiFlows}). */
|
|
264
|
+
export async function loadApiFlows(path) {
|
|
265
|
+
let text;
|
|
266
|
+
try {
|
|
267
|
+
text = await readFile(path, "utf8");
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
throw new Error(`Cannot read the API flow file ${path}: ${e.message}`);
|
|
271
|
+
}
|
|
272
|
+
return parseApiFlows(text, path);
|
|
273
|
+
}
|
|
274
|
+
// ── save a scenario chain as a flow ─────────────────────────────────────────
|
|
275
|
+
/** `pets lifecycle` → `pets`; `user-profiles` → `userProfiles`; a name Playwright uses gets a `Flow` suffix. */
|
|
276
|
+
function flowNameOf(scenario) {
|
|
277
|
+
const words = scenario.name.replace(/\s+lifecycle$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean);
|
|
278
|
+
let name = words.map((w, i) => (i === 0 ? w.charAt(0).toLowerCase() + w.slice(1) : w.charAt(0).toUpperCase() + w.slice(1))).join("") || "flow";
|
|
279
|
+
if (/^[0-9]/.test(name))
|
|
280
|
+
name = `_${name}`;
|
|
281
|
+
return PLAYWRIGHT_NAMES.has(name) ? `${name}Flow` : name;
|
|
282
|
+
}
|
|
283
|
+
const stringMap = (bucket) => {
|
|
284
|
+
const entries = Object.entries(bucket).map(([k, v]) => [k, String(v)]);
|
|
285
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
286
|
+
};
|
|
287
|
+
/** A synthesised value under a secret-shaped key becomes `{{env.FLOW_KEY}}`: the file never holds a secret. */
|
|
288
|
+
function envForSecrets(value, flow) {
|
|
289
|
+
if (Array.isArray(value))
|
|
290
|
+
return value.map((v) => envForSecrets(v, flow));
|
|
291
|
+
if (!value || typeof value !== "object")
|
|
292
|
+
return value;
|
|
293
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [
|
|
294
|
+
k,
|
|
295
|
+
typeof v === "string" && isSecretKey(k) ? `{{env.${`${flow}_${k}`.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase()}}}` : envForSecrets(v, flow),
|
|
296
|
+
]));
|
|
297
|
+
}
|
|
298
|
+
const statusOf = (c) => (/^\d{3}$/.test(c.expectedStatus) ? Number(c.expectedStatus) : undefined);
|
|
299
|
+
/**
|
|
300
|
+
* Turn generated scenario chains (API-9) into flows: the chain's create step, the values its DELETE needs (captured
|
|
301
|
+
* from the create's answer — a declared `links` expression first, a same-name field second, as the scenario runner
|
|
302
|
+
* does), and that DELETE as the cleanup. A chain without a DELETE is not saved: nothing would remove what it creates.
|
|
303
|
+
*/
|
|
304
|
+
export function flowsFromScenarios(scenarios) {
|
|
305
|
+
const flows = [];
|
|
306
|
+
const notSaved = [];
|
|
307
|
+
for (const s of scenarios) {
|
|
308
|
+
const create = s.steps[0];
|
|
309
|
+
const del = s.steps.find((c) => c.method === "DELETE");
|
|
310
|
+
if (!create || create.method !== "POST" || !del) {
|
|
311
|
+
notSaved.push({ name: s.name, reason: "no DELETE step to clean up what it creates" });
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (create.body !== undefined && JSON.stringify(create.body).includes('"type":"Buffer"')) {
|
|
315
|
+
notSaved.push({ name: s.name, reason: "its create step sends a file (binary body), which a flow file cannot hold" });
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const name = flowNameOf(s);
|
|
319
|
+
const needed = Object.keys(del.params.path);
|
|
320
|
+
const capture = {};
|
|
321
|
+
for (const param of needed) {
|
|
322
|
+
const link = Object.values(create.responseLinks ?? {}).find((l) => l.operationId === del.operationId && l.parameters[param]);
|
|
323
|
+
const expr = link?.parameters[param];
|
|
324
|
+
capture[param] = expr && /^\$response\.body#\//.test(expr) ? expr.replace(/^\$response\.body#/, "") : `/${param}`;
|
|
325
|
+
}
|
|
326
|
+
// Path parameters of the create (a parent's id) keep their synthesised value; the delete's come from the capture.
|
|
327
|
+
let createPath = create.path;
|
|
328
|
+
for (const [k, v] of Object.entries(create.params.path))
|
|
329
|
+
createPath = createPath.replace(`{${k}}`, encodeURIComponent(String(v)));
|
|
330
|
+
let deletePath = del.path;
|
|
331
|
+
for (const param of needed)
|
|
332
|
+
deletePath = deletePath.replace(`{${param}}`, `{{${param}}}`);
|
|
333
|
+
const createStatus = statusOf(create);
|
|
334
|
+
const deleteStatus = statusOf(del);
|
|
335
|
+
const headers = stringMap(Object.fromEntries(Object.entries(create.params.header).filter(([k]) => !SENSITIVE.test(k) && !isSecretKey(k))));
|
|
336
|
+
const asEnv = (q) => q && envForSecrets(q, name);
|
|
337
|
+
const query = asEnv(stringMap(create.params.query));
|
|
338
|
+
const delQuery = asEnv(stringMap(Object.fromEntries(Object.entries(del.params.query).filter(([k]) => !needed.includes(k)))));
|
|
339
|
+
flows.push({
|
|
340
|
+
name,
|
|
341
|
+
kind: "data",
|
|
342
|
+
description: `${s.name}: ${create.name} → ${del.name}, saved from cairn api --scenarios`,
|
|
343
|
+
steps: [
|
|
344
|
+
{
|
|
345
|
+
name: create.name,
|
|
346
|
+
method: "POST",
|
|
347
|
+
path: createPath,
|
|
348
|
+
...(headers ? { headers } : {}),
|
|
349
|
+
...(query ? { query } : {}),
|
|
350
|
+
...(create.body !== undefined ? { body: envForSecrets(create.body, name) } : {}),
|
|
351
|
+
...(createStatus ? { expect: createStatus } : {}),
|
|
352
|
+
capture,
|
|
353
|
+
},
|
|
354
|
+
],
|
|
355
|
+
returns: needed,
|
|
356
|
+
cleanup: [
|
|
357
|
+
{
|
|
358
|
+
name: del.name,
|
|
359
|
+
method: "DELETE",
|
|
360
|
+
path: deletePath,
|
|
361
|
+
...(delQuery ? { query: delQuery } : {}),
|
|
362
|
+
// 404: the test itself already removed it — nothing is left behind either way.
|
|
363
|
+
...(deleteStatus ? { expect: [deleteStatus, 404] } : {}),
|
|
364
|
+
},
|
|
365
|
+
],
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return { flows, notSaved };
|
|
369
|
+
}
|
|
370
|
+
/** Put `flows` into `file`: a flow with the same name is replaced in place, a new one is appended, the rest kept. */
|
|
371
|
+
export function mergeApiFlows(file, flows) {
|
|
372
|
+
const byName = new Map(flows.map((f) => [f.name, f]));
|
|
373
|
+
const merged = file.flows.map((f) => byName.get(f.name) ?? f);
|
|
374
|
+
for (const f of flows)
|
|
375
|
+
if (!file.flows.some((e) => e.name === f.name))
|
|
376
|
+
merged.push(f);
|
|
377
|
+
return { ...file, flows: merged };
|
|
378
|
+
}
|
|
379
|
+
// ── the Playwright fixture ──────────────────────────────────────────────────
|
|
380
|
+
/**
|
|
381
|
+
* The fixture module's runtime: the generic step runner the per-flow fixtures call. Kept as plain text so the
|
|
382
|
+
* written file needs nothing but `@playwright/test`.
|
|
383
|
+
*/
|
|
384
|
+
const RUNTIME = String.raw `type Step = {
|
|
385
|
+
name?: string;
|
|
386
|
+
method: string;
|
|
387
|
+
path: string;
|
|
388
|
+
headers?: Record<string, string>;
|
|
389
|
+
query?: Record<string, string>;
|
|
390
|
+
body?: unknown;
|
|
391
|
+
form?: Record<string, string>;
|
|
392
|
+
expect?: number | number[];
|
|
393
|
+
capture?: Record<string, string>;
|
|
394
|
+
};
|
|
395
|
+
type Flow = { name: string; kind: 'data' | 'signin'; description?: string; changesData: boolean; steps: Step[]; returns: string[]; cleanup: Step[] };
|
|
396
|
+
type Vars = Record<string, string>;
|
|
397
|
+
type Playwright = PlaywrightWorkerArgs['playwright'];
|
|
398
|
+
type StorageState = PlaywrightTestOptions['storageState'];
|
|
399
|
+
|
|
400
|
+
const TEMPLATE = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
401
|
+
const READ_ONLY = ['GET', 'HEAD', 'OPTIONS'];
|
|
402
|
+
|
|
403
|
+
/** A value that cannot stand as one path segment: empty, '.' or '..', or one holding a '/'. */
|
|
404
|
+
const badSegment = (v: string): boolean => v === '' || v === '.' || v === '..' || v.includes('/');
|
|
405
|
+
|
|
406
|
+
/** Where the API lives: API_BASE_URL, then the flow file / the flag, then use.baseURL of the Playwright config. */
|
|
407
|
+
function apiBaseUrl(baseURL: string | undefined): string {
|
|
408
|
+
const url = process.env.API_BASE_URL || DEFAULT_BASE_URL || baseURL;
|
|
409
|
+
if (!url) throw new Error('API flows need a base URL: set API_BASE_URL, baseUrl in the flow file, or use.baseURL in the Playwright config');
|
|
410
|
+
return url.replace(/\/+$/, '');
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const originOf = (url: string): string | undefined => {
|
|
414
|
+
try {
|
|
415
|
+
return new URL(url).origin;
|
|
416
|
+
} catch {
|
|
417
|
+
return undefined;
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
/** A flow that changes data runs only against an origin the flag allowed, or one listed in CAIRN_ALLOW_MUTATIONS. */
|
|
422
|
+
function mutationsAllowed(url: string): boolean {
|
|
423
|
+
const origin = originOf(url);
|
|
424
|
+
const fromEnv = (process.env.CAIRN_ALLOW_MUTATIONS ?? '').split(',').map((s) => originOf(s.trim()));
|
|
425
|
+
return origin !== undefined && (MUTATIONS_ALLOWED_FOR.includes(origin) || fromEnv.includes(origin));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const uid = (): string => Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
429
|
+
|
|
430
|
+
function fill(value: unknown, vars: Vars, encode = false): unknown {
|
|
431
|
+
if (typeof value === 'string') {
|
|
432
|
+
return value.replace(TEMPLATE, (_m, key: string) => {
|
|
433
|
+
const v = key.startsWith('env.') ? process.env[key.slice(4)] : vars[key];
|
|
434
|
+
if (v === undefined) {
|
|
435
|
+
throw new Error(key.startsWith('env.') ? 'API flow: the environment variable ' + key.slice(4) + ' is not set' : 'API flow: no value for {{' + key + '}}');
|
|
436
|
+
}
|
|
437
|
+
// In a path a value is one segment: never an empty one, never '.' or '..', never two. The value may be a secret,
|
|
438
|
+
// or anything the server answered: name it, never print it.
|
|
439
|
+
if (encode && badSegment(v)) throw new Error('API flow: {{' + key + '}} is a value, which cannot stand in the path ' + value);
|
|
440
|
+
return encode ? encodeURIComponent(v) : v;
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
if (Array.isArray(value)) return value.map((v) => fill(v, vars, encode));
|
|
444
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fill(v, vars, encode)]));
|
|
445
|
+
return value;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Every {{name}} in a value's strings. A key is sent as written, so it names nothing (as when the file is read). */
|
|
449
|
+
const namesIn = (value: unknown): string[] =>
|
|
450
|
+
typeof value === 'string' ? [...value.matchAll(TEMPLATE)].map((m) => m[1]!) : value && typeof value === 'object' ? Object.values(value).flatMap(namesIn) : [];
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Whether every value a step names was captured (and those in its path can stand as a path segment) — a cleanup step
|
|
454
|
+
* for something never created, or never named, is left out.
|
|
455
|
+
*/
|
|
456
|
+
const canFill = (step: Step, vars: Vars): boolean =>
|
|
457
|
+
namesIn([step.path, step.headers, step.query, step.body, step.form]).every((n) => n.startsWith('env.') || n in vars) &&
|
|
458
|
+
[...step.path.matchAll(TEMPLATE)].every((m) => m[1]!.startsWith('env.') || !badSegment(vars[m[1]!]!));
|
|
459
|
+
|
|
460
|
+
function at(body: unknown, pointer: string): unknown {
|
|
461
|
+
let cur: unknown = body;
|
|
462
|
+
for (const raw of pointer.split('/').slice(1)) {
|
|
463
|
+
const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
464
|
+
if (cur === null || typeof cur !== 'object') return undefined;
|
|
465
|
+
cur = (cur as Record<string, unknown>)[key];
|
|
466
|
+
}
|
|
467
|
+
return cur;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** The answer with every number kept as the text the server wrote: JSON.parse makes a double of it. */
|
|
471
|
+
const numbersAsWritten = (text: string): unknown =>
|
|
472
|
+
JSON.parse(text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (t) => (t.startsWith('"') ? t : '"' + t + '"')));
|
|
473
|
+
|
|
474
|
+
/** A number's text as its sign, its digits with no zero at either end and its exponent: '3.50', '35e-1' → '35e-1'. */
|
|
475
|
+
const digitsOf = (n: string): string => {
|
|
476
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(n);
|
|
477
|
+
if (!m) return n; // Infinity
|
|
478
|
+
const all = (m[2]! + (m[3] ?? '')).replace(/^0+/, '');
|
|
479
|
+
const digits = all.replace(/0+$/, '');
|
|
480
|
+
return digits ? m[1] + digits + 'e' + (Number(m[4] ?? 0) - (m[3] ?? '').length + all.length - digits.length) : '0';
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Whether a captured number may go into a request: not a whole number past 2^53, which JSON.parse may have rounded to
|
|
485
|
+
* another record's id, and only the number the server wrote ('1e400' reads as Infinity, '3.0000000000000000001' as 3).
|
|
486
|
+
*/
|
|
487
|
+
const isExactNumber = (v: number, written: string): boolean =>
|
|
488
|
+
!(Number.isInteger(v) && !Number.isSafeInteger(v)) && digitsOf(String(v)) === digitsOf(written);
|
|
489
|
+
|
|
490
|
+
const pick = (vars: Vars, names: string[]): Vars => Object.fromEntries(names.map((n) => [n, vars[n]!]));
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Why a request got no answer: a fixed word, or a system code read from the first line of Playwright's error. Its text
|
|
494
|
+
* is never repeated: the call log in it holds the full URL and every header, with the values read from the environment.
|
|
495
|
+
*/
|
|
496
|
+
function whyNoAnswer(e: unknown): string {
|
|
497
|
+
const first = String((e as Error | null)?.message).split('\n')[0]!;
|
|
498
|
+
if (/\bTimeout \d+ms exceeded/.test(first)) return 'timeout';
|
|
499
|
+
return /\bE[A-Z0-9_]{2,40}\b/.exec(first)?.[0] ?? 'network error';
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function runStep(ctx: APIRequestContext, base: string, flow: string, step: Step, vars: Vars): Promise<void> {
|
|
503
|
+
const label = 'API flow "' + flow + '" step "' + (step.name ?? step.method + ' ' + step.path) + '"';
|
|
504
|
+
const options: NonNullable<Parameters<APIRequestContext['fetch']>[1]> = {
|
|
505
|
+
method: step.method,
|
|
506
|
+
headers: fill({ ...HEADERS, ...step.headers }, vars) as Record<string, string>,
|
|
507
|
+
maxRedirects: 0,
|
|
508
|
+
};
|
|
509
|
+
if (step.query) options.params = fill(step.query, vars) as Record<string, string>;
|
|
510
|
+
if (step.body !== undefined) options.data = fill(step.body, vars);
|
|
511
|
+
if (step.form) options.form = fill(step.form, vars) as Record<string, string>;
|
|
512
|
+
const res = await ctx.fetch(base + (fill(step.path, vars, true) as string), options).catch((e: unknown): never => {
|
|
513
|
+
throw new Error(label + ' got no answer: ' + whyNoAnswer(e));
|
|
514
|
+
});
|
|
515
|
+
const want = step.expect === undefined ? undefined : ([] as number[]).concat(step.expect);
|
|
516
|
+
const ok = want ? want.includes(res.status()) : res.status() >= 200 && res.status() < 400;
|
|
517
|
+
if (!ok) throw new Error(label + ' answered ' + res.status() + ' (want ' + (want ? want.join(' or ') : '2xx or 3xx') + ')');
|
|
518
|
+
if (!step.capture) return;
|
|
519
|
+
let text: string;
|
|
520
|
+
let body: unknown;
|
|
521
|
+
try {
|
|
522
|
+
text = await res.text();
|
|
523
|
+
body = JSON.parse(text);
|
|
524
|
+
} catch {
|
|
525
|
+
throw new Error(label + ': the answer is not JSON, so nothing can be captured from it');
|
|
526
|
+
}
|
|
527
|
+
// An empty value counts as not captured: nothing can be found or deleted by it.
|
|
528
|
+
const missing: string[] = [];
|
|
529
|
+
const inexact: string[] = [];
|
|
530
|
+
for (const [name, pointer] of Object.entries(step.capture)) {
|
|
531
|
+
const v = at(body, pointer);
|
|
532
|
+
if (v === undefined || v === null || typeof v === 'object' || String(v) === '') missing.push(pointer + ' for ' + name);
|
|
533
|
+
// A number JSON.parse rounded may be another record's id: it is never kept, as in the two-actor check.
|
|
534
|
+
else if (typeof v === 'number' && !isExactNumber(v, String(at(numbersAsWritten(text), pointer)))) inexact.push('{{' + name + '}}');
|
|
535
|
+
else vars[name] = String(v);
|
|
536
|
+
}
|
|
537
|
+
if (missing.length) throw new Error(label + ': the answer has no value at ' + missing.join(', '));
|
|
538
|
+
if (inexact.length) throw new Error(label + ': ' + inexact.join(', ') + ' is not a safe integer (the number may have been rounded), so it is not used');
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Run a data flow, hand its values to the test, and clean up afterwards — after a failed test too. */
|
|
542
|
+
async function dataFlow(
|
|
543
|
+
flow: Flow,
|
|
544
|
+
playwright: Playwright,
|
|
545
|
+
baseURL: string | undefined,
|
|
546
|
+
storageState: StorageState,
|
|
547
|
+
use: (value: Vars) => Promise<void>,
|
|
548
|
+
testInfo: TestInfo,
|
|
549
|
+
): Promise<void> {
|
|
550
|
+
const base = apiBaseUrl(baseURL);
|
|
551
|
+
if (flow.changesData && !mutationsAllowed(base)) {
|
|
552
|
+
const origin = originOf(base) ?? base;
|
|
553
|
+
testInfo.skip(true, 'API flow "' + flow.name + '" changes data, and ' + origin + ' is not allowed: write the fixture with --allow-mutations for it, or set CAIRN_ALLOW_MUTATIONS=' + origin);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const ctx = await playwright.request.newContext(storageState ? { storageState } : {});
|
|
557
|
+
const vars: Vars = { uid: uid() };
|
|
558
|
+
try {
|
|
559
|
+
for (const step of flow.steps) await runStep(ctx, base, flow.name, step, vars);
|
|
560
|
+
await use(pick(vars, flow.returns));
|
|
561
|
+
} finally {
|
|
562
|
+
const errors: string[] = [];
|
|
563
|
+
for (const step of flow.cleanup) {
|
|
564
|
+
if (!canFill(step, vars)) continue;
|
|
565
|
+
try {
|
|
566
|
+
await runStep(ctx, base, flow.name, step, vars);
|
|
567
|
+
} catch (e) {
|
|
568
|
+
errors.push((e as Error).message);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
await ctx.dispose();
|
|
572
|
+
if (errors.length) throw new Error('API flow "' + flow.name + '": the cleanup failed, the data may still be there\n' + errors.join('\n'));
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Run a sign-in flow in a fresh request context and return its cookies as a storageState. */
|
|
577
|
+
async function signIn(flow: Flow, playwright: Playwright, baseURL: string | undefined): Promise<StorageState> {
|
|
578
|
+
const base = apiBaseUrl(baseURL);
|
|
579
|
+
// The login is the one request a sign-in flow may send that changes data; a flow file is checked for this on read.
|
|
580
|
+
if (flow.steps.filter((s) => !READ_ONLY.includes(s.method)).length > 1) {
|
|
581
|
+
throw new Error('API flow "' + flow.name + '": a sign-in flow sends one request that changes data (the login); nothing was sent');
|
|
582
|
+
}
|
|
583
|
+
const ctx = await playwright.request.newContext();
|
|
584
|
+
try {
|
|
585
|
+
const vars: Vars = { uid: uid() };
|
|
586
|
+
for (const step of flow.steps) await runStep(ctx, base, flow.name, step, vars);
|
|
587
|
+
return await ctx.storageState();
|
|
588
|
+
} finally {
|
|
589
|
+
await ctx.dispose();
|
|
590
|
+
}
|
|
591
|
+
}`;
|
|
592
|
+
/**
|
|
593
|
+
* The Playwright fixture module for a flow file: one test-scoped fixture per data flow (its value is the flow's
|
|
594
|
+
* `returns`), and the sign-in flow, if any, as an override of `storageState`. Values written as `{{env.NAME}}` are
|
|
595
|
+
* read when a test runs; none is written into the module.
|
|
596
|
+
*/
|
|
597
|
+
export function renderFlowFixture(file, opts) {
|
|
598
|
+
const baseUrl = opts.baseUrl ?? file.baseUrl;
|
|
599
|
+
const allowed = opts.allowMutationsFor ? [new URL(opts.allowMutationsFor).origin] : [];
|
|
600
|
+
const flows = Object.fromEntries(file.flows.map((f) => [f.name, { ...f, changesData: flowChangesData(f) }]));
|
|
601
|
+
const data = file.flows.filter((f) => f.kind === "data");
|
|
602
|
+
const signin = file.flows.find((f) => f.kind === "signin");
|
|
603
|
+
const L = [
|
|
604
|
+
`// Playwright fixtures for the API flows${opts.source ? ` in ${opts.source.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ")}` : ""} (cairn, #230). Written by \`cairn api --flows\`;`,
|
|
605
|
+
"// edit the flow file and write this module again rather than editing it by hand.",
|
|
606
|
+
"// {{env.NAME}} values are read from the environment when a test runs; none is stored here.",
|
|
607
|
+
"import {",
|
|
608
|
+
" test as base,",
|
|
609
|
+
" expect,",
|
|
610
|
+
" type APIRequestContext,",
|
|
611
|
+
" type PlaywrightTestOptions,",
|
|
612
|
+
" type PlaywrightWorkerArgs,",
|
|
613
|
+
" type TestInfo,",
|
|
614
|
+
"} from '@playwright/test';",
|
|
615
|
+
"",
|
|
616
|
+
`const HEADERS: Record<string, string> = ${JSON.stringify(file.headers ?? {})};`,
|
|
617
|
+
`const FLOWS: Record<string, Flow> = ${JSON.stringify(flows, null, 2)};`,
|
|
618
|
+
`const DEFAULT_BASE_URL: string | undefined = ${baseUrl ? JSON.stringify(baseUrl) : "undefined"};`,
|
|
619
|
+
`const MUTATIONS_ALLOWED_FOR: string[] = ${JSON.stringify(allowed)};`,
|
|
620
|
+
"",
|
|
621
|
+
RUNTIME,
|
|
622
|
+
"",
|
|
623
|
+
];
|
|
624
|
+
for (const f of data) {
|
|
625
|
+
const fields = f.returns.map((r) => `${r}: string`).join("; ");
|
|
626
|
+
L.push(`export type ${typeNameOf(f.name)} = ${fields ? `{ ${fields} }` : "Record<string, never>"};`);
|
|
627
|
+
}
|
|
628
|
+
if (data.length)
|
|
629
|
+
L.push("");
|
|
630
|
+
const shape = data.map((f) => `${f.name}: ${typeNameOf(f.name)}`).join("; ");
|
|
631
|
+
L.push(`export const test = base.extend<{ ${shape} }>({`);
|
|
632
|
+
for (const f of data) {
|
|
633
|
+
L.push(` ${f.name}: async ({ playwright, baseURL, storageState }, use, testInfo) => {`);
|
|
634
|
+
L.push(` await dataFlow(FLOWS[${JSON.stringify(f.name)}]!, playwright, baseURL, storageState, (v) => use(v as ${typeNameOf(f.name)}), testInfo);`);
|
|
635
|
+
L.push(" },");
|
|
636
|
+
}
|
|
637
|
+
if (signin) {
|
|
638
|
+
L.push(" storageState: async ({ playwright, baseURL }, use) => {");
|
|
639
|
+
L.push(` await use(await signIn(FLOWS[${JSON.stringify(signin.name)}]!, playwright, baseURL));`);
|
|
640
|
+
L.push(" },");
|
|
641
|
+
}
|
|
642
|
+
L.push("});", "", "export { expect };", "");
|
|
643
|
+
return L.join("\n");
|
|
644
|
+
}
|
|
645
|
+
/** The suite with Cairn's fixture module in it, in place of any file of that name the model wrote. */
|
|
646
|
+
export function withFlowFixture(suite, fixture) {
|
|
647
|
+
return { files: [...suite.files.filter((f) => f.path !== FLOW_FIXTURE_FILE), { path: FLOW_FIXTURE_FILE, content: fixture }] };
|
|
648
|
+
}
|
|
649
|
+
// ── what design and automate are told ───────────────────────────────────────
|
|
650
|
+
/** One line per flow: its name, what it does and returns, and its description — for the design and codegen prompts. */
|
|
651
|
+
export function formatFlowsForPrompt(file) {
|
|
652
|
+
return file.flows
|
|
653
|
+
.map((f) => {
|
|
654
|
+
const desc = f.description ? ` — ${f.description}` : "";
|
|
655
|
+
if (f.kind === "signin")
|
|
656
|
+
return `- ${f.name} (signs in through the API; the test starts with its session as storageState)${desc}`;
|
|
657
|
+
const returns = f.returns.length ? `returns ${f.returns.join(", ")}` : "returns nothing";
|
|
658
|
+
const what = flowChangesData(f) ? `creates data; ${returns}; its cleanup deletes it afterwards` : `reads data; ${returns}`;
|
|
659
|
+
return `- ${f.name} (${what})${desc}`;
|
|
660
|
+
})
|
|
661
|
+
.join("\n");
|
|
662
|
+
}
|
|
663
|
+
//# sourceMappingURL=flows.js.map
|