@okam/directus-next 1.2.26 → 1.2.28

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 CHANGED
@@ -1,3 +1,12 @@
1
+ ## 1.2.27 (2026-01-21)
2
+
3
+ ### 🧱 Updated Dependencies
4
+
5
+ - Updated core-lib to 1.17.2
6
+ - Updated next-component to 1.3.5
7
+ - Updated directus-node to 0.7.3
8
+ - Updated directus-query to 1.5.3
9
+
1
10
  ## 1.2.26 (2026-01-19)
2
11
 
3
12
  ### 🧱 Updated Dependencies
package/draft/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { default as handleDraftRoute, getPathFromRoute, parseDraftParams } from './route';
2
1
  export { getDraftSecretDefault } from './env';
2
+ export { getPathFromRoute, default as handleDraftRoute, parseDraftParams } from './route';
3
3
  export type { HandleDraftOptions } from './route';
package/draft/route.d.ts CHANGED
@@ -30,12 +30,12 @@ export declare function parseDraftParams(url: string, expectedSecret: string): z
30
30
  * @returns {string}
31
31
  */
32
32
  export declare function getPathFromRoute(routeUrl: string, url: string, index?: number): string;
33
- export type HandleDraftOptions = {
33
+ export interface HandleDraftOptions {
34
34
  url: string;
35
35
  getDirectusLanguage: () => string;
36
36
  getDraftSecret?: (() => string) | undefined;
37
37
  getJsonError?: (() => Response) | undefined;
38
- };
38
+ }
39
39
  /**
40
40
  * Use handleDraft inside the default GET export of route.ts
41
41
  * You need to provide url and getDirectusLanguage
@@ -1,8 +1,8 @@
1
- export type TFiles = {
1
+ export interface TFiles {
2
2
  id?: string | null;
3
3
  title?: string | null;
4
4
  description?: string | null;
5
- tags?: any | null;
5
+ tags?: unknown;
6
6
  location?: string | null;
7
7
  storage?: string | null;
8
8
  focal_point_divider?: string | null;
@@ -21,4 +21,4 @@ export type TFiles = {
21
21
  * @deprecated Use `filename_download` instead
22
22
  */
23
23
  filenameDownload?: string | null;
24
- };
24
+ }
package/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export * from './draft';
2
- export * from './redirect';
2
+ export type { TFiles } from './files/interface';
3
3
  export { logger as DirectusNextLogger } from './logger';
4
- export { directusRouteRouter } from './router/router';
4
+ export * from './redirect';
5
5
  export { getJsonErrorResponse } from './response';
6
- export * from './types';
7
- export type { TFiles } from './files/interface';
6
+ export { directusRouteRouter } from './router/router';
7
+ export type * from './types';
package/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const router = require("./router-CwzG5Cu9.js");
3
4
  const headers = require("next/headers");
4
5
  const navigation = require("next/navigation");
5
6
  const radashi = require("radashi");
6
7
  const zod = require("zod");
7
- const router = require("./router-DTZYUtal.js");
8
8
  const edge = require("@okam/directus-node/edge");
9
9
  function _interopNamespaceDefault(e) {
10
10
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
@@ -23,9 +23,11 @@ function _interopNamespaceDefault(e) {
23
23
  return Object.freeze(n);
24
24
  }
25
25
  const zod__namespace = /* @__PURE__ */ _interopNamespaceDefault(zod);
26
+ function getDraftSecretDefault() {
27
+ return process.env.NEXT_API_DRAFT_SECRET || "";
28
+ }
26
29
  function getJsonErrorResponse(data, status) {
27
30
  const headers2 = {
28
- // eslint-disable-next-line @typescript-eslint/naming-convention
29
31
  "Content-Type": "text/json; charset=UTF-8"
30
32
  };
31
33
  const body = JSON.stringify(data);
@@ -34,32 +36,33 @@ function getJsonErrorResponse(data, status) {
34
36
  headers: headers2
35
37
  });
36
38
  }
