@cookiemunch/testing 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/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog: @cookiemunch/testing
2
+
3
+ Every published release, newest first. Dates are the day the version was cut.
4
+
5
+ ## 0.1.1 (2026-10-25)
6
+
7
+ - Changed: the stub sets `window.__consent` as well as `window.__fdConsent` (the same object).
8
+
9
+ ## 0.1.0 (2026-10-24)
10
+
11
+ - Added: `installStub(page, { decision })` (an official stub of the embed's API, versioned as `STUB_VERSION`), `previewUrl(cbid, url, { region, lang, apiKey })` and `decide(page, 'accept' | 'reject' | {…})`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cookie Munch
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,16 @@
1
- # Temporary Holding Version
1
+ # @cookiemunch/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for sites running Cookie Munch: an official, versioned stub of the embed's API, preview
4
+ links, and a helper that answers the real banner. Works with Playwright, or anything with its `Page` shape.
5
+
6
+ ```ts
7
+ import { installStub, previewUrl, decide } from '@cookiemunch/testing';
8
+
9
+ await installStub(page, { decision: 'accept' }); // no network, the real API surface
10
+ await page.goto(await previewUrl('your-site-id', 'https://acme.com/pricing', { region: 'de', apiKey }));
11
+ await decide(page, 'reject'); // answers the real banner
12
+ ```
13
+
14
+ For a local or preview origin, list it in the site's `devOrigins` (or put `data-env="test"` on the tag):
15
+ the banner then shows to headless browsers and nothing reaches your consent log.
16
+ Docs: [cookiemunch.net/docs/testing](https://cookiemunch.net/docs/testing).
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The official stub of the embed's public API — `window.CookieMunch` (and its `Cookiebot`
3
+ * alias) plus `window.__fdConsent` — for tests that should not load the real embed.
4
+ *
5
+ * It passes the same contract tests as the real embed (test/contract.test.ts), so code that
6
+ * works against it works against Cookie Munch. It is ONE self-contained function: Playwright
7
+ * serialises it into the page (`page.addInitScript(cookieMunchStub, options)`), so it may not
8
+ * close over anything outside itself.
9
+ */
10
+ type StubDecision = 'accept' | 'reject' | 'none' | Record<string, boolean>;
11
+ interface StubOptions {
12
+ /** The visitor's answer at load. `none` (default): not decided yet. */
13
+ decision?: StubDecision;
14
+ /** The site's custom category ids (`referrals`, `support_chat`, …). */
15
+ categories?: string[];
16
+ /** Region code the snapshot reports. Default `eu`. */
17
+ region?: string;
18
+ /** `false`: a region that needs no decision (everything allowed until refused). Default true. */
19
+ required?: boolean;
20
+ }
21
+ /** The version of the stub's contract; it follows `__fdConsent.version`. */
22
+ declare const STUB_VERSION = 1;
23
+ declare function cookieMunchStub(options?: StubOptions): void;
24
+
25
+ /**
26
+ * @cookiemunch/testing — test helpers for sites running Cookie Munch (CMU-D02).
27
+ *
28
+ * import { installStub, previewUrl, decide } from '@cookiemunch/testing';
29
+ *
30
+ * await installStub(page, { decision: 'accept' }); // no network, the real API surface
31
+ * await page.goto(await previewUrl('cb-…', 'https://acme.com/pricing', { region: 'de', apiKey }));
32
+ * await decide(page, 'reject'); // answers the REAL banner
33
+ *
34
+ * Playwright is not a dependency: anything with Playwright's `Page` shape works.
35
+ * For a local or preview origin, list it in the site's `devOrigins` (or put `data-env="test"`
36
+ * on the tag): the banner then shows to headless browsers and nothing is recorded.
37
+ */
38
+
39
+ /** The part of Playwright's `Page` these helpers use. */
40
+ interface PageLike {
41
+ addInitScript<A>(script: (arg: A) => unknown, arg: A): Promise<unknown>;
42
+ evaluate<R, A>(fn: (arg: A) => R | Promise<R>, arg: A): Promise<R>;
43
+ locator(selector: string): LocatorLike;
44
+ }
45
+ interface LocatorLike {
46
+ first(): LocatorLike;
47
+ click(opts?: {
48
+ timeout?: number;
49
+ }): Promise<void>;
50
+ waitFor(opts?: {
51
+ state?: 'attached' | 'visible';
52
+ timeout?: number;
53
+ }): Promise<void>;
54
+ setChecked(checked: boolean, opts?: {
55
+ timeout?: number;
56
+ }): Promise<void>;
57
+ count(): Promise<number>;
58
+ }
59
+ /**
60
+ * Put the official stub on every page the browser opens, before any page script runs: the
61
+ * embed's API (`CookieMunch`, `Cookiebot`) and `__fdConsent`, with the decision you choose.
62
+ * Do not load consent.js as well; block it (`page.route('**\/consent.js', r => r.abort())`).
63
+ */
64
+ declare function installStub(page: PageLike, options?: StubOptions): Promise<void>;
65
+ interface PreviewOptions {
66
+ /** A country or subdivision code (`de`, `us-ca`) or `eu`. */
67
+ region?: string;
68
+ /** A BCP 47 language tag. */
69
+ lang?: string;
70
+ /** An API key with sites:read. Default: process.env.COOKIEMUNCH_API_KEY. */
71
+ apiKey?: string;
72
+ /** Default https://api.cookiemunch.net. */
73
+ baseUrl?: string;
74
+ /** Token lifetime in seconds, at most 3600. Default 900. */
75
+ ttlSeconds?: number;
76
+ fetch?: typeof fetch;
77
+ }
78
+ /**
79
+ * A preview link for `url`: the real banner, forced to a region and language, shown to a
80
+ * headless browser, recording nothing. Mints a signed token (POST /v1/sites/{cbid}/preview-token).
81
+ */
82
+ declare function previewUrl(cbid: string, url: string, opts?: PreviewOptions): Promise<string>;
83
+ /**
84
+ * Answer the REAL banner as a visitor would: `accept`, `reject`, or per category
85
+ * (`{ statistics: true, referrals: false }`, opening the settings and saving). Resolves once
86
+ * the embed has the decision. The banner lives in an open shadow root, which Playwright's CSS
87
+ * locators pierce.
88
+ */
89
+ declare function decide(page: PageLike, choice: StubDecision, opts?: {
90
+ timeout?: number;
91
+ }): Promise<void>;
92
+
93
+ export { type LocatorLike, type PageLike, type PreviewOptions, STUB_VERSION, type StubDecision, type StubOptions, cookieMunchStub, decide, installStub, previewUrl };
package/dist/index.js ADDED
@@ -0,0 +1,200 @@
1
+ // src/stub.ts
2
+ var STUB_VERSION = 1;
3
+ function cookieMunchStub(options = {}) {
4
+ const w = window;
5
+ const custom = options.categories ?? [];
6
+ const required = options.required !== false;
7
+ const all = ["preferences", "statistics", "marketing", ...custom];
8
+ let decided = false;
9
+ let state = {};
10
+ let stamp = "stub-" + Math.random().toString(36).slice(2, 10);
11
+ let decidedAt = null;
12
+ const set = (d) => {
13
+ if (d === "none" || d === void 0) {
14
+ decided = false;
15
+ state = {};
16
+ for (const c of all) state[c] = !required;
17
+ return;
18
+ }
19
+ decided = true;
20
+ decidedAt = (/* @__PURE__ */ new Date()).toISOString();
21
+ state = {};
22
+ for (const c of all) state[c] = d === "accept" ? true : d === "reject" ? false : d[c] === true || d.all === true && d[c] !== false;
23
+ };
24
+ set(options.decision ?? "none");
25
+ const listeners = {};
26
+ const fire = (event, ...args) => {
27
+ for (const fn of (listeners[event] ?? []).slice()) fn(...args);
28
+ };
29
+ const consent = () => ({ necessary: true, ...state, stamp });
30
+ const snapshot = () => ({
31
+ decided,
32
+ required,
33
+ categories: { necessary: true, ...state },
34
+ stamp,
35
+ region: options.region ?? "eu",
36
+ gpc: false,
37
+ decidedAt
38
+ });
39
+ const fdListeners = [];
40
+ const announce = (cause) => {
41
+ const c = consent();
42
+ fire("consentReady", c);
43
+ const any = state.preferences || state.statistics || state.marketing;
44
+ fire(any ? "accept" : "decline", c);
45
+ for (const ev of ["CookieMunchOnConsentReady", any ? "CookieMunchOnAccept" : "CookieMunchOnDecline"]) {
46
+ w.dispatchEvent(new CustomEvent(ev, { detail: c }));
47
+ }
48
+ w.dispatchEvent(new CustomEvent("CookieMunchOnChange", { detail: { consent: c, previous: null, cause } }));
49
+ const s = snapshot();
50
+ for (const fn of fdListeners.slice()) fn(s, cause);
51
+ };
52
+ const decide2 = (d, cause) => {
53
+ set(d);
54
+ announce(cause);
55
+ };
56
+ const known = (c) => c === "necessary" || all.indexOf(c) >= 0;
57
+ const api = {
58
+ version: "stub",
59
+ get consent() {
60
+ return consent();
61
+ },
62
+ get hasResponse() {
63
+ return decided;
64
+ },
65
+ get consented() {
66
+ return decided && all.some((c) => state[c]);
67
+ },
68
+ get declined() {
69
+ return decided && !all.some((c) => state[c]);
70
+ },
71
+ // Boolean, like the real one: tri-state lives on __fdConsent.has.
72
+ hasConsent: (c) => c === "necessary" || state[c] === true,
73
+ consentId: () => stamp,
74
+ on: (event, fn) => {
75
+ (listeners[event] ??= []).push(fn);
76
+ return () => api.off(event, fn);
77
+ },
78
+ once: (event, fn) => {
79
+ const off = api.on(event, (...a) => (off(), fn(...a)));
80
+ return off;
81
+ },
82
+ off: (event, fn) => {
83
+ const l = listeners[event] ?? [];
84
+ const i = l.indexOf(fn);
85
+ if (i >= 0) l.splice(i, 1);
86
+ },
87
+ show: () => Promise.resolve(),
88
+ showSettings: () => void 0,
89
+ hide: () => void 0,
90
+ renew: () => void 0,
91
+ withdraw: () => decide2("reject", "withdraw"),
92
+ submitCustomConsent: (p, s, m) => decide2({ ...state, preferences: p, statistics: s, marketing: m }, "selection"),
93
+ getStatus: () => ({ ui: "ready" })
94
+ };
95
+ w.CookieMunch = api;
96
+ w.Cookiebot = api;
97
+ const alt = w.__consent && typeof w.__consent === "object" && ("q" in w.__consent || "version" in w.__consent) ? w.__consent : void 0;
98
+ const qOf = (o) => o && Array.isArray(o.q) ? o.q : [];
99
+ const queued = [...qOf(w.__fdConsent), ...alt && alt !== w.__fdConsent ? qOf(alt) : []];
100
+ const fd = {
101
+ version: 1,
102
+ provider: "stub",
103
+ has: (c) => !known(c) ? false : c === "necessary" ? true : decided || !required ? state[c] === true : null,
104
+ on: (ev, cb) => {
105
+ if (ev !== "change") return () => void 0;
106
+ fdListeners.push(cb);
107
+ if (decided || !required) Promise.resolve().then(() => fdListeners.indexOf(cb) >= 0 && cb(snapshot(), "replay"));
108
+ return () => {
109
+ const i = fdListeners.indexOf(cb);
110
+ if (i >= 0) fdListeners.splice(i, 1);
111
+ };
112
+ },
113
+ ready: () => new Promise((done) => {
114
+ if (decided || !required) return done(snapshot());
115
+ const off = fd.on("change", (s) => (off(), done(s)));
116
+ }),
117
+ request: (c) => Promise.resolve(fd.has(c) === true),
118
+ identify: () => void 0,
119
+ layout: { bottomInset: () => 0, on: () => () => void 0 }
120
+ };
121
+ const run = (call) => {
122
+ const [m, a, b, d] = call;
123
+ if (m === "on") fd.on(a, b);
124
+ else if (m === "ready") fd.ready().then(a);
125
+ else if (m === "request") fd.request(a, b).then(d);
126
+ };
127
+ fd.q = { push: (...calls) => (calls.forEach(run), 0) };
128
+ w.__fdConsent = fd;
129
+ if (w.__consent === void 0 || alt) w.__consent = fd;
130
+ queued.forEach(run);
131
+ w.__cmStub = { decide: (d) => decide2(d, d === "accept" ? "accept" : d === "reject" ? "decline" : "selection") };
132
+ if (decided) Promise.resolve().then(() => announce("replay"));
133
+ }
134
+
135
+ // src/index.ts
136
+ async function installStub(page, options = {}) {
137
+ await page.addInitScript(cookieMunchStub, options);
138
+ }
139
+ async function previewUrl(cbid, url, opts = {}) {
140
+ const env = globalThis.process?.env ?? {};
141
+ const apiKey = opts.apiKey ?? env.COOKIEMUNCH_API_KEY;
142
+ if (!apiKey) throw new Error("previewUrl needs an API key with sites:read (apiKey, or COOKIEMUNCH_API_KEY)");
143
+ const f = opts.fetch ?? globalThis.fetch;
144
+ if (!f) throw new Error("previewUrl needs fetch");
145
+ const base = (opts.baseUrl ?? "https://api.cookiemunch.net").replace(/\/+$/, "");
146
+ const res = await f(`${base}/v1/sites/${encodeURIComponent(cbid)}/preview-token`, {
147
+ method: "POST",
148
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
149
+ body: JSON.stringify({ url, ...opts.region ? { region: opts.region } : {}, ...opts.lang ? { lang: opts.lang } : {}, ...opts.ttlSeconds ? { ttlSeconds: opts.ttlSeconds } : {} })
150
+ });
151
+ const body = await res.json().catch(() => ({}));
152
+ if (!res.ok) throw new Error(`preview-token: ${res.status} ${body.error ?? ""}`.trim());
153
+ if (body.previewUrl) return body.previewUrl;
154
+ const u = new URL(url);
155
+ u.searchParams.set("cm_preview", body.token ?? "");
156
+ if (opts.region) u.searchParams.set("cm_region", opts.region);
157
+ if (opts.lang) u.searchParams.set("cm_lang", opts.lang);
158
+ return u.toString();
159
+ }
160
+ async function decide(page, choice, opts = {}) {
161
+ const timeout = opts.timeout ?? 1e4;
162
+ const action = async (name) => {
163
+ const el = page.locator(`[data-action="${name}"]`).first();
164
+ await el.waitFor({ state: "visible", timeout });
165
+ await el.click({ timeout });
166
+ };
167
+ if (choice === "accept") await action("accept-all");
168
+ else if (choice === "reject") await action("reject-all");
169
+ else if (choice !== "none") {
170
+ await action("customize");
171
+ for (const [cat, on] of Object.entries(choice)) {
172
+ const toggle = page.locator(`input[data-cat="${cat}"]`).first();
173
+ if (await toggle.count() > 0) await toggle.setChecked(on, { timeout });
174
+ }
175
+ await action("save");
176
+ }
177
+ if (choice !== "none") {
178
+ await page.evaluate(
179
+ (t) => new Promise((done, fail) => {
180
+ const start = Date.now();
181
+ const tick = () => {
182
+ const cm = window.CookieMunch;
183
+ if (cm?.hasResponse) return done();
184
+ if (Date.now() - start > t) return fail(new Error("the banner did not record a decision"));
185
+ setTimeout(tick, 50);
186
+ };
187
+ tick();
188
+ }),
189
+ timeout
190
+ );
191
+ }
192
+ }
193
+ export {
194
+ STUB_VERSION,
195
+ cookieMunchStub,
196
+ decide,
197
+ installStub,
198
+ previewUrl
199
+ };
200
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stub.ts","../src/index.ts"],"sourcesContent":["/**\n * The official stub of the embed's public API — `window.CookieMunch` (and its `Cookiebot`\n * alias) plus `window.__fdConsent` — for tests that should not load the real embed.\n *\n * It passes the same contract tests as the real embed (test/contract.test.ts), so code that\n * works against it works against Cookie Munch. It is ONE self-contained function: Playwright\n * serialises it into the page (`page.addInitScript(cookieMunchStub, options)`), so it may not\n * close over anything outside itself.\n */\n\nexport type StubDecision = 'accept' | 'reject' | 'none' | Record<string, boolean>;\n\nexport interface StubOptions {\n /** The visitor's answer at load. `none` (default): not decided yet. */\n decision?: StubDecision;\n /** The site's custom category ids (`referrals`, `support_chat`, …). */\n categories?: string[];\n /** Region code the snapshot reports. Default `eu`. */\n region?: string;\n /** `false`: a region that needs no decision (everything allowed until refused). Default true. */\n required?: boolean;\n}\n\n/** The version of the stub's contract; it follows `__fdConsent.version`. */\nexport const STUB_VERSION = 1;\n\nexport function cookieMunchStub(options: StubOptions = {}): void {\n const w = window as unknown as Record<string, any>;\n const custom: string[] = options.categories ?? [];\n const required = options.required !== false;\n const all = ['preferences', 'statistics', 'marketing', ...custom];\n let decided = false;\n let state: Record<string, boolean> = {};\n let stamp = 'stub-' + Math.random().toString(36).slice(2, 10);\n let decidedAt: string | null = null;\n const set = (d: any): void => {\n if (d === 'none' || d === undefined) {\n decided = false;\n state = {};\n for (const c of all) state[c] = !required;\n return;\n }\n decided = true;\n decidedAt = new Date().toISOString();\n state = {};\n for (const c of all) state[c] = d === 'accept' ? true : d === 'reject' ? false : d[c] === true || (d.all === true && d[c] !== false);\n };\n set(options.decision ?? 'none');\n\n const listeners: Record<string, Array<(...a: any[]) => void>> = {};\n const fire = (event: string, ...args: any[]): void => {\n for (const fn of (listeners[event] ?? []).slice()) fn(...args);\n };\n const consent = (): Record<string, any> => ({ necessary: true, ...state, stamp });\n const snapshot = () => ({\n decided,\n required,\n categories: { necessary: true, ...state },\n stamp,\n region: options.region ?? 'eu',\n gpc: false,\n decidedAt,\n });\n const fdListeners: Array<(s: any, cause: string) => void> = [];\n const announce = (cause: string): void => {\n const c = consent();\n fire('consentReady', c);\n const any = state.preferences || state.statistics || state.marketing;\n fire(any ? 'accept' : 'decline', c);\n for (const ev of ['CookieMunchOnConsentReady', any ? 'CookieMunchOnAccept' : 'CookieMunchOnDecline']) {\n w.dispatchEvent(new CustomEvent(ev, { detail: c }));\n }\n w.dispatchEvent(new CustomEvent('CookieMunchOnChange', { detail: { consent: c, previous: null, cause } }));\n const s = snapshot();\n for (const fn of fdListeners.slice()) fn(s, cause);\n };\n const decide = (d: StubDecision, cause: string): void => {\n set(d);\n announce(cause);\n };\n const known = (c: string): boolean => c === 'necessary' || all.indexOf(c) >= 0;\n\n const api: Record<string, any> = {\n version: 'stub',\n get consent() {\n return consent();\n },\n get hasResponse() {\n return decided;\n },\n get consented() {\n return decided && all.some((c) => state[c]);\n },\n get declined() {\n return decided && !all.some((c) => state[c]);\n },\n // Boolean, like the real one: tri-state lives on __fdConsent.has.\n hasConsent: (c: string) => c === 'necessary' || state[c] === true,\n consentId: () => stamp,\n on: (event: string, fn: (...a: any[]) => void) => {\n (listeners[event] ??= []).push(fn);\n return () => api.off(event, fn);\n },\n once: (event: string, fn: (...a: any[]) => void) => {\n const off = api.on(event, (...a: any[]) => (off(), fn(...a)));\n return off;\n },\n off: (event: string, fn: (...a: any[]) => void) => {\n const l = listeners[event] ?? [];\n const i = l.indexOf(fn);\n if (i >= 0) l.splice(i, 1);\n },\n show: () => Promise.resolve(),\n showSettings: () => undefined,\n hide: () => undefined,\n renew: () => undefined,\n withdraw: () => decide('reject', 'withdraw'),\n submitCustomConsent: (p: boolean, s: boolean, m: boolean) => decide({ ...state, preferences: p, statistics: s, marketing: m }, 'selection'),\n getStatus: () => ({ ui: 'ready' }),\n };\n w.CookieMunch = api;\n w.Cookiebot = api;\n\n const alt = w.__consent && typeof w.__consent === 'object' && ('q' in w.__consent || 'version' in w.__consent) ? w.__consent : undefined;\n const qOf = (o: any): any[] => (o && Array.isArray(o.q) ? o.q : []);\n const queued: any[] = [...qOf(w.__fdConsent), ...(alt && alt !== w.__fdConsent ? qOf(alt) : [])];\n const fd: Record<string, any> = {\n version: 1,\n provider: 'stub',\n has: (c: string) => (!known(c) ? false : c === 'necessary' ? true : decided || !required ? state[c] === true : null),\n on: (ev: string, cb: (s: any, cause: string) => void) => {\n if (ev !== 'change') return () => undefined;\n fdListeners.push(cb);\n if (decided || !required) Promise.resolve().then(() => fdListeners.indexOf(cb) >= 0 && cb(snapshot(), 'replay'));\n return () => {\n const i = fdListeners.indexOf(cb);\n if (i >= 0) fdListeners.splice(i, 1);\n };\n },\n ready: () =>\n new Promise((done) => {\n if (decided || !required) return done(snapshot());\n const off = fd.on('change', (s: any) => (off(), done(s)));\n }),\n request: (c: string) => Promise.resolve(fd.has(c) === true),\n identify: () => undefined,\n layout: { bottomInset: () => 0, on: () => () => undefined },\n };\n const run = (call: any[]): void => {\n const [m, a, b, d] = call;\n if (m === 'on') fd.on(a, b);\n else if (m === 'ready') fd.ready().then(a);\n else if (m === 'request') fd.request(a, b).then(d);\n };\n fd.q = { push: (...calls: any[][]) => (calls.forEach(run), 0) };\n w.__fdConsent = fd;\n if (w.__consent === undefined || alt) w.__consent = fd;\n queued.forEach(run);\n // For tests: change the answer as a visitor would (`window.__cmStub.decide('accept')`).\n w.__cmStub = { decide: (d: StubDecision) => decide(d, d === 'accept' ? 'accept' : d === 'reject' ? 'decline' : 'selection') };\n if (decided) Promise.resolve().then(() => announce('replay'));\n}\n","/**\n * @cookiemunch/testing — test helpers for sites running Cookie Munch (CMU-D02).\n *\n * import { installStub, previewUrl, decide } from '@cookiemunch/testing';\n *\n * await installStub(page, { decision: 'accept' }); // no network, the real API surface\n * await page.goto(await previewUrl('cb-…', 'https://acme.com/pricing', { region: 'de', apiKey }));\n * await decide(page, 'reject'); // answers the REAL banner\n *\n * Playwright is not a dependency: anything with Playwright's `Page` shape works.\n * For a local or preview origin, list it in the site's `devOrigins` (or put `data-env=\"test\"`\n * on the tag): the banner then shows to headless browsers and nothing is recorded.\n */\n\nimport { cookieMunchStub, type StubOptions, type StubDecision } from './stub.js';\n\nexport { cookieMunchStub, STUB_VERSION, type StubOptions, type StubDecision } from './stub.js';\n\n/** The part of Playwright's `Page` these helpers use. */\nexport interface PageLike {\n addInitScript<A>(script: (arg: A) => unknown, arg: A): Promise<unknown>;\n evaluate<R, A>(fn: (arg: A) => R | Promise<R>, arg: A): Promise<R>;\n locator(selector: string): LocatorLike;\n}\nexport interface LocatorLike {\n first(): LocatorLike;\n click(opts?: { timeout?: number }): Promise<void>;\n waitFor(opts?: { state?: 'attached' | 'visible'; timeout?: number }): Promise<void>;\n setChecked(checked: boolean, opts?: { timeout?: number }): Promise<void>;\n count(): Promise<number>;\n}\n\n/**\n * Put the official stub on every page the browser opens, before any page script runs: the\n * embed's API (`CookieMunch`, `Cookiebot`) and `__fdConsent`, with the decision you choose.\n * Do not load consent.js as well; block it (`page.route('**\\/consent.js', r => r.abort())`).\n */\nexport async function installStub(page: PageLike, options: StubOptions = {}): Promise<void> {\n await page.addInitScript(cookieMunchStub, options);\n}\n\nexport interface PreviewOptions {\n /** A country or subdivision code (`de`, `us-ca`) or `eu`. */\n region?: string;\n /** A BCP 47 language tag. */\n lang?: string;\n /** An API key with sites:read. Default: process.env.COOKIEMUNCH_API_KEY. */\n apiKey?: string;\n /** Default https://api.cookiemunch.net. */\n baseUrl?: string;\n /** Token lifetime in seconds, at most 3600. Default 900. */\n ttlSeconds?: number;\n fetch?: typeof fetch;\n}\n\n/**\n * A preview link for `url`: the real banner, forced to a region and language, shown to a\n * headless browser, recording nothing. Mints a signed token (POST /v1/sites/{cbid}/preview-token).\n */\nexport async function previewUrl(cbid: string, url: string, opts: PreviewOptions = {}): Promise<string> {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const apiKey = opts.apiKey ?? env.COOKIEMUNCH_API_KEY;\n if (!apiKey) throw new Error('previewUrl needs an API key with sites:read (apiKey, or COOKIEMUNCH_API_KEY)');\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch;\n if (!f) throw new Error('previewUrl needs fetch');\n const base = (opts.baseUrl ?? 'https://api.cookiemunch.net').replace(/\\/+$/, '');\n const res = await f(`${base}/v1/sites/${encodeURIComponent(cbid)}/preview-token`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ url, ...(opts.region ? { region: opts.region } : {}), ...(opts.lang ? { lang: opts.lang } : {}), ...(opts.ttlSeconds ? { ttlSeconds: opts.ttlSeconds } : {}) }),\n });\n const body = (await res.json().catch(() => ({}))) as { previewUrl?: string; token?: string; error?: string };\n if (!res.ok) throw new Error(`preview-token: ${res.status} ${body.error ?? ''}`.trim());\n if (body.previewUrl) return body.previewUrl;\n const u = new URL(url);\n u.searchParams.set('cm_preview', body.token ?? '');\n if (opts.region) u.searchParams.set('cm_region', opts.region);\n if (opts.lang) u.searchParams.set('cm_lang', opts.lang);\n return u.toString();\n}\n\n/**\n * Answer the REAL banner as a visitor would: `accept`, `reject`, or per category\n * (`{ statistics: true, referrals: false }`, opening the settings and saving). Resolves once\n * the embed has the decision. The banner lives in an open shadow root, which Playwright's CSS\n * locators pierce.\n */\nexport async function decide(page: PageLike, choice: StubDecision, opts: { timeout?: number } = {}): Promise<void> {\n const timeout = opts.timeout ?? 10_000;\n const action = async (name: string): Promise<void> => {\n const el = page.locator(`[data-action=\"${name}\"]`).first();\n await el.waitFor({ state: 'visible', timeout });\n await el.click({ timeout });\n };\n if (choice === 'accept') await action('accept-all');\n else if (choice === 'reject') await action('reject-all');\n else if (choice !== 'none') {\n await action('customize');\n for (const [cat, on] of Object.entries(choice)) {\n const toggle = page.locator(`input[data-cat=\"${cat}\"]`).first();\n if ((await toggle.count()) > 0) await toggle.setChecked(on, { timeout });\n }\n await action('save');\n }\n if (choice !== 'none') {\n await page.evaluate(\n (t: number) =>\n new Promise<void>((done, fail) => {\n const start = Date.now();\n const tick = (): void => {\n const cm = (window as unknown as { CookieMunch?: { hasResponse?: boolean } }).CookieMunch;\n if (cm?.hasResponse) return done();\n if (Date.now() - start > t) return fail(new Error('the banner did not record a decision'));\n setTimeout(tick, 50);\n };\n tick();\n }),\n timeout,\n );\n }\n}\n"],"mappings":";AAwBO,IAAM,eAAe;AAErB,SAAS,gBAAgB,UAAuB,CAAC,GAAS;AAC/D,QAAM,IAAI;AACV,QAAM,SAAmB,QAAQ,cAAc,CAAC;AAChD,QAAM,WAAW,QAAQ,aAAa;AACtC,QAAM,MAAM,CAAC,eAAe,cAAc,aAAa,GAAG,MAAM;AAChE,MAAI,UAAU;AACd,MAAI,QAAiC,CAAC;AACtC,MAAI,QAAQ,UAAU,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE;AAC5D,MAAI,YAA2B;AAC/B,QAAM,MAAM,CAAC,MAAiB;AAC5B,QAAI,MAAM,UAAU,MAAM,QAAW;AACnC,gBAAU;AACV,cAAQ,CAAC;AACT,iBAAW,KAAK,IAAK,OAAM,CAAC,IAAI,CAAC;AACjC;AAAA,IACF;AACA,cAAU;AACV,iBAAY,oBAAI,KAAK,GAAE,YAAY;AACnC,YAAQ,CAAC;AACT,eAAW,KAAK,IAAK,OAAM,CAAC,IAAI,MAAM,WAAW,OAAO,MAAM,WAAW,QAAQ,EAAE,CAAC,MAAM,QAAS,EAAE,QAAQ,QAAQ,EAAE,CAAC,MAAM;AAAA,EAChI;AACA,MAAI,QAAQ,YAAY,MAAM;AAE9B,QAAM,YAA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AK;AAAA,MACT,CAAC,MACC,IAAI,QAAc,CAAC,MAAM,SAAS;AAChC,cAAM,QAAQ,KAAK,IAAI;AACvB,cAAM,OAAO,MAAY;AACvB,gBAAM,KAAM,OAAkE;AAC9E,cAAI,IAAI,YAAa,QAAO,KAAK;AACjC,cAAI,KAAK,IAAI,IAAI,QAAQ,EAAG,QAAO,KAAK,IAAI,MAAM,sCAAsC,CAAC;AACzF,qBAAW,MAAM,EAAE;AAAA,QACrB;AACA,aAAK;AAAA,MACP,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["decide"]}
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@cookiemunch/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Test helpers for sites running Cookie Munch: an official versioned stub of the embed's API, preview links, and a helper that answers the real banner",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsup",
22
+ "test": "vitest run"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Cookie-Munch/testing.git"
27
+ },
28
+ "homepage": "https://cookiemunch.net/docs/testing",
29
+ "bugs": {
30
+ "url": "https://github.com/Cookie-Munch/testing/issues"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "22.20.0",
34
+ "tsup": "8.5.1",
35
+ "typescript": "5.9.3",
36
+ "vitest": "2.1.9"
37
+ }
38
+ }