@veroxm/react-sdk 0.0.0-stage → 0.1.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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +295 -2
- package/dist/cache.d.ts +69 -0
- package/dist/cache.js +89 -0
- package/dist/client-slots.d.ts +35 -0
- package/dist/client-slots.js +169 -0
- package/dist/client.d.ts +65 -0
- package/dist/client.js +87 -0
- package/dist/editor/constants.d.ts +12 -0
- package/dist/editor/constants.js +12 -0
- package/dist/editor/handler.d.ts +16 -0
- package/dist/editor/handler.js +175 -0
- package/dist/editor/inline.d.ts +25 -0
- package/dist/editor/inline.js +149 -0
- package/dist/editor/menu-input.d.ts +26 -0
- package/dist/editor/menu-input.js +110 -0
- package/dist/editor/overlay.d.ts +31 -0
- package/dist/editor/overlay.js +856 -0
- package/dist/editor/rich-text.d.ts +21 -0
- package/dist/editor/rich-text.js +232 -0
- package/dist/editor/server.d.ts +9 -0
- package/dist/editor/server.js +43 -0
- package/dist/errors.d.ts +20 -0
- package/dist/errors.js +26 -0
- package/dist/hooks/use-cached-query.d.ts +21 -0
- package/dist/hooks/use-cached-query.js +59 -0
- package/dist/hooks/use-collection.d.ts +10 -0
- package/dist/hooks/use-collection.js +14 -0
- package/dist/hooks/use-entries.d.ts +18 -0
- package/dist/hooks/use-entries.js +25 -0
- package/dist/hooks/use-entry.d.ts +21 -0
- package/dist/hooks/use-entry.js +22 -0
- package/dist/hooks/use-media.d.ts +9 -0
- package/dist/hooks/use-media.js +13 -0
- package/dist/hydration-boundary.d.ts +35 -0
- package/dist/hydration-boundary.js +38 -0
- package/dist/image.d.ts +34 -0
- package/dist/image.js +39 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +32 -0
- package/dist/next/cache-components.d.ts +15 -0
- package/dist/next/cache-components.js +25 -0
- package/dist/next/cached.d.ts +9 -0
- package/dist/next/cached.js +20 -0
- package/dist/next/edge-slot.d.ts +21 -0
- package/dist/next/edge-slot.js +29 -0
- package/dist/next/editor.d.ts +7 -0
- package/dist/next/editor.js +13 -0
- package/dist/next/index.d.ts +17 -0
- package/dist/next/index.js +21 -0
- package/dist/next/llms.d.ts +2 -0
- package/dist/next/llms.js +44 -0
- package/dist/next/route.d.ts +12 -0
- package/dist/next/route.js +16 -0
- package/dist/next/slot.d.ts +21 -0
- package/dist/next/slot.js +160 -0
- package/dist/node.d.ts +43 -0
- package/dist/node.js +67 -0
- package/dist/preview.d.ts +35 -0
- package/dist/preview.js +46 -0
- package/dist/provider.d.ts +29 -0
- package/dist/provider.js +37 -0
- package/dist/query-keys.d.ts +19 -0
- package/dist/query-keys.js +49 -0
- package/dist/site/chart-view.d.ts +14 -0
- package/dist/site/chart-view.js +44 -0
- package/dist/site/chart.d.ts +127 -0
- package/dist/site/chart.js +639 -0
- package/dist/site/map-embed.d.ts +32 -0
- package/dist/site/map-embed.js +139 -0
- package/dist/site/map-math.d.ts +27 -0
- package/dist/site/map-math.js +89 -0
- package/dist/site/nav-menu.d.ts +19 -0
- package/dist/site/nav-menu.js +76 -0
- package/dist/site/site-parts.d.ts +87 -0
- package/dist/site/site-parts.js +46 -0
- package/dist/site/slider.d.ts +17 -0
- package/dist/site/slider.js +78 -0
- package/dist/site/styles.d.ts +3 -0
- package/dist/site/styles.js +155 -0
- package/dist/site/video-embed.d.ts +15 -0
- package/dist/site/video-embed.js +27 -0
- package/dist/site/video.d.ts +18 -0
- package/dist/site/video.js +73 -0
- package/dist/slots-core.d.ts +397 -0
- package/dist/slots-core.js +367 -0
- package/dist/slots.d.ts +13 -0
- package/dist/slots.js +30 -0
- package/dist/ssr.d.ts +20 -0
- package/dist/ssr.js +35 -0
- package/dist/structured-data.d.ts +13 -0
- package/dist/structured-data.js +36 -0
- package/dist/tracking.d.ts +142 -0
- package/dist/tracking.js +152 -0
- package/dist/types.d.ts +106 -0
- package/dist/types.js +6 -0
- package/package.json +95 -4
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
/** Field builders for a slot's `fields` prop. */
|
|
2
|
+
export const field = {
|
|
3
|
+
text: (o = {}) => ({ type: 'text', ...o }),
|
|
4
|
+
richText: (o = {}) => ({ type: 'richText', ...o }),
|
|
5
|
+
media: (o = {}) => ({ type: 'media', ...o }),
|
|
6
|
+
link: (o = {}) => ({ type: 'link', ...o }),
|
|
7
|
+
number: (o = {}) => ({ type: 'number', ...o }),
|
|
8
|
+
boolean: (o = {}) => ({ type: 'boolean', ...o }),
|
|
9
|
+
select: (options, o = {}) => ({ type: 'select', options, ...o }),
|
|
10
|
+
/** A navigation menu marketers edit: links, with sub-menus up to `depth` levels (default 2, at most 3). */
|
|
11
|
+
menu: (o = {}) => ({ type: 'menu', ...o }),
|
|
12
|
+
/** A YouTube or Vimeo link, or a video file, that the site shows as a player. */
|
|
13
|
+
video: (o = {}) => ({ type: 'video', ...o }),
|
|
14
|
+
/** Slides for a slider: each an image with optional title, text and link. `max` 1 to 20 (default 10). */
|
|
15
|
+
slides: (o = {}) => ({ type: 'slides', ...o }),
|
|
16
|
+
/** Places on a map (OpenStreetMap): each with a name, an address and a position. `max` 1 to 50 places (default 20). */
|
|
17
|
+
map: (o = {}) => ({ type: 'map', ...o }),
|
|
18
|
+
/** A chart: numbers typed in, read from your own systems (Connected APIs), or from VeroXM's analytics. */
|
|
19
|
+
chart: (o = {}) => ({ type: 'chart', ...o }),
|
|
20
|
+
};
|
|
21
|
+
let config = {};
|
|
22
|
+
let warned = false;
|
|
23
|
+
/** Overrides the environment-variable defaults for every slot in this process. */
|
|
24
|
+
export function configureSlots(next) {
|
|
25
|
+
config = { ...config, ...next };
|
|
26
|
+
}
|
|
27
|
+
const isServer = typeof window === 'undefined';
|
|
28
|
+
function env(name) {
|
|
29
|
+
return typeof process !== 'undefined' ? process?.env?.[name] : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** The effective slots configuration (configureSlots over environment variables). */
|
|
32
|
+
export function resolveSlotsConfig() {
|
|
33
|
+
const baseUrl = (config.baseUrl ?? env('VEROXM_API_BASE') ?? '').replace(/\/+$/, '');
|
|
34
|
+
const projectId = config.projectId ?? env('VEROXM_PROJECT_ID') ?? '';
|
|
35
|
+
const apiKey = config.apiKey ?? env('VEROXM_API_KEY') ?? '';
|
|
36
|
+
return {
|
|
37
|
+
baseUrl,
|
|
38
|
+
projectId,
|
|
39
|
+
apiKey,
|
|
40
|
+
locale: config.locale,
|
|
41
|
+
report: config.report ?? isServer,
|
|
42
|
+
revalidate: config.revalidate ?? 30,
|
|
43
|
+
edge: config.edge ?? ['1', 'true'].includes((env('VEROXM_EDGE') ?? '').toLowerCase()),
|
|
44
|
+
fetch: config.fetch ?? (typeof fetch === 'function' ? fetch.bind(globalThis) : undefined),
|
|
45
|
+
ready: Boolean(baseUrl && projectId && apiKey),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function warnOnce(message) {
|
|
49
|
+
if (warned)
|
|
50
|
+
return;
|
|
51
|
+
warned = true;
|
|
52
|
+
console.warn(`[veroxm] ${message}`);
|
|
53
|
+
}
|
|
54
|
+
const MAX_NAMES_PER_REQUEST = 50;
|
|
55
|
+
const pending = new Map(); // by locale ('' = project default)
|
|
56
|
+
let flushScheduled = false;
|
|
57
|
+
/** Published content of one slot; requests made in the same tick share one HTTP call. */
|
|
58
|
+
export function loadPublishedSlot(name, locale) {
|
|
59
|
+
const cfg = resolveSlotsConfig();
|
|
60
|
+
if (!cfg.ready || !cfg.fetch) {
|
|
61
|
+
warnOnce('VEROXM_API_BASE, VEROXM_PROJECT_ID and VEROXM_API_KEY (or configureSlots) are needed for slots; showing fallback content.');
|
|
62
|
+
return Promise.resolve(null);
|
|
63
|
+
}
|
|
64
|
+
const key = locale ?? cfg.locale ?? '';
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
const list = pending.get(key) ?? [];
|
|
67
|
+
list.push({ name, resolve });
|
|
68
|
+
pending.set(key, list);
|
|
69
|
+
if (!flushScheduled) {
|
|
70
|
+
flushScheduled = true;
|
|
71
|
+
setTimeout(flushReads, 0);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function flushReads() {
|
|
76
|
+
flushScheduled = false;
|
|
77
|
+
const cfg = resolveSlotsConfig();
|
|
78
|
+
const batches = [...pending.entries()];
|
|
79
|
+
pending.clear();
|
|
80
|
+
for (const [locale, waiters] of batches) {
|
|
81
|
+
const names = [...new Set(waiters.map((w) => w.name))];
|
|
82
|
+
for (let i = 0; i < names.length; i += MAX_NAMES_PER_REQUEST) {
|
|
83
|
+
const chunk = names.slice(i, i + MAX_NAMES_PER_REQUEST);
|
|
84
|
+
const mine = waiters.filter((w) => chunk.includes(w.name));
|
|
85
|
+
const qs = new URLSearchParams({ names: chunk.join(',') });
|
|
86
|
+
if (locale)
|
|
87
|
+
qs.set('locale', locale);
|
|
88
|
+
if (cfg.edge)
|
|
89
|
+
qs.set('variants', '1');
|
|
90
|
+
const url = `${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots?${qs}`;
|
|
91
|
+
cfg.fetch(url, {
|
|
92
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
93
|
+
// Next.js: cache briefly and allow revalidateTag('veroxm-slots').
|
|
94
|
+
next: { revalidate: cfg.revalidate, tags: ['veroxm-slots'] },
|
|
95
|
+
})
|
|
96
|
+
.then(async (res) => {
|
|
97
|
+
if (!res.ok)
|
|
98
|
+
throw new Error(`HTTP ${res.status}`);
|
|
99
|
+
const body = (await res.json());
|
|
100
|
+
for (const w of mine)
|
|
101
|
+
w.resolve(slotFromBody(body, w.name));
|
|
102
|
+
})
|
|
103
|
+
.catch((err) => {
|
|
104
|
+
warnOnce(`could not load slots (${err.message}); showing fallback content.`);
|
|
105
|
+
for (const w of mine)
|
|
106
|
+
w.resolve(null);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** One slot from a shared read: marked when it has a live test (with its variants in edge mode) or personalised versions. */
|
|
112
|
+
function slotFromBody(body, name) {
|
|
113
|
+
let slot = body.slots?.[name] ?? null;
|
|
114
|
+
if (body.personalised?.includes(name) && slot)
|
|
115
|
+
slot = { ...slot, personalised: true };
|
|
116
|
+
if (!body.testing?.includes(name))
|
|
117
|
+
return slot;
|
|
118
|
+
return { values: {}, version: 0, ...slot, testing: true, variants: body.variants?.[name] ?? null };
|
|
119
|
+
}
|
|
120
|
+
// -------------------------------------------------------------- reporting
|
|
121
|
+
const reported = new Set();
|
|
122
|
+
const reportQueue = new Map();
|
|
123
|
+
let reportScheduled = false;
|
|
124
|
+
function stable(value) {
|
|
125
|
+
if (Array.isArray(value))
|
|
126
|
+
return `[${value.map(stable).join(',')}]`;
|
|
127
|
+
if (value && typeof value === 'object') {
|
|
128
|
+
return `{${Object.keys(value)
|
|
129
|
+
.sort()
|
|
130
|
+
.map((k) => `${k}:${stable(value[k])}`)
|
|
131
|
+
.join(',')}}`;
|
|
132
|
+
}
|
|
133
|
+
return JSON.stringify(value);
|
|
134
|
+
}
|
|
135
|
+
const timerScheduler = (send) => void setTimeout(() => void send(), 0);
|
|
136
|
+
export function reportSlot(name, fields, label, path, schedule = timerScheduler, shown) {
|
|
137
|
+
const cfg = resolveSlotsConfig();
|
|
138
|
+
if (!cfg.report || !cfg.ready || !cfg.fetch)
|
|
139
|
+
return;
|
|
140
|
+
const key = reportKey(name, fields, label, shown);
|
|
141
|
+
if (reported.has(key))
|
|
142
|
+
return;
|
|
143
|
+
reported.add(key);
|
|
144
|
+
reportQueue.set(`${name}|${shown?.locale ?? ''}`, queued(key, name, fields, label, path, shown));
|
|
145
|
+
if (!reportScheduled) {
|
|
146
|
+
reportScheduled = true;
|
|
147
|
+
try {
|
|
148
|
+
schedule(flushReports);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
timerScheduler(flushReports);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Reports one slot right away and waits for the answer (once per process,
|
|
157
|
+
* like reportSlot). For code that must finish its requests inside the
|
|
158
|
+
* render, such as a Next.js 'use cache' function.
|
|
159
|
+
*/
|
|
160
|
+
export async function reportSlotNow(name, fields, label, path, shown) {
|
|
161
|
+
const cfg = resolveSlotsConfig();
|
|
162
|
+
if (!cfg.report || !cfg.ready || !cfg.fetch)
|
|
163
|
+
return;
|
|
164
|
+
const key = reportKey(name, fields, label, shown);
|
|
165
|
+
if (reported.has(key))
|
|
166
|
+
return;
|
|
167
|
+
reported.add(key);
|
|
168
|
+
await sendReports([queued(key, name, fields, label, path, shown)]);
|
|
169
|
+
}
|
|
170
|
+
const reportKey = (name, fields, label, shown) => `${name}|${stable(fields)}|${label ?? ''}|${shown ? `${shown.locale ?? ''}:${stable(shown.values)}` : ''}`;
|
|
171
|
+
function queued(key, name, fields, label, path, shown) {
|
|
172
|
+
const hasShown = shown && Object.keys(shown.values).length > 0;
|
|
173
|
+
return { key, name, label, fields, path, ...(hasShown ? { shown: shown.values, ...(shown.locale ? { locale: shown.locale } : {}) } : {}) };
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The values a slot shows from its `fallback` alone (fields the fallback
|
|
177
|
+
* leaves empty are left out): what the site shows before anything is
|
|
178
|
+
* published, sent to VeroXM so its dashboard can show it in empty fields.
|
|
179
|
+
*/
|
|
180
|
+
export function fallbackValues(fields, fallback) {
|
|
181
|
+
const out = {};
|
|
182
|
+
if (!fallback)
|
|
183
|
+
return out;
|
|
184
|
+
for (const name of Object.keys(fields)) {
|
|
185
|
+
const v = fallback[name];
|
|
186
|
+
if (v !== undefined && v !== null && v !== '')
|
|
187
|
+
out[name] = v;
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
async function flushReports() {
|
|
192
|
+
reportScheduled = false;
|
|
193
|
+
const queued = [...reportQueue.values()];
|
|
194
|
+
reportQueue.clear();
|
|
195
|
+
await sendReports(queued);
|
|
196
|
+
}
|
|
197
|
+
async function sendReports(queued) {
|
|
198
|
+
const cfg = resolveSlotsConfig();
|
|
199
|
+
if (!queued.length || !cfg.fetch)
|
|
200
|
+
return;
|
|
201
|
+
// A definition that didn't get through is reported again on a later render.
|
|
202
|
+
const retryLater = () => queued.forEach((q) => reported.delete(q.key));
|
|
203
|
+
try {
|
|
204
|
+
const res = await cfg.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots/report`, {
|
|
205
|
+
method: 'POST',
|
|
206
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, 'Content-Type': 'application/json' },
|
|
207
|
+
body: JSON.stringify({ slots: queued.map(({ key: _key, ...slot }) => slot) }),
|
|
208
|
+
// No cache option: in Next.js an explicit 'no-store' here would turn
|
|
209
|
+
// every page with a slot into a dynamic page. POSTs aren't cached anyway.
|
|
210
|
+
});
|
|
211
|
+
if (!res.ok) {
|
|
212
|
+
if (res.status >= 500)
|
|
213
|
+
retryLater();
|
|
214
|
+
return warnOnce(`slot definitions were not accepted (HTTP ${res.status}); check the key has "read".`);
|
|
215
|
+
}
|
|
216
|
+
const body = (await res.json().catch(() => ({})));
|
|
217
|
+
for (const p of body.problems ?? [])
|
|
218
|
+
console.warn(`[veroxm] slot "${p.name}": ${p.problems.join('; ')}`);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
retryLater();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// ------------------------------------------------------------------ values
|
|
225
|
+
function emptyValue(def) {
|
|
226
|
+
switch (def.type) {
|
|
227
|
+
case 'text':
|
|
228
|
+
case 'richText':
|
|
229
|
+
return '';
|
|
230
|
+
case 'boolean':
|
|
231
|
+
return false;
|
|
232
|
+
case 'select':
|
|
233
|
+
return def.options[0];
|
|
234
|
+
case 'menu':
|
|
235
|
+
case 'slides':
|
|
236
|
+
return [];
|
|
237
|
+
default:
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Published value where there is one, else the fallback, else an empty value for the field type. */
|
|
242
|
+
export function mergeSlotValues(fields, fallback, published) {
|
|
243
|
+
const out = {};
|
|
244
|
+
for (const [name, def] of Object.entries(fields)) {
|
|
245
|
+
const live = published?.[name];
|
|
246
|
+
const hasLive = live !== undefined && live !== null && live !== '';
|
|
247
|
+
const fb = fallback?.[name];
|
|
248
|
+
out[name] = hasLive ? live : fb !== undefined && fb !== null ? fb : emptyValue(def);
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
/** SlotInfo for published content (or the fallback when null). */
|
|
253
|
+
export function slotInfo(name, published) {
|
|
254
|
+
return {
|
|
255
|
+
name,
|
|
256
|
+
version: published?.version || null,
|
|
257
|
+
source: published && (published.version || published.test) ? 'published' : 'fallback',
|
|
258
|
+
test: published?.test ?? null,
|
|
259
|
+
// Only the on-page editor (@veroxm/react-sdk/next, draft mode) marks fields.
|
|
260
|
+
editing: false,
|
|
261
|
+
edit: () => ({}),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Published content of one slot, fetched on its own (no batching, no
|
|
266
|
+
* Next.js fetch cache) -- for callers that cache it themselves, such as
|
|
267
|
+
* the Cache Components path in '@veroxm/react-sdk/next'.
|
|
268
|
+
*/
|
|
269
|
+
export async function fetchPublishedSlot(name, locale) {
|
|
270
|
+
const cfg = resolveSlotsConfig();
|
|
271
|
+
if (!cfg.ready || !cfg.fetch)
|
|
272
|
+
return null;
|
|
273
|
+
const qs = new URLSearchParams({ names: name });
|
|
274
|
+
if (locale ?? cfg.locale)
|
|
275
|
+
qs.set('locale', (locale ?? cfg.locale));
|
|
276
|
+
if (cfg.edge)
|
|
277
|
+
qs.set('variants', '1');
|
|
278
|
+
try {
|
|
279
|
+
const res = await cfg.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots?${qs}`, {
|
|
280
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
281
|
+
});
|
|
282
|
+
if (!res.ok)
|
|
283
|
+
return null;
|
|
284
|
+
return slotFromBody((await res.json()), name);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* One visitor's values for slots under a live A/B test (uncached): their
|
|
292
|
+
* variant over the published values. Null when it can't be loaded.
|
|
293
|
+
*/
|
|
294
|
+
export async function loadSlotForVisitor(name, visitorId, locale) {
|
|
295
|
+
return loadSlotFor(name, { visitorId }, locale);
|
|
296
|
+
}
|
|
297
|
+
/** The query a person's read adds: userId, consent, country and ctx.<name>. */
|
|
298
|
+
export function personQuery(person, qs) {
|
|
299
|
+
if (!person)
|
|
300
|
+
return qs;
|
|
301
|
+
if (person.userId)
|
|
302
|
+
qs.set('userId', String(person.userId));
|
|
303
|
+
if (person.consent)
|
|
304
|
+
qs.set('consent', 'personalization');
|
|
305
|
+
if (person.country && /^[A-Za-z]{2}$/.test(person.country))
|
|
306
|
+
qs.set('country', person.country.toUpperCase());
|
|
307
|
+
for (const [k, v] of Object.entries(person.ctx ?? {}).slice(0, 10))
|
|
308
|
+
qs.set(`ctx.${k}`, String(v));
|
|
309
|
+
return qs;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* One person's values for a slot (uncached): their A/B variant when given
|
|
313
|
+
* the visitor's id, and their personalised version when given `person`.
|
|
314
|
+
* Null when it can't be loaded.
|
|
315
|
+
*/
|
|
316
|
+
export async function loadSlotFor(name, who, locale) {
|
|
317
|
+
const cfg = resolveSlotsConfig();
|
|
318
|
+
if (!cfg.ready || !cfg.fetch)
|
|
319
|
+
return null;
|
|
320
|
+
const qs = personQuery(who.person, new URLSearchParams({ names: name }));
|
|
321
|
+
if (who.visitorId)
|
|
322
|
+
qs.set('visitorId', who.visitorId);
|
|
323
|
+
if (locale ?? cfg.locale)
|
|
324
|
+
qs.set('locale', (locale ?? cfg.locale));
|
|
325
|
+
try {
|
|
326
|
+
const res = await cfg.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots?${qs}`, {
|
|
327
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
328
|
+
cache: 'no-store',
|
|
329
|
+
});
|
|
330
|
+
if (!res.ok)
|
|
331
|
+
return null;
|
|
332
|
+
const body = (await res.json());
|
|
333
|
+
return body.slots?.[name] ?? null;
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/** Loads one slot (batched), reports its definition, and merges in the fallback. `hidden`: render nothing. */
|
|
340
|
+
export async function loadSlot(name, options) {
|
|
341
|
+
reportSlot(name, options.fields, options.label, options.path);
|
|
342
|
+
let published = await loadPublishedSlot(name, options.locale);
|
|
343
|
+
const visitorId = published?.testing ? options.visitorId : null;
|
|
344
|
+
const person = published?.personalised ? options.person : null;
|
|
345
|
+
if (visitorId || person)
|
|
346
|
+
published = (await loadSlotFor(name, { visitorId, person }, options.locale)) ?? published;
|
|
347
|
+
return { values: mergeSlotValues(options.fields, options.fallback, published?.values ?? null), slot: slotInfo(name, published), hidden: !!published?.hidden };
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Server component (Next.js App Router, React Server Components). Renders
|
|
351
|
+
* the slot's published content, or its fallback. For client-only React
|
|
352
|
+
* apps, use `useSlot` instead.
|
|
353
|
+
*/
|
|
354
|
+
export async function VeroxmSlot({ name, children, ...options }) {
|
|
355
|
+
const { values, slot, hidden } = await loadSlot(name, options);
|
|
356
|
+
return hidden ? null : children(values, slot);
|
|
357
|
+
}
|
|
358
|
+
/** Test helper: forgets configuration, queued requests and reported definitions. */
|
|
359
|
+
export function resetSlotsForTests() {
|
|
360
|
+
config = {};
|
|
361
|
+
warned = false;
|
|
362
|
+
pending.clear();
|
|
363
|
+
reported.clear();
|
|
364
|
+
reportQueue.clear();
|
|
365
|
+
flushScheduled = false;
|
|
366
|
+
reportScheduled = false;
|
|
367
|
+
}
|
package/dist/slots.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type LoadSlotOptions, type SlotFieldDefs, type SlotInfo, type SlotValues } from './slots-core.js';
|
|
2
|
+
export * from './slots-core.js';
|
|
3
|
+
export interface SlotState<F extends SlotFieldDefs> {
|
|
4
|
+
values: SlotValues<F>;
|
|
5
|
+
slot: SlotInfo;
|
|
6
|
+
loading: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Client hook for React apps without server components (Vite, CRA, React
|
|
10
|
+
* Native). Shows the fallback immediately and swaps in published content
|
|
11
|
+
* when it arrives.
|
|
12
|
+
*/
|
|
13
|
+
export declare function useSlot<F extends SlotFieldDefs>(name: string, options: LoadSlotOptions<F>): SlotState<F>;
|
package/dist/slots.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { loadSlot, mergeSlotValues, slotInfo } from './slots-core.js';
|
|
3
|
+
// Visual slots: everything from the server-safe core (slots-core.tsx),
|
|
4
|
+
// plus useSlot, the client hook (which Server Components can't import).
|
|
5
|
+
export * from './slots-core.js';
|
|
6
|
+
/**
|
|
7
|
+
* Client hook for React apps without server components (Vite, CRA, React
|
|
8
|
+
* Native). Shows the fallback immediately and swaps in published content
|
|
9
|
+
* when it arrives.
|
|
10
|
+
*/
|
|
11
|
+
export function useSlot(name, options) {
|
|
12
|
+
const optsRef = useRef(options);
|
|
13
|
+
optsRef.current = options;
|
|
14
|
+
const initial = useMemo(() => ({ values: mergeSlotValues(options.fields, options.fallback, null), slot: slotInfo(name, null), loading: true }),
|
|
15
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
16
|
+
[name]);
|
|
17
|
+
const [state, setState] = useState(initial);
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
let live = true;
|
|
20
|
+
setState(initial);
|
|
21
|
+
loadSlot(name, optsRef.current).then(({ values, slot }) => {
|
|
22
|
+
if (live)
|
|
23
|
+
setState({ values, slot, loading: false });
|
|
24
|
+
});
|
|
25
|
+
return () => {
|
|
26
|
+
live = false;
|
|
27
|
+
};
|
|
28
|
+
}, [name, options.locale, initial]);
|
|
29
|
+
return state;
|
|
30
|
+
}
|
package/dist/ssr.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { VeroxmClient } from './client.js';
|
|
2
|
+
import type { CollectionMeta, Entry, EntriesQueryOptions, EntryConnection, MediaView } from './types.js';
|
|
3
|
+
/** One server-fetched query's cache entry, in the exact shape <VeroxmHydrationBoundary> needs -- pass the `hydration` field each fetchX() below returns straight through as its `state` prop. */
|
|
4
|
+
export interface VeroxmHydrationEntry {
|
|
5
|
+
key: string;
|
|
6
|
+
data: unknown;
|
|
7
|
+
tags: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
export interface SsrResult<T> {
|
|
10
|
+
data: T;
|
|
11
|
+
/** See VeroxmHydrationEntry -- pass this to <VeroxmHydrationBoundary state={...}>. */
|
|
12
|
+
hydration: VeroxmHydrationEntry;
|
|
13
|
+
}
|
|
14
|
+
export declare function fetchCollection(client: VeroxmClient, slug: string): Promise<SsrResult<CollectionMeta | null>>;
|
|
15
|
+
export declare function fetchCollections(client: VeroxmClient): Promise<SsrResult<CollectionMeta[]>>;
|
|
16
|
+
export declare function fetchEntry<T = Record<string, unknown>>(client: VeroxmClient, collection: string, id: number, options?: {
|
|
17
|
+
timestamps?: boolean;
|
|
18
|
+
}): Promise<SsrResult<Entry<T> | null>>;
|
|
19
|
+
export declare function fetchEntries<T = Record<string, unknown>>(client: VeroxmClient, collection: string, options?: EntriesQueryOptions): Promise<SsrResult<EntryConnection<T>>>;
|
|
20
|
+
export declare function fetchMedia(client: VeroxmClient, id: number): Promise<SsrResult<MediaView | null>>;
|
package/dist/ssr.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { collectionKey, collectionTag, collectionsKey, entriesKey, entryKey, entryTags, mediaKey, mediaTag } from './query-keys.js';
|
|
2
|
+
// Framework-agnostic fetch helpers (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-
|
|
3
|
+
// PLAN.md §5.5) -- plain async functions, no React hooks, safe to call
|
|
4
|
+
// from a Next.js Server Component, `getServerSideProps`, a route handler,
|
|
5
|
+
// or any other non-React server context. Each one is a thin pass-through
|
|
6
|
+
// to the matching VeroxmClient method (see client.ts) PLUS the cache
|
|
7
|
+
// key/tags a client-side hook for the identical query would compute
|
|
8
|
+
// (query-keys.ts) -- that pairing is what lets <VeroxmHydrationBoundary>
|
|
9
|
+
// seed the client's cache so the corresponding hook (§5.2) recognizes
|
|
10
|
+
// the data as already-fresh and skips an immediate refetch. The
|
|
11
|
+
// server-side `client` you call these with is a SEPARATE object from the
|
|
12
|
+
// browser's (different process/JS realm entirely) -- seeding only
|
|
13
|
+
// happens once its data crosses into the hydration boundary client-side,
|
|
14
|
+
// not here.
|
|
15
|
+
export async function fetchCollection(client, slug) {
|
|
16
|
+
const data = await client.getCollection(slug);
|
|
17
|
+
return { data, hydration: { key: collectionKey(slug), data, tags: [collectionTag(slug)] } };
|
|
18
|
+
}
|
|
19
|
+
export async function fetchCollections(client) {
|
|
20
|
+
const data = await client.listCollections();
|
|
21
|
+
return { data, hydration: { key: collectionsKey(), data, tags: [] } };
|
|
22
|
+
}
|
|
23
|
+
export async function fetchEntry(client, collection, id, options = {}) {
|
|
24
|
+
const timestamps = options.timestamps ?? false;
|
|
25
|
+
const data = await client.getEntry(collection, id, { timestamps });
|
|
26
|
+
return { data, hydration: { key: entryKey(collection, id, timestamps), data, tags: entryTags(collection, undefined) } };
|
|
27
|
+
}
|
|
28
|
+
export async function fetchEntries(client, collection, options = {}) {
|
|
29
|
+
const data = await client.listEntries(collection, options);
|
|
30
|
+
return { data, hydration: { key: entriesKey(collection, options), data, tags: entryTags(collection, options.locale) } };
|
|
31
|
+
}
|
|
32
|
+
export async function fetchMedia(client, id) {
|
|
33
|
+
const data = await client.getMedia(id);
|
|
34
|
+
return { data, hydration: { key: mediaKey(id), data, tags: [mediaTag(id)] } };
|
|
35
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface StructuredDataOptions {
|
|
2
|
+
/** The page's language, when entries differ by language. */
|
|
3
|
+
locale?: string;
|
|
4
|
+
}
|
|
5
|
+
/** The JSON-LD objects for a page (organisation, site, and the entry the path shows); [] when unavailable. */
|
|
6
|
+
export declare function loadStructuredData(path: string, opts?: StructuredDataOptions): Promise<Array<Record<string, unknown>>>;
|
|
7
|
+
/** JSON for a <script> tag: "<" escaped so text in the data can't close the tag. */
|
|
8
|
+
export declare function jsonLdScript(data: unknown): string;
|
|
9
|
+
/** <script type="application/ld+json"> for the page (a React server component). */
|
|
10
|
+
export declare function VeroxmStructuredData({ path, locale }: {
|
|
11
|
+
path: string;
|
|
12
|
+
locale?: string;
|
|
13
|
+
}): Promise<import("react").JSX.Element | null>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { resolveSlotsConfig } from './slots-core.js';
|
|
3
|
+
/** The JSON-LD objects for a page (organisation, site, and the entry the path shows); [] when unavailable. */
|
|
4
|
+
export async function loadStructuredData(path, opts = {}) {
|
|
5
|
+
const cfg = resolveSlotsConfig();
|
|
6
|
+
if (!cfg.ready || !cfg.fetch)
|
|
7
|
+
return [];
|
|
8
|
+
const qs = new URLSearchParams({ path: path || '/' });
|
|
9
|
+
const locale = opts.locale ?? cfg.locale;
|
|
10
|
+
if (locale)
|
|
11
|
+
qs.set('locale', locale);
|
|
12
|
+
try {
|
|
13
|
+
const res = await cfg.fetch(`${cfg.baseUrl}/public/v2/projects/${encodeURIComponent(cfg.projectId)}/schema.json?${qs}`, {
|
|
14
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
15
|
+
next: { revalidate: 300 },
|
|
16
|
+
});
|
|
17
|
+
if (!res.ok)
|
|
18
|
+
return [];
|
|
19
|
+
const body = (await res.json());
|
|
20
|
+
return Array.isArray(body) ? body.filter((x) => x && typeof x === 'object') : [];
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** JSON for a <script> tag: "<" escaped so text in the data can't close the tag. */
|
|
27
|
+
export function jsonLdScript(data) {
|
|
28
|
+
return JSON.stringify(data).replace(/</g, '\\u003c');
|
|
29
|
+
}
|
|
30
|
+
/** <script type="application/ld+json"> for the page (a React server component). */
|
|
31
|
+
export async function VeroxmStructuredData({ path, locale }) {
|
|
32
|
+
const data = await loadStructuredData(path, { locale });
|
|
33
|
+
if (!data.length)
|
|
34
|
+
return null;
|
|
35
|
+
return _jsx("script", { type: "application/ld+json", dangerouslySetInnerHTML: { __html: jsonLdScript(data.length === 1 ? data[0] : data) } });
|
|
36
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* What the hooks below need from a tracker -- satisfied by @veroxm/sdk's
|
|
4
|
+
* createTracker(). Kept as a structural type so this package doesn't depend
|
|
5
|
+
* on @veroxm/sdk (and tests or apps can pass their own implementation).
|
|
6
|
+
*/
|
|
7
|
+
export interface VeroxmTrackerLike {
|
|
8
|
+
track(name: string, properties?: Record<string, unknown>): void;
|
|
9
|
+
page(properties?: Record<string, unknown>): void;
|
|
10
|
+
identify(userId: string, traits?: Record<string, unknown>): Promise<void>;
|
|
11
|
+
consent(choices: {
|
|
12
|
+
analytics?: boolean;
|
|
13
|
+
personalization?: boolean;
|
|
14
|
+
marketing?: boolean;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
getConsent(): {
|
|
17
|
+
analytics: 'granted' | 'denied' | 'unknown';
|
|
18
|
+
personalization: 'granted' | 'denied' | 'unknown';
|
|
19
|
+
marketing: 'granted' | 'denied' | 'unknown';
|
|
20
|
+
};
|
|
21
|
+
getVisitorId(): string;
|
|
22
|
+
reset(): void;
|
|
23
|
+
/** Experiences (Phase 2). Optional so older trackers still type-check; without it the hooks below show the default. */
|
|
24
|
+
getExperience?<TContent = Record<string, unknown>, TConfig = Record<string, unknown>>(placement: string, options?: {
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}): Promise<ExperienceDecision<TContent, TConfig>>;
|
|
27
|
+
subscribe?(listener: () => void): () => void;
|
|
28
|
+
/** Recommendations (Phase 3). Optional like getExperience. */
|
|
29
|
+
viewContent?(contentId: number, properties?: Record<string, unknown>): void;
|
|
30
|
+
getRecommendations?<TEntry = Record<string, unknown>>(collection: string, options?: {
|
|
31
|
+
limit?: number;
|
|
32
|
+
exclude?: number[];
|
|
33
|
+
}): Promise<{
|
|
34
|
+
strategy: 'personal' | 'popular';
|
|
35
|
+
items: TEntry[];
|
|
36
|
+
error?: string;
|
|
37
|
+
}>;
|
|
38
|
+
}
|
|
39
|
+
/** What GET /decide answered (mirrors @veroxm/sdk's ExperienceDecision). */
|
|
40
|
+
export interface ExperienceDecision<TContent = Record<string, unknown>, TConfig = Record<string, unknown>> {
|
|
41
|
+
placement: string;
|
|
42
|
+
experienceId: number | null;
|
|
43
|
+
variantId: number | null;
|
|
44
|
+
variant: {
|
|
45
|
+
label: string;
|
|
46
|
+
isControl: boolean;
|
|
47
|
+
} | null;
|
|
48
|
+
reason: 'targeted' | 'split' | 'journey' | 'none';
|
|
49
|
+
content: TContent | null;
|
|
50
|
+
config: TConfig | null;
|
|
51
|
+
waitingForConsent?: boolean;
|
|
52
|
+
error?: string;
|
|
53
|
+
}
|
|
54
|
+
export interface VeroxmTrackerProviderProps {
|
|
55
|
+
/** A tracker from @veroxm/sdk's createTracker(), created once (module scope or useMemo). */
|
|
56
|
+
tracker: VeroxmTrackerLike | null;
|
|
57
|
+
children: ReactNode;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Makes a visitor tracker available to useTracker()/usePageViews()
|
|
61
|
+
* (Experience OS Phase 1). `tracker` may be null during server rendering --
|
|
62
|
+
* the hooks then do nothing -- so create it only in the browser:
|
|
63
|
+
*
|
|
64
|
+
* ```tsx
|
|
65
|
+
* const tracker = typeof window === 'undefined' ? null
|
|
66
|
+
* : createTracker({ baseUrl, projectId, eventsKey });
|
|
67
|
+
* <VeroxmTrackerProvider tracker={tracker}>...</VeroxmTrackerProvider>
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function VeroxmTrackerProvider({ tracker, children }: VeroxmTrackerProviderProps): ReactElement;
|
|
71
|
+
/** The current tracker, or a no-op one outside a provider / during server rendering -- tracking never breaks rendering. */
|
|
72
|
+
export declare function useTracker(): VeroxmTrackerLike;
|
|
73
|
+
/**
|
|
74
|
+
* Records a page view whenever `path` changes. Pass your router's current
|
|
75
|
+
* path, e.g. Next.js App Router: `usePageViews(usePathname())`.
|
|
76
|
+
*/
|
|
77
|
+
export declare function usePageViews(path: string | null | undefined, properties?: Record<string, unknown>): void;
|
|
78
|
+
export interface ExperienceState<TContent, TConfig> {
|
|
79
|
+
/** null while deciding (and during server rendering). */
|
|
80
|
+
decision: ExperienceDecision<TContent, TConfig> | null;
|
|
81
|
+
loading: boolean;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* This visitor's variant of a placement (Experience OS Phase 2):
|
|
85
|
+
*
|
|
86
|
+
* ```tsx
|
|
87
|
+
* const { decision, loading } = useExperience<HeroEntry>('home.hero');
|
|
88
|
+
* if (loading) return <HeroSkeleton />;
|
|
89
|
+
* return decision?.content ? <Hero entry={decision.content} /> : <DefaultHero />;
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* Asks again when consent, identity or the visitor changes. Never throws:
|
|
93
|
+
* errors, timeouts and missing consent come back as reason "none".
|
|
94
|
+
*/
|
|
95
|
+
export declare function useExperience<TContent = Record<string, unknown>, TConfig = Record<string, unknown>>(placement: string, options?: {
|
|
96
|
+
timeoutMs?: number;
|
|
97
|
+
}): ExperienceState<TContent, TConfig>;
|
|
98
|
+
export interface ExperienceProps<TContent, TConfig> {
|
|
99
|
+
placement: string;
|
|
100
|
+
/** What visitors see when no experience applies (and, unless `loading` is given, while deciding). */
|
|
101
|
+
fallback: ReactNode;
|
|
102
|
+
/** Shown while deciding; defaults to `fallback`. */
|
|
103
|
+
loading?: ReactNode;
|
|
104
|
+
timeoutMs?: number;
|
|
105
|
+
/** Renders the chosen variant. */
|
|
106
|
+
children: (decision: ExperienceDecision<TContent, TConfig>) => ReactNode;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Declarative form of useExperience:
|
|
110
|
+
*
|
|
111
|
+
* ```tsx
|
|
112
|
+
* <Experience<HeroEntry> placement="home.hero" fallback={<DefaultHero />}>
|
|
113
|
+
* {(d) => <Hero entry={d.content!} cta={d.config?.cta} />}
|
|
114
|
+
* </Experience>
|
|
115
|
+
* ```
|
|
116
|
+
*
|
|
117
|
+
* A variant with neither content nor config (usually the control) renders
|
|
118
|
+
* the fallback, so "control = the current site" needs no extra code.
|
|
119
|
+
*/
|
|
120
|
+
export declare function Experience<TContent = Record<string, unknown>, TConfig = Record<string, unknown>>({ placement, fallback, loading, timeoutMs, children, }: ExperienceProps<TContent, TConfig>): ReactElement;
|
|
121
|
+
/** Records one view of a CMS entry when it is shown (the signal behind recommendations). */
|
|
122
|
+
export declare function useContentView(contentId: number | null | undefined, properties?: Record<string, unknown>): void;
|
|
123
|
+
export interface RecommendationsState<TEntry> {
|
|
124
|
+
items: TEntry[];
|
|
125
|
+
strategy: 'personal' | 'popular' | null;
|
|
126
|
+
loading: boolean;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Entries of a collection ranked for this visitor (Experience OS Phase 3):
|
|
130
|
+
*
|
|
131
|
+
* ```tsx
|
|
132
|
+
* const { items } = useRecommendations<Article>('articles', { limit: 3, exclude: [article.id] });
|
|
133
|
+
* ```
|
|
134
|
+
*
|
|
135
|
+
* Personal when the visitor allowed personalisation and has read a few
|
|
136
|
+
* entries, otherwise the most read. Asks again when consent or identity
|
|
137
|
+
* changes. Never throws (an error gives an empty list).
|
|
138
|
+
*/
|
|
139
|
+
export declare function useRecommendations<TEntry = Record<string, unknown>>(collection: string, options?: {
|
|
140
|
+
limit?: number;
|
|
141
|
+
exclude?: number[];
|
|
142
|
+
}): RecommendationsState<TEntry>;
|