37
- function getDraftSecretDefault() {
38
- return process.env.NEXT_API_DRAFT_SECRET || "";
39
+ function jsonStringsArraySchema(message, code) {
40
+ return zod__namespace.string().transform((val, ctx) => {
41
+ try {
42
+ const decodedVal = decodeURIComponent(decodeURIComponent(val));
43
+ return JSON.parse(decodedVal);
44
+ } catch {
45
+ ctx.addIssue({
46
+ code: zod__namespace.ZodIssueCode.custom,
47
+ message: "Invalid JSON string",
48
+ params: { code }
49
+ });
50
+ return zod__namespace.NEVER;
51
+ }
52
+ }).pipe(zod__namespace.array(zod__namespace.string(), { error: () => ({ message }) }));
39
53
  }
40
- const jsonStringsArraySchema = (message, code) => zod__namespace.string().transform((val, ctx) => {
41
- try {
42
- const decodedVal = decodeURIComponent(decodeURIComponent(val));
43
- return JSON.parse(decodedVal);
44
- } catch (error) {
45
- ctx.addIssue({
46
- code: zod__namespace.ZodIssueCode.custom,
47
- message: "Invalid JSON string",
48
- params: { code }
49
- });
50
- return zod__namespace.NEVER;
51
- }
52
- }).pipe(zod__namespace.array(zod__namespace.string(), { error: () => ({ message }) }));
53
54
  const languagesSchema = jsonStringsArraySchema("Invalid languages argument", 400);
54
55
  const commonSchema = zod__namespace.object({
55
56
  version: zod__namespace.string().optional(),
56
57
  enable: zod__namespace.enum(["true", "false"]).transform((val) => val === "true").optional(),
57
58
  pk: zod__namespace.string().optional()
58
59
  });
59
- const createSecretSchema = (expectedSecret) => zod__namespace.string({ error: () => ({ message: "Invalid secret argument" }) }).refine((val) => val === expectedSecret, {
60
- message: "Invalid secret argument",
61
- params: { code: 401 }
62
- });
60
+ function createSecretSchema(expectedSecret) {
61
+ return zod__namespace.string({ error: () => ({ message: "Invalid secret argument" }) }).refine((val) => val === expectedSecret, {
62
+ message: "Invalid secret argument",
63
+ params: { code: 401 }
64
+ });
65
+ }
63
66
  const draftParamsSchema = zod__namespace.discriminatedUnion(
64
67
  "type",
65
68
  [
@@ -97,22 +100,22 @@ function getPathFromRoute(routeUrl, url, index = 0) {
97
100
  const matches = [...routeUrl.matchAll(/\{\{([a-z]+)\}\}/gi)];
98
101
  const map = {};
99
102
  matches.forEach((match) => {
100
- const key = match[1] || "";
101
- if (!key) {
103
+ const key = match[1] ?? "";
104
+ if (key == null || key === "") {
102
105
  return;
103
106
  }
104
107
  const listkey = `${key}s`;
105
108
  const listParam = searchParams.get(listkey);
106
- if (listParam) {
109
+ if (listParam != null && listParam !== "") {
107
110
  try {
108
111
  const list = JSON.parse(listParam);
109
- map[key] = list[index] || "";
110
- } catch (e) {
112
+ map[key] = list[index] ?? "";
113
+ } catch {
111
114
  map[key] = "";
112
115
  }
113
116
  } else {
114
117
  const param = searchParams.get(key);
115
- map[key] = param || "";
118
+ map[key] = param ?? "";
116
119
  }
117
120
  });
118
121
  return radashi.template(routeUrl, map);
@@ -123,14 +126,15 @@ async function handleDraftRoute({
123
126
  getDraftSecret,
124
127
  getJsonError
125
128
  }) {
126
- var _a, _b, _c;
127
- const getSecretFunction = getDraftSecret || getDraftSecretDefault;
128
- const getJsonErrorResponseFunction = getJsonError || getJsonErrorResponse;
129
+ const getSecretFunction = getDraftSecret ?? getDraftSecretDefault;
130
+ const getJsonErrorResponseFunction = getJsonError ?? getJsonErrorResponse;
129
131
  const { success, error, data } = parseDraftParams(url, getSecretFunction());
130
132
  if (!success) {
133
+ const issue = error.issues[0];
134
+ const statusCode = issue?.code === "custom" && typeof issue.params?.code === "number" ? issue.params.code : 400;
131
135
  return getJsonErrorResponseFunction(
132
136
  { error: error.issues },
133
- ((_a = error.issues[0]) == null ? void 0 : _a.code) === "custom" ? (_c = (_b = error.issues[0]) == null ? void 0 : _b.params) == null ? void 0 : _c.code : 400
137
+ statusCode
134
138
  );
135
139
  }
136
140
  const { type, languages, version, enable } = data;
@@ -141,14 +145,14 @@ async function handleDraftRoute({
141
145
  const index = indexDefault !== -1 ? indexDefault : 0;
142
146
  if (type === "path") {
143
147
  const { urls } = data;
144
- const path = urls[index] || "";
148
+ const path = urls[index] ?? "";
145
149
  if (!path) {
146
150
  return getJsonErrorResponseFunction({ error: "Invalid path" }, 400);
147
151
  }
148
152
  redirectUrl = path;
149
153
  } else if (type === "route") {
150
154
  const { routes } = data;
151
- const route = (routes == null ? void 0 : routes[index]) || "";
155
+ const route = routes?.[index] ?? "";
152
156
  if (!route) {
153
157
  return getJsonErrorResponseFunction({ error: "Invalid route" }, 400);
154
158
  }
@@ -166,9 +170,9 @@ async function handleDraftRoute({
166
170
  if (enable === false) {
167
171
  draft.disable();
168
172
  }
169
- if (redirectUrl) {
170
- if (version) {
171
- const withParams = redirectUrl.indexOf("?") !== -1;
173
+ if (redirectUrl != null && redirectUrl !== "") {
174
+ if (version != null && version !== "") {
175
+ const withParams = redirectUrl.includes("?");
172
176
  redirectUrl = `${redirectUrl}${withParams ? "&" : "?"}version=${encodeURIComponent(version)}`;
173
177
  }
174
178
  navigation.redirect(redirectUrl);
@@ -177,7 +181,7 @@ async function handleDraftRoute({
177
181
  }
178
182
  function parseRedirectParams(url) {
179
183
  const { searchParams } = new URL(url);
180
- const secret = searchParams.get("secret") || "";
184
+ const secret = searchParams.get("secret") ?? "";
181
185
  return { secret };
182
186
  }
183
187
  async function handleRedirectsRoute({
@@ -193,8 +197,8 @@ async function handleRedirectsRoute({
193
197
  if (secret !== getRedirectSecret()) {
194
198
  return getJsonError({ error: "Invalid argument" }, 401);
195
199
  }
196
- const graphqlEndpoint = getDirectusGraphqlUrl == null ? void 0 : getDirectusGraphqlUrl();
197
- const graphqlApiKey = getDirectusApiToken == null ? void 0 : getDirectusApiToken();
200
+ const graphqlEndpoint = getDirectusGraphqlUrl?.();
201
+ const graphqlApiKey = getDirectusApiToken?.();
198
202
  const { redirects, rewrites } = await edge.fetchRedirectsData({ graphqlEndpoint, graphqlApiKey, limit }, init);
199
203
  return new Response(JSON.stringify({ redirects, rewrites }), { status: 200 });
200
204
  }
package/index.mjs CHANGED
@@ -1,13 +1,15 @@
1
+ import { g as getRedirectSecretDefault } from "./router-oaFeb_tY.mjs";
2
+ import { l, d, b, a, h } from "./router-oaFeb_tY.mjs";
1
3
  import { draftMode } from "next/headers";
2
4
  import { redirect } from "next/navigation";
3
5
  import { template } from "radashi";
4
6
  import * as zod from "zod";
5
- import { g as getRedirectSecretDefault } from "./router-CA4ItnAc.mjs";
6
- import { l, d, b, a, h } from "./router-CA4ItnAc.mjs";
7
7
  import { fetchRedirectsData } from "@okam/directus-node/edge";
8
+ function getDraftSecretDefault() {
9
+ return process.env.NEXT_API_DRAFT_SECRET || "";
10
+ }
8
11
  function getJsonErrorResponse(data, status) {
9
12
  const headers = {
10
- // eslint-disable-next-line @typescript-eslint/naming-convention
11
13
  "Content-Type": "text/json; charset=UTF-8"
12
14
  };
13
15
  const body = JSON.stringify(data);
@@ -16,32 +18,33 @@ function getJsonErrorResponse(data, status) {
16
18
  headers
17
19
  });
18
20
  }
19
- function getDraftSecretDefault() {
20
- return process.env.NEXT_API_DRAFT_SECRET || "";
21
+ function jsonStringsArraySchema(message, code) {
22
+ return zod.string().transform((val, ctx) => {
23
+ try {
24
+ const decodedVal = decodeURIComponent(decodeURIComponent(val));
25
+ return JSON.parse(decodedVal);
26
+ } catch {
27
+ ctx.addIssue({
28
+ code: zod.ZodIssueCode.custom,
29
+ message: "Invalid JSON string",
30
+ params: { code }
31
+ });
32
+ return zod.NEVER;
33
+ }
34
+ }).pipe(zod.array(zod.string(), { error: () => ({ message }) }));
21
35
  }
22
- const jsonStringsArraySchema = (message, code) => zod.string().transform((val, ctx) => {
23
- try {
24
- const decodedVal = decodeURIComponent(decodeURIComponent(val));
25
- return JSON.parse(decodedVal);
26
- } catch (error) {
27
- ctx.addIssue({
28
- code: zod.ZodIssueCode.custom,
29
- message: "Invalid JSON string",
30
- params: { code }
31
- });
32
- return zod.NEVER;
33
- }
34
- }).pipe(zod.array(zod.string(), { error: () => ({ message }) }));
35
36
  const languagesSchema = jsonStringsArraySchema("Invalid languages argument", 400);
36
37
  const commonSchema = zod.object({
37
38
  version: zod.string().optional(),
38
39
  enable: zod.enum(["true", "false"]).transform((val) => val === "true").optional(),
39
40
  pk: zod.string().optional()
40
41
  });
41
- const createSecretSchema = (expectedSecret) => zod.string({ error: () => ({ message: "Invalid secret argument" }) }).refine((val) => val === expectedSecret, {
42
- message: "Invalid secret argument",
43
- params: { code: 401 }
44
- });
42
+ function createSecretSchema(expectedSecret) {
43
+ return zod.string({ error: () => ({ message: "Invalid secret argument" }) }).refine((val) => val === expectedSecret, {
44
+ message: "Invalid secret argument",
45
+ params: { code: 401 }
46
+ });
47
+ }
45
48
  const draftParamsSchema = zod.discriminatedUnion(
46
49
  "type",
47
50
  [
@@ -79,22 +82,22 @@ function getPathFromRoute(routeUrl, url, index = 0) {
79
82
  const matches = [...routeUrl.matchAll(/\{\{([a-z]+)\}\}/gi)];
80
83
  const map = {};
81
84
  matches.forEach((match) => {
82
- const key = match[1] || "";
83
- if (!key) {
85
+ const key = match[1] ?? "";
86
+ if (key == null || key === "") {
84
87
  return;
85
88
  }
86
89
  const listkey = `${key}s`;
87
90
  const listParam = searchParams.get(listkey);
88
- if (listParam) {
91
+ if (listParam != null && listParam !== "") {
89
92
  try {
90
93
  const list = JSON.parse(listParam);
91
- map[key] = list[index] || "";
92
- } catch (e) {
94
+ map[key] = list[index] ?? "";
95
+ } catch {
93
96
  map[key] = "";
94
97
  }
95
98
  } else {
96
99
  const param = searchParams.get(key);
97
- map[key] = param || "";
100
+ map[key] = param ?? "";
98
101
  }
99
102
  });
100
103
  return template(routeUrl, map);
@@ -105,14 +108,15 @@ async function handleDraftRoute({
105
108
  getDraftSecret,
106
109
  getJsonError
107
110
  }) {
108
- var _a, _b, _c;
109
- const getSecretFunction = getDraftSecret || getDraftSecretDefault;
110
- const getJsonErrorResponseFunction = getJsonError || getJsonErrorResponse;
111
+ const getSecretFunction = getDraftSecret ?? getDraftSecretDefault;
112
+ const getJsonErrorResponseFunction = getJsonError ?? getJsonErrorResponse;
111
113
  const { success, error, data } = parseDraftParams(url, getSecretFunction());
112
114
  if (!success) {
115
+ const issue = error.issues[0];
116
+ const statusCode = issue?.code === "custom" && typeof issue.params?.code === "number" ? issue.params.code : 400;
113
117
  return getJsonErrorResponseFunction(
114
118
  { error: error.issues },
115
- ((_a = error.issues[0]) == null ? void 0 : _a.code) === "custom" ? (_c = (_b = error.issues[0]) == null ? void 0 : _b.params) == null ? void 0 : _c.code : 400
119
+ statusCode
116
120
  );
117
121
  }
118
122
  const { type, languages, version, enable } = data;
@@ -123,14 +127,14 @@ async function handleDraftRoute({
123
127
  const index = indexDefault !== -1 ? indexDefault : 0;
124
128
  if (type === "path") {
125
129
  const { urls } = data;
126
- const path = urls[index] || "";
130
+ const path = urls[index] ?? "";
127
131
  if (!path) {
128
132
  return getJsonErrorResponseFunction({ error: "Invalid path" }, 400);
129
133
  }
130
134
  redirectUrl = path;
131
135
  } else if (type === "route") {
132
136
  const { routes } = data;
133
- const route = (routes == null ? void 0 : routes[index]) || "";
137
+ const route = routes?.[index] ?? "";
134
138
  if (!route) {
135
139
  return getJsonErrorResponseFunction({ error: "Invalid route" }, 400);
136
140
  }
@@ -148,9 +152,9 @@ async function handleDraftRoute({
148
152
  if (enable === false) {
149
153
  draft.disable();
150
154
  }
151
- if (redirectUrl) {
152
- if (version) {
153
- const withParams = redirectUrl.indexOf("?") !== -1;
155
+ if (redirectUrl != null && redirectUrl !== "") {
156
+ if (version != null && version !== "") {
157
+ const withParams = redirectUrl.includes("?");
154
158
  redirectUrl = `${redirectUrl}${withParams ? "&" : "?"}version=${encodeURIComponent(version)}`;
155
159
  }
156
160
  redirect(redirectUrl);
@@ -159,7 +163,7 @@ async function handleDraftRoute({
159
163
  }
160
164
  function parseRedirectParams(url) {
161
165
  const { searchParams } = new URL(url);
162
- const secret = searchParams.get("secret") || "";
166
+ const secret = searchParams.get("secret") ?? "";
163
167
  return { secret };
164
168
  }
165
169
  async function handleRedirectsRoute({
@@ -175,8 +179,8 @@ async function handleRedirectsRoute({
175
179
  if (secret !== getRedirectSecret()) {
176
180
  return getJsonError({ error: "Invalid argument" }, 401);
177
181
  }
178
- const graphqlEndpoint = getDirectusGraphqlUrl == null ? void 0 : getDirectusGraphqlUrl();
179
- const graphqlApiKey = getDirectusApiToken == null ? void 0 : getDirectusApiToken();
182
+ const graphqlEndpoint = getDirectusGraphqlUrl?.();
183
+ const graphqlApiKey = getDirectusApiToken?.();
180
184
  const { redirects, rewrites } = await fetchRedirectsData({ graphqlEndpoint, graphqlApiKey, limit }, init);
181
185
  return new Response(JSON.stringify({ redirects, rewrites }), { status: 200 });
182
186
  }
package/logger.d.ts CHANGED
@@ -1,4 +1,3 @@
1
1
  import { LogSeverity } from '@okam/logger';
2
-
3
2
  export declare const logger: import('@okam/logger').Logger;
4
3
  export declare function log(msg: string, context?: unknown, severity?: LogSeverity): void;
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@okam/directus-next",
3
- "main": "./index.js",
4
- "version": "1.2.26",
5
- "types": "./index.d.ts",
3
+ "version": "1.2.28",
4
+ "repository": {
5
+ "url": "https://github.com/OKAMca/stack.git"
6
+ },
7
+ "sideEffects": [
8
+ "./server.mjs"
9
+ ],
6
10
  "exports": {
7
11
  ".": {
8
12
  "import": {
@@ -25,23 +29,28 @@
25
29
  }
26
30
  }
27
31
  },
28
- "repository": {
29
- "url": "https://github.com/OKAMca/stack.git"
32
+ "main": "./index.js",
33
+ "types": "./index.d.ts",
34
+ "engines": {
35
+ "node": ">=20.19.0"
30
36
  },
31
37
  "publishConfig": {
32
38
  "access": "public"
33
39
  },
40
+ "peerDependencies": {
41
+ "next": "^15.1.0 || ^16.0.0"
42
+ },
34
43
  "dependencies": {
35
- "@okam/core-lib": "1.17.1",
36
- "@okam/directus-node": "0.7.2",
44
+ "@graphql-typed-document-node/core": "3.2.0",
45
+ "@okam/core-lib": "1.17.3",
46
+ "@okam/directus-node": "0.7.4",
47
+ "@okam/directus-query": "1.5.4",
37
48
  "@okam/logger": "1.1.0",
38
- "@okam/next-component": "1.3.4",
39
- "next": "^15.0.0",
40
- "radashi": "^12.3.0",
41
- "@okam/directus-query": "1.5.2",
49
+ "@okam/next-component": "1.3.6",
42
50
  "graphql-request": "^7.1.2",
43
- "@graphql-typed-document-node/core": "3.2.0",
44
- "zod": "^4.3.5",
45
- "server-only": "0.0.1"
51
+ "next": "^15.1.0 || ^16.0.0",
52
+ "radashi": "^12.3.0",
53
+ "server-only": "0.0.1",
54
+ "zod": "^4.3.5"
46
55
  }
47
56
  }
@@ -1,6 +1,5 @@
1
1
  import { Variables } from 'graphql-request';
2
2
  import { TPageSettingsQueryItem } from '../types/pageSettings';
3
3
  import { TGetPageSettingsReturn } from './interface';
4
-
5
4
  export declare function pageSettingsContext<Item extends TPageSettingsQueryItem>(defaultValue?: TGetPageSettingsReturn<Item>): readonly [() => TGetPageSettingsReturn<Item> | undefined, (value: TGetPageSettingsReturn<Item> | undefined) => void];
6
5
  export declare function pageSettingsVariablesContext(variables?: Variables): readonly [() => object | undefined, (value: object | undefined) => void];
@@ -1,7 +1,6 @@
1
1
  import { Variables } from 'graphql-request';
2
2
  import { TPageSettingsQueryItem } from '../types/pageSettings';
3
3
  import { TGetPageSettingsProps, TGetPageSettingsReturn } from './interface';
4
-
5
4
  /**
6
5
  * @param props Optional props. Passing new props will trigger a new query if the variables have changed compared to the value of the variables in the cache. Omitting props will return the cached value.
7
6
  * @param itemKey Required if the query has more than a single root field
@@ -1,2 +1,3 @@
1
- export type { TGetPageSettingsConfig, TGetPageSettingsProps, TGetPageSettingsReturn } from './interface';
1
+ export * from './context';
2
2
  export { getPageSettings, usePageSettings } from './getPageSettings';
3
+ export type { TGetPageSettingsConfig, TGetPageSettingsProps, TGetPageSettingsReturn } from './interface';
@@ -3,7 +3,6 @@ import { Variables } from 'graphql-request';
3
3
  import { TDirectusRouteConfig } from '../types/directusRouteConfig';
4
4
  import { Fragmentize } from '../types/Fragments';
5
5
  import { TPageSettings, TPageSettingsItemQuery, TPageSettingsQueryItem } from '../types/pageSettings';
6
-
7
6
  export type TPageSettingsItemDocument<Item extends TPageSettingsQueryItem, ItemKey extends string, QueryVariables extends Variables> = TypedDocumentNode<TPageSettingsItemQuery<Item, ItemKey>, QueryVariables>;
8
7
  export type TGetPageSettingsConfig = TDirectusRouteConfig | Record<string, string>;
9
8
  /**
@@ -1,5 +1,5 @@
1
1
  export * from './env';
2
- export { default as handleRedirectsRoute, parseRedirectParams } from './route';
3
2
  export type { HandleRedirectOptions } from './interface';
3
+ export { default as handleRedirectsRoute, parseRedirectParams } from './route';
4
4
  export { getRedirectsRoute } from './utils/getRedirectsRoute';
5
5
  export { handleRedirect } from './utils/handleRedirect';
@@ -12,7 +12,7 @@ export interface HandleRedirectOptions {
12
12
  * @default process.env.NEXT_API_TOKEN_ADMIN
13
13
  */
14
14
  getDirectusApiToken?: () => string;
15
- getJsonError?: (data: any, status: number) => Response;
15
+ getJsonError?: (_data: unknown, _status: number) => Response;
16
16
  /**
17
17
  * @default 2000
18
18
  */
@@ -1,5 +1,4 @@
1
1
  import { HandleRedirectOptions } from './interface';
2
-
3
2
  export declare function parseRedirectParams(url: string): {
4
3
  secret: string;
5
4
  };
@@ -1,6 +1,5 @@
1
1
  import { TFetchRedirectsResponse } from '@okam/directus-node/edge';
2
2
  import { TDirectusRouteRedirectsModule } from '../../types/directusRouteConfig';
3
-
4
3
  /**
5
4
  * Gets a response from `options.apiRoute`
6
5
  * @param {TDirectusRouteRedirectsModule} options
@@ -1,6 +1,5 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { TDirectusRouteRedirectsModule } from '../../types/directusRouteConfig';
3
-
4
3
  /**
5
4
  * Handles next redirection using directus redirects
6
5
  */
package/response.d.ts CHANGED
@@ -1 +1 @@
1
- export declare function getJsonErrorResponse(data: any, status: number): Response;
1
+ export declare function getJsonErrorResponse(data: unknown, status: number): Response;
@@ -1,8 +1,7 @@
1
1
  import { NextRequest, NextResponse as NextResponseType } from 'next/server';
2
2
  import { TDirectusRouteConfig } from '../types/directusRouteConfig';
3
-
4
3
  /**
5
- * Handles incoming middleware requests and rewrites the path to the new format according to fetched page settings.
4
+ * Handles incoming proxy requests and rewrites the path to the new format according to fetched page settings.
6
5
  * @param request - The NextRequest object
7
6
  * @param config - The TDirectusRouteConfig object
8
7
  * @deprecated Use `directusRouteRouter(request, config)` instead. NextResponse is now directly imported in this file.
@@ -11,6 +10,7 @@ import { TDirectusRouteConfig } from '../types/directusRouteConfig';
11
10
  *
12
11
  * @example
13
12
  * ```typescript
13
+ * // proxy.ts (Next.js 16+) or middleware.ts (legacy)
14
14
  * export const directusConfig: TDirectusRouteConfig = {
15
15
  * localeMap: {
16
16
  * 'fr-CA': 'fr',
@@ -23,7 +23,7 @@ import { TDirectusRouteConfig } from '../types/directusRouteConfig';
23
23
  * },
24
24
  * }
25
25
  *
26
- * export async function middleware(request: NextRequest) {
26
+ * export async function proxy(request: NextRequest) {
27
27
  * return directusRouteRouter(request, directusConfig)
28
28
  * }
29
29
  * ```
@@ -1,3 +1,2 @@
1
1
  import { TPageSettingsTranslation } from '../../types';
2
-
3
2
  export declare function fetchPageSettingsTranslation(path: string): Promise<TPageSettingsTranslation[] | null>;
@@ -1,5 +1,4 @@
1
1
  import { TDirectusRouteConfig } from '../../types';
2
-
3
2
  /**
4
3
  * Validates if a given string is a valid locale from the directus route configuration.
5
4
  * @param maybeLocale The string to validate as a locale
@@ -15,12 +15,14 @@ function getRedirectSecretDefault() {
15
15
  }
16
16
  function getVercelUrl() {
17
17
  const url = process.env.VERCEL_URL;
18
- if (!url) return null;
18
+ if (url == null || url === "")
19
+ return null;
19
20
  return `https://${url}`;
20
21
  }
21
22
  function getApiRouteUrlDefault() {
22
23
  const url = process.env.NEXT_MIDDLEWARE_REDIRECT_URL ?? getVercelUrl() ?? defaultInternalUrl;
23
- if (URL.canParse(url)) return url;
24
+ if (URL.canParse(url))
25
+ return url;
24
26
  log(`Invalid URL ${url}. Falling back to default`, { url }, "warn");
25
27
  return defaultInternalUrl;
26
28
  }
@@ -47,8 +49,8 @@ async function getRedirectsRoute({
47
49
  }
48
50
  }
49
51
  function splitDestination(destination) {
50
- const [pathname, search] = destination.split("?");
51
- if (!search) {
52
+ const [pathname = "", search] = destination.split("?");
53
+ if (search == null || search === "") {
52
54
  return [pathname];
53
55
  }
54
56
  return [pathname, `?${search}`];
@@ -66,22 +68,23 @@ async function handleRedirect(request, options = {}) {
66
68
  const { redirects, rewrites } = await getRedirectsRoute(options);
67
69
  const redirect = redirects.find(({ source }) => source === normalizedPathname);
68
70
  const rewrite = rewrites.find(({ source }) => source === normalizedPathname);
69
- const type = redirect ? "redirect" : "rewrite";
71
+ const type = redirect != null ? "redirect" : "rewrite";
70
72
  const reroute = redirect ?? rewrite;
71
- if (!reroute) {
73
+ if (reroute == null) {
72
74
  return null;
73
75
  }
74
76
  const { permanent } = reroute;
75
77
  const status = permanent ? 308 : 307;
76
78
  const externalRedirect = validateExternalRedirect(reroute);
77
- if (externalRedirect) {
79
+ if (externalRedirect != null && externalRedirect !== "") {
78
80
  log(`External ${type} found`, { [type]: externalRedirect, permanent });
79
81
  return server.NextResponse.redirect(externalRedirect, { status });
80
82
  }
81
83
  log(`${radashi.capitalize(type)} found`, { [type]: reroute, permanent });
82
84
  const { destination } = reroute;
83
85
  const [destinationPathname, search] = splitDestination(destination);
84
- if (search) url.search = search;
86
+ if (search != null)
87
+ url.search = search;
85
88
  url.pathname = destinationPathname;
86
89
  log(`${radashi.capitalize(type)}ing to ${url.toString()} with status ${status}`);
87
90
  return server.NextResponse[type](url, { status });
@@ -106,10 +109,10 @@ const query = `
106
109
  async function fetchPageSettingsTranslation(path) {
107
110
  const graphqlEndpoint = process.env.NEXT_SERVER_GRAPHQL_URL || process.env.NEXT_PUBLIC_GRAPHQL_URL;
108
111
  const graphqlApiKey = process.env.NEXT_PUBLIC_API_TOKEN;
109
- if (!graphqlEndpoint) {
112
+ if (graphqlEndpoint == null || graphqlEndpoint === "") {
110
113
  throw new Error("Missing GraphQL configuration `graphqlEndpoint`");
111
114
  }
112
- if (!graphqlApiKey) {
115
+ if (graphqlApiKey == null || graphqlApiKey === "") {
113
116
  throw new Error("Missing GraphQL configuration `graphqlApiKey`");
114
117
  }
115
118
  const variables = {
@@ -124,15 +127,14 @@ async function fetchPageSettingsTranslation(path) {
124
127
  const response = await fetch(graphqlEndpoint, {
125
128
  method: "POST",
126
129
  headers: {
127
- // eslint-disable-next-line @typescript-eslint/naming-convention
128
130
  "Content-Type": "application/json",
129
- Authorization: `Bearer ${graphqlApiKey}`
131
+ "Authorization": `Bearer ${graphqlApiKey}`
130
132
  },
131
133
  body: JSON.stringify({ query, variables })
132
134
  });
133
- const { data } = await response.json();
134
- log("GraphQL response:", data);
135
- return data.page_settings_translations;
135
+ const json = await response.json();
136
+ log("GraphQL response:", json.data);
137
+ return json.data?.page_settings_translations ?? null;
136
138
  } catch (error) {
137
139
  log("GraphQL Error:", error);
138
140
  return null;
@@ -145,7 +147,7 @@ function getValidLocale(maybeLocale, config) {
145
147
  function splitLocaleFromPathname(pathname, config) {
146
148
  const [, maybeLocale, ...parts] = pathname.split("/");
147
149
  const locale = getValidLocale(maybeLocale, config);
148
- if (locale) {
150
+ if (locale != null && locale !== "") {
149
151
  const newPathname = parts.length > 0 ? `/${parts.join("/")}` : "/";
150
152
  return { locale, pathname: newPathname };
151
153
  }
@@ -153,22 +155,18 @@ function splitLocaleFromPathname(pathname, config) {
153
155
  }
154
156
  function getValidTranslation(translations, locale) {
155
157
  const translation = translations[0];
156
- if (!locale) {
158
+ if (locale == null || locale === "") {
157
159
  log("No locale provided, using first translation as default:", { translation });
158
160
  return translation;
159
161
  }
160
- return (translations == null ? void 0 : translations.find((t) => {
161
- var _a, _b;
162
- return (_b = (_a = t.languages_code) == null ? void 0 : _a.code) == null ? void 0 : _b.startsWith(locale);
163
- })) ?? translation;
162
+ return translations?.find((t) => t.languages_code?.code?.startsWith(locale)) ?? translation;
164
163
  }
165
164
  async function directusRouteRouter(request, config, NextResponse = server.NextResponse) {
166
- var _a, _b, _c;
167
165
  const { pathname: localizedPathname } = request.nextUrl;
168
166
  const { locale, pathname } = splitLocaleFromPathname(localizedPathname, config);
169
167
  log("Processing request for pathname:", { locale, pathname });
170
- const redirect = await handleRedirect(request, (_a = config.modules) == null ? void 0 : _a.redirects);
171
- if (redirect) {
168
+ const redirect = await handleRedirect(request, config.modules?.redirects);
169
+ if (redirect != null) {
172
170
  return redirect;
173
171
  }
174
172
  const translations = await fetchPageSettingsTranslation(pathname);
@@ -178,23 +176,23 @@ async function directusRouteRouter(request, config, NextResponse = server.NextRe
178
176
  }
179
177
  const translation = getValidTranslation(translations, locale);
180
178
  log("Using translation:", translation);
181
- if (!translation || !translation.languages_code || !translation.page_settings_id) {
179
+ if (translation == null || translation.languages_code == null || translation.page_settings_id == null) {
182
180
  log(`Invalid translation data for path: ${pathname}`, { pathname }, "warn");
183
181
  return NextResponse.next();
184
182
  }
185
183
  const directusLocale = translation.languages_code.code;
186
184
  const collection = translation.page_settings_id.belongs_to_collection;
187
185
  const id = translation.page_settings_id.belongs_to_key;
188
- if (!collection) {
186
+ if (collection == null || collection === "") {
189
187
  log(`PageSettings with id ${id} was found but is not associated with any collection.`, { id }, "warn");
190
188
  return NextResponse.next();
191
189
  }
192
- if (!directusLocale) {
190
+ if (directusLocale == null || directusLocale === "") {
193
191
  log(`PageSettings with id ${id} was found but is not associated with any locale.`, { id }, "warn");
194
192
  return NextResponse.next();
195
193
  }
196
- const mappedLocale = ((_b = config.localeMap) == null ? void 0 : _b[directusLocale]) || directusLocale;
197
- const idField = ((_c = config.collectionSettings[collection]) == null ? void 0 : _c.idField) || config.collectionSettings.default.idField;
194
+ const mappedLocale = config.localeMap?.[directusLocale] || directusLocale;
195
+ const idField = config.collectionSettings[collection]?.idField || config.collectionSettings.default.idField;
198
196
  log("Directus locale:", directusLocale);
199
197
  log("Mapped locale:", mappedLocale);
200
198
  log("Collection:", collection);
@@ -14,12 +14,14 @@ function getRedirectSecretDefault() {
14
14
  }
15
15
  function getVercelUrl() {
16
16
  const url = process.env.VERCEL_URL;
17
- if (!url) return null;
17
+ if (url == null || url === "")
18
+ return null;
18
19
  return `https://${url}`;
19
20
  }
20
21
  function getApiRouteUrlDefault() {
21
22
  const url = process.env.NEXT_MIDDLEWARE_REDIRECT_URL ?? getVercelUrl() ?? defaultInternalUrl;
22
- if (URL.canParse(url)) return url;
23
+ if (URL.canParse(url))
24
+ return url;
23
25
  log(`Invalid URL ${url}. Falling back to default`, { url }, "warn");
24
26
  return defaultInternalUrl;
25
27
  }
@@ -46,8 +48,8 @@ async function getRedirectsRoute({
46
48
  }
47
49
  }
48
50
  function splitDestination(destination) {
49
- const [pathname, search] = destination.split("?");
50
- if (!search) {
51
+ const [pathname = "", search] = destination.split("?");
52
+ if (search == null || search === "") {
51
53
  return [pathname];
52
54
  }
53
55
  return [pathname, `?${search}`];
@@ -65,22 +67,23 @@ async function handleRedirect(request, options = {}) {
65
67
  const { redirects, rewrites } = await getRedirectsRoute(options);
66
68
  const redirect = redirects.find(({ source }) => source === normalizedPathname);
67
69
  const rewrite = rewrites.find(({ source }) => source === normalizedPathname);
68
- const type = redirect ? "redirect" : "rewrite";
70
+ const type = redirect != null ? "redirect" : "rewrite";
69
71
  const reroute = redirect ?? rewrite;
70
- if (!reroute) {
72
+ if (reroute == null) {
71
73
  return null;
72
74
  }
73
75
  const { permanent } = reroute;
74
76
  const status = permanent ? 308 : 307;
75
77
  const externalRedirect = validateExternalRedirect(reroute);
76
- if (externalRedirect) {
78
+ if (externalRedirect != null && externalRedirect !== "") {
77
79
  log(`External ${type} found`, { [type]: externalRedirect, permanent });
78
80
  return NextResponse.redirect(externalRedirect, { status });
79
81
  }
80
82
  log(`${capitalize(type)} found`, { [type]: reroute, permanent });
81
83
  const { destination } = reroute;
82
84
  const [destinationPathname, search] = splitDestination(destination);
83
- if (search) url.search = search;
85
+ if (search != null)
86
+ url.search = search;
84
87
  url.pathname = destinationPathname;
85
88
  log(`${capitalize(type)}ing to ${url.toString()} with status ${status}`);
86
89
  return NextResponse[type](url, { status });
@@ -105,10 +108,10 @@ const query = `
105
108
  async function fetchPageSettingsTranslation(path) {
106
109
  const graphqlEndpoint = process.env.NEXT_SERVER_GRAPHQL_URL || process.env.NEXT_PUBLIC_GRAPHQL_URL;
107
110
  const graphqlApiKey = process.env.NEXT_PUBLIC_API_TOKEN;
108
- if (!graphqlEndpoint) {
111
+ if (graphqlEndpoint == null || graphqlEndpoint === "") {
109
112
  throw new Error("Missing GraphQL configuration `graphqlEndpoint`");
110
113
  }
111
- if (!graphqlApiKey) {
114
+ if (graphqlApiKey == null || graphqlApiKey === "") {
112
115
  throw new Error("Missing GraphQL configuration `graphqlApiKey`");
113
116
  }
114
117
  const variables = {
@@ -123,15 +126,14 @@ async function fetchPageSettingsTranslation(path) {
123
126
  const response = await fetch(graphqlEndpoint, {
124
127
  method: "POST",
125
128
  headers: {
126
- // eslint-disable-next-line @typescript-eslint/naming-convention
127
129
  "Content-Type": "application/json",
128
- Authorization: `Bearer ${graphqlApiKey}`
130
+ "Authorization": `Bearer ${graphqlApiKey}`
129
131
  },
130
132
  body: JSON.stringify({ query, variables })
131
133
  });
132
- const { data } = await response.json();
133
- log("GraphQL response:", data);
134
- return data.page_settings_translations;
134
+ const json = await response.json();
135
+ log("GraphQL response:", json.data);
136
+ return json.data?.page_settings_translations ?? null;
135
137
  } catch (error) {
136
138
  log("GraphQL Error:", error);
137
139
  return null;
@@ -144,7 +146,7 @@ function getValidLocale(maybeLocale, config) {
144
146
  function splitLocaleFromPathname(pathname, config) {
145
147
  const [, maybeLocale, ...parts] = pathname.split("/");
146
148
  const locale = getValidLocale(maybeLocale, config);
147
- if (locale) {
149
+ if (locale != null && locale !== "") {
148
150
  const newPathname = parts.length > 0 ? `/${parts.join("/")}` : "/";
149
151
  return { locale, pathname: newPathname };
150
152
  }
@@ -152,22 +154,18 @@ function splitLocaleFromPathname(pathname, config) {
152
154
  }
153
155
  function getValidTranslation(translations, locale) {
154
156
  const translation = translations[0];
155
- if (!locale) {
157
+ if (locale == null || locale === "") {
156
158
  log("No locale provided, using first translation as default:", { translation });
157
159
  return translation;
158
160
  }
159
- return (translations == null ? void 0 : translations.find((t) => {
160
- var _a, _b;
161
- return (_b = (_a = t.languages_code) == null ? void 0 : _a.code) == null ? void 0 : _b.startsWith(locale);
162
- })) ?? translation;
161
+ return translations?.find((t) => t.languages_code?.code?.startsWith(locale)) ?? translation;
163
162
  }
164
163
  async function directusRouteRouter(request, config, NextResponse$1 = NextResponse) {
165
- var _a, _b, _c;
166
164
  const { pathname: localizedPathname } = request.nextUrl;
167
165
  const { locale, pathname } = splitLocaleFromPathname(localizedPathname, config);
168
166
  log("Processing request for pathname:", { locale, pathname });
169
- const redirect = await handleRedirect(request, (_a = config.modules) == null ? void 0 : _a.redirects);
170
- if (redirect) {
167
+ const redirect = await handleRedirect(request, config.modules?.redirects);
168
+ if (redirect != null) {
171
169
  return redirect;
172
170
  }
173
171
  const translations = await fetchPageSettingsTranslation(pathname);
@@ -177,23 +175,23 @@ async function directusRouteRouter(request, config, NextResponse$1 = NextRespons
177
175
  }
178
176
  const translation = getValidTranslation(translations, locale);
179
177
  log("Using translation:", translation);
180
- if (!translation || !translation.languages_code || !translation.page_settings_id) {
178
+ if (translation == null || translation.languages_code == null || translation.page_settings_id == null) {
181
179
  log(`Invalid translation data for path: ${pathname}`, { pathname }, "warn");
182
180
  return NextResponse$1.next();
183
181
  }
184
182
  const directusLocale = translation.languages_code.code;
185
183
  const collection = translation.page_settings_id.belongs_to_collection;
186
184
  const id = translation.page_settings_id.belongs_to_key;
187
- if (!collection) {
185
+ if (collection == null || collection === "") {
188
186
  log(`PageSettings with id ${id} was found but is not associated with any collection.`, { id }, "warn");
189
187
  return NextResponse$1.next();
190
188
  }
191
- if (!directusLocale) {
189
+ if (directusLocale == null || directusLocale === "") {
192
190
  log(`PageSettings with id ${id} was found but is not associated with any locale.`, { id }, "warn");
193
191
  return NextResponse$1.next();
194
192
  }
195
- const mappedLocale = ((_b = config.localeMap) == null ? void 0 : _b[directusLocale]) || directusLocale;
196
- const idField = ((_c = config.collectionSettings[collection]) == null ? void 0 : _c.idField) || config.collectionSettings.default.idField;
193
+ const mappedLocale = config.localeMap?.[directusLocale] || directusLocale;
194
+ const idField = config.collectionSettings[collection]?.idField || config.collectionSettings.default.idField;
197
195
  log("Directus locale:", directusLocale);
198
196
  log("Mapped locale:", mappedLocale);
199
197
  log("Collection:", collection);
package/server.d.ts CHANGED
@@ -1,3 +1,3 @@
1
+ export * from './pageSettings';
1
2
  export { directusRouteRouter } from './router/router';
2
3
  export type { TDirectusRouteConfig } from './types/directusRouteConfig';
3
- export * from './pageSettings';
package/server.js CHANGED
@@ -1,11 +1,11 @@
1
1
  "use server";
2
2
  "use strict";
3
3
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
- const router = require("./router-DTZYUtal.js");
4
+ const router = require("./router-CwzG5Cu9.js");
5
5
  const directusQuery = require("@okam/directus-query");
6
6
  const radashi = require("radashi");
7
- require("server-only");
8
7
  const server = require("@okam/next-component/server");
8
+ require("server-only");
9
9
  function pageSettingsContext(defaultValue) {
10
10
  const [pageSettings, setPageSettings] = server.createServerContext(defaultValue);
11
11
  return [pageSettings, setPageSettings];
@@ -17,11 +17,11 @@ function pageSettingsVariablesContext(variables) {
17
17
  const [getPageSettingsContext, setPageSettingsContext] = pageSettingsContext();
18
18
  const [getVariables, setVariables] = pageSettingsVariablesContext();
19
19
  function isTDirectusRouteConfig(config) {
20
- return !!config && "localeMap" in config;
20
+ return config != null && "localeMap" in config;
21
21
  }
22
22
  function getDirectusVariables(variables, config) {
23
23
  const localeMap = isTDirectusRouteConfig(config) ? config.localeMap : config;
24
- if (!localeMap) {
24
+ if (localeMap == null) {
25
25
  return variables;
26
26
  }
27
27
  const locale = radashi.get(variables, "locale");
@@ -29,27 +29,26 @@ function getDirectusVariables(variables, config) {
29
29
  return { ...variables, locale: directusLocale };
30
30
  }
31
31
  async function getPageSettings(props, itemKey) {
32
- var _a, _b, _c, _d, _e;
33
32
  const { variables, config } = props ?? {};
34
33
  const directusVariables = getDirectusVariables(variables, config);
35
34
  const defaultReturn = getPageSettingsContext();
36
- if (!props || radashi.isEqual(getVariables(), directusVariables)) {
37
- router.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 });
35
+ if (props == null || radashi.isEqual(getVariables(), directusVariables)) {
36
+ router.log("Using cached page settings", { path: defaultReturn.page_settings?.translations?.[0]?.path });
38
37
  return defaultReturn;
39
38
  }
40
39
  const { document } = props;
41
40
  const key = itemKey ?? radashi.get(document, "definitions[0].selectionSet.selections[0].name.value");
42
41
  router.log("Querying new page settings", directusVariables);
43
42
  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) {
43
+ const items = result?.[key];
44
+ const currentItem = Array.isArray(items) ? items?.[0] : items;
45
+ const currentPageSettings = currentItem?.page_settings;
46
+ const currentPath = currentPageSettings?.translations?.[0]?.path;
47
+ if (currentItem == null) {
49
48
  router.log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
50
49
  return defaultReturn;
51
50
  }
52
- if (!currentPageSettings) {
51
+ if (currentPageSettings == null) {
53
52
  router.log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
54
53
  return defaultReturn;
55
54
  }
@@ -61,4 +60,6 @@ async function getPageSettings(props, itemKey) {
61
60
  const usePageSettings = getPageSettings;
62
61
  exports.directusRouteRouter = router.directusRouteRouter;
63
62
  exports.getPageSettings = getPageSettings;
63
+ exports.pageSettingsContext = pageSettingsContext;
64
+ exports.pageSettingsVariablesContext = pageSettingsVariablesContext;
64
65
  exports.usePageSettings = usePageSettings;
package/server.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  "use server";
2
- import { c as log } from "./router-CA4ItnAc.mjs";
3
- import { d } from "./router-CA4ItnAc.mjs";
2
+ import { c as log } from "./router-oaFeb_tY.mjs";
3
+ import { d } from "./router-oaFeb_tY.mjs";
4
4
  import { queryGql } from "@okam/directus-query";
5
5
  import { isEqual, get, invert } from "radashi";
6
- import "server-only";
7
6
  import { createServerContext } from "@okam/next-component/server";
7
+ import "server-only";
8
8
  function pageSettingsContext(defaultValue) {
9
9
  const [pageSettings, setPageSettings] = createServerContext(defaultValue);
10
10
  return [pageSettings, setPageSettings];
@@ -16,11 +16,11 @@ function pageSettingsVariablesContext(variables) {
16
16
  const [getPageSettingsContext, setPageSettingsContext] = pageSettingsContext();
17
17
  const [getVariables, setVariables] = pageSettingsVariablesContext();
18
18
  function isTDirectusRouteConfig(config) {
19
- return !!config && "localeMap" in config;
19
+ return config != null && "localeMap" in config;
20
20
  }
21
21
  function getDirectusVariables(variables, config) {
22
22
  const localeMap = isTDirectusRouteConfig(config) ? config.localeMap : config;
23
- if (!localeMap) {
23
+ if (localeMap == null) {
24
24
  return variables;
25
25
  }
26
26
  const locale = get(variables, "locale");
@@ -28,27 +28,26 @@ function getDirectusVariables(variables, config) {
28
28
  return { ...variables, locale: directusLocale };
29
29
  }
30
30
  async function getPageSettings(props, itemKey) {
31
- var _a, _b, _c, _d, _e;
32
31
  const { variables, config } = props ?? {};
33
32
  const directusVariables = getDirectusVariables(variables, config);
34
33
  const defaultReturn = getPageSettingsContext();
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 });
34
+ if (props == null || isEqual(getVariables(), directusVariables)) {
35
+ log("Using cached page settings", { path: defaultReturn.page_settings?.translations?.[0]?.path });
37
36
  return defaultReturn;
38
37
  }
39
38
  const { document } = props;
40
39
  const key = itemKey ?? get(document, "definitions[0].selectionSet.selections[0].name.value");
41
40
  log("Querying new page settings", directusVariables);
42
41
  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) {
42
+ const items = result?.[key];
43
+ const currentItem = Array.isArray(items) ? items?.[0] : items;
44
+ const currentPageSettings = currentItem?.page_settings;
45
+ const currentPath = currentPageSettings?.translations?.[0]?.path;
46
+ if (currentItem == null) {
48
47
  log("No item found. Falling back to cached page settings", { path: currentPath }, "warn");
49
48
  return defaultReturn;
50
49
  }
51
- if (!currentPageSettings) {
50
+ if (currentPageSettings == null) {
52
51
  log("No page settings found. Falling back to cached page settings", { path: currentPath }, "warn");
53
52
  return defaultReturn;
54
53
  }
@@ -61,5 +60,7 @@ const usePageSettings = getPageSettings;
61
60
  export {
62
61
  d as directusRouteRouter,
63
62
  getPageSettings,
63
+ pageSettingsContext,
64
+ pageSettingsVariablesContext,
64
65
  usePageSettings
65
66
  };
package/types/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export type { TDirectusRouteConfig, TDirectusRouteRedirectsModule } from './directusRouteConfig';
2
- export type { TPageSettingsTranslation, TPageSettings, TPageSettingsItemQuery, TPageSettingsQueryItem, } from './pageSettings';
2
+ export type { TPageSettings, TPageSettingsItemQuery, TPageSettingsQueryItem, TPageSettingsTranslation, } from './pageSettings';
@@ -1,6 +1,5 @@
1
1
  import { TFiles } from '../files';
2
2
  import { Fragmentize } from './Fragments';
3
-
4
3
  export interface TPageSettingsTranslation {
5
4
  languages_code?: {
6
5
  code?: string | null | undefined;