@zachariaz/strapi-plugin-experience-context 0.0.0-stage → 0.1.0-dev.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/LICENSE +21 -0
- package/README.md +78 -2
- package/dist/_chunks/en-8ms9Hfxr.mjs +27 -0
- package/dist/_chunks/en-yERKDiB0.js +27 -0
- package/dist/admin/index.js +464 -0
- package/dist/admin/index.mjs +448 -0
- package/dist/admin/src/api/client.d.ts +13 -0
- package/dist/admin/src/api/types.d.ts +93 -0
- package/dist/admin/src/api/useInspect.d.ts +3 -0
- package/dist/admin/src/components/BlockMarkers.d.ts +12 -0
- package/dist/admin/src/components/ExperienceModal.d.ts +28 -0
- package/dist/admin/src/components/HeaderBadge.d.ts +19 -0
- package/dist/admin/src/components/Initializer.d.ts +5 -0
- package/dist/admin/src/components/ModalTrigger.d.ts +10 -0
- package/dist/admin/src/contentManagerHooks/editView.d.ts +7 -0
- package/dist/admin/src/index.d.ts +17 -0
- package/dist/admin/src/pluginId.d.ts +2 -0
- package/dist/admin/src/utils/dzSlots.d.ts +16 -0
- package/dist/admin/src/utils/labels.d.ts +30 -0
- package/dist/admin/src/utils/markers.d.ts +12 -0
- package/dist/admin/src/utils/modal.d.ts +10 -0
- package/dist/admin/src/utils/targets.d.ts +12 -0
- package/dist/server/index.js +3694 -0
- package/dist/server/index.mjs +3695 -0
- package/dist/server/src/admin-api/access.d.ts +40 -0
- package/dist/server/src/admin-api/inspect.d.ts +132 -0
- package/dist/server/src/admin-api/mark.d.ts +9 -0
- package/dist/server/src/block-keys/index.d.ts +16 -0
- package/dist/server/src/block-keys/middleware.d.ts +17 -0
- package/dist/server/src/block-keys/stamp.d.ts +55 -0
- package/dist/server/src/block-keys/store.d.ts +33 -0
- package/dist/server/src/block-keys/targets.d.ts +43 -0
- package/dist/server/src/bootstrap.d.ts +16 -0
- package/dist/server/src/changes.d.ts +80 -0
- package/dist/server/src/config/index.d.ts +67 -0
- package/dist/server/src/constants.d.ts +18 -0
- package/dist/server/src/content-types/index.d.ts +309 -0
- package/dist/server/src/controllers/admin.d.ts +10 -0
- package/dist/server/src/controllers/experience.d.ts +15 -0
- package/dist/server/src/controllers/index.d.ts +16 -0
- package/dist/server/src/destroy.d.ts +5 -0
- package/dist/server/src/index.d.ts +441 -0
- package/dist/server/src/integrity/index.d.ts +34 -0
- package/dist/server/src/integrity/orphans.d.ts +40 -0
- package/dist/server/src/mcp/index.d.ts +2 -0
- package/dist/server/src/mcp/operations.d.ts +765 -0
- package/dist/server/src/mcp/permissions.d.ts +56 -0
- package/dist/server/src/mcp/tools.d.ts +59 -0
- package/dist/server/src/model/content.d.ts +32 -0
- package/dist/server/src/model/mapping.d.ts +90 -0
- package/dist/server/src/model/records.d.ts +132 -0
- package/dist/server/src/model/store.d.ts +44 -0
- package/dist/server/src/model/target.d.ts +40 -0
- package/dist/server/src/policies/index.d.ts +4 -0
- package/dist/server/src/rbac/index.d.ts +24 -0
- package/dist/server/src/read-path/editor.d.ts +28 -0
- package/dist/server/src/read-path/gate.d.ts +26 -0
- package/dist/server/src/read-path/index.d.ts +12 -0
- package/dist/server/src/read-path/loader.d.ts +31 -0
- package/dist/server/src/read-path/middleware.d.ts +32 -0
- package/dist/server/src/read-path/payload.d.ts +34 -0
- package/dist/server/src/read-path/populate.d.ts +6 -0
- package/dist/server/src/register.d.ts +14 -0
- package/dist/server/src/registry/index.d.ts +29 -0
- package/dist/server/src/registry/unomi.d.ts +53 -0
- package/dist/server/src/routes/index.d.ts +25 -0
- package/dist/server/src/services/index.d.ts +79 -0
- package/package.json +140 -4
- package/scripts/experience-smoke.mjs +430 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Scripted MCP session against a running Strapi with the experience-context
|
|
4
|
+
* plugin: the two agent workflows of plan §1.5 and the §10.3 scenarios.
|
|
5
|
+
* JSON-RPC over `POST /mcp`, no dependencies (Node >= 22).
|
|
6
|
+
*
|
|
7
|
+
* MCP_ACCESS_TOKEN=... STOREFRONT_TOKEN=... node scripts/experience-smoke.mjs
|
|
8
|
+
* MCP_ACCESS_TOKEN=... npx experience-smoke # from an app that installed the plugin (package bin)
|
|
9
|
+
*
|
|
10
|
+
* Steps (each prints PASS/FAIL):
|
|
11
|
+
* 0. initialize + tools/list: all 14 experience_* tools are enabled for the token
|
|
12
|
+
* 1. describe the target (default: home, locale en) and pick two blocks
|
|
13
|
+
* 2. audience workflow: list_registry → create_content_variant (dryRun, then
|
|
14
|
+
* for real: a Gold copy of the hero) → a readable V3 rejection →
|
|
15
|
+
* associate_variant_with_audience → validate_mapping
|
|
16
|
+
* 3. experiment workflow: set_experiment (draft) → create the outcome b copy
|
|
17
|
+
* of the second block (default = outcome a) → running is accepted →
|
|
18
|
+
* an X1 rejection (audience variation in the experiment section)
|
|
19
|
+
* 4. concepts on the page
|
|
20
|
+
* 5. read path (needs STOREFRONT_TOKEN, a content-API token holding
|
|
21
|
+
* plugin::experience-context.experience.read): ?withExperience=true
|
|
22
|
+
* returns _experience v2 with private, no-store; without the flag and
|
|
23
|
+
* for Public there is no _experience
|
|
24
|
+
* 6. experience_explain_variant_resolution for the §10.3 scenarios 1–5
|
|
25
|
+
* (5 concludes the experiment with winner a)
|
|
26
|
+
* 7. remove everything the run created (also on failure, unless SMOKE_KEEP=1)
|
|
27
|
+
*
|
|
28
|
+
* Environment:
|
|
29
|
+
* MCP_ACCESS_TOKEN required. Admin API token with Plugins → Experience Context
|
|
30
|
+
* "read", "variations.write", "experiments.write" and
|
|
31
|
+
* "maintenance" (re-save the token after installing or
|
|
32
|
+
* upgrading the plugin).
|
|
33
|
+
* STOREFRONT_TOKEN optional. Content-API token with ...experience.read and find on the target.
|
|
34
|
+
* STRAPI_URL default http://127.0.0.1:1337 (use 127.0.0.1, not localhost)
|
|
35
|
+
* MCP_URL default $STRAPI_URL/mcp
|
|
36
|
+
* SMOKE_TARGET_UID default api::home.home
|
|
37
|
+
* SMOKE_TARGET_DOCUMENT_ID required for collection types; optional for single types
|
|
38
|
+
* SMOKE_REST_PATH REST path of the target for step 5, default /api/home
|
|
39
|
+
* SMOKE_LOCALE default en
|
|
40
|
+
* SMOKE_HERO_KEY block for the audience section (default: the first zone.hero)
|
|
41
|
+
* SMOKE_EXPERIMENT_KEY block for the experiment section (default: another keyed block)
|
|
42
|
+
* SMOKE_KEEP=1 keep what the run created (skip step 7)
|
|
43
|
+
* SMOKE_TIMEOUT_MS per request, default 30000
|
|
44
|
+
* SMOKE_VERBOSE=1 print every tool result
|
|
45
|
+
*
|
|
46
|
+
* Exit code: 0 when every step passed, 1 on a failed check, 2 on a setup problem.
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
const env = process.env;
|
|
50
|
+
const STRAPI_URL = (env.STRAPI_URL || 'http://127.0.0.1:1337').replace(/\/$/, '');
|
|
51
|
+
const MCP_URL = env.MCP_URL || `${STRAPI_URL}/mcp`;
|
|
52
|
+
const TOKEN = env.MCP_ACCESS_TOKEN || '';
|
|
53
|
+
const STOREFRONT_TOKEN = env.STOREFRONT_TOKEN || '';
|
|
54
|
+
const TARGET_UID = env.SMOKE_TARGET_UID || 'api::home.home';
|
|
55
|
+
const TARGET_DOCUMENT_ID = env.SMOKE_TARGET_DOCUMENT_ID || undefined;
|
|
56
|
+
const REST_PATH = env.SMOKE_REST_PATH || '/api/home';
|
|
57
|
+
const WANT_LOCALE = env.SMOKE_LOCALE || 'en';
|
|
58
|
+
const KEEP = env.SMOKE_KEEP === '1';
|
|
59
|
+
const VERBOSE = env.SMOKE_VERBOSE === '1';
|
|
60
|
+
const TIMEOUT_MS = Number(env.SMOKE_TIMEOUT_MS || 30000);
|
|
61
|
+
const RUN = `smoke-${Date.now().toString(36)}`;
|
|
62
|
+
|
|
63
|
+
const HERO_SECTION = 'smoke-hero';
|
|
64
|
+
const EXP_SECTION = 'smoke-categories';
|
|
65
|
+
const EXP_KEY = 'smoke-category-lift';
|
|
66
|
+
const GOLD = 'audience/loyalty-gold';
|
|
67
|
+
|
|
68
|
+
const TOOLS = [
|
|
69
|
+
'experience_describe_target',
|
|
70
|
+
'experience_list_registry',
|
|
71
|
+
'experience_list_content_variants',
|
|
72
|
+
'experience_create_content_variant',
|
|
73
|
+
'experience_update_content_variant',
|
|
74
|
+
'experience_associate_variant_with_audience',
|
|
75
|
+
'experience_set_experiment',
|
|
76
|
+
'experience_associate_variant_with_experiment',
|
|
77
|
+
'experience_conclude_experiment',
|
|
78
|
+
'experience_annotate_content_with_concepts',
|
|
79
|
+
'experience_validate_mapping',
|
|
80
|
+
'experience_explain_variant_resolution',
|
|
81
|
+
'experience_remove_mapping',
|
|
82
|
+
'experience_backfill_block_keys',
|
|
83
|
+
];
|
|
84
|
+
|
|
85
|
+
class SetupError extends Error {}
|
|
86
|
+
class CheckError extends Error {}
|
|
87
|
+
|
|
88
|
+
let failures = 0;
|
|
89
|
+
const pass = (step, msg) => console.log(`PASS ${step} ${msg}`);
|
|
90
|
+
const fail = (step, msg) => {
|
|
91
|
+
failures++;
|
|
92
|
+
console.log(`FAIL ${step} ${msg}`);
|
|
93
|
+
};
|
|
94
|
+
const note = (msg) => console.log(` ${msg}`);
|
|
95
|
+
const check = (cond, msg) => {
|
|
96
|
+
if (!cond) throw new CheckError(msg);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// ── JSON-RPC over Streamable HTTP ──────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
let rpcId = 0;
|
|
102
|
+
let protocolVersion = '2025-06-18';
|
|
103
|
+
let sessionId;
|
|
104
|
+
|
|
105
|
+
/** Reads a JSON or SSE response and returns the JSON-RPC message with our id. */
|
|
106
|
+
const readMessage = async (res, id) => {
|
|
107
|
+
const type = res.headers.get('content-type') || '';
|
|
108
|
+
const text = await res.text();
|
|
109
|
+
if (type.includes('text/event-stream')) {
|
|
110
|
+
for (const event of text.split(/\r?\n\r?\n/)) {
|
|
111
|
+
const data = event
|
|
112
|
+
.split(/\r?\n/)
|
|
113
|
+
.filter((l) => l.startsWith('data:'))
|
|
114
|
+
.map((l) => l.slice(5).trimStart())
|
|
115
|
+
.join('\n');
|
|
116
|
+
if (!data) continue;
|
|
117
|
+
try {
|
|
118
|
+
const msg = JSON.parse(data);
|
|
119
|
+
if (msg.id === id) return msg;
|
|
120
|
+
} catch {
|
|
121
|
+
// not JSON; skip
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
throw new SetupError(`No JSON-RPC response with id ${id} in the event stream: ${text.slice(0, 300)}`);
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
const msg = JSON.parse(text);
|
|
128
|
+
return Array.isArray(msg) ? msg.find((m) => m.id === id) : msg;
|
|
129
|
+
} catch {
|
|
130
|
+
throw new SetupError(`HTTP ${res.status}, not JSON: ${text.slice(0, 300)}`);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const post = async (body) => {
|
|
135
|
+
const headers = {
|
|
136
|
+
'content-type': 'application/json',
|
|
137
|
+
accept: 'application/json, text/event-stream',
|
|
138
|
+
authorization: `Bearer ${TOKEN}`,
|
|
139
|
+
'mcp-protocol-version': protocolVersion,
|
|
140
|
+
};
|
|
141
|
+
if (sessionId) headers['mcp-session-id'] = sessionId;
|
|
142
|
+
let res;
|
|
143
|
+
try {
|
|
144
|
+
res = await fetch(MCP_URL, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
145
|
+
} catch (e) {
|
|
146
|
+
throw new SetupError(`Cannot reach ${MCP_URL}: ${e.cause?.code || e.message}. Is Strapi running with server.mcp.enabled?`);
|
|
147
|
+
}
|
|
148
|
+
const sid = res.headers.get('mcp-session-id');
|
|
149
|
+
if (sid) sessionId = sid;
|
|
150
|
+
return res;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const rpc = async (method, params) => {
|
|
154
|
+
const id = ++rpcId;
|
|
155
|
+
const res = await post({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) });
|
|
156
|
+
if (res.status === 404) throw new SetupError(`${MCP_URL} returned 404. Enable it in config/server.ts: mcp: { enabled: true }.`);
|
|
157
|
+
const msg = await readMessage(res, id);
|
|
158
|
+
if (msg?.error) {
|
|
159
|
+
const auth = /auth/i.test(msg.error.message || '') || res.status === 401;
|
|
160
|
+
throw new SetupError(
|
|
161
|
+
`${method}: JSON-RPC error ${msg.error.code}: ${msg.error.message}${auth ? ' (check MCP_ACCESS_TOKEN: an admin API token)' : ''}`
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
if (!msg || !('result' in msg)) throw new SetupError(`${method}: unexpected response ${JSON.stringify(msg).slice(0, 300)}`);
|
|
165
|
+
return msg.result;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const notify = async (method) => {
|
|
169
|
+
await post({ jsonrpc: '2.0', method });
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/** tools/call; returns { ok, data, text }. */
|
|
173
|
+
const tool = async (name, args) => {
|
|
174
|
+
const result = await rpc('tools/call', { name, arguments: args });
|
|
175
|
+
const text = (result.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
|
|
176
|
+
let data = result.structuredContent;
|
|
177
|
+
if (data === undefined && !result.isError) {
|
|
178
|
+
try {
|
|
179
|
+
data = JSON.parse(text);
|
|
180
|
+
} catch {
|
|
181
|
+
data = undefined;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (VERBOSE) note(`${name} ${JSON.stringify(args)} → ${result.isError ? 'ERROR ' : ''}${text.slice(0, 2000)}`);
|
|
185
|
+
return { ok: !result.isError, data, text };
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const must = async (name, args) => {
|
|
189
|
+
const r = await tool(name, args);
|
|
190
|
+
if (!r.ok) throw new CheckError(`${name} failed: ${r.text}`);
|
|
191
|
+
return r.data;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
/** tools/call that must fail; returns the error text. */
|
|
196
|
+
const mustReject = async (name, args, pattern) => {
|
|
197
|
+
const r = await tool(name, args);
|
|
198
|
+
check(!r.ok, `${name} was expected to be rejected but succeeded`);
|
|
199
|
+
check(pattern.test(r.text), `${name} rejection does not match ${pattern}: ${r.text.slice(0, 300)}`);
|
|
200
|
+
return r.text;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// ── Run ────────────────────────────────────────────────────────────────
|
|
204
|
+
|
|
205
|
+
const target = { targetUid: TARGET_UID, ...(TARGET_DOCUMENT_ID ? { targetDocumentId: TARGET_DOCUMENT_ID } : {}) };
|
|
206
|
+
const created = { sections: [], experiment: false, concepts: null };
|
|
207
|
+
|
|
208
|
+
const step = async (name, fn) => {
|
|
209
|
+
try {
|
|
210
|
+
await fn();
|
|
211
|
+
return true;
|
|
212
|
+
} catch (e) {
|
|
213
|
+
if (e instanceof SetupError) throw e;
|
|
214
|
+
fail(name, e.message);
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const selected = (explained, section) => explained.sections?.[section]?.selected ?? null;
|
|
220
|
+
|
|
221
|
+
const rest = async (query, token) => {
|
|
222
|
+
const res = await fetch(`${STRAPI_URL}${REST_PATH}?${query}`, {
|
|
223
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
224
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
225
|
+
});
|
|
226
|
+
const text = await res.text();
|
|
227
|
+
return { status: res.status, cacheControl: res.headers.get('cache-control'), text, json: (() => { try { return JSON.parse(text); } catch { return null; } })() };
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const stripExperience = (value) => {
|
|
231
|
+
if (Array.isArray(value)) return value.map(stripExperience);
|
|
232
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).filter(([k]) => k !== '_experience').map(([k, v]) => [k, stripExperience(v)]));
|
|
233
|
+
return value;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const main = async () => {
|
|
237
|
+
if (!TOKEN) throw new SetupError('MCP_ACCESS_TOKEN is not set (an admin API token with all four experience-context actions: read, variations.write, experiments.write, maintenance).');
|
|
238
|
+
console.log(`experience smoke → ${MCP_URL} target ${TARGET_UID}${TARGET_DOCUMENT_ID ? ` ${TARGET_DOCUMENT_ID}` : ''} locale ${WANT_LOCALE} correlationId ${RUN}`);
|
|
239
|
+
|
|
240
|
+
// 0. handshake
|
|
241
|
+
const init = await rpc('initialize', { protocolVersion, capabilities: {}, clientInfo: { name: 'experience-smoke', version: '1.0.0' } });
|
|
242
|
+
if (init.protocolVersion) protocolVersion = init.protocolVersion;
|
|
243
|
+
await notify('notifications/initialized');
|
|
244
|
+
const listed = await rpc('tools/list', {});
|
|
245
|
+
const names = new Set((listed.tools || []).map((t) => t.name));
|
|
246
|
+
const missing = TOOLS.filter((t) => !names.has(t));
|
|
247
|
+
if (missing.length) {
|
|
248
|
+
throw new SetupError(
|
|
249
|
+
`Tools not enabled for this token: ${missing.join(', ')}. Grant Plugins → Experience Context read, variations.write, experiments.write and maintenance on the admin API token (its owner needs them too, e.g. the Experience Manager role) and save it again, and make sure the plugin is installed.`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
pass('0 tools/list', `${TOOLS.length} experience tools enabled (server ${init.serverInfo?.name ?? '?'} ${init.protocolVersion ?? ''})`);
|
|
253
|
+
|
|
254
|
+
// 1. describe
|
|
255
|
+
let locale = WANT_LOCALE;
|
|
256
|
+
let heroKey;
|
|
257
|
+
let expKey;
|
|
258
|
+
let before;
|
|
259
|
+
const ok1 = await step('1 describe', async () => {
|
|
260
|
+
before = await must('experience_describe_target', { ...target, locale });
|
|
261
|
+
if (!before.target.localized) locale = null;
|
|
262
|
+
target.targetDocumentId = before.target.documentId;
|
|
263
|
+
const free = before.blocks.filter((b) => b.blockKey && !b.section);
|
|
264
|
+
heroKey = env.SMOKE_HERO_KEY || free.find((b) => b.componentUid === 'zone.hero')?.blockKey || free[0]?.blockKey;
|
|
265
|
+
expKey = env.SMOKE_EXPERIMENT_KEY || free.find((b) => b.blockKey !== heroKey && b.componentUid !== 'zone.hero')?.blockKey || free.find((b) => b.blockKey !== heroKey)?.blockKey;
|
|
266
|
+
check(heroKey && expKey, `need two keyed blocks outside any section, have ${free.length} (run experience_backfill_block_keys, or remove old smoke sections)`);
|
|
267
|
+
check(!before.sections.some((s) => [HERO_SECTION, EXP_SECTION].includes(s.sectionKey)), `sections ${HERO_SECTION}/${EXP_SECTION} exist already (a kept run?); remove them first`);
|
|
268
|
+
pass('1 describe', `${before.blocks.length} blocks in ${locale ?? 'document'}; audience section on ${heroKey}, experiment section on ${expKey}; validation ${before.validation.ok ? 'ok' : 'has errors'}`);
|
|
269
|
+
});
|
|
270
|
+
if (!ok1) return;
|
|
271
|
+
const where = { ...target, locale };
|
|
272
|
+
|
|
273
|
+
// 2. audience workflow
|
|
274
|
+
let goldKey;
|
|
275
|
+
await step('2 audience variation', async () => {
|
|
276
|
+
const registry = await must('experience_list_registry', {});
|
|
277
|
+
note(`registry: ${JSON.stringify(registry.counts)}${registry.audiences?.some((a) => a.id === GOLD) ? '' : ` (${GOLD} is not in it: expect a W1 warning)`}`);
|
|
278
|
+
const args = { ...where, sectionKey: HERO_SECTION, variantKey: 'gold', sourceBlockKey: heroKey, displayName: 'Gold loyalty hero', description: 'Smoke: for Gold loyalty members', targetAudiences: [GOLD], correlationId: RUN };
|
|
279
|
+
const dry = await must('experience_create_content_variant', { ...args, dryRun: true });
|
|
280
|
+
const still = await must('experience_describe_target', where);
|
|
281
|
+
check(dry.dryRun === true && still.blocks.length === before.blocks.length && !still.sections.some((s) => s.sectionKey === HERO_SECTION), 'dryRun wrote something');
|
|
282
|
+
const out = await must('experience_create_content_variant', args);
|
|
283
|
+
created.sections.push(HERO_SECTION);
|
|
284
|
+
goldKey = out.block.blockKey;
|
|
285
|
+
check(goldKey && goldKey !== heroKey, 'the copy has no fresh blockKey');
|
|
286
|
+
const rejection = await mustReject('experience_associate_variant_with_audience', { ...where, sectionKey: HERO_SECTION, variantKey: 'gold', targetAudiences: ['Loyalty Gold'], correlationId: RUN }, /V3 sections\.smoke-hero\.variations\.gold\.targetAudiences\[0\]/);
|
|
287
|
+
note(`readable rejection: ${rejection.split('\n')[1]}`);
|
|
288
|
+
await must('experience_associate_variant_with_audience', { ...where, sectionKey: HERO_SECTION, variantKey: 'gold', targetAudiences: [GOLD], correlationId: RUN });
|
|
289
|
+
const v = await must('experience_validate_mapping', where);
|
|
290
|
+
check(v.targets[0].ok, `validation errors: ${JSON.stringify(v.targets[0].errors)}`);
|
|
291
|
+
pass('2 audience variation', `copied ${heroKey} → ${goldKey} (dryRun wrote nothing), V3 rejected with its path, validation ok (${v.targets[0].checklist.filter((l) => l.startsWith('✓')).length} ✓, ${v.targets[0].warnings.length} ⚠)`);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
// 3. experiment workflow
|
|
295
|
+
let bKey;
|
|
296
|
+
await step('3 experiment', async () => {
|
|
297
|
+
await tool('experience_remove_mapping', { kind: 'experiment', experimentKey: EXP_KEY });
|
|
298
|
+
await must('experience_set_experiment', { key: EXP_KEY, name: 'Smoke category lift', outcomes: [{ key: 'a', label: 'A (control)' }, { key: 'b', label: 'B' }], controlOutcome: 'a', externalId: 'unomi-smoke', correlationId: RUN });
|
|
299
|
+
created.experiment = true;
|
|
300
|
+
await mustReject('experience_set_experiment', { key: EXP_KEY, status: 'running', correlationId: RUN }, /V6 experiments\.smoke-category-lift\.outcomes\.a/);
|
|
301
|
+
const out = await must('experience_create_content_variant', {
|
|
302
|
+
...where,
|
|
303
|
+
sectionKey: EXP_SECTION,
|
|
304
|
+
variantKey: 'b',
|
|
305
|
+
sourceBlockKey: expKey,
|
|
306
|
+
displayName: 'Category lift',
|
|
307
|
+
description: 'Smoke: outcome b',
|
|
308
|
+
experiment: { key: EXP_KEY, outcome: 'b' },
|
|
309
|
+
defaultVariantKey: 'a',
|
|
310
|
+
defaultOutcome: 'a',
|
|
311
|
+
correlationId: RUN,
|
|
312
|
+
});
|
|
313
|
+
created.sections.push(EXP_SECTION);
|
|
314
|
+
bKey = out.block.blockKey;
|
|
315
|
+
const running = await must('experience_set_experiment', { key: EXP_KEY, status: 'running', validity: { startsAt: '2026-01-01T00:00:00Z', endsAt: '2027-12-31T00:00:00Z' }, correlationId: RUN });
|
|
316
|
+
check(running.experiment.status === 'running', 'experiment is not running');
|
|
317
|
+
await mustReject('experience_create_content_variant', { ...where, sectionKey: EXP_SECTION, variantKey: 'gold', targetAudiences: [GOLD], description: 'x', correlationId: RUN }, /X1 sections\.smoke-categories/);
|
|
318
|
+
const listedVariants = await must('experience_list_content_variants', { experimentKey: EXP_KEY });
|
|
319
|
+
check(listedVariants.count === 2, `expected 2 blocks mapped to ${EXP_KEY}, got ${listedVariants.count}`);
|
|
320
|
+
pass('3 experiment', `${EXP_KEY} a=${expKey} b=${bKey}; running rejected while b had no content (V6), accepted after; X1 rejected`);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// 4. concepts
|
|
324
|
+
await step('4 concepts', async () => {
|
|
325
|
+
created.concepts = before.page.concepts;
|
|
326
|
+
const out = await must('experience_annotate_content_with_concepts', { targetUid: TARGET_UID, targetDocumentId: target.targetDocumentId, concepts: ['application/power-drills', 'campaign/spring-pro'], mode: 'add', correlationId: RUN });
|
|
327
|
+
const d = await must('experience_describe_target', where);
|
|
328
|
+
check(JSON.stringify(d.page.concepts) === JSON.stringify(out.concepts), 'describe_target does not return the stored concepts');
|
|
329
|
+
pass('4 concepts', `page is about ${out.concepts.join(', ')}`);
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
// 5. read path
|
|
333
|
+
await step('5 read path', async () => {
|
|
334
|
+
if (!STOREFRONT_TOKEN) {
|
|
335
|
+
note('STOREFRONT_TOKEN not set: skipped (create one with the app\'s scripts/experience/local-setup.mjs storefront)');
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const q = `locale=${locale ?? ''}&status=draft&populate=content`;
|
|
339
|
+
const flagged = await rest(`${q}&withExperience=true`, STOREFRONT_TOKEN);
|
|
340
|
+
check(flagged.status === 200, `flagged read: HTTP ${flagged.status} ${flagged.text.slice(0, 200)}`);
|
|
341
|
+
const data = flagged.json.data;
|
|
342
|
+
check(data._experience?.v === 2, `root _experience is ${JSON.stringify(data._experience)}`);
|
|
343
|
+
check(data._experience.concepts.includes('application/power-drills'), 'root concepts missing');
|
|
344
|
+
check(data._experience.experiments?.[EXP_KEY]?.status === 'running', `experiments.${EXP_KEY} missing`);
|
|
345
|
+
check(JSON.stringify(data._experience.experiments[EXP_KEY].blockKeys) === JSON.stringify({ a: [expKey], b: [bKey] }), `per-outcome blockKeys: ${JSON.stringify(data._experience.experiments[EXP_KEY].blockKeys)}`);
|
|
346
|
+
const gold = data.content.find((b) => b.blockKey === goldKey);
|
|
347
|
+
check(gold?._experience?.variation?.targetAudiences?.includes(GOLD), 'Gold block has no variation');
|
|
348
|
+
check(/private/.test(flagged.cacheControl ?? '') && /no-store/.test(flagged.cacheControl ?? ''), `Cache-Control is ${flagged.cacheControl}`);
|
|
349
|
+
const plain = await rest(q, STOREFRONT_TOKEN);
|
|
350
|
+
check(plain.status === 200 && !plain.text.includes('_experience'), 'a read without the flag carries _experience');
|
|
351
|
+
check(JSON.stringify(stripExperience(flagged.json)) === JSON.stringify(plain.json), 'the flagged read differs from the plain one beyond _experience');
|
|
352
|
+
const pub = await rest(`${q}&withExperience=true`, null);
|
|
353
|
+
check(!pub.text.includes('_experience'), `Public got _experience (HTTP ${pub.status})`);
|
|
354
|
+
pass('5 read path', `_experience v2 (concepts, ${EXP_KEY} with blockKeys a/b, Gold variation), ${flagged.cacheControl}; no flag → none (identical otherwise); Public (HTTP ${pub.status}) → none`);
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// 6. §10.3 scenarios
|
|
358
|
+
await step('6 scenarios', async () => {
|
|
359
|
+
const explain = (context, extra = {}) => must('experience_explain_variant_resolution', { ...where, context, ...extra });
|
|
360
|
+
const results = [];
|
|
361
|
+
const s1 = await explain({ visitorId: 'visitor-1', audiences: [GOLD], consent: { analytics: true, marketing: true } });
|
|
362
|
+
check(selected(s1, HERO_SECTION) === goldKey, `1: Gold context selected ${selected(s1, HERO_SECTION)}`);
|
|
363
|
+
results.push('1 Gold → Gold hero');
|
|
364
|
+
const s2 = await explain({ visitorId: 'visitor-2', audiences: ['audience/power-drill-intent'], affinities: { 'application/power-drills': 'high' }, experiments: { [EXP_KEY]: 'b' } });
|
|
365
|
+
check(selected(s2, EXP_SECTION) === bKey && selected(s2, HERO_SECTION) === heroKey, `2: got ${selected(s2, HERO_SECTION)} / ${selected(s2, EXP_SECTION)}`);
|
|
366
|
+
results.push('2 drill intent + b → outcome b');
|
|
367
|
+
const s3 = await explain({});
|
|
368
|
+
check(selected(s3, HERO_SECTION) === heroKey && selected(s3, EXP_SECTION) === expKey, `3: empty context got ${selected(s3, HERO_SECTION)} / ${selected(s3, EXP_SECTION)}`);
|
|
369
|
+
check(/No variation matched; showing the default/.test(s3.explanation.text), '3: explanation has no fallback line');
|
|
370
|
+
results.push('3 empty → defaults');
|
|
371
|
+
const legacy = await must('experience_create_content_variant', { ...where, sectionKey: HERO_SECTION, variantKey: 'legacy-vip', targetAudiences: ['audience/legacy-vip'], description: 'Smoke: unknown audience', correlationId: RUN });
|
|
372
|
+
check(legacy.validation.warnings.some((w) => w.code === 'W1' && /legacy-vip/.test(w.message)), '4: no registry warning for audience/legacy-vip');
|
|
373
|
+
const s4 = await explain({ visitorId: 'visitor-4' });
|
|
374
|
+
check(selected(s4, HERO_SECTION) === heroKey, `4: got ${selected(s4, HERO_SECTION)}`);
|
|
375
|
+
results.push('4 unknown audience → W1 + fallback');
|
|
376
|
+
await must('experience_conclude_experiment', { key: EXP_KEY, winner: 'a', reason: 'smoke', correlationId: RUN });
|
|
377
|
+
const s5 = await explain({ visitorId: 'visitor-5', experiments: { [EXP_KEY]: 'b' } }, { preview: false });
|
|
378
|
+
check(selected(s5, EXP_SECTION) === expKey, `5: winner a, got ${selected(s5, EXP_SECTION)}`);
|
|
379
|
+
check(s5.experiments[EXP_KEY]?.source === 'winner' && s5.experiments[EXP_KEY]?.exposable === false, `5: ${JSON.stringify(s5.experiments[EXP_KEY])}`);
|
|
380
|
+
results.push('5 winner a → a, not exposable');
|
|
381
|
+
note(s1.explanation.text.split('\n').filter((l) => l.startsWith(`[${HERO_SECTION}]`) || l.startsWith(' ✓')).slice(0, 2).join(' | '));
|
|
382
|
+
pass('6 scenarios', results.join('; '));
|
|
383
|
+
});
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const cleanup = async () => {
|
|
387
|
+
if (KEEP) {
|
|
388
|
+
note(`SMOKE_KEEP=1: kept sections ${created.sections.join(', ') || 'none'}${created.experiment ? ` and experiment ${EXP_KEY}` : ''}`);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const errors = [];
|
|
392
|
+
const run = async (name, args) => {
|
|
393
|
+
const r = await tool(name, args).catch((e) => ({ ok: false, text: e.message }));
|
|
394
|
+
if (!r.ok) errors.push(`${name}: ${r.text.slice(0, 200)}`);
|
|
395
|
+
};
|
|
396
|
+
const locale = WANT_LOCALE;
|
|
397
|
+
for (const sectionKey of created.sections) {
|
|
398
|
+
await run('experience_remove_mapping', { kind: 'section', ...target, locale, sectionKey, deleteBlocks: true, correlationId: RUN, reason: 'smoke cleanup' });
|
|
399
|
+
}
|
|
400
|
+
if (created.experiment) await run('experience_remove_mapping', { kind: 'experiment', experimentKey: EXP_KEY, correlationId: RUN });
|
|
401
|
+
if (created.concepts) {
|
|
402
|
+
await run('experience_annotate_content_with_concepts', { targetUid: TARGET_UID, targetDocumentId: target.targetDocumentId, concepts: created.concepts, correlationId: RUN });
|
|
403
|
+
}
|
|
404
|
+
if (errors.length) fail('7 cleanup', errors.join('; '));
|
|
405
|
+
else pass('7 cleanup', `removed ${created.sections.length} section(s) with their copied blocks${created.experiment ? `, experiment ${EXP_KEY}` : ''}, restored page concepts`);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
let exitCode = 0;
|
|
409
|
+
try {
|
|
410
|
+
await main();
|
|
411
|
+
} catch (e) {
|
|
412
|
+
if (e instanceof SetupError) {
|
|
413
|
+
console.error(`SETUP ${e.message}`);
|
|
414
|
+
exitCode = 2;
|
|
415
|
+
} else {
|
|
416
|
+
console.error(e);
|
|
417
|
+
exitCode = 1;
|
|
418
|
+
}
|
|
419
|
+
} finally {
|
|
420
|
+
if (exitCode !== 2 || sessionId) {
|
|
421
|
+
try {
|
|
422
|
+
await cleanup();
|
|
423
|
+
} catch (e) {
|
|
424
|
+
fail('7 cleanup', e.message);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (!exitCode && failures) exitCode = 1;
|
|
429
|
+
console.log(exitCode === 0 ? '\nsmoke: all steps passed' : `\nsmoke: ${failures} failed step(s)${exitCode === 2 ? ' (setup problem)' : ''}`);
|
|
430
|
+
process.exit(exitCode);
|