drupal-canvas 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -45
- package/dist/context-Cb4HbPbR.d.ts +32 -0
- package/dist/drupal-utils-CUaK4jOk.d.ts +117 -0
- package/dist/drupal-utils.d.ts +2 -79
- package/dist/drupal-utils.js +23 -0
- package/dist/index.d.ts +209 -3
- package/dist/index.js +220 -2
- package/dist/json-render-utils.d.ts +3 -3
- package/dist/json-render-utils.js +11 -1
- package/dist/jsonapi-client-BAQ3V5CC.d.ts +329 -0
- package/dist/jsonapi-client-CejP62bM.js +539 -0
- package/dist/jsonapi-client.d.ts +2 -2
- package/dist/jsonapi-client.js +2 -17
- package/dist/migration-CPBzW78_.js +63 -0
- package/dist/react.d.ts +25 -0
- package/dist/react.js +158 -0
- package/package.json +11 -1
- package/dist/jsonapi-client-Q84JvzCD.d.ts +0 -13
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
import { r as assertLegacyRuntime } from "./migration-CPBzW78_.js";
|
|
2
|
+
import { DefaultSerializer, JsonApiClient } from "@drupal-api-client/json-api-client";
|
|
3
|
+
//#region src/jsonapi-proxy.ts
|
|
4
|
+
/**
|
|
5
|
+
* @file
|
|
6
|
+
* Framework-agnostic URL mapping between a Drupal backend's JSON:API
|
|
7
|
+
* endpoints and a same-origin application proxy. The browser client maps
|
|
8
|
+
* upstream URLs to the proxy; the proxy (in the Canvas Headless SDK) validates
|
|
9
|
+
* and maps them back. Both sides share this module so they cannot disagree
|
|
10
|
+
* about which paths are supported.
|
|
11
|
+
*
|
|
12
|
+
* The supported endpoints are those the JSON:API client reaches:
|
|
13
|
+
* - the JSON:API prefix (resources, collections, views, the index), and
|
|
14
|
+
* - the Decoupled Router path translation endpoint (`getResourceByPath()`).
|
|
15
|
+
* Both may be preceded by one Drupal language path prefix.
|
|
16
|
+
*
|
|
17
|
+
* @see docs/adr/0021-code-component-runtime-compatibility-across-frontend-modes.md
|
|
18
|
+
*/
|
|
19
|
+
/** The default JSON:API prefix of Drupal core's JSON:API module. */
|
|
20
|
+
const DEFAULT_JSONAPI_PREFIX = "jsonapi";
|
|
21
|
+
/** The default path of the Decoupled Router module's endpoint. */
|
|
22
|
+
const DEFAULT_ROUTER_PREFIX = "router/translate-path";
|
|
23
|
+
/**
|
|
24
|
+
* The response header the proxy sets on draft-session errors, and the value
|
|
25
|
+
* it carries when the session expired or is invalid.
|
|
26
|
+
*/
|
|
27
|
+
const JSONAPI_PROXY_SESSION_HEADER = "X-Canvas-Draft-Session";
|
|
28
|
+
const JSONAPI_PROXY_SESSION_EXPIRED = "expired";
|
|
29
|
+
/** The `error` code of the proxy's draft-session error body. */
|
|
30
|
+
const JSONAPI_DRAFT_SESSION_EXPIRED_ERROR = "draft_session_expired";
|
|
31
|
+
/**
|
|
32
|
+
* Resolves the JSON:API base and prefix. A full URL override under the
|
|
33
|
+
* backend base URL is a prefix override (a locale prefix goes between the
|
|
34
|
+
* site path and the prefix, as Drupal serves it); an override elsewhere is a
|
|
35
|
+
* foreign base whose path is the prefix.
|
|
36
|
+
*/
|
|
37
|
+
function resolveJsonApiBase(baseUrl, endpoints = {}) {
|
|
38
|
+
const site = normalizeBaseUrl(baseUrl);
|
|
39
|
+
if (endpoints.apiUrl) {
|
|
40
|
+
const api = normalizeBaseUrl(endpoints.apiUrl);
|
|
41
|
+
if (api === site || api.startsWith(`${site}/`)) return {
|
|
42
|
+
base: site,
|
|
43
|
+
apiPrefix: trimSlashes(api.slice(site.length)) || "jsonapi",
|
|
44
|
+
foreign: false,
|
|
45
|
+
siteKnown: true
|
|
46
|
+
};
|
|
47
|
+
if (endpoints.apiSiteUrl) {
|
|
48
|
+
const apiSite = normalizeBaseUrl(endpoints.apiSiteUrl);
|
|
49
|
+
if (api !== apiSite && !api.startsWith(`${apiSite}/`)) throw new Error(`[drupal-canvas] The JSON:API URL (${api}) is not under its site base URL (${apiSite}).`);
|
|
50
|
+
return {
|
|
51
|
+
base: apiSite,
|
|
52
|
+
apiPrefix: trimSlashes(api.slice(apiSite.length)) || "jsonapi",
|
|
53
|
+
foreign: true,
|
|
54
|
+
siteKnown: true
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const url = new URL(api);
|
|
58
|
+
return {
|
|
59
|
+
base: url.origin,
|
|
60
|
+
apiPrefix: trimSlashes(url.pathname) || "jsonapi",
|
|
61
|
+
foreign: true,
|
|
62
|
+
siteKnown: false
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
base: site,
|
|
67
|
+
apiPrefix: trimSlashes(endpoints.apiPrefix || "jsonapi"),
|
|
68
|
+
foreign: false,
|
|
69
|
+
siteKnown: true
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A possible language prefix is one safe path segment, not a language code.
|
|
74
|
+
* Drupal permits custom text (but no slash); this is not a configuration lookup.
|
|
75
|
+
* Reject ambiguous escapes and URL delimiters before allowing an extra segment
|
|
76
|
+
* in front of the configured endpoint. Never decode the forwarded path itself.
|
|
77
|
+
*/
|
|
78
|
+
function isSafeOptionalPrefix(segment) {
|
|
79
|
+
try {
|
|
80
|
+
const decoded = decodeURIComponent(segment);
|
|
81
|
+
return decoded !== "." && decoded !== ".." && !/[/\\%?#\p{Cc}]/u.test(decoded);
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Strips surrounding slashes. */
|
|
87
|
+
function trimSlashes(value) {
|
|
88
|
+
return value.replace(/^\/+|\/+$/g, "");
|
|
89
|
+
}
|
|
90
|
+
function splitSegments(prefix) {
|
|
91
|
+
return trimSlashes(prefix).split("/").filter(Boolean);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Whether `path` is a safe site-relative path: one leading slash, no empty,
|
|
95
|
+
* dot, or dot-dot segments, no backslashes, and no encoded slashes that could
|
|
96
|
+
* decode into a different path upstream.
|
|
97
|
+
*/
|
|
98
|
+
function isSafeProxyPath(path) {
|
|
99
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return false;
|
|
100
|
+
if (/%2f|%5c/i.test(path)) return false;
|
|
101
|
+
const segments = path.slice(1).split("/");
|
|
102
|
+
return segments.every((segment, index) => (segment !== "" || index === segments.length - 1) && segment !== "." && segment !== "..");
|
|
103
|
+
}
|
|
104
|
+
function matchesPrefix(segments, prefix) {
|
|
105
|
+
return prefix.length > 0 && segments.length >= prefix.length && prefix.every((segment, index) => segments[index] === segment);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Validates a site-relative path against the supported endpoints. Returns the
|
|
109
|
+
* endpoint it belongs to, or `null` when the path is unsafe or outside the
|
|
110
|
+
* boundary.
|
|
111
|
+
*/
|
|
112
|
+
function resolveJsonApiProxyPath(path, endpoints = {}) {
|
|
113
|
+
if (!isSafeProxyPath(path)) return null;
|
|
114
|
+
const apiPrefix = splitSegments(endpoints.apiPrefix || "jsonapi");
|
|
115
|
+
const routerPrefix = splitSegments(endpoints.routerPrefix || "router/translate-path");
|
|
116
|
+
const segments = path.slice(1).split("/").filter(Boolean);
|
|
117
|
+
const candidates = [segments];
|
|
118
|
+
if (segments.length > 1 && isSafeOptionalPrefix(segments[0])) candidates.push(segments.slice(1));
|
|
119
|
+
for (const candidate of candidates) {
|
|
120
|
+
if (matchesPrefix(candidate, apiPrefix)) return {
|
|
121
|
+
endpoint: "jsonapi",
|
|
122
|
+
path
|
|
123
|
+
};
|
|
124
|
+
if (matchesPrefix(candidate, routerPrefix)) return {
|
|
125
|
+
endpoint: "router",
|
|
126
|
+
path
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
/** Normalizes a backend base URL: absolute, no trailing slash. */
|
|
132
|
+
function normalizeBaseUrl(baseUrl) {
|
|
133
|
+
const url = new URL(baseUrl);
|
|
134
|
+
url.search = "";
|
|
135
|
+
url.hash = "";
|
|
136
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Splits an absolute upstream URL into the part relative to the backend base
|
|
140
|
+
* URL. Returns `null` when the URL is not on the backend.
|
|
141
|
+
*/
|
|
142
|
+
function toBackendRelativePath(url, baseUrl) {
|
|
143
|
+
let target;
|
|
144
|
+
try {
|
|
145
|
+
target = new URL(url);
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
const base = new URL(normalizeBaseUrl(baseUrl));
|
|
150
|
+
if (target.origin !== base.origin) return null;
|
|
151
|
+
const basePath = base.pathname.replace(/\/+$/, "");
|
|
152
|
+
if (basePath !== "" && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) return null;
|
|
153
|
+
return {
|
|
154
|
+
path: target.pathname.slice(basePath.length) || "/",
|
|
155
|
+
search: target.search
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Maps an absolute upstream JSON:API URL to the same-origin proxy. Returns
|
|
160
|
+
* `null` for URLs that are not on the backend. Throws for backend URLs
|
|
161
|
+
* outside the supported endpoints, so an absolute Drupal URL can never bypass
|
|
162
|
+
* the proxy.
|
|
163
|
+
*/
|
|
164
|
+
function mapJsonApiRequestToProxy(url, options) {
|
|
165
|
+
const api = resolveJsonApiBase(options.baseUrl, options);
|
|
166
|
+
const site = normalizeBaseUrl(options.baseUrl);
|
|
167
|
+
const endpoints = {
|
|
168
|
+
apiPrefix: api.apiPrefix,
|
|
169
|
+
routerPrefix: options.routerPrefix
|
|
170
|
+
};
|
|
171
|
+
const targets = api.foreign ? [{
|
|
172
|
+
base: api.base,
|
|
173
|
+
endpoint: "jsonapi"
|
|
174
|
+
}, {
|
|
175
|
+
base: site,
|
|
176
|
+
endpoint: "router"
|
|
177
|
+
}] : [{
|
|
178
|
+
base: site,
|
|
179
|
+
endpoint: null
|
|
180
|
+
}];
|
|
181
|
+
let origin;
|
|
182
|
+
try {
|
|
183
|
+
origin = new URL(url).origin;
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
let onBackend = false;
|
|
188
|
+
for (const target of targets) {
|
|
189
|
+
if (new URL(target.base).origin === origin) onBackend = true;
|
|
190
|
+
const relative = toBackendRelativePath(url, target.base);
|
|
191
|
+
if (relative === null) continue;
|
|
192
|
+
const resolved = resolveJsonApiProxyPath(relative.path, endpoints);
|
|
193
|
+
if (resolved !== null && (target.endpoint === null || resolved.endpoint === target.endpoint) && (resolved.endpoint !== "jsonapi" || api.siteKnown || matchesPrefix(splitSegments(resolved.path), splitSegments(api.apiPrefix)))) return `${options.proxyUrl.replace(/\/+$/, "")}${resolved.path}${relative.search}`;
|
|
194
|
+
}
|
|
195
|
+
if (!onBackend) return null;
|
|
196
|
+
throw new Error(`[drupal-canvas] The browser JSON:API client only reaches the Drupal backend through the application proxy, and "${url}" is not a supported JSON:API or path-translation endpoint.`);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Maps a proxied request path back to its absolute upstream URL. Returns
|
|
200
|
+
* `null` when the path is unsafe or outside the supported endpoints.
|
|
201
|
+
*/
|
|
202
|
+
function mapProxyPathToUpstream(proxiedPath, options) {
|
|
203
|
+
const proxyPath = new URL(options.proxyUrl, "http://localhost").pathname.replace(/\/+$/, "");
|
|
204
|
+
if (proxyPath !== "" && !proxiedPath.startsWith(`${proxyPath}/`)) return null;
|
|
205
|
+
const path = proxyPath === "" ? proxiedPath : proxiedPath.slice(proxyPath.length);
|
|
206
|
+
const api = resolveJsonApiBase(options.baseUrl, options);
|
|
207
|
+
const resolved = resolveJsonApiProxyPath(path, {
|
|
208
|
+
apiPrefix: api.apiPrefix,
|
|
209
|
+
routerPrefix: options.routerPrefix
|
|
210
|
+
});
|
|
211
|
+
if (resolved === null || resolved.endpoint === "jsonapi" && !api.siteKnown && !matchesPrefix(splitSegments(resolved.path), splitSegments(api.apiPrefix))) return null;
|
|
212
|
+
return {
|
|
213
|
+
url: `${resolved.endpoint === "jsonapi" ? api.base : normalizeBaseUrl(options.baseUrl)}${resolved.path}`,
|
|
214
|
+
endpoint: resolved.endpoint
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/jsonapi-client.ts
|
|
219
|
+
/**
|
|
220
|
+
* @file
|
|
221
|
+
* The shared, framework-agnostic JSON:API client for Drupal Canvas. It
|
|
222
|
+
* extends `@drupal-api-client/json-api-client` with:
|
|
223
|
+
* - draft reads at a configured resource version (working copies), resolved
|
|
224
|
+
* before the configured serializer runs;
|
|
225
|
+
* - transparent mapping of browser requests to a same-origin proxy, including
|
|
226
|
+
* absolute pagination links and the path-translation endpoint;
|
|
227
|
+
* - draft-session errors surfaced as `DraftSessionError`;
|
|
228
|
+
* - client caches separated by resource version and session scope.
|
|
229
|
+
*
|
|
230
|
+
* The legacy `new JsonApiClient()` API remains for Drupal-rendered Code
|
|
231
|
+
* Components and Workbench; it reads `drupalSettings` and throws an actionable
|
|
232
|
+
* migration error elsewhere. Rendering integrations and the Headless SDK use
|
|
233
|
+
* `createJsonApiClient()` instead, which has no environment guard.
|
|
234
|
+
*
|
|
235
|
+
* @see docs/adr/0021-code-component-runtime-compatibility-across-frontend-modes.md
|
|
236
|
+
*/
|
|
237
|
+
/**
|
|
238
|
+
* Thrown when the draft preview session is rejected: the application proxy
|
|
239
|
+
* reports it expired or invalid, or Drupal answers an authenticated request
|
|
240
|
+
* with 401. Never swallowed by the client's fallbacks.
|
|
241
|
+
*/
|
|
242
|
+
var DraftSessionError = class extends Error {
|
|
243
|
+
status;
|
|
244
|
+
constructor(message, status = 401) {
|
|
245
|
+
super(message);
|
|
246
|
+
this.name = "DraftSessionError";
|
|
247
|
+
this.status = status;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
function isDraftSessionError(error) {
|
|
251
|
+
return error instanceof DraftSessionError || typeof error === "object" && error !== null && error.name === "DraftSessionError";
|
|
252
|
+
}
|
|
253
|
+
function toUrlString(input) {
|
|
254
|
+
if (typeof input === "string") return input;
|
|
255
|
+
if (input instanceof URL) return input.href;
|
|
256
|
+
return input.url;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Creates the transport for the shared client: routes backend requests through
|
|
260
|
+
* the configured proxy, applies the credentials mode, and turns the proxy's
|
|
261
|
+
* draft-session errors into exceptions.
|
|
262
|
+
*/
|
|
263
|
+
function createTransport(config) {
|
|
264
|
+
const fetchImpl = config.fetch ?? fetch;
|
|
265
|
+
return async (input, init) => {
|
|
266
|
+
let url = toUrlString(input);
|
|
267
|
+
if (config.proxyUrl) url = mapJsonApiRequestToProxy(url, {
|
|
268
|
+
baseUrl: config.baseUrl,
|
|
269
|
+
proxyUrl: config.proxyUrl,
|
|
270
|
+
apiPrefix: config.apiPrefix,
|
|
271
|
+
apiUrl: config.apiUrl,
|
|
272
|
+
apiSiteUrl: config.apiSiteUrl,
|
|
273
|
+
routerPrefix: config.routerPrefix
|
|
274
|
+
}) ?? url;
|
|
275
|
+
const request = { ...init };
|
|
276
|
+
if (config.credentials && request.credentials === void 0) request.credentials = config.credentials;
|
|
277
|
+
const response = await fetchImpl(url, request);
|
|
278
|
+
const optedOut = request.credentials === "omit";
|
|
279
|
+
const carriesSession = new Headers(request.headers).has("authorization") || !optedOut && (config.credentials === "same-origin" || config.credentials === "include" || config.fetchAuthenticates === true);
|
|
280
|
+
if (!config.proxyUrl && response.status === 401 && carriesSession) throw new DraftSessionError("The draft preview session was rejected by Drupal.", 401);
|
|
281
|
+
if (config.proxyUrl && response.headers.get("X-Canvas-Draft-Session") === "expired") {
|
|
282
|
+
let message = "The draft preview session has expired.";
|
|
283
|
+
try {
|
|
284
|
+
const body = await response.clone().json();
|
|
285
|
+
if (typeof body?.message === "string") message = body.message;
|
|
286
|
+
} catch {}
|
|
287
|
+
throw new DraftSessionError(message, response.status);
|
|
288
|
+
}
|
|
289
|
+
return response;
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
/** Prefixes every key of a cache so scopes never share entries. */
|
|
293
|
+
function scopeCache(cache, scope) {
|
|
294
|
+
return {
|
|
295
|
+
get: (key, ...args) => cache.get(`${scope}:${key}`, ...args),
|
|
296
|
+
set: (key, value, ...args) => cache.set(`${scope}:${key}`, value, ...args)
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The shared client implementation. Construct it with
|
|
301
|
+
* {@link createJsonApiClient}; the legacy `JsonApiClient` constructor extends
|
|
302
|
+
* it for Drupal and Workbench.
|
|
303
|
+
*/
|
|
304
|
+
var CanvasJsonApiClient = class extends JsonApiClient {
|
|
305
|
+
/** The serializable part of the configuration. */
|
|
306
|
+
runtimeConfig;
|
|
307
|
+
/** The resource version applied to reads, or `null`. */
|
|
308
|
+
resourceVersion;
|
|
309
|
+
/** Where JSON:API requests go (base URL, prefix, foreign site or not). */
|
|
310
|
+
apiBase;
|
|
311
|
+
constructor(config) {
|
|
312
|
+
const baseUrl = normalizeBaseUrl(config.baseUrl);
|
|
313
|
+
const apiUrl = config.apiUrl ? normalizeBaseUrl(config.apiUrl) : void 0;
|
|
314
|
+
const api = resolveJsonApiBase(baseUrl, {
|
|
315
|
+
apiPrefix: config.apiPrefix,
|
|
316
|
+
apiUrl,
|
|
317
|
+
apiSiteUrl: config.apiSiteUrl
|
|
318
|
+
});
|
|
319
|
+
const apiPrefix = api.apiPrefix;
|
|
320
|
+
const routerPrefix = trimSlashes(config.routerPrefix ?? "router/translate-path") || "router/translate-path";
|
|
321
|
+
const resourceVersion = config.resourceVersion || null;
|
|
322
|
+
const sessionSensitive = Boolean(config.authentication) || Boolean(config.proxyUrl) || Boolean(config.fetch) || config.credentials === "same-origin" || config.credentials === "include" || config.credentials === void 0 && typeof window !== "undefined" || Boolean(config.preview) || resourceVersion !== null;
|
|
323
|
+
const cache = config.cache && (!sessionSensitive || config.cacheScope) ? scopeCache(config.cache, [resourceVersion ?? "default", config.cacheScope ?? "public"].join(":")) : void 0;
|
|
324
|
+
const serializer = config.serializer === void 0 ? new DefaultSerializer() : config.serializer ?? void 0;
|
|
325
|
+
super(baseUrl, {
|
|
326
|
+
...config.upstreamOptions,
|
|
327
|
+
apiPrefix,
|
|
328
|
+
decoupledRouterApiPrefix: routerPrefix,
|
|
329
|
+
serializer,
|
|
330
|
+
cache,
|
|
331
|
+
authentication: config.authentication,
|
|
332
|
+
customFetch: createTransport({
|
|
333
|
+
...config,
|
|
334
|
+
baseUrl
|
|
335
|
+
})
|
|
336
|
+
});
|
|
337
|
+
this.runtimeConfig = {
|
|
338
|
+
baseUrl,
|
|
339
|
+
apiPrefix,
|
|
340
|
+
...apiUrl && { apiUrl },
|
|
341
|
+
...apiUrl && config.apiSiteUrl && { apiSiteUrl: normalizeBaseUrl(config.apiSiteUrl) },
|
|
342
|
+
routerPrefix,
|
|
343
|
+
...config.proxyUrl && { proxyUrl: config.proxyUrl },
|
|
344
|
+
resourceVersion,
|
|
345
|
+
preview: config.preview ?? false
|
|
346
|
+
};
|
|
347
|
+
this.resourceVersion = resourceVersion;
|
|
348
|
+
this.apiBase = api;
|
|
349
|
+
const router = this.router;
|
|
350
|
+
router.createURL = ({ localeSegment, path }) => `${baseUrl}/${localeSegment ? `${localeSegment}/` : ""}${routerPrefix}?path=${path}`;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Obtaining or renewing the configured credentials is part of the session
|
|
354
|
+
* lifecycle: a failure there (for example an OAuth renewal answered with
|
|
355
|
+
* `invalid_grant`) is a rejected session, never an ordinary request error
|
|
356
|
+
* that a collection read could paper over with published items.
|
|
357
|
+
*/
|
|
358
|
+
async addAuthorizationHeader(options) {
|
|
359
|
+
try {
|
|
360
|
+
return await super.addAuthorizationHeader(options);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (isDraftSessionError(error)) throw error;
|
|
363
|
+
throw new DraftSessionError(`The session credentials could not be obtained: ${error instanceof Error ? error.message : String(error)}`, 401);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Builds JSON:API URLs as Drupal serves them: the backend base URL
|
|
368
|
+
* including any site path, then a locale prefix, then the JSON:API prefix
|
|
369
|
+
* (the upstream builder resolves root-relative and would drop a site path
|
|
370
|
+
* such as `/sub`). A same-site full URL override is a prefix override; a
|
|
371
|
+
* foreign one has no known site root, so a locale prefix is refused.
|
|
372
|
+
*/
|
|
373
|
+
async createURL(segments) {
|
|
374
|
+
const { localeSegment, entityTypeId, bundleId, viewName, viewDisplayId, resourceId, queryString } = segments;
|
|
375
|
+
if (localeSegment && !this.apiBase.siteKnown) throw new Error(`[drupal-canvas] A locale path prefix ("${localeSegment}") cannot be applied to a JSON:API base URL on another site (${this.apiBase.base}) without its site base URL (apiSiteUrl).`);
|
|
376
|
+
const prefixUrl = `${this.apiBase.base}/${localeSegment ? `${localeSegment}/` : ""}${this.apiPrefix}`;
|
|
377
|
+
const query = queryString ? `?${queryString}` : "";
|
|
378
|
+
if (this.indexLookup) {
|
|
379
|
+
const cacheKey = `${localeSegment ? `${localeSegment}/` : ""}${this.apiPrefix}`;
|
|
380
|
+
let index = await this.getCachedResponse(cacheKey);
|
|
381
|
+
if (!index) {
|
|
382
|
+
const { response, error } = await this.fetch(prefixUrl);
|
|
383
|
+
if (error) throw error;
|
|
384
|
+
index = await response.json();
|
|
385
|
+
if (this.cache && response.status < 400) await this.cache.set(cacheKey, index);
|
|
386
|
+
}
|
|
387
|
+
const href = index?.links?.[`${entityTypeId}${bundleId ? `--${bundleId}` : ""}`]?.href;
|
|
388
|
+
if (href) return `${href}${resourceId ? `/${resourceId}` : ""}${query}`;
|
|
389
|
+
}
|
|
390
|
+
return viewName ? `${prefixUrl}/views/${viewName}/${viewDisplayId}${query}` : `${prefixUrl}/${entityTypeId}${bundleId ? `/${bundleId}` : ""}${resourceId ? `/${resourceId}` : ""}${query}`;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Adds the configured resource version to a read unless the caller selected
|
|
394
|
+
* one explicitly.
|
|
395
|
+
*/
|
|
396
|
+
withResourceVersion(options) {
|
|
397
|
+
if (this.resourceVersion === null || options?.queryString?.includes("resourceVersion=")) return options;
|
|
398
|
+
const version = `resourceVersion=${encodeURIComponent(this.resourceVersion)}`;
|
|
399
|
+
return {
|
|
400
|
+
...options,
|
|
401
|
+
queryString: options?.queryString ? `${options.queryString}&${version}` : version
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
async getResource(type, resourceId, options) {
|
|
405
|
+
return super.getResource(type, resourceId, options?.rawResponse ? options : this.withResourceVersion(options));
|
|
406
|
+
}
|
|
407
|
+
async getCollection(type, options) {
|
|
408
|
+
if (this.resourceVersion === null || options?.rawResponse) return super.getCollection(type, options);
|
|
409
|
+
const { entityTypeId, bundleId } = JsonApiClient.getEntityTypeIdAndBundleId(type);
|
|
410
|
+
const localeSegment = options?.locale || this.defaultLocale;
|
|
411
|
+
const cacheKey = await JsonApiClient.createCacheKey({
|
|
412
|
+
entityTypeId,
|
|
413
|
+
bundleId,
|
|
414
|
+
localeSegment,
|
|
415
|
+
queryString: options?.queryString,
|
|
416
|
+
cacheKey: options?.cacheKey
|
|
417
|
+
});
|
|
418
|
+
if (!options?.disableCache) {
|
|
419
|
+
const cached = await this.getCachedResponse(cacheKey);
|
|
420
|
+
if (cached) return cached;
|
|
421
|
+
}
|
|
422
|
+
const url = await this.createURL({
|
|
423
|
+
localeSegment,
|
|
424
|
+
entityTypeId,
|
|
425
|
+
bundleId,
|
|
426
|
+
queryString: options?.queryString
|
|
427
|
+
});
|
|
428
|
+
const init = options?.disableAuthentication ? { credentials: "omit" } : {};
|
|
429
|
+
const { response, error } = await this.fetch(url, init);
|
|
430
|
+
if (error) throw error;
|
|
431
|
+
const status = response.status;
|
|
432
|
+
let document = status === 204 ? "" : await response.json();
|
|
433
|
+
if (status < 400 && isCollectionDocument(document)) document = await this.hydrateWorkingCopies(type, document, init, {
|
|
434
|
+
localeSegment,
|
|
435
|
+
queryString: options?.queryString
|
|
436
|
+
});
|
|
437
|
+
const result = this.serializer?.deserialize ? this.serializer.deserialize(document) : document;
|
|
438
|
+
if (this.cache && !options?.disableCache && status < 400) await this.cache.set(cacheKey, result);
|
|
439
|
+
return result;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Replaces each collection item with its working copy. Item reads keep the
|
|
443
|
+
* read options that apply to a single resource — the locale, sparse
|
|
444
|
+
* fieldsets, includes, and a resource version the caller selected
|
|
445
|
+
* explicitly — but not collection-only parameters (filter, sort, page).
|
|
446
|
+
* Included resources returned with the working copies replace the
|
|
447
|
+
* collection's included resources of the same identity, so relationships
|
|
448
|
+
* of a working copy resolve against the document.
|
|
449
|
+
*/
|
|
450
|
+
async hydrateWorkingCopies(type, document, init, read) {
|
|
451
|
+
const { entityTypeId, bundleId } = JsonApiClient.getEntityTypeIdAndBundleId(type);
|
|
452
|
+
const itemParams = new URLSearchParams();
|
|
453
|
+
for (const [key, value] of new URLSearchParams(read.queryString ?? "")) if (key === "include" || key === "resourceVersion" || /^fields\[[^\]]+\]$/.test(key)) itemParams.append(key, value);
|
|
454
|
+
if (!itemParams.has("resourceVersion")) itemParams.set("resourceVersion", this.resourceVersion);
|
|
455
|
+
const included = /* @__PURE__ */ new Map();
|
|
456
|
+
const includedKey = (resource) => typeof resource === "object" && resource !== null && typeof resource.type === "string" && typeof resource.id === "string" ? `${resource.type}:${resource.id}` : null;
|
|
457
|
+
if (Array.isArray(document.included)) for (const resource of document.included) {
|
|
458
|
+
const key = includedKey(resource);
|
|
459
|
+
if (key !== null) included.set(key, resource);
|
|
460
|
+
}
|
|
461
|
+
const data = await Promise.all(document.data.map(async (item) => {
|
|
462
|
+
if (typeof item?.id !== "string") return item;
|
|
463
|
+
const url = await this.createURL({
|
|
464
|
+
localeSegment: read.localeSegment,
|
|
465
|
+
entityTypeId,
|
|
466
|
+
bundleId,
|
|
467
|
+
resourceId: item.id,
|
|
468
|
+
queryString: itemParams.toString()
|
|
469
|
+
});
|
|
470
|
+
try {
|
|
471
|
+
const { response, error } = await this.fetch(url, init);
|
|
472
|
+
if (error) throw error;
|
|
473
|
+
if (!response.ok) return item;
|
|
474
|
+
const workingCopy = await response.json();
|
|
475
|
+
if (!workingCopy || typeof workingCopy !== "object" || !("data" in workingCopy) || !workingCopy.data) return item;
|
|
476
|
+
if (Array.isArray(workingCopy.included)) for (const resource of workingCopy.included) {
|
|
477
|
+
const key = includedKey(resource);
|
|
478
|
+
if (key !== null) included.set(key, resource);
|
|
479
|
+
}
|
|
480
|
+
return workingCopy.data;
|
|
481
|
+
} catch (error) {
|
|
482
|
+
if (isDraftSessionError(error)) throw error;
|
|
483
|
+
return item;
|
|
484
|
+
}
|
|
485
|
+
}));
|
|
486
|
+
for (const item of data) {
|
|
487
|
+
const key = includedKey(item);
|
|
488
|
+
if (key !== null) included.delete(key);
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
...document,
|
|
492
|
+
data,
|
|
493
|
+
...included.size > 0 ? { included: [...included.values()] } : Array.isArray(document.included) ? { included: [] } : {}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
function isCollectionDocument(value) {
|
|
498
|
+
return typeof value === "object" && value !== null && Array.isArray(value.data);
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Creates the shared JSON:API client from explicit configuration. This is the
|
|
502
|
+
* construction path for rendering integrations and the Headless SDK; it has
|
|
503
|
+
* no environment guard.
|
|
504
|
+
*/
|
|
505
|
+
function createJsonApiClient(config) {
|
|
506
|
+
return new CanvasJsonApiClient(config);
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* The legacy JSON:API client for Drupal-rendered Code Components and
|
|
510
|
+
* Workbench: configured from `drupalSettings`, with `DefaultSerializer` and
|
|
511
|
+
* the site's JSON:API prefix. Outside those environments it throws an
|
|
512
|
+
* actionable migration error, even when a base URL is supplied.
|
|
513
|
+
*
|
|
514
|
+
* @deprecated Use `useJsonApiClient()` in React Code Components, or the
|
|
515
|
+
* Headless SDK's `getClient()` in headless server code.
|
|
516
|
+
*/
|
|
517
|
+
var LegacyJsonApiClient = class extends CanvasJsonApiClient {
|
|
518
|
+
constructor(baseUrl, options) {
|
|
519
|
+
assertLegacyRuntime("new JsonApiClient()");
|
|
520
|
+
const settings = globalThis.drupalSettings?.canvasData?.v0;
|
|
521
|
+
if (settings?.jsonapiSettings === null) throw new Error("The JSON:API module is not installed. Please install it to use JsonApiClient.");
|
|
522
|
+
const clientBaseUrl = baseUrl || settings?.baseUrl;
|
|
523
|
+
if (!clientBaseUrl) throw new Error("Could not determine your site's base URL for the JSON:API client. If working outside of Drupal Canvas, you can use the @drupal-canvas/vite-plugin to automatically configure it for you. Otherwise you must explicitly provide a base URL, i.e. `const client = new JsonApiClient(\"https://...\")`");
|
|
524
|
+
const { apiPrefix, authentication, cache, customFetch, decoupledRouterApiPrefix, serializer, ...upstreamOptions } = options ?? {};
|
|
525
|
+
super({
|
|
526
|
+
baseUrl: clientBaseUrl,
|
|
527
|
+
apiPrefix: apiPrefix ?? settings?.jsonapiSettings?.apiPrefix,
|
|
528
|
+
routerPrefix: decoupledRouterApiPrefix,
|
|
529
|
+
authentication,
|
|
530
|
+
cache,
|
|
531
|
+
cacheScope: options?.cacheScope,
|
|
532
|
+
fetch: customFetch,
|
|
533
|
+
serializer: options && "serializer" in options ? serializer ?? null : void 0,
|
|
534
|
+
upstreamOptions
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
//#endregion
|
|
539
|
+
export { toBackendRelativePath as _, isDraftSessionError as a, JSONAPI_DRAFT_SESSION_EXPIRED_ERROR as c, isSafeProxyPath as d, mapJsonApiRequestToProxy as f, resolveJsonApiProxyPath as g, resolveJsonApiBase as h, createJsonApiClient as i, JSONAPI_PROXY_SESSION_EXPIRED as l, normalizeBaseUrl as m, DraftSessionError as n, DEFAULT_JSONAPI_PREFIX as o, mapProxyPathToUpstream as p, LegacyJsonApiClient as r, DEFAULT_ROUTER_PREFIX as s, CanvasJsonApiClient as t, JSONAPI_PROXY_SESSION_HEADER as u, trimSlashes as v };
|
package/dist/jsonapi-client.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as CanvasJsonApiClient } from "./jsonapi-client-
|
|
1
|
+
import { C as trimSlashes, S as toBackendRelativePath, _ as mapJsonApiRequestToProxy, a as LegacyJsonApiClient, b as resolveJsonApiBase, c as DEFAULT_JSONAPI_PREFIX, d as JSONAPI_PROXY_SESSION_EXPIRED, f as JSONAPI_PROXY_SESSION_HEADER, g as isSafeProxyPath, h as ResolvedJsonApiProxyPath, i as JsonApiRuntimeConfig, l as DEFAULT_ROUTER_PREFIX, m as JsonApiProxyEndpoints, n as DraftSessionError, o as createJsonApiClient, p as JsonApiProxyEndpointName, r as JsonApiClientConfig, s as isDraftSessionError, t as CanvasJsonApiClient, u as JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, v as mapProxyPathToUpstream, x as resolveJsonApiProxyPath, y as normalizeBaseUrl } from "./jsonapi-client-BAQ3V5CC.js";
|
|
2
2
|
export * from "@drupal-api-client/json-api-client";
|
|
3
|
-
export { CanvasJsonApiClient as JsonApiClient };
|
|
3
|
+
export { CanvasJsonApiClient, DEFAULT_JSONAPI_PREFIX, DEFAULT_ROUTER_PREFIX, DraftSessionError, JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, JSONAPI_PROXY_SESSION_EXPIRED, JSONAPI_PROXY_SESSION_HEADER, LegacyJsonApiClient as JsonApiClient, JsonApiClientConfig, type JsonApiProxyEndpointName, type JsonApiProxyEndpoints, JsonApiRuntimeConfig, type ResolvedJsonApiProxyPath, createJsonApiClient, isDraftSessionError, isSafeProxyPath, mapJsonApiRequestToProxy, mapProxyPathToUpstream, normalizeBaseUrl, resolveJsonApiBase, resolveJsonApiProxyPath, toBackendRelativePath, trimSlashes };
|
package/dist/jsonapi-client.js
CHANGED
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as toBackendRelativePath, a as isDraftSessionError, c as JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, d as isSafeProxyPath, f as mapJsonApiRequestToProxy, g as resolveJsonApiProxyPath, h as resolveJsonApiBase, i as createJsonApiClient, l as JSONAPI_PROXY_SESSION_EXPIRED, m as normalizeBaseUrl, n as DraftSessionError, o as DEFAULT_JSONAPI_PREFIX, p as mapProxyPathToUpstream, r as LegacyJsonApiClient, s as DEFAULT_ROUTER_PREFIX, t as CanvasJsonApiClient, u as JSONAPI_PROXY_SESSION_HEADER, v as trimSlashes } from "./jsonapi-client-CejP62bM.js";
|
|
2
2
|
export * from "@drupal-api-client/json-api-client";
|
|
3
|
-
|
|
4
|
-
var CanvasJsonApiClient = class extends JsonApiClient {
|
|
5
|
-
constructor(baseUrl, options) {
|
|
6
|
-
if (globalThis?.drupalSettings?.canvasData?.v0?.jsonapiSettings === null) throw new Error("The JSON:API module is not installed. Please install it to use JsonApiClient.");
|
|
7
|
-
const clientBaseUrl = baseUrl || globalThis?.drupalSettings?.canvasData?.v0?.baseUrl;
|
|
8
|
-
if (!baseUrl && !clientBaseUrl) throw new Error("Could not determine your site's base URL for the JSON:API client. If working outside of Drupal Canvas, you can use the @drupal-canvas/vite-plugin to automatically configure it for you. Otherwise you must explicitly provide a base URL, i.e. `const client = new JsonApiClient(\"https://...\")`");
|
|
9
|
-
const clientOptions = {
|
|
10
|
-
apiPrefix: globalThis?.drupalSettings?.canvasData?.v0?.jsonapiSettings?.apiPrefix,
|
|
11
|
-
serializer: new DefaultSerializer(),
|
|
12
|
-
...options
|
|
13
|
-
};
|
|
14
|
-
super(clientBaseUrl, clientOptions);
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
//#endregion
|
|
18
|
-
export { CanvasJsonApiClient as JsonApiClient };
|
|
3
|
+
export { CanvasJsonApiClient, DEFAULT_JSONAPI_PREFIX, DEFAULT_ROUTER_PREFIX, DraftSessionError, JSONAPI_DRAFT_SESSION_EXPIRED_ERROR, JSONAPI_PROXY_SESSION_EXPIRED, JSONAPI_PROXY_SESSION_HEADER, LegacyJsonApiClient as JsonApiClient, createJsonApiClient, isDraftSessionError, isSafeProxyPath, mapJsonApiRequestToProxy, mapProxyPathToUpstream, normalizeBaseUrl, resolveJsonApiBase, resolveJsonApiProxyPath, toBackendRelativePath, trimSlashes };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
//#region src/runtime.ts
|
|
2
|
+
/**
|
|
3
|
+
* The global property holding the marker. Integrations that cannot import this
|
|
4
|
+
* package (Drupal's classic hydration script) set it directly.
|
|
5
|
+
*/
|
|
6
|
+
const CANVAS_RUNTIME_GLOBAL = "__drupalCanvasRuntime";
|
|
7
|
+
/**
|
|
8
|
+
* Declares the current runtime environment. Called by Drupal and Workbench
|
|
9
|
+
* integrations, never by Code Components or headless applications.
|
|
10
|
+
*/
|
|
11
|
+
function declareCanvasRuntime(environment) {
|
|
12
|
+
globalThis[CANVAS_RUNTIME_GLOBAL] = { environment };
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Returns the declared runtime environment, or `null` outside Drupal and
|
|
16
|
+
* Workbench.
|
|
17
|
+
*/
|
|
18
|
+
function getCanvasRuntime() {
|
|
19
|
+
const marker = globalThis[CANVAS_RUNTIME_GLOBAL];
|
|
20
|
+
if (marker !== null && typeof marker === "object" && (marker.environment === "drupal" || marker.environment === "workbench")) return marker.environment;
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Whether the legacy runtime APIs are supported in the current environment.
|
|
25
|
+
*/
|
|
26
|
+
function isLegacyRuntimeSupported() {
|
|
27
|
+
return getCanvasRuntime() !== null;
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/migration.ts
|
|
31
|
+
/**
|
|
32
|
+
* @file
|
|
33
|
+
* Migration guidance shared by the legacy API errors, the hook warnings, and
|
|
34
|
+
* the Canvas CLI's pull codemod report.
|
|
35
|
+
*/
|
|
36
|
+
/**
|
|
37
|
+
* The AI-agent migration prompt included in legacy API errors and printed by
|
|
38
|
+
* the Canvas CLI for components it could not migrate automatically.
|
|
39
|
+
*/
|
|
40
|
+
const AGENT_MIGRATION_PROMPT = "Replace `getPageData()`, `getSiteData()`, and `new JsonApiClient()` with `usePageContext()`, `useSiteContext()`, and `useJsonApiClient()` from `drupal-canvas/react` in function components or custom hooks. Call hooks unconditionally at the top level before any possible return; handle missing context or clients. Outside components and custom hooks, use SDK page context data or `getClient()` in headless server code; pass data or a client to browser helpers. Preserve output, types, hook order, and access controls. Never expose credentials.";
|
|
41
|
+
/** Replacement guidance per legacy API. */
|
|
42
|
+
const LEGACY_API_GUIDANCE = {
|
|
43
|
+
"getPageData()": "Use `usePageContext()` in React components, or read `page.context.page` from the Headless SDK's page response outside components.",
|
|
44
|
+
"getSiteData()": "Use `useSiteContext()` in React components, or read `page.context.site` from the Headless SDK's page response outside components.",
|
|
45
|
+
"new JsonApiClient()": "Use `useJsonApiClient()` in React components, or the Headless SDK's `getClient()` in headless server code."
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Builds the error message thrown when a legacy API is invoked outside Drupal
|
|
49
|
+
* and Workbench.
|
|
50
|
+
*/
|
|
51
|
+
function formatLegacyApiError(api) {
|
|
52
|
+
return `[drupal-canvas] ${api} is only supported in Drupal-rendered Code Components and Canvas Workbench previews; it is not available in this environment. ${LEGACY_API_GUIDANCE[api]}\n\nMigration prompt for AI agents: ${AGENT_MIGRATION_PROMPT}`;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Throws the actionable migration error for a legacy API when the current
|
|
56
|
+
* environment is neither Drupal nor Workbench. Importing the API is always
|
|
57
|
+
* allowed; only invoking it is guarded.
|
|
58
|
+
*/
|
|
59
|
+
function assertLegacyRuntime(api) {
|
|
60
|
+
if (!isLegacyRuntimeSupported()) throw new Error(formatLegacyApiError(api));
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { declareCanvasRuntime as a, formatLegacyApiError as i, LEGACY_API_GUIDANCE as n, getCanvasRuntime as o, assertLegacyRuntime as r, isLegacyRuntimeSupported as s, AGENT_MIGRATION_PROMPT as t };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { a as useSiteContext, i as usePageContext, n as CanvasContextProviderProps, r as useHasCanvasContext, t as CanvasContextProvider } from "./context-Cb4HbPbR.js";
|
|
2
|
+
import { a as LegacyJsonApiClient } from "./jsonapi-client-BAQ3V5CC.js";
|
|
3
|
+
import { ReactNode } from "react";
|
|
4
|
+
//#region src/jsonapi-client-context.d.ts
|
|
5
|
+
interface JsonApiClientProviderProps {
|
|
6
|
+
client: LegacyJsonApiClient;
|
|
7
|
+
children?: ReactNode;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Makes a configured JSON:API client available to every React descendant.
|
|
11
|
+
* It does not construct the client or manage authentication.
|
|
12
|
+
*/
|
|
13
|
+
declare function JsonApiClientProvider({ client, children }: JsonApiClientProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
14
|
+
/**
|
|
15
|
+
* Returns the nearest provider's client, or `null` with a deduplicated
|
|
16
|
+
* warning when no provider exists. The hook never fetches data or creates a
|
|
17
|
+
* client on render.
|
|
18
|
+
*/
|
|
19
|
+
declare function useJsonApiClient(): LegacyJsonApiClient | null;
|
|
20
|
+
/**
|
|
21
|
+
* Whether a `JsonApiClientProvider` is mounted above the calling component.
|
|
22
|
+
*/
|
|
23
|
+
declare function useHasJsonApiClient(): boolean;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { CanvasContextProvider, type CanvasContextProviderProps, JsonApiClientProvider, type JsonApiClientProviderProps, useHasCanvasContext, useHasJsonApiClient, useJsonApiClient, usePageContext, useSiteContext };
|