@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,169 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
|
4
|
+
import { fallbackValues, field, mergeSlotValues } from './slots-core.js';
|
|
5
|
+
import { EDITING_FLAG_COOKIE, PREVIEW_COOKIE, ROUTE_BASE } from './editor/constants.js';
|
|
6
|
+
import { VeroxmEditorOverlay, resetSentFallbacksForTests } from './editor/overlay.js';
|
|
7
|
+
// @veroxm/react-sdk/client -- visual slots for client-rendered React apps
|
|
8
|
+
// (Vite, CRA...) whose server runs the /api/veroxm middleware from
|
|
9
|
+
// '@veroxm/react-sdk/node'. The browser never holds an API key: published
|
|
10
|
+
// content comes through that route, and so does the on-page editor.
|
|
11
|
+
//
|
|
12
|
+
// <VeroxmSlot name="home.hero" fields={heroFields} fallback={{ title: 'Welcome' }}>
|
|
13
|
+
// {(s, slot) => <h1 {...slot.edit('title')}>{s.title}</h1>}
|
|
14
|
+
// </VeroxmSlot>
|
|
15
|
+
//
|
|
16
|
+
// - Shows the fallback at once, then published content (slots rendering
|
|
17
|
+
// together share one request).
|
|
18
|
+
// - After "Edit on page", shows drafts instead, marks slots for the
|
|
19
|
+
// overlay, and re-renders after every save.
|
|
20
|
+
export { field };
|
|
21
|
+
// ---------------------------------------------------------------- editing
|
|
22
|
+
function readEditingFlag() {
|
|
23
|
+
return typeof document !== 'undefined' && document.cookie.split(';').some((c) => c.trim() === `${EDITING_FLAG_COOKIE}=1`);
|
|
24
|
+
}
|
|
25
|
+
/** True while this browser is in an "Edit on page" session. */
|
|
26
|
+
export function isEditingSlots() {
|
|
27
|
+
return readEditingFlag();
|
|
28
|
+
}
|
|
29
|
+
// A change counter: the overlay bumps it after a save, publish or discard,
|
|
30
|
+
// and every slot re-fetches its draft.
|
|
31
|
+
let revision = 0;
|
|
32
|
+
const listeners = new Set();
|
|
33
|
+
function bump() {
|
|
34
|
+
revision++;
|
|
35
|
+
listeners.forEach((l) => l());
|
|
36
|
+
}
|
|
37
|
+
function useRevision() {
|
|
38
|
+
return useSyncExternalStore((l) => {
|
|
39
|
+
listeners.add(l);
|
|
40
|
+
return () => listeners.delete(l);
|
|
41
|
+
}, () => revision, () => 0);
|
|
42
|
+
}
|
|
43
|
+
// ---------------------------------------------------------------- loading
|
|
44
|
+
let routeBase = ROUTE_BASE;
|
|
45
|
+
/** Where the server mounted veroxmMiddleware. Default '/api/veroxm'. */
|
|
46
|
+
export function configureClientSlots(options) {
|
|
47
|
+
if (options.routeBase)
|
|
48
|
+
routeBase = options.routeBase.replace(/\/+$/, '');
|
|
49
|
+
}
|
|
50
|
+
const pending = new Map();
|
|
51
|
+
let scheduled = false;
|
|
52
|
+
function loadPublished(name, locale) {
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
const list = pending.get(locale) ?? [];
|
|
55
|
+
list.push({ name, resolve });
|
|
56
|
+
pending.set(locale, list);
|
|
57
|
+
if (!scheduled) {
|
|
58
|
+
scheduled = true;
|
|
59
|
+
setTimeout(flush, 0);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function flush() {
|
|
64
|
+
scheduled = false;
|
|
65
|
+
const batches = [...pending.entries()];
|
|
66
|
+
pending.clear();
|
|
67
|
+
for (const [locale, waiters] of batches) {
|
|
68
|
+
const names = [...new Set(waiters.map((w) => w.name))];
|
|
69
|
+
for (let i = 0; i < names.length; i += 50) {
|
|
70
|
+
const chunk = names.slice(i, i + 50);
|
|
71
|
+
const mine = waiters.filter((w) => chunk.includes(w.name));
|
|
72
|
+
const qs = new URLSearchParams({ names: chunk.join(',') });
|
|
73
|
+
if (locale)
|
|
74
|
+
qs.set('locale', locale);
|
|
75
|
+
// no-cache: always ask the site (cheap; VeroXM caches), so a publish shows on the next page view.
|
|
76
|
+
fetch(`${routeBase}/published?${qs}`, { credentials: 'same-origin', cache: 'no-cache' })
|
|
77
|
+
.then(async (res) => {
|
|
78
|
+
if (!res.ok)
|
|
79
|
+
throw new Error(`HTTP ${res.status}`);
|
|
80
|
+
const body = (await res.json());
|
|
81
|
+
for (const w of mine)
|
|
82
|
+
w.resolve(body.slots?.[w.name] ?? null);
|
|
83
|
+
})
|
|
84
|
+
.catch(() => {
|
|
85
|
+
for (const w of mine)
|
|
86
|
+
w.resolve(null);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function previewVariant(name) {
|
|
92
|
+
const raw = document.cookie.split(';').map((c) => c.trim()).find((c) => c.startsWith(`${PREVIEW_COOKIE}=`));
|
|
93
|
+
const value = raw ? decodeURIComponent(raw.slice(PREVIEW_COOKIE.length + 1)) : '';
|
|
94
|
+
return value.startsWith(`${name}:`) ? value.slice(name.length + 1) : null;
|
|
95
|
+
}
|
|
96
|
+
async function loadDraft(name, locale) {
|
|
97
|
+
const qs = new URLSearchParams({ names: name });
|
|
98
|
+
if (locale)
|
|
99
|
+
qs.set('locale', locale);
|
|
100
|
+
const variant = previewVariant(name);
|
|
101
|
+
if (variant && /^\d{1,2}$/.test(variant))
|
|
102
|
+
qs.set('variant', variant);
|
|
103
|
+
try {
|
|
104
|
+
const res = await fetch(`${routeBase}/slots?${qs}`, { credentials: 'same-origin', cache: 'no-store' });
|
|
105
|
+
if (!res.ok)
|
|
106
|
+
return null;
|
|
107
|
+
const body = (await res.json());
|
|
108
|
+
return body.slots?.[name] ?? null;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const noEdit = () => ({});
|
|
115
|
+
/** A slot's values for client-rendered apps. Prefer <VeroxmSlot>, which also marks the slot for the editor. */
|
|
116
|
+
export function useVeroxmSlot(name, options) {
|
|
117
|
+
const [editing, setEditing] = useState(false);
|
|
118
|
+
const [loaded, setLoaded] = useState({ data: null, done: false });
|
|
119
|
+
const rev = useRevision();
|
|
120
|
+
const locale = options.locale ?? '';
|
|
121
|
+
useEffect(() => setEditing(readEditingFlag()), []);
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
let live = true;
|
|
124
|
+
(editing ? loadDraft(name, locale) : loadPublished(name, locale)).then((data) => {
|
|
125
|
+
if (live)
|
|
126
|
+
setLoaded((prev) => (data === null && prev.data && editing ? prev : { data, done: true }));
|
|
127
|
+
});
|
|
128
|
+
return () => {
|
|
129
|
+
live = false;
|
|
130
|
+
};
|
|
131
|
+
}, [name, locale, editing, rev]);
|
|
132
|
+
const fieldsRef = useRef(options.fields);
|
|
133
|
+
fieldsRef.current = options.fields;
|
|
134
|
+
const fallbackRef = useRef(options.fallback);
|
|
135
|
+
fallbackRef.current = options.fallback;
|
|
136
|
+
// Fallbacks often arrive later (copy from another API): re-merge when they change.
|
|
137
|
+
const fallbackKey = JSON.stringify(options.fallback ?? null);
|
|
138
|
+
const values = useMemo(() => mergeSlotValues(fieldsRef.current, fallbackRef.current, loaded.data?.values ?? null),
|
|
139
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
140
|
+
[loaded.data, fallbackKey]);
|
|
141
|
+
const edit = useCallback((f) => ({ 'data-veroxm-field': f }), []);
|
|
142
|
+
const slot = {
|
|
143
|
+
name,
|
|
144
|
+
version: loaded.data?.version || null,
|
|
145
|
+
source: loaded.data ? (editing ? 'draft' : 'published') : 'fallback',
|
|
146
|
+
test: editing ? null : (loaded.data?.test ?? null),
|
|
147
|
+
editing,
|
|
148
|
+
edit: editing ? edit : noEdit,
|
|
149
|
+
};
|
|
150
|
+
return { values, slot, loading: !loaded.done, editing };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* A slot in a client-rendered React app: published content (fallback until
|
|
154
|
+
* it loads), or the draft plus the on-page editor during "Edit on page".
|
|
155
|
+
*/
|
|
156
|
+
export function VeroxmSlot({ name, children, ...options }) {
|
|
157
|
+
const { values, slot, editing } = useVeroxmSlot(name, options);
|
|
158
|
+
if (!editing)
|
|
159
|
+
return children(values, slot);
|
|
160
|
+
return (_jsxs(_Fragment, { children: [_jsx("div", { "data-veroxm-slot": name, "data-veroxm-label": options.label ?? '', "data-veroxm-locale": options.locale ?? '', "data-veroxm-shown": JSON.stringify(values), "data-veroxm-fallback": JSON.stringify(fallbackValues(options.fields, options.fallback)), style: { display: 'contents' }, children: children(values, slot) }), _jsx(VeroxmEditorOverlay, { onChange: bump })] }));
|
|
161
|
+
}
|
|
162
|
+
/** Test helper. */
|
|
163
|
+
export function resetClientSlotsForTests() {
|
|
164
|
+
pending.clear();
|
|
165
|
+
scheduled = false;
|
|
166
|
+
revision = 0;
|
|
167
|
+
routeBase = ROUTE_BASE;
|
|
168
|
+
resetSentFallbacksForTests();
|
|
169
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type Variables } from 'graphql-request';
|
|
2
|
+
import { VeroxmCache, type CacheOptions } from './cache.js';
|
|
3
|
+
import type { CollectionMeta, Entry, EntryConnection, EntriesQueryOptions, MediaView } from './types.js';
|
|
4
|
+
export interface VeroxmClientOptions {
|
|
5
|
+
/** Your VeroXM deployment's origin, e.g. "https://cms.example.com" -- the client builds the full GraphQL endpoint (`/public/v2/graphql`) itself. */
|
|
6
|
+
apiBase: string;
|
|
7
|
+
/**
|
|
8
|
+
* A project-scoped API token (Developer tab > API Keys in the
|
|
9
|
+
* dashboard) -- sent as `Authorization: Bearer <apiKey>` on every
|
|
10
|
+
* request. This token is the request's ONLY source of project
|
|
11
|
+
* identity: unlike the REST v2 API, GraphQL has no project-uuid
|
|
12
|
+
* argument on any query (see apps/api/src/public-api/v2-token.guard.ts's
|
|
13
|
+
* own comment on why that check is a no-op for this transport).
|
|
14
|
+
*/
|
|
15
|
+
apiKey: string;
|
|
16
|
+
/**
|
|
17
|
+
* Not sent on the wire (the schema has no argument for it -- see
|
|
18
|
+
* apiKey above); kept purely so error messages/devtools can identify
|
|
19
|
+
* which project a client instance belongs to in an app that talks to
|
|
20
|
+
* more than one, and for parity with @veroxm/sdk's
|
|
21
|
+
* VeroXMApp.initializeApp({projectId}).
|
|
22
|
+
*/
|
|
23
|
+
projectUuid?: string;
|
|
24
|
+
/** Tuning for this client's request cache (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.3) -- see CacheOptions. Omit for the default 30s staleTimeMs. */
|
|
25
|
+
cache?: CacheOptions;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Thin wrapper over graphql-request's GraphQLClient -- one method per
|
|
29
|
+
* query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
30
|
+
* §5.1), plus request() as an escape hatch for a custom document. Every
|
|
31
|
+
* hook in ./hooks reads one of these through useVeroxmClient() rather
|
|
32
|
+
* than talking to GraphQLClient directly, so this class is the one place
|
|
33
|
+
* request-shaping logic lives -- and it's usable on its own outside
|
|
34
|
+
* React too (see §5.5's SSR helpers in a later phase, which will build
|
|
35
|
+
* on this same class).
|
|
36
|
+
*/
|
|
37
|
+
export declare class VeroxmClient {
|
|
38
|
+
private readonly gql;
|
|
39
|
+
/** Echoes VeroxmClientOptions.projectUuid, if one was given -- see that field's own comment. */
|
|
40
|
+
readonly projectUuid: string | undefined;
|
|
41
|
+
/** This client's request cache -- read directly by every hook in ./hooks (via useVeroxmClient()) and by the SSR helpers in ./ssr.ts, so a server fetch and a client-side hook agree on exactly one cache instance per VeroxmClient. Call cache.invalidateCollection()/invalidateMedia()/invalidateAll() yourself once you know content changed -- see VeroxmCache's own doc comment for why this API is queries-only and has no auto-invalidation. */
|
|
42
|
+
readonly cache: VeroxmCache;
|
|
43
|
+
constructor(options: VeroxmClientOptions);
|
|
44
|
+
/** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
|
|
45
|
+
request<T = unknown>(document: string, variables?: Variables): Promise<T>;
|
|
46
|
+
/** A collection's field list. `null` means no collection with that slug exists on this project. */
|
|
47
|
+
getCollection(slug: string): Promise<CollectionMeta | null>;
|
|
48
|
+
/** Every collection defined on this project. */
|
|
49
|
+
listCollections(): Promise<CollectionMeta[]>;
|
|
50
|
+
/**
|
|
51
|
+
* A single entry by id. `null` means no entry with that id exists in
|
|
52
|
+
* this collection -- same not-an-error semantics as the underlying
|
|
53
|
+
* `entry` query (see apps/api's content.resolver.ts). Only ever
|
|
54
|
+
* returns a PUBLISHED entry, same as the REST v2 API's single-item
|
|
55
|
+
* lookup (see packages/sdk-js/src/content.ts's get() for the full
|
|
56
|
+
* explanation) -- there is no `state` override here.
|
|
57
|
+
*/
|
|
58
|
+
getEntry<T = Record<string, unknown>>(collection: string, id: number, options?: {
|
|
59
|
+
timestamps?: boolean;
|
|
60
|
+
}): Promise<Entry<T> | null>;
|
|
61
|
+
/** A page of entries -- see EntriesQueryOptions for the full filter/sort/pagination vocabulary. */
|
|
62
|
+
listEntries<T = Record<string, unknown>>(collection: string, options?: EntriesQueryOptions): Promise<EntryConnection<T>>;
|
|
63
|
+
/** A single media item by id. `null` means no media with that id exists on this project. */
|
|
64
|
+
getMedia(id: number): Promise<MediaView | null>;
|
|
65
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { GraphQLClient } from 'graphql-request';
|
|
2
|
+
import { VeroxmCache } from './cache.js';
|
|
3
|
+
import { VeroxmGraphQLError } from './errors.js';
|
|
4
|
+
const COLLECTION_FIELDS = `slug name description fields { name label type }`;
|
|
5
|
+
const ENTRY_FIELDS = `id locale createdAt updatedAt publishedAt data`;
|
|
6
|
+
const MEDIA_FIELDS = `id fileName fullUrl thumbUrl thumbWebpUrl fullWebpUrl caption tags size width height focalPoint { x y } hotspots { id x y label url }`;
|
|
7
|
+
/**
|
|
8
|
+
* Thin wrapper over graphql-request's GraphQLClient -- one method per
|
|
9
|
+
* query this API exposes (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md
|
|
10
|
+
* §5.1), plus request() as an escape hatch for a custom document. Every
|
|
11
|
+
* hook in ./hooks reads one of these through useVeroxmClient() rather
|
|
12
|
+
* than talking to GraphQLClient directly, so this class is the one place
|
|
13
|
+
* request-shaping logic lives -- and it's usable on its own outside
|
|
14
|
+
* React too (see §5.5's SSR helpers in a later phase, which will build
|
|
15
|
+
* on this same class).
|
|
16
|
+
*/
|
|
17
|
+
export class VeroxmClient {
|
|
18
|
+
constructor(options) {
|
|
19
|
+
const endpoint = `${options.apiBase.replace(/\/$/, '')}/public/v2/graphql`;
|
|
20
|
+
this.gql = new GraphQLClient(endpoint, {
|
|
21
|
+
headers: { Authorization: `Bearer ${options.apiKey}` },
|
|
22
|
+
});
|
|
23
|
+
this.projectUuid = options.projectUuid;
|
|
24
|
+
this.cache = new VeroxmCache(options.cache);
|
|
25
|
+
}
|
|
26
|
+
/** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
|
|
27
|
+
async request(document, variables) {
|
|
28
|
+
try {
|
|
29
|
+
return await this.gql.request(document, variables);
|
|
30
|
+
}
|
|
31
|
+
catch (cause) {
|
|
32
|
+
throw VeroxmGraphQLError.from(cause);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** A collection's field list. `null` means no collection with that slug exists on this project. */
|
|
36
|
+
async getCollection(slug) {
|
|
37
|
+
const data = await this.request(`query Collection($slug: String!) { collection(slug: $slug) { ${COLLECTION_FIELDS} } }`, { slug });
|
|
38
|
+
return data.collection;
|
|
39
|
+
}
|
|
40
|
+
/** Every collection defined on this project. */
|
|
41
|
+
async listCollections() {
|
|
42
|
+
const data = await this.request(`query Collections { collections { ${COLLECTION_FIELDS} } }`);
|
|
43
|
+
return data.collections;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A single entry by id. `null` means no entry with that id exists in
|
|
47
|
+
* this collection -- same not-an-error semantics as the underlying
|
|
48
|
+
* `entry` query (see apps/api's content.resolver.ts). Only ever
|
|
49
|
+
* returns a PUBLISHED entry, same as the REST v2 API's single-item
|
|
50
|
+
* lookup (see packages/sdk-js/src/content.ts's get() for the full
|
|
51
|
+
* explanation) -- there is no `state` override here.
|
|
52
|
+
*/
|
|
53
|
+
async getEntry(collection, id, options = {}) {
|
|
54
|
+
const data = await this.request(`query Entry($collection: String!, $id: Int!, $timestamps: Boolean) {
|
|
55
|
+
entry(collection: $collection, id: $id, timestamps: $timestamps) { ${ENTRY_FIELDS} }
|
|
56
|
+
}`, { collection, id, timestamps: options.timestamps ?? false });
|
|
57
|
+
return data.entry;
|
|
58
|
+
}
|
|
59
|
+
/** A page of entries -- see EntriesQueryOptions for the full filter/sort/pagination vocabulary. */
|
|
60
|
+
async listEntries(collection, options = {}) {
|
|
61
|
+
// totalCount is only added to the selection set when asked for, so a
|
|
62
|
+
// plain listEntries() call never triggers the resolver's extra count
|
|
63
|
+
// query -- see EntriesQueryOptions.withTotalCount and
|
|
64
|
+
// content.resolver.ts's @ResolveField.
|
|
65
|
+
const totalCountField = options.withTotalCount ? ' totalCount' : '';
|
|
66
|
+
const data = await this.request(`query Entries($collection: String!, $where: [WhereClauseInput!], $sort: String, $locale: String, $state: String, $offset: Int, $limit: Int, $timestamps: Boolean) {
|
|
67
|
+
entries(collection: $collection, where: $where, sort: $sort, locale: $locale, state: $state, offset: $offset, limit: $limit, timestamps: $timestamps) {
|
|
68
|
+
items { ${ENTRY_FIELDS} }${totalCountField}
|
|
69
|
+
}
|
|
70
|
+
}`, {
|
|
71
|
+
collection,
|
|
72
|
+
where: options.where,
|
|
73
|
+
sort: options.sort,
|
|
74
|
+
locale: options.locale,
|
|
75
|
+
state: options.state,
|
|
76
|
+
offset: options.offset,
|
|
77
|
+
limit: options.limit,
|
|
78
|
+
timestamps: options.timestamps ?? false,
|
|
79
|
+
});
|
|
80
|
+
return data.entries;
|
|
81
|
+
}
|
|
82
|
+
/** A single media item by id. `null` means no media with that id exists on this project. */
|
|
83
|
+
async getMedia(id) {
|
|
84
|
+
const data = await this.request(`query Media($id: Int!) { media(id: $id) { ${MEDIA_FIELDS} } }`, { id });
|
|
85
|
+
return data.media;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** httpOnly cookie holding the editor token while draft mode is on. */
|
|
2
|
+
export declare const EDITOR_COOKIE = "veroxm_editor";
|
|
3
|
+
/** Where the route handler is mounted: app/api/veroxm/[...veroxm]/route.ts */
|
|
4
|
+
export declare const ROUTE_BASE = "/api/veroxm";
|
|
5
|
+
/** Sent by the overlay on every change; a cross-site page can't send it without CORS. */
|
|
6
|
+
export declare const EDITOR_HEADER = "x-veroxm-editor";
|
|
7
|
+
/** Readable flag cookie (no secret) so client-rendered pages know to load drafts and the editor. */
|
|
8
|
+
export declare const EDITING_FLAG_COOKIE = "veroxm_editing";
|
|
9
|
+
/** First-party cookie the tracker keeps the visitor id in, so servers can show A/B test variants. */
|
|
10
|
+
export declare const VISITOR_COOKIE = "veroxm_vid";
|
|
11
|
+
/** Editor-only: which test variant the page previews, as "<slot name>:<position>". */
|
|
12
|
+
export declare const PREVIEW_COOKIE = "veroxm_preview";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** httpOnly cookie holding the editor token while draft mode is on. */
|
|
2
|
+
export const EDITOR_COOKIE = 'veroxm_editor';
|
|
3
|
+
/** Where the route handler is mounted: app/api/veroxm/[...veroxm]/route.ts */
|
|
4
|
+
export const ROUTE_BASE = '/api/veroxm';
|
|
5
|
+
/** Sent by the overlay on every change; a cross-site page can't send it without CORS. */
|
|
6
|
+
export const EDITOR_HEADER = 'x-veroxm-editor';
|
|
7
|
+
/** Readable flag cookie (no secret) so client-rendered pages know to load drafts and the editor. */
|
|
8
|
+
export const EDITING_FLAG_COOKIE = 'veroxm_editing';
|
|
9
|
+
/** First-party cookie the tracker keeps the visitor id in, so servers can show A/B test variants. */
|
|
10
|
+
export const VISITOR_COOKIE = 'veroxm_vid';
|
|
11
|
+
/** Editor-only: which test variant the page previews, as "<slot name>:<position>". */
|
|
12
|
+
export const PREVIEW_COOKIE = 'veroxm_preview';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface EditorHandlerHooks {
|
|
2
|
+
/** Whether this request is in editing mode. Default: the editor cookie is present. */
|
|
3
|
+
isEditing?(request: Request): Promise<boolean> | boolean;
|
|
4
|
+
/** Turn framework-level preview on (e.g. Next.js draft mode). */
|
|
5
|
+
enter?(): Promise<void> | void;
|
|
6
|
+
exit?(): Promise<void> | void;
|
|
7
|
+
/** After a publish succeeds (e.g. revalidate cached reads). */
|
|
8
|
+
published?(): void;
|
|
9
|
+
/** Serve GET published?names= with the server key. Default false. */
|
|
10
|
+
servePublished?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export type EditorHandler = (request: Request, segments?: string[]) => Promise<Response>;
|
|
13
|
+
export declare function json(body: unknown, status?: number, cache?: string): Response;
|
|
14
|
+
/** The path segments after /api/veroxm/ in a request URL. */
|
|
15
|
+
export declare function segmentsOf(request: Request): string[];
|
|
16
|
+
export declare function createEditorHandler(hooks?: EditorHandlerHooks): EditorHandler;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { resolveSlotsConfig } from '../slots-core.js';
|
|
2
|
+
import { EDITING_FLAG_COOKIE, EDITOR_COOKIE, EDITOR_HEADER, ROUTE_BASE, VISITOR_COOKIE } from './constants.js';
|
|
3
|
+
import { editorApi, readCookie, safePath, secondsLeft } from './server.js';
|
|
4
|
+
const NOT_FOUND = () => json({ error: 'Not found' }, 404);
|
|
5
|
+
/** Changes the overlay can make to a slot: publish (or send for approval), discard, and approval decisions. */
|
|
6
|
+
const POST_VERBS = new Set(['publish', 'discard', 'approve', 'reject', 'withdraw']);
|
|
7
|
+
export function json(body, status = 200, cache = 'no-store') {
|
|
8
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': cache } });
|
|
9
|
+
}
|
|
10
|
+
function cookie(name, value, maxAge, secure, httpOnly) {
|
|
11
|
+
return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}${httpOnly ? '; HttpOnly' : ''}; SameSite=Lax${secure ? '; Secure' : ''}`;
|
|
12
|
+
}
|
|
13
|
+
function errorPage(message, status) {
|
|
14
|
+
const safe = message.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
15
|
+
return new Response(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Can't open the editor</title>` +
|
|
16
|
+
`<body style="font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px;color:#1a1a1a">` +
|
|
17
|
+
`<h1 style="font-size:1.25rem">Can't open the VeroXM editor</h1><p>${safe}</p><p><a href="/">Go to the home page</a></p></body></html>`, { status, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } });
|
|
18
|
+
}
|
|
19
|
+
/** A redirect that also carries cookies (Response.redirect's headers are immutable). */
|
|
20
|
+
function redirect(to, cookies) {
|
|
21
|
+
const headers = new Headers({ Location: to.toString(), 'Cache-Control': 'no-store' });
|
|
22
|
+
for (const c of cookies)
|
|
23
|
+
headers.append('Set-Cookie', c);
|
|
24
|
+
return new Response(null, { status: 307, headers });
|
|
25
|
+
}
|
|
26
|
+
/** The path segments after /api/veroxm/ in a request URL. */
|
|
27
|
+
export function segmentsOf(request) {
|
|
28
|
+
const path = new URL(request.url).pathname;
|
|
29
|
+
const i = path.indexOf(`${ROUTE_BASE}/`);
|
|
30
|
+
return i === -1 ? [] : path.slice(i + ROUTE_BASE.length + 1).split('/').filter(Boolean).map(decodeURIComponent);
|
|
31
|
+
}
|
|
32
|
+
/** At most this many purge confirmations per minute (a flood of fake pings can't turn into a flood of API calls). */
|
|
33
|
+
const MAX_PURGE_CHECKS_PER_MINUTE = 30;
|
|
34
|
+
export function createEditorHandler(hooks = {}) {
|
|
35
|
+
const purgeChecks = [];
|
|
36
|
+
async function revalidate(request) {
|
|
37
|
+
const body = (await request.json().catch(() => null));
|
|
38
|
+
const id = typeof body?.id === 'string' ? body.id : '';
|
|
39
|
+
if (!/^[A-Za-z0-9_-]{24}$/.test(id))
|
|
40
|
+
return json({ error: 'Bad request' }, 400);
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
while (purgeChecks.length && purgeChecks[0] < now - 60000)
|
|
43
|
+
purgeChecks.shift();
|
|
44
|
+
if (purgeChecks.length >= MAX_PURGE_CHECKS_PER_MINUTE)
|
|
45
|
+
return json({ error: 'Too many requests' }, 429);
|
|
46
|
+
purgeChecks.push(now);
|
|
47
|
+
const cfg = resolveSlotsConfig();
|
|
48
|
+
if (!cfg.ready || !cfg.fetch)
|
|
49
|
+
return json({ error: 'Not configured' }, 404);
|
|
50
|
+
const res = await cfg
|
|
51
|
+
.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots/purges/${id}`, {
|
|
52
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
53
|
+
})
|
|
54
|
+
.catch(() => null);
|
|
55
|
+
if (!res)
|
|
56
|
+
return json({ error: 'VeroXM could not be reached.' }, 502);
|
|
57
|
+
if (res.status === 404)
|
|
58
|
+
return json({ error: 'Unknown purge' }, 403);
|
|
59
|
+
if (!res.ok)
|
|
60
|
+
return json({ error: `VeroXM answered ${res.status}` }, 502);
|
|
61
|
+
const { slots } = (await res.json().catch(() => ({})));
|
|
62
|
+
hooks.published?.();
|
|
63
|
+
return json({ revalidated: true, slots: Array.isArray(slots) ? slots : [] });
|
|
64
|
+
}
|
|
65
|
+
const isEditing = async (request) => hooks.isEditing ? hooks.isEditing(request) : Boolean(readCookie(request.headers.get('cookie'), EDITOR_COOKIE));
|
|
66
|
+
async function relay(request, path, method) {
|
|
67
|
+
const url = new URL(request.url);
|
|
68
|
+
if (!(await isEditing(request)))
|
|
69
|
+
return json({ error: 'Not in editing mode.' }, 401);
|
|
70
|
+
const token = readCookie(request.headers.get('cookie'), EDITOR_COOKIE);
|
|
71
|
+
if (!token)
|
|
72
|
+
return json({ error: 'The editing session has ended. Open "Edit on page" from VeroXM again.' }, 401);
|
|
73
|
+
if (method !== 'GET') {
|
|
74
|
+
// Changes only from the overlay on this site: a custom header (which a
|
|
75
|
+
// cross-site page can't send without CORS) and, when present, our origin.
|
|
76
|
+
const origin = request.headers.get('origin');
|
|
77
|
+
if (request.headers.get(EDITOR_HEADER) !== '1' || (origin && origin !== url.origin))
|
|
78
|
+
return json({ error: 'Forbidden' }, 403);
|
|
79
|
+
}
|
|
80
|
+
const res = await editorApi(token, `${path}${url.search}`, {
|
|
81
|
+
method,
|
|
82
|
+
...(method !== 'GET' ? { body: (await request.text()) || '{}', headers: { 'Content-Type': 'application/json' } } : {}),
|
|
83
|
+
}).catch(() => null);
|
|
84
|
+
if (!res)
|
|
85
|
+
return json({ error: 'VeroXM could not be reached. Your last change may not be saved.' }, 502);
|
|
86
|
+
const body = await res.text();
|
|
87
|
+
if (res.ok && path.endsWith('/publish'))
|
|
88
|
+
hooks.published?.();
|
|
89
|
+
return new Response(body, { status: res.status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } });
|
|
90
|
+
}
|
|
91
|
+
async function published(request) {
|
|
92
|
+
const cfg = resolveSlotsConfig();
|
|
93
|
+
if (!cfg.ready || !cfg.fetch)
|
|
94
|
+
return json({ error: 'VEROXM_API_BASE, VEROXM_PROJECT_ID and VEROXM_API_KEY must be set on the site.' }, 500);
|
|
95
|
+
const url = new URL(request.url);
|
|
96
|
+
const qs = new URLSearchParams();
|
|
97
|
+
const names = url.searchParams.get('names');
|
|
98
|
+
if (!names)
|
|
99
|
+
return json({ error: 'Pass slot names in "names".' }, 400);
|
|
100
|
+
qs.set('names', names);
|
|
101
|
+
const locale = url.searchParams.get('locale');
|
|
102
|
+
if (locale)
|
|
103
|
+
qs.set('locale', locale);
|
|
104
|
+
// The tracker's visitor cookie: slots under a live A/B test then come
|
|
105
|
+
// back as this visitor's variant (and the answer is per visitor).
|
|
106
|
+
const visitorId = readCookie(request.headers.get('cookie'), VISITOR_COOKIE);
|
|
107
|
+
const perVisitor = !!visitorId && /^[A-Za-z0-9_.:-]{1,64}$/.test(visitorId);
|
|
108
|
+
if (perVisitor)
|
|
109
|
+
qs.set('visitorId', visitorId);
|
|
110
|
+
const res = await cfg
|
|
111
|
+
.fetch(`${cfg.baseUrl}/public/v2/projects/${cfg.projectId}/slots?${qs}`, {
|
|
112
|
+
headers: { Authorization: `Bearer ${cfg.apiKey}`, Accept: 'application/json' },
|
|
113
|
+
})
|
|
114
|
+
.catch(() => null);
|
|
115
|
+
if (!res)
|
|
116
|
+
return json({ error: 'VeroXM could not be reached.' }, 502);
|
|
117
|
+
return new Response(await res.text(), {
|
|
118
|
+
status: res.status,
|
|
119
|
+
headers: {
|
|
120
|
+
'Content-Type': 'application/json',
|
|
121
|
+
'Cache-Control': res.ok && !perVisitor ? 'public, max-age=0, s-maxage=30, stale-while-revalidate=60' : 'private, no-store',
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return async function handle(request, given) {
|
|
126
|
+
const url = new URL(request.url);
|
|
127
|
+
const [action, name, verb, ...rest] = given?.length ? given : segmentsOf(request);
|
|
128
|
+
const secure = url.protocol === 'https:';
|
|
129
|
+
const method = request.method.toUpperCase();
|
|
130
|
+
if (method === 'POST' && action === 'revalidate' && !name)
|
|
131
|
+
return revalidate(request);
|
|
132
|
+
if (method === 'GET') {
|
|
133
|
+
if (action === 'draft') {
|
|
134
|
+
const token = url.searchParams.get('token') ?? '';
|
|
135
|
+
const ttl = secondsLeft(token);
|
|
136
|
+
if (!token || ttl <= 0)
|
|
137
|
+
return errorPage('This editing link has expired. Open "Edit on page" from VeroXM again.', 401);
|
|
138
|
+
const check = await editorApi(token, 'session').catch(() => null);
|
|
139
|
+
if (!check?.ok) {
|
|
140
|
+
const body = (await check?.json().catch(() => null));
|
|
141
|
+
return errorPage(body?.error ?? 'VeroXM could not confirm this editing link.', check?.status === 403 ? 403 : 401);
|
|
142
|
+
}
|
|
143
|
+
await hooks.enter?.();
|
|
144
|
+
return redirect(new URL(safePath(url.searchParams.get('path')), url.origin), [
|
|
145
|
+
cookie(EDITOR_COOKIE, token, ttl, secure, true),
|
|
146
|
+
cookie(EDITING_FLAG_COOKIE, '1', ttl, secure, false),
|
|
147
|
+
]);
|
|
148
|
+
}
|
|
149
|
+
if (action === 'exit') {
|
|
150
|
+
await hooks.exit?.();
|
|
151
|
+
return redirect(new URL(safePath(url.searchParams.get('path')), url.origin), [
|
|
152
|
+
cookie(EDITOR_COOKIE, '', 0, secure, true),
|
|
153
|
+
cookie(EDITING_FLAG_COOKIE, '', 0, secure, false),
|
|
154
|
+
]);
|
|
155
|
+
}
|
|
156
|
+
if (action === 'published' && hooks.servePublished && !name)
|
|
157
|
+
return published(request);
|
|
158
|
+
if ((action === 'session' || action === 'slots' || action === 'media' || action === 'geocode') && !name)
|
|
159
|
+
return relay(request, action, 'GET');
|
|
160
|
+
return NOT_FOUND();
|
|
161
|
+
}
|
|
162
|
+
if (method === 'PUT' && action === 'slots' && name && !verb)
|
|
163
|
+
return relay(request, `slots/${encodeURIComponent(name)}`, 'PUT');
|
|
164
|
+
if (method === 'PUT' && action === 'slots' && name && verb === 'shown' && rest.length === 0) {
|
|
165
|
+
return relay(request, `slots/${encodeURIComponent(name)}/shown`, 'PUT');
|
|
166
|
+
}
|
|
167
|
+
if (method === 'PUT' && action === 'slots' && name && verb === 'variants' && /^\d{1,2}$/.test(rest[0] ?? '') && rest.length === 1) {
|
|
168
|
+
return relay(request, `slots/${encodeURIComponent(name)}/variants/${rest[0]}`, 'PUT');
|
|
169
|
+
}
|
|
170
|
+
if (method === 'POST' && action === 'slots' && name && POST_VERBS.has(verb) && !rest.length) {
|
|
171
|
+
return relay(request, `slots/${encodeURIComponent(name)}/${verb}`, 'POST');
|
|
172
|
+
}
|
|
173
|
+
return NOT_FOUND();
|
|
174
|
+
};
|
|
175
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface InlineEditOptions {
|
|
2
|
+
/** Field max length, if any. */
|
|
3
|
+
max?: number;
|
|
4
|
+
/** Accessible name while editing, e.g. "Headline". */
|
|
5
|
+
label: string;
|
|
6
|
+
/** Where the click landed, to put the caret there. */
|
|
7
|
+
point?: {
|
|
8
|
+
x: number;
|
|
9
|
+
y: number;
|
|
10
|
+
};
|
|
11
|
+
/** Every change, with the current text. */
|
|
12
|
+
onInput(text: string): void;
|
|
13
|
+
/** Editing finished: committed (Enter/blur) or cancelled (Escape, original text restored). */
|
|
14
|
+
onEnd(result: {
|
|
15
|
+
committed: boolean;
|
|
16
|
+
text: string;
|
|
17
|
+
}): void;
|
|
18
|
+
}
|
|
19
|
+
export interface InlineEdit {
|
|
20
|
+
/** Finish from outside (e.g. the panel closed): true commits, false cancels. */
|
|
21
|
+
end(commit: boolean): void;
|
|
22
|
+
}
|
|
23
|
+
/** Whether an element can be edited in place: a single text node, nothing nested, not inside a button. */
|
|
24
|
+
export declare function canEditInline(el: Element | null): el is HTMLElement;
|
|
25
|
+
export declare function startInlineEdit(el: HTMLElement, opts: InlineEditOptions): InlineEdit;
|