@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/draft/route.mjs DELETED
@@ -1,141 +0,0 @@
1
- import { draftMode } from "next/headers";
2
- import { redirect } from "next/navigation";
3
- import { template } from "radashi";
4
- import { getJsonErrorResponse } from "../response.mjs";
5
- import { getDraftSecretDefault } from "./env.mjs";
6
- function parseDraftParams(url) {
7
- const { searchParams } = new URL(url);
8
- const secret = searchParams.get("secret") || "";
9
- const languagesParam = searchParams.get("languages");
10
- const pathsParam = searchParams.get("urls");
11
- const routesParam = searchParams.get("routes");
12
- const pkParam = searchParams.get("pk");
13
- const versionParam = searchParams.get("version");
14
- const emptyReturn = {
15
- secret: "",
16
- languages: [],
17
- paths: [],
18
- routes: [],
19
- type: "",
20
- pk: "",
21
- version: ""
22
- };
23
- if (!secret || !languagesParam || !(pathsParam || routesParam)) {
24
- return emptyReturn;
25
- }
26
- const pk = typeof pkParam === "string" ? pkParam : "";
27
- const version = typeof versionParam === "string" ? versionParam : "";
28
- try {
29
- const languages = JSON.parse(languagesParam);
30
- if (routesParam) {
31
- const routes = JSON.parse(routesParam);
32
- return {
33
- secret,
34
- languages,
35
- paths: [],
36
- routes,
37
- type: "route",
38
- pk,
39
- version
40
- };
41
- }
42
- if (!pathsParam) {
43
- return emptyReturn;
44
- }
45
- const paths = JSON.parse(pathsParam);
46
- return {
47
- secret,
48
- languages,
49
- paths,
50
- routes: [],
51
- type: "path",
52
- pk,
53
- version
54
- };
55
- } catch (e) {
56
- return emptyReturn;
57
- }
58
- }
59
- function getPathFromRoute(routeUrl, url, index = 0) {
60
- const { searchParams } = new URL(url);
61
- const matches = [...routeUrl.matchAll(/\{\{([a-z]+)\}\}/gi)];
62
- const map = {};
63
- matches.forEach((match) => {
64
- const key = match[1] || "";
65
- if (!key) {
66
- return;
67
- }
68
- const listkey = `${key}s`;
69
- const listParam = searchParams.get(listkey);
70
- if (listParam) {
71
- try {
72
- const list = JSON.parse(listParam);
73
- map[key] = list[index] || "";
74
- } catch (e) {
75
- map[key] = "";
76
- }
77
- } else {
78
- const param = searchParams.get(key);
79
- map[key] = param || "";
80
- }
81
- });
82
- return template(routeUrl, map);
83
- }
84
- function handleDraftRoute({
85
- url,
86
- getDirectusLanguage,
87
- getDraftSecret,
88
- getJsonError
89
- }) {
90
- const getSecretFunction = getDraftSecret || getDraftSecretDefault;
91
- const getJsonErrorResponseFunction = getJsonError || getJsonErrorResponse;
92
- const { secret, languages, paths, routes, type, version } = parseDraftParams(url);
93
- if (secret !== getSecretFunction()) {
94
- return getJsonErrorResponseFunction({ error: "Invalid argument" }, 401);
95
- }
96
- if (type === "") {
97
- return getJsonErrorResponseFunction({ error: "Invalid argument" }, 400);
98
- }
99
- if (!Array.isArray(languages) || languages.length <= 0) {
100
- return getJsonErrorResponseFunction({ error: "Invalid languages argument" }, 400);
101
- }
102
- if (type === "path" && (!Array.isArray(paths) || paths.length <= 0)) {
103
- return getJsonErrorResponseFunction({ error: "Invalid paths argument" }, 400);
104
- }
105
- if (type === "route" && (!Array.isArray(routes) || routes.length <= 0)) {
106
- return getJsonErrorResponseFunction({ error: "Invalid routes argument" }, 400);
107
- }
108
- const directusLang = getDirectusLanguage();
109
- const indexDefault = languages.indexOf(directusLang);
110
- const index = indexDefault !== -1 ? indexDefault : 0;
111
- let redirectUrl = "";
112
- if (type === "path") {
113
- const path = paths[index] || "";
114
- if (!path) {
115
- return getJsonErrorResponse({ error: "Invalid path" }, 400);
116
- }
117
- redirectUrl = path;
118
- } else if (type === "route") {
119
- const route = routes[index] || "";
120
- if (!route) {
121
- return getJsonErrorResponse({ error: "Invalid route" }, 400);
122
- }
123
- const pathFromRoute = getPathFromRoute(route, url, index);
124
- if (!pathFromRoute) {
125
- return getJsonErrorResponse({ error: "Invalid route" }, 400);
126
- }
127
- redirectUrl = pathFromRoute;
128
- }
129
- if (redirectUrl && version) {
130
- const withParams = redirectUrl.indexOf("?") !== -1;
131
- redirectUrl = `${redirectUrl}${withParams ? "&" : "?"}version=${encodeURIComponent(version)}`;
132
- }
133
- draftMode().enable();
134
- redirect(redirectUrl);
135
- return void 0;
136
- }
137
- export {
138
- handleDraftRoute as default,
139
- getPathFromRoute,
140
- parseDraftParams
141
- };
@@ -1,102 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const server = require("next/server");
4
- const logger = require("../logger.js");
5
- const handleRedirect = require("../redirect/utils/handleRedirect.js");
6
- async function fetchPageSettingsTranslation(path) {
7
- const graphqlEndpoint = process.env.NEXT_SERVER_GRAPHQL_URL || process.env.NEXT_PUBLIC_GRAPHQL_URL;
8
- const graphqlApiKey = process.env.NEXT_PUBLIC_API_TOKEN;
9
- if (!graphqlEndpoint) {
10
- throw new Error("Missing GraphQL configuration `graphqlEndpoint`");
11
- }
12
- if (!graphqlApiKey) {
13
- throw new Error("Missing GraphQL configuration `graphqlApiKey`");
14
- }
15
- const query = `
16
- query Languages_code($filter: page_settings_translations_filter) {
17
- page_settings_translations(filter: $filter) {
18
- languages_code {
19
- code
20
- }
21
- id
22
- page_settings_id {
23
- belongs_to_collection
24
- belongs_to_key
25
- }
26
- title
27
- slug
28
- path
29
- }
30
- }
31
- `;
32
- const variables = {
33
- filter: {
34
- path: { _eq: path },
35
- _and: [{ page_settings_id: { belongs_to_key: { _nempty: true } } }]
36
- }
37
- };
38
- try {
39
- logger.log("Executing GraphQL query:", query);
40
- logger.log("Query variables:", variables);
41
- const response = await fetch(graphqlEndpoint, {
42
- method: "POST",
43
- headers: {
44
- "Content-Type": "application/json",
45
- Authorization: `Bearer ${graphqlApiKey}`
46
- },
47
- body: JSON.stringify({ query, variables })
48
- });
49
- const { data } = await response.json();
50
- logger.log("GraphQL response:", data);
51
- return data.page_settings_translations;
52
- } catch (error) {
53
- logger.log("GraphQL Error:", error);
54
- return null;
55
- }
56
- }
57
- function removeLocaleFromPathname(pathname, config) {
58
- const currentLocale = Object.values(config.localeMap ?? {}).find((locale) => pathname.startsWith(`/${locale}/`));
59
- return { locale: currentLocale, pathname: currentLocale ? pathname.replace(`/${currentLocale}/`, "/") : pathname };
60
- }
61
- async function directusRouteRouter(request, config, NextResponse = server.NextResponse) {
62
- var _a, _b, _c;
63
- const { pathname: localizedPathname } = request.nextUrl;
64
- const { locale, pathname } = removeLocaleFromPathname(localizedPathname, config);
65
- logger.log("Processing request for pathname:", { locale, pathname });
66
- const redirect = await handleRedirect.handleRedirect(request, (_a = config.modules) == null ? void 0 : _a.redirects);
67
- if (redirect) {
68
- return redirect;
69
- }
70
- const translations = await fetchPageSettingsTranslation(pathname);
71
- if (!translations || translations.length === 0) {
72
- logger.log("No translation found for path:", pathname);
73
- return NextResponse.next();
74
- }
75
- const translation = translations[0];
76
- logger.log("Using translation:", translation);
77
- if (!translation.languages_code || !translation.page_settings_id) {
78
- logger.log(`Invalid translation data for path: ${pathname}`, { pathname }, "warn");
79
- return NextResponse.next();
80
- }
81
- const directusLocale = translation.languages_code.code;
82
- const collection = translation.page_settings_id.belongs_to_collection;
83
- const id = translation.page_settings_id.belongs_to_key;
84
- if (!collection) {
85
- logger.log(`PageSettings with id ${id} was found but is not associated with any collection.`, { id }, "warn");
86
- return NextResponse.next();
87
- }
88
- const mappedLocale = ((_b = config.localeMap) == null ? void 0 : _b[directusLocale]) || directusLocale;
89
- const idField = ((_c = config.collectionSettings[collection]) == null ? void 0 : _c.idField) || config.collectionSettings.default.idField;
90
- logger.log("Directus locale:", directusLocale);
91
- logger.log("Mapped locale:", mappedLocale);
92
- logger.log("Collection:", collection);
93
- logger.log("ID Field:", idField);
94
- logger.log("ID:", id);
95
- const newPath = `/${mappedLocale}/${collection}/${id}`;
96
- logger.log(`Rewriting path: ${pathname} -> ${newPath}`);
97
- const url = request.nextUrl.clone();
98
- url.pathname = newPath;
99
- logger.log("Rewriting to URL:", url.toString());
100
- return NextResponse.rewrite(url);
101
- }
102
- exports.directusRouteRouter = directusRouteRouter;
package/logger.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const logger$1 = require("@okam/logger");
4
- const logger = logger$1.createLogger("[DirectusNext]");
5
- function log(msg, context, severity = "log") {
6
- if (process.env.NODE_ENV === "development") {
7
- logger.log(msg, severity, { context });
8
- }
9
- }
10
- exports.log = log;
11
- exports.logger = logger;
package/logger.mjs DELETED
@@ -1,11 +0,0 @@
1
- import { createLogger } from "@okam/logger";
2
- const logger = createLogger("[DirectusNext]");
3
- function log(msg, context, severity = "log") {
4
- if (process.env.NODE_ENV === "development") {
5
- logger.log(msg, severity, { context });
6
- }
7
- }
8
- export {
9
- log,
10
- logger
11
- };
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- require("server-only");
4
- const createServerContext = require("server-only-context");
5
- function pageSettingsContext(defaultValue) {
6
- const [pageSettings, setPageSettings] = createServerContext(defaultValue);
7
- return [pageSettings, setPageSettings];
8
- }
9
- function pageSettingsVariablesContext(variables) {
10
- const [pageSettingsVariables, setPageSettingsVariables] = createServerContext(variables);
11
- return [pageSettingsVariables, setPageSettingsVariables];
12
- }
13
- exports.pageSettingsContext = pageSettingsContext;
14
- exports.pageSettingsVariablesContext = pageSettingsVariablesContext;
@@ -1,14 +0,0 @@
1
- import "server-only";
2
- import createServerContext from "server-only-context";
3
- function pageSettingsContext(defaultValue) {
4
- const [pageSettings, setPageSettings] = createServerContext(defaultValue);
5
- return [pageSettings, setPageSettings];
6
- }
7
- function pageSettingsVariablesContext(variables) {
8
- const [pageSettingsVariables, setPageSettingsVariables] = createServerContext(variables);
9
- return [pageSettingsVariables, setPageSettingsVariables];
10
- }
11
- export {
12
- pageSettingsContext,
13
- pageSettingsVariablesContext
14
- };
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const directusQuery = require("@okam/directus-query");
4
- const radashi = require("radashi");
5
- const logger = require("../logger.js");
6
- const context = require("./context.js");
7
- const [getPageSettings, setPageSettings] = context.pageSettingsContext();
8
- const [getVariables, setVariables] = context.pageSettingsVariablesContext();
9
- function isDirectusRouteConfig(config) {
10
- return !!config && "localeMap" in config;
11
- }
12
- function getDirectusVariables(variables, config) {
13
- const localeMap = isDirectusRouteConfig(config) ? config.localeMap : config;
14
- if (!localeMap) {
15
- return variables;
16
- }
17
- const locale = radashi.get(variables, "locale");
18
- const directusLocale = radashi.invert(localeMap)[locale] ?? locale;
19
- return { ...variables, locale: directusLocale };
20
- }
21
- async function usePageSettings(props, itemKey) {
22
- var _a, _b, _c, _d, _e;
23
- const { variables, config } = props ?? {};
24
- const directusVariables = getDirectusVariables(variables, config);
25
- const defaultReturn = getPageSettings() ?? {};
26
- if (!props || radashi.isEqual(getVariables(), directusVariables)) {
27
- logger.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 });
28
- return defaultReturn;
29
- }
30
- const { document } = props;
31
- const key = itemKey ?? radashi.get(document, "definitions[0].selectionSet.selections[0].name.value");
32
- logger.log("Querying new page settings", directusVariables);
33
- const result = await directusQuery.queryGql(document, directusVariables);
34
- const items = result == null ? void 0 : result[key];
35
- const currentItem = Array.isArray(items) ? items == null ? void 0 : items[0] : items;
36
- const currentPageSettings = currentItem == null ? void 0 : currentItem.page_settings;
37
- const currentPath = (_e = (_d = currentPageSettings == null ? void 0 : currentPageSettings.translations) == null ? void 0 : _d[0]) == null ? void 0 : _e.path;
38
- if (!currentItem) {
39
- logger.log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
40
- return defaultReturn;
41
- }
42
- if (!currentPageSettings) {
43
- logger.log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
44
- return defaultReturn;
45
- }
46
- logger.log("Caching new page settings", { path: currentPath });
47
- setPageSettings(currentItem);
48
- setVariables(variables);
49
- return currentItem;
50
- }
51
- exports.usePageSettings = usePageSettings;
@@ -1,51 +0,0 @@
1
- import { queryGql } from "@okam/directus-query";
2
- import { isEqual, get, invert } from "radashi";
3
- import { log } from "../logger.mjs";
4
- import { pageSettingsContext, pageSettingsVariablesContext } from "./context.mjs";
5
- const [getPageSettings, setPageSettings] = pageSettingsContext();
6
- const [getVariables, setVariables] = pageSettingsVariablesContext();
7
- function isDirectusRouteConfig(config) {
8
- return !!config && "localeMap" in config;
9
- }
10
- function getDirectusVariables(variables, config) {
11
- const localeMap = isDirectusRouteConfig(config) ? config.localeMap : config;
12
- if (!localeMap) {
13
- return variables;
14
- }
15
- const locale = get(variables, "locale");
16
- const directusLocale = invert(localeMap)[locale] ?? locale;
17
- return { ...variables, locale: directusLocale };
18
- }
19
- async function usePageSettings(props, itemKey) {
20
- var _a, _b, _c, _d, _e;
21
- const { variables, config } = props ?? {};
22
- const directusVariables = getDirectusVariables(variables, config);
23
- const defaultReturn = getPageSettings() ?? {};
24
- if (!props || isEqual(getVariables(), directusVariables)) {
25
- 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 });
26
- return defaultReturn;
27
- }
28
- const { document } = props;
29
- const key = itemKey ?? get(document, "definitions[0].selectionSet.selections[0].name.value");
30
- log("Querying new page settings", directusVariables);
31
- const result = await queryGql(document, directusVariables);
32
- const items = result == null ? void 0 : result[key];
33
- const currentItem = Array.isArray(items) ? items == null ? void 0 : items[0] : items;
34
- const currentPageSettings = currentItem == null ? void 0 : currentItem.page_settings;
35
- const currentPath = (_e = (_d = currentPageSettings == null ? void 0 : currentPageSettings.translations) == null ? void 0 : _d[0]) == null ? void 0 : _e.path;
36
- if (!currentItem) {
37
- log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
38
- return defaultReturn;
39
- }
40
- if (!currentPageSettings) {
41
- log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
42
- return defaultReturn;
43
- }
44
- log("Caching new page settings", { path: currentPath });
45
- setPageSettings(currentItem);
46
- setVariables(variables);
47
- return currentItem;
48
- }
49
- export {
50
- usePageSettings
51
- };
package/redirect/env.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const logger = require("../logger.js");
4
- const defaultInternalUrl = "http://localhost:3000";
5
- function getRedirectSecretDefault() {
6
- return process.env.NEXT_API_REDIRECT_SECRET || "";
7
- }
8
- function getVercelUrl() {
9
- const url = process.env.VERCEL_URL;
10
- if (!url) return null;
11
- return `https://${url}`;
12
- }
13
- function getApiRouteUrlDefault() {
14
- const url = process.env.NEXT_MIDDLEWARE_REDIRECT_URL ?? getVercelUrl() ?? defaultInternalUrl;
15
- if (URL.canParse(url)) return url;
16
- logger.log(`Invalid URL ${url}. Falling back to default`, { url }, "warn");
17
- return defaultInternalUrl;
18
- }
19
- exports.getApiRouteUrlDefault = getApiRouteUrlDefault;
20
- exports.getRedirectSecretDefault = getRedirectSecretDefault;
package/redirect/env.mjs DELETED
@@ -1,20 +0,0 @@
1
- import { log } from "../logger.mjs";
2
- const defaultInternalUrl = "http://localhost:3000";
3
- function getRedirectSecretDefault() {
4
- return process.env.NEXT_API_REDIRECT_SECRET || "";
5
- }
6
- function getVercelUrl() {
7
- const url = process.env.VERCEL_URL;
8
- if (!url) return null;
9
- return `https://${url}`;
10
- }
11
- function getApiRouteUrlDefault() {
12
- const url = process.env.NEXT_MIDDLEWARE_REDIRECT_URL ?? getVercelUrl() ?? defaultInternalUrl;
13
- if (URL.canParse(url)) return url;
14
- log(`Invalid URL ${url}. Falling back to default`, { url }, "warn");
15
- return defaultInternalUrl;
16
- }
17
- export {
18
- getApiRouteUrlDefault,
19
- getRedirectSecretDefault
20
- };
package/redirect/route.js DELETED
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const directusNode = require("@okam/directus-node");
4
- const response = require("../response.js");
5
- const env = require("./env.js");
6
- function parseRedirectParams(url) {
7
- const { searchParams } = new URL(url);
8
- const secret = searchParams.get("secret") || "";
9
- return { secret };
10
- }
11
- async function handleRedirectsRoute({
12
- url,
13
- getRedirectSecret = env.getRedirectSecretDefault,
14
- getJsonError = response.getJsonErrorResponse,
15
- getDirectusApiToken,
16
- getDirectusGraphqlUrl,
17
- limit,
18
- init
19
- }) {
20
- const { secret } = parseRedirectParams(url);
21
- if (secret !== getRedirectSecret()) {
22
- return getJsonError({ error: "Invalid argument" }, 401);
23
- }
24
- const graphqlEndpoint = getDirectusGraphqlUrl == null ? void 0 : getDirectusGraphqlUrl();
25
- const graphqlApiKey = getDirectusApiToken == null ? void 0 : getDirectusApiToken();
26
- const { redirects, rewrites } = await directusNode.fetchRedirectsData({ graphqlEndpoint, graphqlApiKey, limit }, init);
27
- return new Response(JSON.stringify({ redirects, rewrites }), { status: 200 });
28
- }
29
- exports.default = handleRedirectsRoute;
30
- exports.parseRedirectParams = parseRedirectParams;
@@ -1,30 +0,0 @@
1
- import { fetchRedirectsData } from "@okam/directus-node";
2
- import { getJsonErrorResponse } from "../response.mjs";
3
- import { getRedirectSecretDefault } from "./env.mjs";
4
- function parseRedirectParams(url) {
5
- const { searchParams } = new URL(url);
6
- const secret = searchParams.get("secret") || "";
7
- return { secret };
8
- }
9
- async function handleRedirectsRoute({
10
- url,
11
- getRedirectSecret = getRedirectSecretDefault,
12
- getJsonError = getJsonErrorResponse,
13
- getDirectusApiToken,
14
- getDirectusGraphqlUrl,
15
- limit,
16
- init
17
- }) {
18
- const { secret } = parseRedirectParams(url);
19
- if (secret !== getRedirectSecret()) {
20
- return getJsonError({ error: "Invalid argument" }, 401);
21
- }
22
- const graphqlEndpoint = getDirectusGraphqlUrl == null ? void 0 : getDirectusGraphqlUrl();
23
- const graphqlApiKey = getDirectusApiToken == null ? void 0 : getDirectusApiToken();
24
- const { redirects, rewrites } = await fetchRedirectsData({ graphqlEndpoint, graphqlApiKey, limit }, init);
25
- return new Response(JSON.stringify({ redirects, rewrites }), { status: 200 });
26
- }
27
- export {
28
- handleRedirectsRoute as default,
29
- parseRedirectParams
30
- };
@@ -1,27 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const logger = require("../../logger.js");
4
- const env = require("../env.js");
5
- const defaultApiRoute = "/api/redirect";
6
- async function getRedirectsRoute({
7
- apiRoute = defaultApiRoute,
8
- getApiRouteUrl = env.getApiRouteUrlDefault,
9
- getRedirectSecret = env.getRedirectSecretDefault
10
- } = {}) {
11
- const secret = getRedirectSecret();
12
- try {
13
- const url = new URL(apiRoute, getApiRouteUrl());
14
- url.searchParams.set("secret", encodeURIComponent(secret));
15
- const response = await fetch(url);
16
- if (!response.ok) {
17
- logger.log(`${apiRoute} not ok. Returned`, { status: response.status }, "error");
18
- return { redirects: [], rewrites: [] };
19
- }
20
- const data = await response.json();
21
- return data;
22
- } catch (error) {
23
- logger.log(`Error fetching redirects from ${apiRoute}.`, { error }, "error");
24
- return { redirects: [], rewrites: [] };
25
- }
26
- }
27
- exports.getRedirectsRoute = getRedirectsRoute;
@@ -1,27 +0,0 @@
1
- import { log } from "../../logger.mjs";
2
- import { getApiRouteUrlDefault, getRedirectSecretDefault } from "../env.mjs";
3
- const defaultApiRoute = "/api/redirect";
4
- async function getRedirectsRoute({
5
- apiRoute = defaultApiRoute,
6
- getApiRouteUrl = getApiRouteUrlDefault,
7
- getRedirectSecret = getRedirectSecretDefault
8
- } = {}) {
9
- const secret = getRedirectSecret();
10
- try {
11
- const url = new URL(apiRoute, getApiRouteUrl());
12
- url.searchParams.set("secret", encodeURIComponent(secret));
13
- const response = await fetch(url);
14
- if (!response.ok) {
15
- log(`${apiRoute} not ok. Returned`, { status: response.status }, "error");
16
- return { redirects: [], rewrites: [] };
17
- }
18
- const data = await response.json();
19
- return data;
20
- } catch (error) {
21
- log(`Error fetching redirects from ${apiRoute}.`, { error }, "error");
22
- return { redirects: [], rewrites: [] };
23
- }
24
- }
25
- export {
26
- getRedirectsRoute
27
- };
@@ -1,48 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const coreLib = require("@okam/core-lib");
4
- const server = require("next/server");
5
- const radashi = require("radashi");
6
- const logger = require("../../logger.js");
7
- const getRedirectsRoute = require("./getRedirectsRoute.js");
8
- function splitDestination(destination) {
9
- const [pathname, search] = destination.split("?");
10
- if (!search) {
11
- return [pathname];
12
- }
13
- return [pathname, `?${search}`];
14
- }
15
- function validateExternalRedirect(redirect) {
16
- if (!URL.canParse(redirect.destination)) {
17
- return null;
18
- }
19
- return redirect.destination;
20
- }
21
- async function handleRedirect(request, options = {}) {
22
- const url = request.nextUrl.clone();
23
- const { pathname } = request.nextUrl;
24
- const normalizedPathname = coreLib.normalizePath(pathname);
25
- const { redirects, rewrites } = await getRedirectsRoute.getRedirectsRoute(options);
26
- const redirect = redirects.find(({ source }) => source === normalizedPathname);
27
- const rewrite = rewrites.find(({ source }) => source === normalizedPathname);
28
- const type = redirect ? "redirect" : "rewrite";
29
- const reroute = redirect ?? rewrite;
30
- if (!reroute) {
31
- return null;
32
- }
33
- const { permanent } = reroute;
34
- const status = permanent ? 308 : 307;
35
- const externalRedirect = validateExternalRedirect(reroute);
36
- if (externalRedirect) {
37
- logger.log(`External ${type} found`, { [type]: externalRedirect, permanent });
38
- return server.NextResponse.redirect(externalRedirect, { status });
39
- }
40
- logger.log(`${radashi.capitalize(type)} found`, { [type]: reroute, permanent });
41
- const { destination } = reroute;
42
- const [destinationPathname, search] = splitDestination(destination);
43
- if (search) url.search = search;
44
- url.pathname = destinationPathname;
45
- logger.log(`${radashi.capitalize(type)}ing to ${url.toString()} with status ${status}`);
46
- return server.NextResponse[type](url, { status });
47
- }
48
- exports.handleRedirect = handleRedirect;
@@ -1,48 +0,0 @@
1
- import { normalizePath } from "@okam/core-lib";
2
- import { NextResponse } from "next/server";
3
- import { capitalize } from "radashi";
4
- import { log } from "../../logger.mjs";
5
- import { getRedirectsRoute } from "./getRedirectsRoute.mjs";
6
- function splitDestination(destination) {
7
- const [pathname, search] = destination.split("?");
8
- if (!search) {
9
- return [pathname];
10
- }
11
- return [pathname, `?${search}`];
12
- }
13
- function validateExternalRedirect(redirect) {
14
- if (!URL.canParse(redirect.destination)) {
15
- return null;
16
- }
17
- return redirect.destination;
18
- }
19
- async function handleRedirect(request, options = {}) {
20
- const url = request.nextUrl.clone();
21
- const { pathname } = request.nextUrl;
22
- const normalizedPathname = normalizePath(pathname);
23
- const { redirects, rewrites } = await getRedirectsRoute(options);
24
- const redirect = redirects.find(({ source }) => source === normalizedPathname);
25
- const rewrite = rewrites.find(({ source }) => source === normalizedPathname);
26
- const type = redirect ? "redirect" : "rewrite";
27
- const reroute = redirect ?? rewrite;
28
- if (!reroute) {
29
- return null;
30
- }
31
- const { permanent } = reroute;
32
- const status = permanent ? 308 : 307;
33
- const externalRedirect = validateExternalRedirect(reroute);
34
- if (externalRedirect) {
35
- log(`External ${type} found`, { [type]: externalRedirect, permanent });
36
- return NextResponse.redirect(externalRedirect, { status });
37
- }
38
- log(`${capitalize(type)} found`, { [type]: reroute, permanent });
39
- const { destination } = reroute;
40
- const [destinationPathname, search] = splitDestination(destination);
41
- if (search) url.search = search;
42
- url.pathname = destinationPathname;
43
- log(`${capitalize(type)}ing to ${url.toString()} with status ${status}`);
44
- return NextResponse[type](url, { status });
45
- }
46
- export {
47
- handleRedirect
48
- };
package/response.js DELETED
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- function getJsonErrorResponse(data, status) {
4
- const headers = {
5
- // eslint-disable-next-line @typescript-eslint/naming-convention
6
- "Content-Type": "text/json; charset=UTF-8"
7
- };
8
- const body = JSON.stringify(data);
9
- return new Response(body, {
10
- status,
11
- headers
12
- });
13
- }
14
- exports.getJsonErrorResponse = getJsonErrorResponse;