@okam/directus-next 1.2.0 → 1.2.2

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/index.mjs CHANGED
@@ -1,24 +1,292 @@
1
- import { getPathFromRoute, default as default2, parseDraftParams } from "./draft/route.mjs";
2
- import { getDraftSecretDefault } from "./draft/env.mjs";
3
- import { getApiRouteUrlDefault, getRedirectSecretDefault } from "./redirect/env.mjs";
4
- import { default as default3, parseRedirectParams } from "./redirect/route.mjs";
5
- import { getRedirectsRoute } from "./redirect/utils/getRedirectsRoute.mjs";
6
- import { handleRedirect } from "./redirect/utils/handleRedirect.mjs";
7
- import { logger } from "./logger.mjs";
8
- import { directusRouteRouter } from "./lib/directusRouteRouter.mjs";
9
- import { getJsonErrorResponse } from "./response.mjs";
1
+ import { draftMode } from "next/headers";
2
+ import { redirect } from "next/navigation";
3
+ import { template } from "radashi";
4
+ import { g as getRedirectSecretDefault } from "./directusRouteRouter-Bt3bEq4S.mjs";
5
+ import { l, d, b, a, h } from "./directusRouteRouter-Bt3bEq4S.mjs";
6
+ import { logger } from "@okam/logger";
7
+ import { normalizePath } from "@okam/core-lib";
8
+ function getJsonErrorResponse(data, status) {
9
+ const headers = {
10
+ // eslint-disable-next-line @typescript-eslint/naming-convention
11
+ "Content-Type": "text/json; charset=UTF-8"
12
+ };
13
+ const body = JSON.stringify(data);
14
+ return new Response(body, {
15
+ status,
16
+ headers
17
+ });
18
+ }
19
+ function getDraftSecretDefault() {
20
+ return process.env.NEXT_API_DRAFT_SECRET || "";
21
+ }
22
+ function parseDraftParams(url) {
23
+ const { searchParams } = new URL(url);
24
+ const secret = searchParams.get("secret") || "";
25
+ const languagesParam = searchParams.get("languages");
26
+ const pathsParam = searchParams.get("urls");
27
+ const routesParam = searchParams.get("routes");
28
+ const pkParam = searchParams.get("pk");
29
+ const versionParam = searchParams.get("version");
30
+ const emptyReturn = {
31
+ secret: "",
32
+ languages: [],
33
+ paths: [],
34
+ routes: [],
35
+ type: "",
36
+ pk: "",
37
+ version: ""
38
+ };
39
+ if (!secret || !languagesParam || !(pathsParam || routesParam)) {
40
+ return emptyReturn;
41
+ }
42
+ const pk = typeof pkParam === "string" ? pkParam : "";
43
+ const version = typeof versionParam === "string" ? versionParam : "";
44
+ try {
45
+ const languages = JSON.parse(languagesParam);
46
+ if (routesParam) {
47
+ const routes = JSON.parse(routesParam);
48
+ return {
49
+ secret,
50
+ languages,
51
+ paths: [],
52
+ routes,
53
+ type: "route",
54
+ pk,
55
+ version
56
+ };
57
+ }
58
+ if (!pathsParam) {
59
+ return emptyReturn;
60
+ }
61
+ const paths = JSON.parse(pathsParam);
62
+ return {
63
+ secret,
64
+ languages,
65
+ paths,
66
+ routes: [],
67
+ type: "path",
68
+ pk,
69
+ version
70
+ };
71
+ } catch (e) {
72
+ return emptyReturn;
73
+ }
74
+ }
75
+ function getPathFromRoute(routeUrl, url, index = 0) {
76
+ const { searchParams } = new URL(url);
77
+ const matches = [...routeUrl.matchAll(/\{\{([a-z]+)\}\}/gi)];
78
+ const map = {};
79
+ matches.forEach((match) => {
80
+ const key = match[1] || "";
81
+ if (!key) {
82
+ return;
83
+ }
84
+ const listkey = `${key}s`;
85
+ const listParam = searchParams.get(listkey);
86
+ if (listParam) {
87
+ try {
88
+ const list = JSON.parse(listParam);
89
+ map[key] = list[index] || "";
90
+ } catch (e) {
91
+ map[key] = "";
92
+ }
93
+ } else {
94
+ const param = searchParams.get(key);
95
+ map[key] = param || "";
96
+ }
97
+ });
98
+ return template(routeUrl, map);
99
+ }
100
+ function handleDraftRoute({
101
+ url,
102
+ getDirectusLanguage,
103
+ getDraftSecret,
104
+ getJsonError
105
+ }) {
106
+ const getSecretFunction = getDraftSecret || getDraftSecretDefault;
107
+ const getJsonErrorResponseFunction = getJsonError || getJsonErrorResponse;
108
+ const { secret, languages, paths, routes, type, version } = parseDraftParams(url);
109
+ if (secret !== getSecretFunction()) {
110
+ return getJsonErrorResponseFunction({ error: "Invalid argument" }, 401);
111
+ }
112
+ if (type === "") {
113
+ return getJsonErrorResponseFunction({ error: "Invalid argument" }, 400);
114
+ }
115
+ if (!Array.isArray(languages) || languages.length <= 0) {
116
+ return getJsonErrorResponseFunction({ error: "Invalid languages argument" }, 400);
117
+ }
118
+ if (type === "path" && (!Array.isArray(paths) || paths.length <= 0)) {
119
+ return getJsonErrorResponseFunction({ error: "Invalid paths argument" }, 400);
120
+ }
121
+ if (type === "route" && (!Array.isArray(routes) || routes.length <= 0)) {
122
+ return getJsonErrorResponseFunction({ error: "Invalid routes argument" }, 400);
123
+ }
124
+ const directusLang = getDirectusLanguage();
125
+ const indexDefault = languages.indexOf(directusLang);
126
+ const index = indexDefault !== -1 ? indexDefault : 0;
127
+ let redirectUrl = "";
128
+ if (type === "path") {
129
+ const path = paths[index] || "";
130
+ if (!path) {
131
+ return getJsonErrorResponse({ error: "Invalid path" }, 400);
132
+ }
133
+ redirectUrl = path;
134
+ } else if (type === "route") {
135
+ const route = routes[index] || "";
136
+ if (!route) {
137
+ return getJsonErrorResponse({ error: "Invalid route" }, 400);
138
+ }
139
+ const pathFromRoute = getPathFromRoute(route, url, index);
140
+ if (!pathFromRoute) {
141
+ return getJsonErrorResponse({ error: "Invalid route" }, 400);
142
+ }
143
+ redirectUrl = pathFromRoute;
144
+ }
145
+ if (redirectUrl && version) {
146
+ const withParams = redirectUrl.indexOf("?") !== -1;
147
+ redirectUrl = `${redirectUrl}${withParams ? "&" : "?"}version=${encodeURIComponent(version)}`;
148
+ }
149
+ draftMode().enable();
150
+ redirect(redirectUrl);
151
+ return void 0;
152
+ }
153
+ function isRedirect(redirect2) {
154
+ return !!redirect2 && typeof redirect2 === "object" && "source" in redirect2 && "destination" in redirect2;
155
+ }
156
+ function normalizeRedirects(redirects) {
157
+ if (!redirects || !Array.isArray(redirects)) return [];
158
+ return redirects.flatMap((redirect2) => {
159
+ const { source, destination, ...rest } = redirect2 ?? {};
160
+ if (!redirect2 || !source || !destination || !isRedirect(redirect2)) return [];
161
+ return [
162
+ {
163
+ ...rest,
164
+ source: normalizePath(source),
165
+ destination: normalizePath(destination)
166
+ }
167
+ ];
168
+ });
169
+ }
170
+ const redirectDefaultLimit = 2e3;
171
+ function getDefaultConfig() {
172
+ return {
173
+ graphqlEndpoint: process.env["NEXT_REDIRECT_GRAPHQL_URL"] || process.env["NEXT_PUBLIC_GRAPHQL_URL"] || "",
174
+ graphqlApiKey: process.env["NEXT_API_TOKEN_ADMIN"] || "",
175
+ redirectsFilename: "./redirect/redirects.json",
176
+ rewritesFilename: "./redirect/rewrites.json",
177
+ limit: redirectDefaultLimit
178
+ };
179
+ }
180
+ async function fetchRedirectsData(config, init) {
181
+ const {
182
+ graphqlApiKey: defaultGraphqlApiKey,
183
+ graphqlEndpoint: defaultGraphqlEndpoint,
184
+ limit: defaultLimit
185
+ } = getDefaultConfig();
186
+ const {
187
+ graphqlEndpoint = defaultGraphqlEndpoint,
188
+ graphqlApiKey = defaultGraphqlApiKey,
189
+ limit = defaultLimit
190
+ } = config;
191
+ if (!graphqlEndpoint) {
192
+ throw new Error(
193
+ "Missing fetchRedirects configuration `graphqlEndpoint`. Check environment variables NEXT_REDIRECT_GRAPHQL_URL or NEXT_PUBLIC_GRAPHQL_URL"
194
+ );
195
+ }
196
+ if (!graphqlApiKey) {
197
+ throw new Error(
198
+ "Missing fetchRedirects configuration `graphqlApiKey`. Check environment variable NEXT_API_TOKEN_ADMIN"
199
+ );
200
+ }
201
+ const query = `query fetchRedirects($limit: Int = 2000) {
202
+ redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:false}}, sort: "sort", limit: $limit) {
203
+ source
204
+ destination
205
+ permanent
206
+ locale
207
+ }
208
+ rewrites: redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:true}}, sort: "sort", limit: $limit) {
209
+ source
210
+ destination
211
+ permanent
212
+ locale
213
+ }
214
+ }`;
215
+ const graphqlBody = {
216
+ query,
217
+ // "operationName": "",
218
+ variables: {
219
+ limit: Number(limit) || redirectDefaultLimit
220
+ }
221
+ };
222
+ try {
223
+ const response = await fetch(graphqlEndpoint, {
224
+ ...init,
225
+ method: "POST",
226
+ headers: {
227
+ // eslint-disable-next-line @typescript-eslint/naming-convention
228
+ "Content-Type": "application/json",
229
+ Authorization: `Bearer ${graphqlApiKey}`
230
+ },
231
+ body: JSON.stringify(graphqlBody)
232
+ });
233
+ const { data } = await response.json();
234
+ const { redirects, rewrites } = data ?? {};
235
+ if (!(redirects == null ? void 0 : redirects.length) && !(rewrites == null ? void 0 : rewrites.length)) {
236
+ logger.log("No redirects/rewrites found", "warn");
237
+ return {
238
+ redirects: [],
239
+ rewrites: []
240
+ };
241
+ }
242
+ logger.log(`Fetch redirects count: ${(redirects == null ? void 0 : redirects.length) || 0}, rewrites count: ${(rewrites == null ? void 0 : rewrites.length) || 0}`);
243
+ return {
244
+ redirects: normalizeRedirects(redirects),
245
+ rewrites: normalizeRedirects(rewrites)
246
+ };
247
+ } catch (e) {
248
+ logger.log(`Error fetching redirects: ${e.message}`, "error");
249
+ }
250
+ return {
251
+ redirects: [],
252
+ rewrites: []
253
+ };
254
+ }
255
+ function parseRedirectParams(url) {
256
+ const { searchParams } = new URL(url);
257
+ const secret = searchParams.get("secret") || "";
258
+ return { secret };
259
+ }
260
+ async function handleRedirectsRoute({
261
+ url,
262
+ getRedirectSecret = getRedirectSecretDefault,
263
+ getJsonError = getJsonErrorResponse,
264
+ getDirectusApiToken,
265
+ getDirectusGraphqlUrl,
266
+ limit,
267
+ init
268
+ }) {
269
+ const { secret } = parseRedirectParams(url);
270
+ if (secret !== getRedirectSecret()) {
271
+ return getJsonError({ error: "Invalid argument" }, 401);
272
+ }
273
+ const graphqlEndpoint = getDirectusGraphqlUrl == null ? void 0 : getDirectusGraphqlUrl();
274
+ const graphqlApiKey = getDirectusApiToken == null ? void 0 : getDirectusApiToken();
275
+ const { redirects, rewrites } = await fetchRedirectsData({ graphqlEndpoint, graphqlApiKey, limit }, init);
276
+ return new Response(JSON.stringify({ redirects, rewrites }), { status: 200 });
277
+ }
10
278
  export {
11
- logger as DirectusNextLogger,
12
- directusRouteRouter,
13
- getApiRouteUrlDefault,
279
+ l as DirectusNextLogger,
280
+ d as directusRouteRouter,
281
+ b as getApiRouteUrlDefault,
14
282
  getDraftSecretDefault,
15
283
  getJsonErrorResponse,
16
284
  getPathFromRoute,
17
285
  getRedirectSecretDefault,
18
- getRedirectsRoute,
19
- default2 as handleDraftRoute,
20
- handleRedirect,
21
- default3 as handleRedirectsRoute,
286
+ a as getRedirectsRoute,
287
+ handleDraftRoute,
288
+ h as handleRedirect,
289
+ handleRedirectsRoute,
22
290
  parseDraftParams,
23
291
  parseRedirectParams
24
292
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@okam/directus-next",
3
3
  "main": "./index.js",
4
- "version": "1.2.0",
4
+ "version": "1.2.2",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
7
7
  ".": {
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@okam/core-lib": "1.16.0",
36
- "@okam/directus-node": "0.5.0",
36
+ "@okam/directus-node": "0.6.1",
37
37
  "@okam/logger": "1.1.0",
38
38
  "next": "^14.1.1",
39
39
  "radashi": "^12.3.0",
@@ -1,4 +1,4 @@
1
- import type { TFetchRedirectsResponse } from '@okam/directus-node';
1
+ import type { TFetchRedirectsResponse } from '@okam/directus-node/edge';
2
2
  import type { DirectusRouteRedirectsModule } from '../../types/directusRouteConfig';
3
3
  /**
4
4
  * Gets a response from `options.apiRoute`
package/server.js CHANGED
@@ -1,9 +1,64 @@
1
+ "use server";
1
2
  "use strict";
2
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const directusRouteRouter = require("./lib/directusRouteRouter.js");
4
- const context = require("./pageSettings/context.js");
5
- const usePageSettings = require("./pageSettings/usePageSettings.js");
4
+ const directusRouteRouter = require("./directusRouteRouter-CfK0xrh0.js");
5
+ require("server-only");
6
+ const createServerContext = require("server-only-context");
7
+ const directusQuery = require("@okam/directus-query");
8
+ const radashi = require("radashi");
9
+ function pageSettingsContext(defaultValue) {
10
+ const [pageSettings, setPageSettings2] = createServerContext(defaultValue);
11
+ return [pageSettings, setPageSettings2];
12
+ }
13
+ function pageSettingsVariablesContext(variables) {
14
+ const [pageSettingsVariables, setPageSettingsVariables] = createServerContext(variables);
15
+ return [pageSettingsVariables, setPageSettingsVariables];
16
+ }
17
+ const [getPageSettings, setPageSettings] = pageSettingsContext();
18
+ const [getVariables, setVariables] = pageSettingsVariablesContext();
19
+ function isDirectusRouteConfig(config) {
20
+ return !!config && "localeMap" in config;
21
+ }
22
+ function getDirectusVariables(variables, config) {
23
+ const localeMap = isDirectusRouteConfig(config) ? config.localeMap : config;
24
+ if (!localeMap) {
25
+ return variables;
26
+ }
27
+ const locale = radashi.get(variables, "locale");
28
+ const directusLocale = radashi.invert(localeMap)[locale] ?? locale;
29
+ return { ...variables, locale: directusLocale };
30
+ }
31
+ async function usePageSettings(props, itemKey) {
32
+ var _a, _b, _c, _d, _e;
33
+ const { variables, config } = props ?? {};
34
+ const directusVariables = getDirectusVariables(variables, config);
35
+ const defaultReturn = getPageSettings() ?? {};
36
+ if (!props || radashi.isEqual(getVariables(), directusVariables)) {
37
+ directusRouteRouter.log("Using cached page settings", { path: (_c = (_b = (_a = defaultReturn.page_settings) == null ? void 0 : _a.translations) == null ? void 0 : _b[0]) == null ? void 0 : _c.path });
38
+ return defaultReturn;
39
+ }
40
+ const { document } = props;
41
+ const key = itemKey ?? radashi.get(document, "definitions[0].selectionSet.selections[0].name.value");
42
+ directusRouteRouter.log("Querying new page settings", directusVariables);
43
+ const result = await directusQuery.queryGql(document, directusVariables);
44
+ const items = result == null ? void 0 : result[key];
45
+ const currentItem = Array.isArray(items) ? items == null ? void 0 : items[0] : items;
46
+ const currentPageSettings = currentItem == null ? void 0 : currentItem.page_settings;
47
+ const currentPath = (_e = (_d = currentPageSettings == null ? void 0 : currentPageSettings.translations) == null ? void 0 : _d[0]) == null ? void 0 : _e.path;
48
+ if (!currentItem) {
49
+ directusRouteRouter.log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
50
+ return defaultReturn;
51
+ }
52
+ if (!currentPageSettings) {
53
+ directusRouteRouter.log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
54
+ return defaultReturn;
55
+ }
56
+ directusRouteRouter.log("Caching new page settings", { path: currentPath });
57
+ setPageSettings(currentItem);
58
+ setVariables(variables);
59
+ return currentItem;
60
+ }
6
61
  exports.directusRouteRouter = directusRouteRouter.directusRouteRouter;
7
- exports.pageSettingsContext = context.pageSettingsContext;
8
- exports.pageSettingsVariablesContext = context.pageSettingsVariablesContext;
9
- exports.usePageSettings = usePageSettings.usePageSettings;
62
+ exports.pageSettingsContext = pageSettingsContext;
63
+ exports.pageSettingsVariablesContext = pageSettingsVariablesContext;
64
+ exports.usePageSettings = usePageSettings;
package/server.mjs CHANGED
@@ -1,8 +1,64 @@
1
- import { directusRouteRouter } from "./lib/directusRouteRouter.mjs";
2
- import { pageSettingsContext, pageSettingsVariablesContext } from "./pageSettings/context.mjs";
3
- import { usePageSettings } from "./pageSettings/usePageSettings.mjs";
1
+ "use server";
2
+ import { c as log } from "./directusRouteRouter-Bt3bEq4S.mjs";
3
+ import { d } from "./directusRouteRouter-Bt3bEq4S.mjs";
4
+ import "server-only";
5
+ import createServerContext from "server-only-context";
6
+ import { queryGql } from "@okam/directus-query";
7
+ import { isEqual, get, invert } from "radashi";
8
+ function pageSettingsContext(defaultValue) {
9
+ const [pageSettings, setPageSettings2] = createServerContext(defaultValue);
10
+ return [pageSettings, setPageSettings2];
11
+ }
12
+ function pageSettingsVariablesContext(variables) {
13
+ const [pageSettingsVariables, setPageSettingsVariables] = createServerContext(variables);
14
+ return [pageSettingsVariables, setPageSettingsVariables];
15
+ }
16
+ const [getPageSettings, setPageSettings] = pageSettingsContext();
17
+ const [getVariables, setVariables] = pageSettingsVariablesContext();
18
+ function isDirectusRouteConfig(config) {
19
+ return !!config && "localeMap" in config;
20
+ }
21
+ function getDirectusVariables(variables, config) {
22
+ const localeMap = isDirectusRouteConfig(config) ? config.localeMap : config;
23
+ if (!localeMap) {
24
+ return variables;
25
+ }
26
+ const locale = get(variables, "locale");
27
+ const directusLocale = invert(localeMap)[locale] ?? locale;
28
+ return { ...variables, locale: directusLocale };
29
+ }
30
+ async function usePageSettings(props, itemKey) {
31
+ var _a, _b, _c, _d, _e;
32
+ const { variables, config } = props ?? {};
33
+ const directusVariables = getDirectusVariables(variables, config);
34
+ const defaultReturn = getPageSettings() ?? {};
35
+ if (!props || isEqual(getVariables(), directusVariables)) {
36
+ log("Using cached page settings", { path: (_c = (_b = (_a = defaultReturn.page_settings) == null ? void 0 : _a.translations) == null ? void 0 : _b[0]) == null ? void 0 : _c.path });
37
+ return defaultReturn;
38
+ }
39
+ const { document } = props;
40
+ const key = itemKey ?? get(document, "definitions[0].selectionSet.selections[0].name.value");
41
+ log("Querying new page settings", directusVariables);
42
+ const result = await queryGql(document, directusVariables);
43
+ const items = result == null ? void 0 : result[key];
44
+ const currentItem = Array.isArray(items) ? items == null ? void 0 : items[0] : items;
45
+ const currentPageSettings = currentItem == null ? void 0 : currentItem.page_settings;
46
+ const currentPath = (_e = (_d = currentPageSettings == null ? void 0 : currentPageSettings.translations) == null ? void 0 : _d[0]) == null ? void 0 : _e.path;
47
+ if (!currentItem) {
48
+ log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
49
+ return defaultReturn;
50
+ }
51
+ if (!currentPageSettings) {
52
+ log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
53
+ return defaultReturn;
54
+ }
55
+ log("Caching new page settings", { path: currentPath });
56
+ setPageSettings(currentItem);
57
+ setVariables(variables);
58
+ return currentItem;
59
+ }
4
60
  export {
5
- directusRouteRouter,
61
+ d as directusRouteRouter,
6
62
  pageSettingsContext,
7
63
  pageSettingsVariablesContext,
8
64
  usePageSettings
package/draft/env.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- function getDraftSecretDefault() {
4
- return process.env.NEXT_API_DRAFT_SECRET || "";
5
- }
6
- exports.getDraftSecretDefault = getDraftSecretDefault;
package/draft/env.mjs DELETED
@@ -1,6 +0,0 @@
1
- function getDraftSecretDefault() {
2
- return process.env.NEXT_API_DRAFT_SECRET || "";
3
- }
4
- export {
5
- getDraftSecretDefault
6
- };
package/draft/route.js DELETED
@@ -1,141 +0,0 @@
1
- "use strict";
2
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const headers = require("next/headers");
4
- const navigation = require("next/navigation");
5
- const radashi = require("radashi");
6
- const response = require("../response.js");
7
- const env = require("./env.js");
8
- function parseDraftParams(url) {
9
- const { searchParams } = new URL(url);
10
- const secret = searchParams.get("secret") || "";
11
- const languagesParam = searchParams.get("languages");
12
- const pathsParam = searchParams.get("urls");
13
- const routesParam = searchParams.get("routes");
14
- const pkParam = searchParams.get("pk");
15
- const versionParam = searchParams.get("version");
16
- const emptyReturn = {
17
- secret: "",
18
- languages: [],
19
- paths: [],
20
- routes: [],
21
- type: "",
22
- pk: "",
23
- version: ""
24
- };
25
- if (!secret || !languagesParam || !(pathsParam || routesParam)) {
26
- return emptyReturn;
27
- }
28
- const pk = typeof pkParam === "string" ? pkParam : "";
29
- const version = typeof versionParam === "string" ? versionParam : "";
30
- try {
31
- const languages = JSON.parse(languagesParam);
32
- if (routesParam) {
33
- const routes = JSON.parse(routesParam);
34
- return {
35
- secret,
36
- languages,
37
- paths: [],
38
- routes,
39
- type: "route",
40
- pk,
41
- version
42
- };
43
- }
44
- if (!pathsParam) {
45
- return emptyReturn;
46
- }
47
- const paths = JSON.parse(pathsParam);
48
- return {
49
- secret,
50
- languages,
51
- paths,
52
- routes: [],
53
- type: "path",
54
- pk,
55
- version
56
- };
57
- } catch (e) {
58
- return emptyReturn;
59
- }
60
- }
61
- function getPathFromRoute(routeUrl, url, index = 0) {
62
- const { searchParams } = new URL(url);
63
- const matches = [...routeUrl.matchAll(/\{\{([a-z]+)\}\}/gi)];
64
- const map = {};
65
- matches.forEach((match) => {
66
- const key = match[1] || "";
67
- if (!key) {
68
- return;
69
- }
70
- const listkey = `${key}s`;
71
- const listParam = searchParams.get(listkey);
72
- if (listParam) {
73
- try {
74
- const list = JSON.parse(listParam);
75
- map[key] = list[index] || "";
76
- } catch (e) {
77
- map[key] = "";
78
- }
79
- } else {
80
- const param = searchParams.get(key);
81
- map[key] = param || "";
82
- }
83
- });
84
- return radashi.template(routeUrl, map);
85
- }
86
- function handleDraftRoute({
87
- url,
88
- getDirectusLanguage,
89
- getDraftSecret,
90
- getJsonError
91
- }) {
92
- const getSecretFunction = getDraftSecret || env.getDraftSecretDefault;
93
- const getJsonErrorResponseFunction = getJsonError || response.getJsonErrorResponse;
94
- const { secret, languages, paths, routes, type, version } = parseDraftParams(url);
95
- if (secret !== getSecretFunction()) {
96
- return getJsonErrorResponseFunction({ error: "Invalid argument" }, 401);
97
- }
98
- if (type === "") {
99
- return getJsonErrorResponseFunction({ error: "Invalid argument" }, 400);
100
- }
101
- if (!Array.isArray(languages) || languages.length <= 0) {
102
- return getJsonErrorResponseFunction({ error: "Invalid languages argument" }, 400);
103
- }
104
- if (type === "path" && (!Array.isArray(paths) || paths.length <= 0)) {
105
- return getJsonErrorResponseFunction({ error: "Invalid paths argument" }, 400);
106
- }
107
- if (type === "route" && (!Array.isArray(routes) || routes.length <= 0)) {
108
- return getJsonErrorResponseFunction({ error: "Invalid routes argument" }, 400);
109
- }
110
- const directusLang = getDirectusLanguage();
111
- const indexDefault = languages.indexOf(directusLang);
112
- const index = indexDefault !== -1 ? indexDefault : 0;
113
- let redirectUrl = "";
114
- if (type === "path") {
115
- const path = paths[index] || "";
116
- if (!path) {
117
- return response.getJsonErrorResponse({ error: "Invalid path" }, 400);
118
- }
119
- redirectUrl = path;
120
- } else if (type === "route") {
121
- const route = routes[index] || "";
122
- if (!route) {
123
- return response.getJsonErrorResponse({ error: "Invalid route" }, 400);
124
- }
125
- const pathFromRoute = getPathFromRoute(route, url, index);
126
- if (!pathFromRoute) {
127
- return response.getJsonErrorResponse({ error: "Invalid route" }, 400);
128
- }
129
- redirectUrl = pathFromRoute;
130
- }
131
- if (redirectUrl && version) {
132
- const withParams = redirectUrl.indexOf("?") !== -1;
133
- redirectUrl = `${redirectUrl}${withParams ? "&" : "?"}version=${encodeURIComponent(version)}`;
134
- }
135
- headers.draftMode().enable();
136
- navigation.redirect(redirectUrl);
137
- return void 0;
138
- }
139
- exports.default = handleDraftRoute;
140
- exports.getPathFromRoute = getPathFromRoute;
141
- exports.parseDraftParams = parseDraftParams;