@okam/directus-node 0.5.0 → 0.6.1

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,31 @@
1
+ ## 0.6.1 (2025-07-23)
2
+
3
+ ### 🩹 Fixes
4
+
5
+ - directus next directus node builds ([#317](https://github.com/OKAMca/stack/pull/317))
6
+
7
+ ### ❤️ Thank You
8
+
9
+ - Pierre-Olivier Clerson @poclerson
10
+
11
+ ## 0.6.0 (2025-07-22)
12
+
13
+ ### 🚀 Features
14
+
15
+ - **directus-next:** /api/redirect route handler to fetch + cache directus redirects ([c21b953](https://github.com/OKAMca/stack/commit/c21b953))
16
+
17
+ ### 🩹 Fixes
18
+
19
+ - **directus-node:** export edge-compatible code from separate file ([9f77744](https://github.com/OKAMca/stack/commit/9f77744))
20
+ - package deps error ([b665a45](https://github.com/OKAMca/stack/commit/b665a45))
21
+ - search field icon ([0850fde](https://github.com/OKAMca/stack/commit/0850fde))
22
+
23
+ ### ❤️ Thank You
24
+
25
+ - Marie-Maxime Tanguay
26
+ - Pierre-Olivier Clerson @poclerson
27
+ - poclerson
28
+
1
29
  ## 0.5.0 (2025-01-30)
2
30
 
3
31
  ### 🚀 Features
package/edge.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @fileoverview Export file for functions that are used in edge functions (middleware-compatible)
3
+ */
4
+ export type { TFetchRedirectsConfig, TFetchRedirectsResponse, TRedirectData, TRedirectType, } from './lib/redirection/interface';
5
+ export { fetchRedirectsData, getDefaultConfig } from './lib/redirection/fetchRedirectsData';
6
+ export { isRedirect, normalizeRedirects } from './lib/redirection/utils/validateRedirects';
package/edge.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const fetchRedirectsData = require("./fetchRedirectsData-nz-uddGa.js");
4
+ exports.fetchRedirectsData = fetchRedirectsData.fetchRedirectsData;
5
+ exports.getDefaultConfig = fetchRedirectsData.getDefaultConfig;
6
+ exports.isRedirect = fetchRedirectsData.isRedirect;
7
+ exports.normalizeRedirects = fetchRedirectsData.normalizeRedirects;
package/edge.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { f, g, i, n } from "./fetchRedirectsData-DGLawlch.mjs";
2
+ export {
3
+ f as fetchRedirectsData,
4
+ g as getDefaultConfig,
5
+ i as isRedirect,
6
+ n as normalizeRedirects
7
+ };
@@ -0,0 +1,111 @@
1
+ import { logger } from "@okam/logger";
2
+ import { normalizePath } from "@okam/core-lib";
3
+ function isRedirect(redirect) {
4
+ return !!redirect && typeof redirect === "object" && "source" in redirect && "destination" in redirect;
5
+ }
6
+ function normalizeRedirects(redirects) {
7
+ if (!redirects || !Array.isArray(redirects)) return [];
8
+ return redirects.flatMap((redirect) => {
9
+ const { source, destination, ...rest } = redirect ?? {};
10
+ if (!redirect || !source || !destination || !isRedirect(redirect)) return [];
11
+ return [
12
+ {
13
+ ...rest,
14
+ source: normalizePath(source),
15
+ destination: normalizePath(destination)
16
+ }
17
+ ];
18
+ });
19
+ }
20
+ const redirectDefaultLimit = 2e3;
21
+ function getDefaultConfig() {
22
+ return {
23
+ graphqlEndpoint: process.env["NEXT_REDIRECT_GRAPHQL_URL"] || process.env["NEXT_PUBLIC_GRAPHQL_URL"] || "",
24
+ graphqlApiKey: process.env["NEXT_API_TOKEN_ADMIN"] || "",
25
+ redirectsFilename: "./redirect/redirects.json",
26
+ rewritesFilename: "./redirect/rewrites.json",
27
+ limit: redirectDefaultLimit
28
+ };
29
+ }
30
+ async function fetchRedirectsData(config, init) {
31
+ const {
32
+ graphqlApiKey: defaultGraphqlApiKey,
33
+ graphqlEndpoint: defaultGraphqlEndpoint,
34
+ limit: defaultLimit
35
+ } = getDefaultConfig();
36
+ const {
37
+ graphqlEndpoint = defaultGraphqlEndpoint,
38
+ graphqlApiKey = defaultGraphqlApiKey,
39
+ limit = defaultLimit
40
+ } = config;
41
+ if (!graphqlEndpoint) {
42
+ throw new Error(
43
+ "Missing fetchRedirects configuration `graphqlEndpoint`. Check environment variables NEXT_REDIRECT_GRAPHQL_URL or NEXT_PUBLIC_GRAPHQL_URL"
44
+ );
45
+ }
46
+ if (!graphqlApiKey) {
47
+ throw new Error(
48
+ "Missing fetchRedirects configuration `graphqlApiKey`. Check environment variable NEXT_API_TOKEN_ADMIN"
49
+ );
50
+ }
51
+ const query = `query fetchRedirects($limit: Int = 2000) {
52
+ redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:false}}, sort: "sort", limit: $limit) {
53
+ source
54
+ destination
55
+ permanent
56
+ locale
57
+ }
58
+ rewrites: redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:true}}, sort: "sort", limit: $limit) {
59
+ source
60
+ destination
61
+ permanent
62
+ locale
63
+ }
64
+ }`;
65
+ const graphqlBody = {
66
+ query,
67
+ // "operationName": "",
68
+ variables: {
69
+ limit: Number(limit) || redirectDefaultLimit
70
+ }
71
+ };
72
+ try {
73
+ const response = await fetch(graphqlEndpoint, {
74
+ ...init,
75
+ method: "POST",
76
+ headers: {
77
+ // eslint-disable-next-line @typescript-eslint/naming-convention
78
+ "Content-Type": "application/json",
79
+ Authorization: `Bearer ${graphqlApiKey}`
80
+ },
81
+ body: JSON.stringify(graphqlBody)
82
+ });
83
+ const { data } = await response.json();
84
+ const { redirects, rewrites } = data ?? {};
85
+ if (!(redirects == null ? void 0 : redirects.length) && !(rewrites == null ? void 0 : rewrites.length)) {
86
+ logger.log("No redirects/rewrites found", "warn");
87
+ return {
88
+ redirects: [],
89
+ rewrites: []
90
+ };
91
+ }
92
+ logger.log(`Fetch redirects count: ${(redirects == null ? void 0 : redirects.length) || 0}, rewrites count: ${(rewrites == null ? void 0 : rewrites.length) || 0}`);
93
+ return {
94
+ redirects: normalizeRedirects(redirects),
95
+ rewrites: normalizeRedirects(rewrites)
96
+ };
97
+ } catch (e) {
98
+ logger.log(`Error fetching redirects: ${e.message}`, "error");
99
+ }
100
+ return {
101
+ redirects: [],
102
+ rewrites: []
103
+ };
104
+ }
105
+ export {
106
+ fetchRedirectsData as f,
107
+ getDefaultConfig as g,
108
+ isRedirect as i,
109
+ normalizeRedirects as n,
110
+ redirectDefaultLimit as r
111
+ };
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ const logger = require("@okam/logger");
3
+ const coreLib = require("@okam/core-lib");
4
+ function isRedirect(redirect) {
5
+ return !!redirect && typeof redirect === "object" && "source" in redirect && "destination" in redirect;
6
+ }
7
+ function normalizeRedirects(redirects) {
8
+ if (!redirects || !Array.isArray(redirects)) return [];
9
+ return redirects.flatMap((redirect) => {
10
+ const { source, destination, ...rest } = redirect ?? {};
11
+ if (!redirect || !source || !destination || !isRedirect(redirect)) return [];
12
+ return [
13
+ {
14
+ ...rest,
15
+ source: coreLib.normalizePath(source),
16
+ destination: coreLib.normalizePath(destination)
17
+ }
18
+ ];
19
+ });
20
+ }
21
+ const redirectDefaultLimit = 2e3;
22
+ function getDefaultConfig() {
23
+ return {
24
+ graphqlEndpoint: process.env["NEXT_REDIRECT_GRAPHQL_URL"] || process.env["NEXT_PUBLIC_GRAPHQL_URL"] || "",
25
+ graphqlApiKey: process.env["NEXT_API_TOKEN_ADMIN"] || "",
26
+ redirectsFilename: "./redirect/redirects.json",
27
+ rewritesFilename: "./redirect/rewrites.json",
28
+ limit: redirectDefaultLimit
29
+ };
30
+ }
31
+ async function fetchRedirectsData(config, init) {
32
+ const {
33
+ graphqlApiKey: defaultGraphqlApiKey,
34
+ graphqlEndpoint: defaultGraphqlEndpoint,
35
+ limit: defaultLimit
36
+ } = getDefaultConfig();
37
+ const {
38
+ graphqlEndpoint = defaultGraphqlEndpoint,
39
+ graphqlApiKey = defaultGraphqlApiKey,
40
+ limit = defaultLimit
41
+ } = config;
42
+ if (!graphqlEndpoint) {
43
+ throw new Error(
44
+ "Missing fetchRedirects configuration `graphqlEndpoint`. Check environment variables NEXT_REDIRECT_GRAPHQL_URL or NEXT_PUBLIC_GRAPHQL_URL"
45
+ );
46
+ }
47
+ if (!graphqlApiKey) {
48
+ throw new Error(
49
+ "Missing fetchRedirects configuration `graphqlApiKey`. Check environment variable NEXT_API_TOKEN_ADMIN"
50
+ );
51
+ }
52
+ const query = `query fetchRedirects($limit: Int = 2000) {
53
+ redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:false}}, sort: "sort", limit: $limit) {
54
+ source
55
+ destination
56
+ permanent
57
+ locale
58
+ }
59
+ rewrites: redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:true}}, sort: "sort", limit: $limit) {
60
+ source
61
+ destination
62
+ permanent
63
+ locale
64
+ }
65
+ }`;
66
+ const graphqlBody = {
67
+ query,
68
+ // "operationName": "",
69
+ variables: {
70
+ limit: Number(limit) || redirectDefaultLimit
71
+ }
72
+ };
73
+ try {
74
+ const response = await fetch(graphqlEndpoint, {
75
+ ...init,
76
+ method: "POST",
77
+ headers: {
78
+ // eslint-disable-next-line @typescript-eslint/naming-convention
79
+ "Content-Type": "application/json",
80
+ Authorization: `Bearer ${graphqlApiKey}`
81
+ },
82
+ body: JSON.stringify(graphqlBody)
83
+ });
84
+ const { data } = await response.json();
85
+ const { redirects, rewrites } = data ?? {};
86
+ if (!(redirects == null ? void 0 : redirects.length) && !(rewrites == null ? void 0 : rewrites.length)) {
87
+ logger.logger.log("No redirects/rewrites found", "warn");
88
+ return {
89
+ redirects: [],
90
+ rewrites: []
91
+ };
92
+ }
93
+ logger.logger.log(`Fetch redirects count: ${(redirects == null ? void 0 : redirects.length) || 0}, rewrites count: ${(rewrites == null ? void 0 : rewrites.length) || 0}`);
94
+ return {
95
+ redirects: normalizeRedirects(redirects),
96
+ rewrites: normalizeRedirects(rewrites)
97
+ };
98
+ } catch (e) {
99
+ logger.logger.log(`Error fetching redirects: ${e.message}`, "error");
100
+ }
101
+ return {
102
+ redirects: [],
103
+ rewrites: []
104
+ };
105
+ }
106
+ exports.fetchRedirectsData = fetchRedirectsData;
107
+ exports.getDefaultConfig = getDefaultConfig;
108
+ exports.isRedirect = isRedirect;
109
+ exports.normalizeRedirects = normalizeRedirects;
110
+ exports.redirectDefaultLimit = redirectDefaultLimit;
package/index.js ADDED
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const fetchRedirectsData$1 = require("./fetchRedirectsData-nz-uddGa.js");
4
+ require("@okam/core-lib");
5
+ const logger$1 = require("@okam/logger");
6
+ const promises = require("fs/promises");
7
+ const path = require("path");
8
+ function _interopNamespaceDefault(e) {
9
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
10
+ if (e) {
11
+ for (const k in e) {
12
+ if (k !== "default") {
13
+ const d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: () => e[k]
17
+ });
18
+ }
19
+ }
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+ const path__namespace = /* @__PURE__ */ _interopNamespaceDefault(path);
25
+ const logger = logger$1.createLogger("[DirectusNode]");
26
+ async function writeRedirectFile(filename, data) {
27
+ try {
28
+ const writeData = JSON.stringify(data || []);
29
+ await promises.writeFile(filename, writeData);
30
+ return true;
31
+ } catch (e) {
32
+ logger.log(`Error writing redirect file ${filename}: ${e.message}`, "error");
33
+ }
34
+ return false;
35
+ }
36
+ async function readRedirectFileData(filename) {
37
+ try {
38
+ const file = await promises.readFile(filename, { encoding: "utf8" });
39
+ const data = JSON.parse(file);
40
+ return data;
41
+ } catch (e) {
42
+ logger.log(`Failed loading redirects JSON from ${filename}: ${e.message}`, "error");
43
+ }
44
+ return [];
45
+ }
46
+ async function readRedirectFile(filePath, type = "redirects") {
47
+ const absolutePath = path__namespace.resolve(process.cwd(), filePath);
48
+ const data = await readRedirectFileData(absolutePath);
49
+ if (Array.isArray(data)) {
50
+ const checkedData = data.filter((x) => {
51
+ return x && typeof (x == null ? void 0 : x.source) === "string" && typeof (x == null ? void 0 : x.destination) === "string";
52
+ });
53
+ logger.log(`Loading ${type} length: ${checkedData.length}`);
54
+ return checkedData;
55
+ }
56
+ logger.log(`Failed loading ${type}, not a valid array`, "error");
57
+ return [];
58
+ }
59
+ async function fetchRedirects(config) {
60
+ const { redirectsFilename, rewritesFilename } = config;
61
+ if (!redirectsFilename) {
62
+ throw new Error("Missing fetchRedirects configuration `redirectsFilename`");
63
+ }
64
+ if (!rewritesFilename) {
65
+ throw new Error("Missing fetchRedirects configuration `rewritesFilename`");
66
+ }
67
+ const data = await fetchRedirectsData$1.fetchRedirectsData(config);
68
+ await writeRedirectFile(redirectsFilename, data.redirects);
69
+ await writeRedirectFile(rewritesFilename, data.rewrites);
70
+ return true;
71
+ }
72
+ const fetchRedirectsData = fetchRedirectsData$1.fetchRedirectsData;
73
+ const getDefaultConfig = fetchRedirectsData$1.getDefaultConfig;
74
+ const redirectDefaultLimit = fetchRedirectsData$1.redirectDefaultLimit;
75
+ const graphqlCodegenConfig = (schemaUrl, generatePath, headers) => {
76
+ const config = {
77
+ overwrite: true,
78
+ schema: [
79
+ {
80
+ [schemaUrl]: {
81
+ headers
82
+ }
83
+ }
84
+ ],
85
+ documents: [`${__dirname}/apps/demo/**/*.graphql`],
86
+ ignoreNoDocuments: true,
87
+ // for better experience with the watcher
88
+ generates: {
89
+ [generatePath]: {
90
+ preset: "client"
91
+ }
92
+ }
93
+ };
94
+ return config;
95
+ };
96
+ exports.isRedirect = fetchRedirectsData$1.isRedirect;
97
+ exports.normalizeRedirects = fetchRedirectsData$1.normalizeRedirects;
98
+ exports.DirectusNodeLogger = logger;
99
+ exports.fetchRedirects = fetchRedirects;
100
+ exports.fetchRedirectsData = fetchRedirectsData;
101
+ exports.getDefaultConfig = getDefaultConfig;
102
+ exports.graphqlCodegenConfig = graphqlCodegenConfig;
103
+ exports.readRedirectFile = readRedirectFile;
104
+ exports.readRedirectFileData = readRedirectFileData;
105
+ exports.redirectDefaultLimit = redirectDefaultLimit;
106
+ exports.writeRedirectFile = writeRedirectFile;
package/index.mjs ADDED
@@ -0,0 +1,90 @@
1
+ import { f as fetchRedirectsData$1, g as getDefaultConfig$1, r as redirectDefaultLimit$1 } from "./fetchRedirectsData-DGLawlch.mjs";
2
+ import { i, n } from "./fetchRedirectsData-DGLawlch.mjs";
3
+ import "@okam/core-lib";
4
+ import { createLogger } from "@okam/logger";
5
+ import { writeFile, readFile } from "fs/promises";
6
+ import * as path from "path";
7
+ const logger = createLogger("[DirectusNode]");
8
+ async function writeRedirectFile(filename, data) {
9
+ try {
10
+ const writeData = JSON.stringify(data || []);
11
+ await writeFile(filename, writeData);
12
+ return true;
13
+ } catch (e) {
14
+ logger.log(`Error writing redirect file ${filename}: ${e.message}`, "error");
15
+ }
16
+ return false;
17
+ }
18
+ async function readRedirectFileData(filename) {
19
+ try {
20
+ const file = await readFile(filename, { encoding: "utf8" });
21
+ const data = JSON.parse(file);
22
+ return data;
23
+ } catch (e) {
24
+ logger.log(`Failed loading redirects JSON from ${filename}: ${e.message}`, "error");
25
+ }
26
+ return [];
27
+ }
28
+ async function readRedirectFile(filePath, type = "redirects") {
29
+ const absolutePath = path.resolve(process.cwd(), filePath);
30
+ const data = await readRedirectFileData(absolutePath);
31
+ if (Array.isArray(data)) {
32
+ const checkedData = data.filter((x) => {
33
+ return x && typeof (x == null ? void 0 : x.source) === "string" && typeof (x == null ? void 0 : x.destination) === "string";
34
+ });
35
+ logger.log(`Loading ${type} length: ${checkedData.length}`);
36
+ return checkedData;
37
+ }
38
+ logger.log(`Failed loading ${type}, not a valid array`, "error");
39
+ return [];
40
+ }
41
+ async function fetchRedirects(config) {
42
+ const { redirectsFilename, rewritesFilename } = config;
43
+ if (!redirectsFilename) {
44
+ throw new Error("Missing fetchRedirects configuration `redirectsFilename`");
45
+ }
46
+ if (!rewritesFilename) {
47
+ throw new Error("Missing fetchRedirects configuration `rewritesFilename`");
48
+ }
49
+ const data = await fetchRedirectsData$1(config);
50
+ await writeRedirectFile(redirectsFilename, data.redirects);
51
+ await writeRedirectFile(rewritesFilename, data.rewrites);
52
+ return true;
53
+ }
54
+ const fetchRedirectsData = fetchRedirectsData$1;
55
+ const getDefaultConfig = getDefaultConfig$1;
56
+ const redirectDefaultLimit = redirectDefaultLimit$1;
57
+ const graphqlCodegenConfig = (schemaUrl, generatePath, headers) => {
58
+ const config = {
59
+ overwrite: true,
60
+ schema: [
61
+ {
62
+ [schemaUrl]: {
63
+ headers
64
+ }
65
+ }
66
+ ],
67
+ documents: [`${__dirname}/apps/demo/**/*.graphql`],
68
+ ignoreNoDocuments: true,
69
+ // for better experience with the watcher
70
+ generates: {
71
+ [generatePath]: {
72
+ preset: "client"
73
+ }
74
+ }
75
+ };
76
+ return config;
77
+ };
78
+ export {
79
+ logger as DirectusNodeLogger,
80
+ fetchRedirects,
81
+ fetchRedirectsData,
82
+ getDefaultConfig,
83
+ graphqlCodegenConfig,
84
+ i as isRedirect,
85
+ n as normalizeRedirects,
86
+ readRedirectFile,
87
+ readRedirectFileData,
88
+ redirectDefaultLimit,
89
+ writeRedirectFile
90
+ };
@@ -0,0 +1,8 @@
1
+ import type { TFetchRedirectsConfig, TFetchRedirectsResponse } from './interface';
2
+ export declare const redirectDefaultLimit = 2000;
3
+ /**
4
+ * Get Fetch Redirects Configuration
5
+ * @returns {object}
6
+ */
7
+ export declare function getDefaultConfig(): TFetchRedirectsConfig;
8
+ export declare function fetchRedirectsData(config: TFetchRedirectsConfig, init?: Omit<RequestInit, 'body' | 'method' | 'headers'>): Promise<TFetchRedirectsResponse>;
@@ -0,0 +1,16 @@
1
+ import * as fetchRedirectsDataFile from './fetchRedirectsData';
2
+ /**
3
+ * @deprecated Import from `@okam/directus-node/edge` instead
4
+ */
5
+ export declare const fetchRedirectsData: typeof fetchRedirectsDataFile.fetchRedirectsData;
6
+ /**
7
+ * @deprecated Import from `@okam/directus-node/edge` instead
8
+ */
9
+ export declare const getDefaultConfig: typeof fetchRedirectsDataFile.getDefaultConfig;
10
+ /**
11
+ * @deprecated Import from `@okam/directus-node/edge` instead
12
+ */
13
+ export declare const redirectDefaultLimit = 2000;
14
+ export type { TFetchRedirectsConfig, TFetchRedirectsResponse, TRedirectData, TRedirectType } from './interface';
15
+ export * from './utils/validateRedirects';
16
+ export * from './redirectsFile';
@@ -0,0 +1,18 @@
1
+ export interface TFetchRedirectsConfig {
2
+ graphqlEndpoint: string | undefined;
3
+ graphqlApiKey: string | undefined;
4
+ redirectsFilename?: string;
5
+ rewritesFilename?: string;
6
+ limit: number | undefined;
7
+ }
8
+ export interface TFetchRedirectsResponse {
9
+ redirects: TRedirectData[];
10
+ rewrites: TRedirectData[];
11
+ }
12
+ export interface TRedirectData {
13
+ source: string;
14
+ destination: string;
15
+ permanent?: boolean;
16
+ locale?: boolean;
17
+ }
18
+ export type TRedirectType = 'redirects' | 'rewrites';
@@ -1,28 +1,4 @@
1
- interface TFetchRedirectsConfig {
2
- graphqlEndpoint: string;
3
- graphqlApiKey: string;
4
- redirectsFilename?: string;
5
- rewritesFilename?: string;
6
- limit: number | undefined;
7
- }
8
- interface TFetchRedirectsResponse {
9
- redirects: unknown;
10
- rewrites: unknown;
11
- }
12
- interface TRedirectData {
13
- source: string;
14
- destination: string;
15
- permanent?: boolean;
16
- locale?: boolean;
17
- }
18
- type TRedirectType = 'redirects' | 'rewrites';
19
- export declare const redirectDefaultLimit = 2000;
20
- /**
21
- * Get Fetch Redirects Configuration
22
- * @returns {object}
23
- */
24
- export declare function getDefaultConfig(): TFetchRedirectsConfig;
25
- export declare function fetchRedirectsData(config: TFetchRedirectsConfig): Promise<TFetchRedirectsResponse>;
1
+ import type { TFetchRedirectsConfig, TRedirectType, TRedirectData } from './interface';
26
2
  /**
27
3
  * Write Redirect Data
28
4
  * @param {string} filename filename
@@ -44,4 +20,3 @@ export declare function readRedirectFile(filePath: string, type?: TRedirectType)
44
20
  * @throws {Error}
45
21
  */
46
22
  export declare function fetchRedirects(config: TFetchRedirectsConfig): Promise<boolean>;
47
- export {};
@@ -0,0 +1,3 @@
1
+ import type { TRedirectData } from '../interface';
2
+ export declare function isRedirect(redirect: unknown): boolean;
3
+ export declare function normalizeRedirects(redirects: (TRedirectData | null)[] | null): TRedirectData[];
package/package.json CHANGED
@@ -1,18 +1,39 @@
1
1
  {
2
2
  "name": "@okam/directus-node",
3
3
  "main": "./src/index.js",
4
- "version": "0.5.0",
4
+ "version": "0.6.1",
5
5
  "types": "./src/index.d.ts",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./index.d.ts",
13
+ "default": "./index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./index.d.ts",
17
+ "default": "./index.mjs"
18
+ }
19
+ },
20
+ "./edge": {
21
+ "import": {
22
+ "types": "./edge.d.ts",
23
+ "default": "./edge.mjs"
24
+ },
25
+ "require": {
26
+ "types": "./edge.d.ts",
27
+ "default": "./edge.mjs"
28
+ }
29
+ }
30
+ },
9
31
  "repository": {
10
32
  "url": "https://github.com/OKAMca/stack.git"
11
33
  },
12
34
  "dependencies": {
13
35
  "@graphql-codegen/cli": "^5.0.3",
14
36
  "@okam/logger": "1.1.0",
15
- "tslib": "^2.8.1"
16
- },
17
- "type": "commonjs"
18
- }
37
+ "@okam/core-lib": "1.16.0"
38
+ }
39
+ }
package/src/index.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DirectusNodeLogger = exports.graphqlCodegenConfig = void 0;
4
- const tslib_1 = require("tslib");
5
- tslib_1.__exportStar(require("./lib/redirection"), exports);
6
- var codegen_1 = require("./lib/codegen");
7
- Object.defineProperty(exports, "graphqlCodegenConfig", { enumerable: true, get: function () { return tslib_1.__importDefault(codegen_1).default; } });
8
- var logger_1 = require("./logger");
9
- Object.defineProperty(exports, "DirectusNodeLogger", { enumerable: true, get: function () { return logger_1.logger; } });
10
- //# sourceMappingURL=index.js.map
package/src/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../libs/directus/directus-node/src/index.ts"],"names":[],"mappings":";;;;AAAA,4DAAiC;AACjC,yCAA+D;AAAtD,wIAAA,OAAO,OAAwB;AACxC,mCAAuD;AAA9C,4GAAA,MAAM,OAAsB"}
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const graphqlCodegenConfig = (schemaUrl, generatePath, headers) => {
4
- const config = {
5
- overwrite: true,
6
- schema: [
7
- {
8
- [schemaUrl]: {
9
- headers,
10
- },
11
- },
12
- ],
13
- documents: [`${__dirname}/apps/demo/**/*.graphql`],
14
- ignoreNoDocuments: true, // for better experience with the watcher
15
- generates: {
16
- [generatePath]: {
17
- preset: 'client',
18
- },
19
- },
20
- };
21
- return config;
22
- };
23
- exports.default = graphqlCodegenConfig;
24
- //# sourceMappingURL=codegen.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"codegen.js","sourceRoot":"","sources":["../../../../../../libs/directus/directus-node/src/lib/codegen.ts"],"names":[],"mappings":";;AAEA,MAAM,oBAAoB,GAAG,CAAC,SAAiB,EAAE,YAAoB,EAAE,OAA+B,EAAE,EAAE;IACxG,MAAM,MAAM,GAAkB;QAC5B,SAAS,EAAE,IAAI;QACf,MAAM,EAAE;YACN;gBACE,CAAC,SAAS,CAAC,EAAE;oBACX,OAAO;iBACR;aACF;SACF;QACD,SAAS,EAAE,CAAC,GAAG,SAAS,yBAAyB,CAAC;QAClD,iBAAiB,EAAE,IAAI,EAAE,yCAAyC;QAClE,SAAS,EAAE;YACT,CAAC,YAAY,CAAC,EAAE;gBACd,MAAM,EAAE,QAAQ;aACjB;SACF;KACF,CAAA;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAED,kBAAe,oBAAoB,CAAA"}
@@ -1,162 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.redirectDefaultLimit = void 0;
4
- exports.getDefaultConfig = getDefaultConfig;
5
- exports.fetchRedirectsData = fetchRedirectsData;
6
- exports.writeRedirectFile = writeRedirectFile;
7
- exports.readRedirectFileData = readRedirectFileData;
8
- exports.readRedirectFile = readRedirectFile;
9
- exports.fetchRedirects = fetchRedirects;
10
- const tslib_1 = require("tslib");
11
- const promises_1 = require("node:fs/promises");
12
- const path = tslib_1.__importStar(require("node:path"));
13
- const logger_1 = require("../logger");
14
- exports.redirectDefaultLimit = 2000;
15
- /**
16
- * Get Fetch Redirects Configuration
17
- * @returns {object}
18
- */
19
- function getDefaultConfig() {
20
- return {
21
- graphqlEndpoint: process.env['NEXT_REDIRECT_GRAPHQL_URL'] || process.env['NEXT_PUBLIC_GRAPHQL_URL'] || '',
22
- graphqlApiKey: process.env['NEXT_API_TOKEN_ADMIN'] || '',
23
- redirectsFilename: './redirect/redirects.json',
24
- rewritesFilename: './redirect/rewrites.json',
25
- limit: exports.redirectDefaultLimit,
26
- };
27
- }
28
- function fetchRedirectsData(config) {
29
- return tslib_1.__awaiter(this, void 0, void 0, function* () {
30
- var _a, _b;
31
- const { graphqlEndpoint, graphqlApiKey, limit } = config;
32
- if (!graphqlEndpoint) {
33
- throw new Error('Missing fetchRedirects configuration `graphqlEndpoint`. Check environment variables NEXT_REDIRECT_GRAPHQL_URL or NEXT_PUBLIC_GRAPHQL_URL');
34
- }
35
- if (!graphqlApiKey) {
36
- throw new Error('Missing fetchRedirects configuration `graphqlApiKey`. Check environment variable NEXT_API_TOKEN_ADMIN');
37
- }
38
- const query = `query fetchRedirects($limit: Int = 2000) {
39
- redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:false}}, sort: "sort", limit: $limit) {
40
- source
41
- destination
42
- permanent
43
- locale
44
- }
45
- rewrites: redirects(filter: {status:{_eq:"published"},isrewrite:{_eq:true}}, sort: "sort", limit: $limit) {
46
- source
47
- destination
48
- permanent
49
- locale
50
- }
51
- }`;
52
- const graphqlBody = {
53
- query,
54
- // "operationName": "",
55
- variables: {
56
- limit: Number(limit) || exports.redirectDefaultLimit,
57
- },
58
- };
59
- try {
60
- // console.info(`Fetching redirects on ${graphqlEndpoint}`)
61
- const response = yield fetch(graphqlEndpoint, {
62
- method: 'POST',
63
- headers: {
64
- // eslint-disable-next-line @typescript-eslint/naming-convention
65
- 'Content-Type': 'application/json',
66
- Authorization: `Bearer ${graphqlApiKey}`,
67
- },
68
- body: JSON.stringify(graphqlBody),
69
- });
70
- const { data } = yield response.json();
71
- logger_1.logger.log(`Fetch redirects count: ${((_a = data.redirects) === null || _a === void 0 ? void 0 : _a.length) || 0}, rewrites count: ${((_b = data.rewrites) === null || _b === void 0 ? void 0 : _b.length) || 0}`);
72
- return {
73
- redirects: data.redirects || [],
74
- rewrites: data.rewrites || [],
75
- };
76
- }
77
- catch (e) {
78
- logger_1.logger.log(`Error fetching redirects: ${e.message}`, 'error');
79
- }
80
- return {
81
- redirects: [],
82
- rewrites: [],
83
- };
84
- });
85
- }
86
- /**
87
- * Write Redirect Data
88
- * @param {string} filename filename
89
- * @param {unknown} data redirects data (rewrites or redirects)
90
- */
91
- function writeRedirectFile(filename, data) {
92
- return tslib_1.__awaiter(this, void 0, void 0, function* () {
93
- try {
94
- const writeData = JSON.stringify(data || []);
95
- yield (0, promises_1.writeFile)(filename, writeData);
96
- return true;
97
- }
98
- catch (e) {
99
- logger_1.logger.log(`Error writing redirect file ${filename}: ${e.message}`, 'error');
100
- }
101
- return false;
102
- });
103
- }
104
- function readRedirectFileData(filename) {
105
- return tslib_1.__awaiter(this, void 0, void 0, function* () {
106
- try {
107
- const file = yield (0, promises_1.readFile)(filename, { encoding: 'utf8' });
108
- const data = JSON.parse(file);
109
- return data;
110
- }
111
- catch (e) {
112
- logger_1.logger.log(`Failed loading redirects JSON from ${filename}: ${e.message}`, 'error');
113
- }
114
- return [];
115
- });
116
- }
117
- /**
118
- * Read one redirects or rewrites file
119
- * @param {string} filePath relative file path like './redirect/redirects.json' to the current working dir
120
- * @param {TRedirectType} type redirects or rewrites
121
- * @returns {Promise<TRedirectData[]>} an array of redirect information
122
- */
123
- function readRedirectFile(filePath_1) {
124
- return tslib_1.__awaiter(this, arguments, void 0, function* (filePath, type = 'redirects') {
125
- const absolutePath = path.resolve(process.cwd(), filePath);
126
- const data = yield readRedirectFileData(absolutePath);
127
- if (Array.isArray(data)) {
128
- // check data integrity
129
- const checkedData = data.filter((x) => {
130
- return x && typeof (x === null || x === void 0 ? void 0 : x.source) === 'string' && typeof (x === null || x === void 0 ? void 0 : x.destination) === 'string';
131
- });
132
- logger_1.logger.log(`Loading ${type} length: ${checkedData.length}`);
133
- return checkedData;
134
- }
135
- logger_1.logger.log(`Failed loading ${type}, not a valid array`, 'error');
136
- return [];
137
- });
138
- }
139
- /**
140
- * Fetch and write redirects and rewrites files
141
- * @param {TFetchRedirectsConfig} config fetch redirects configuration
142
- * @returns {Promise<boolean>} true
143
- * @throws {Error}
144
- */
145
- function fetchRedirects(config) {
146
- return tslib_1.__awaiter(this, void 0, void 0, function* () {
147
- const { redirectsFilename, rewritesFilename } = config;
148
- if (!redirectsFilename) {
149
- throw new Error('Missing fetchRedirects configuration `redirectsFilename`');
150
- }
151
- if (!rewritesFilename) {
152
- throw new Error('Missing fetchRedirects configuration `rewritesFilename`');
153
- }
154
- // fetch can throw
155
- const data = yield fetchRedirectsData(config);
156
- // should not throw
157
- yield writeRedirectFile(redirectsFilename, data.redirects);
158
- yield writeRedirectFile(rewritesFilename, data.rewrites);
159
- return true;
160
- });
161
- }
162
- //# sourceMappingURL=redirection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"redirection.js","sourceRoot":"","sources":["../../../../../../libs/directus/directus-node/src/lib/redirection.ts"],"names":[],"mappings":";;;AAgCA,4CAQC;AAED,gDA8DC;AAOD,8CASC;AAED,oDASC;AAQD,4CAaC;AAQD,wCAkBC;;AAlLD,+CAAsD;AACtD,wDAAiC;AACjC,sCAAkC;AAwBrB,QAAA,oBAAoB,GAAG,IAAI,CAAA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IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;QAC5E,CAAC;QAED,kBAAkB;QAClB,MAAM,IAAI,GAAG,MAAM,kBAAkB,CAAC,MAAM,CAAC,CAAA;QAE7C,mBAAmB;QACnB,MAAM,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;QAC1D,MAAM,iBAAiB,CAAC,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QACxD,OAAO,IAAI,CAAA;IACb,CAAC;CAAA"}
package/src/logger.js DELETED
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logger = void 0;
4
- const logger_1 = require("@okam/logger");
5
- exports.logger = (0, logger_1.createLogger)('[DirectusNode]');
6
- //# sourceMappingURL=logger.js.map
package/src/logger.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../../../../libs/directus/directus-node/src/logger.ts"],"names":[],"mappings":";;;AAAA,yCAA2C;AAE9B,QAAA,MAAM,GAAG,IAAA,qBAAY,EAAC,gBAAgB,CAAC,CAAA"}
File without changes
File without changes
File without changes