feat: remove node-fetch

This commit is contained in:
Alessio Gravili
2024-02-28 17:36:48 -05:00
parent 0cc4a7d238
commit 4d2d359b06
18 changed files with 909 additions and 1263 deletions

View File

@@ -12,7 +12,7 @@
"clean": "rimraf dist && rimraf packages/payload/dist",
"clean:cache": "rimraf node_modules/.cache && rimraf packages/payload/node_modules/.cache",
"clean:unix": "find . \\( -type d \\( -name node_modules -o -name dist -o -name .cache \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} +",
"dev": "cross-env node ./test/dev.js",
"dev": "cross-env node --trace-deprecation ./test/dev.js",
"dev:generate-graphql-schema": "ts-node -T ./test/generateGraphQLSchema.ts",
"dev:generate-types": "ts-node -T ./test/generateTypes.ts",
"dev:postgres": "pnpm --filter payload run dev:postgres",
@@ -88,7 +88,6 @@
"minimist": "1.2.8",
"mongodb-memory-server": "^9",
"next": "14.1.1-canary.26",
"node-fetch": "2.6.12",
"node-mocks-http": "^1.14.1",
"nodemon": "3.0.3",
"pino": "8.15.0",

View File

@@ -107,7 +107,6 @@
"graphql": "16.8.1",
"graphql-http": "^1.22.0",
"mini-css-extract-plugin": "1.6.2",
"node-fetch": "2.6.12",
"nodemon": "3.0.3",
"object.assign": "4.1.4",
"object.entries": "1.1.6",

View File

@@ -13,7 +13,6 @@ export const getExternalFile = async ({ data, req }: Args): Promise<File> => {
if (typeof url === 'string') {
const fileURL = `${baseUrl}${url}`
const { default: fetch } = (await import('node-fetch')) as any
const res = await fetch(fileURL, {
credentials: 'include',
@@ -25,11 +24,11 @@ export const getExternalFile = async ({ data, req }: Args): Promise<File> => {
if (!res.ok) throw new APIError(`Failed to fetch file from ${fileURL}`, res.status)
const data = await res.buffer()
const data = await res.arrayBuffer()
return {
name: filename,
data,
data: Buffer.from(data),
mimetype: res.headers.get('content-type') || undefined,
size: Number(res.headers.get('content-length')) || 0,
}

View File

@@ -1,4 +1,3 @@
/* eslint-disable import/no-extraneous-dependencies */
import type express from 'express'
import type serveStatic from 'serve-static'
import type { ResizeOptions, Sharp } from 'sharp'

View File

@@ -1,3 +0,0 @@
export { initI18n, t, matchLanguage } from '../utilities/init';
export { getTranslation } from '../utilities/getTranslation';
export type * from '../types';

View File

@@ -1,9 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTranslation = exports.matchLanguage = exports.t = exports.initI18n = void 0;
var init_1 = require("../utilities/init");
Object.defineProperty(exports, "initI18n", { enumerable: true, get: function () { return init_1.initI18n; } });
Object.defineProperty(exports, "t", { enumerable: true, get: function () { return init_1.t; } });
Object.defineProperty(exports, "matchLanguage", { enumerable: true, get: function () { return init_1.matchLanguage; } });
var getTranslation_1 = require("../utilities/getTranslation");
Object.defineProperty(exports, "getTranslation", { enumerable: true, get: function () { return getTranslation_1.getTranslation; } });

View File

@@ -1,42 +0,0 @@
export type Translations = {
[language: string]: {
$schema: string;
} | {
[namespace: string]: {
[key: string]: string;
};
};
};
export type TFunction = (key: string, options?: Record<string, any>) => string;
export type I18n = {
/** The fallback language */
fallbackLanguage: string;
/** The language of the request */
language: string;
/** Translate function */
t: (key: string, options?: Record<string, unknown>) => string;
};
export type I18nOptions = {
fallbackLanguage?: string;
supportedLanguages?: string[];
translations?: {
[language: string]: {
$schema: string;
} | {
[namespace: string]: {
[key: string]: string;
};
};
};
};
export type InitTFunction = (args: {
config: I18nOptions;
language?: string;
translations?: Translations;
}) => TFunction;
export type InitI18n = (args: {
config: I18nOptions;
language?: string;
translations: Translations;
context: 'api' | 'client';
}) => I18n;

View File

@@ -1,2 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -1 +0,0 @@
export declare function deepMerge(obj1: any, obj2: any): any;

View File

@@ -1,18 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepMerge = void 0;
function deepMerge(obj1, obj2) {
const output = { ...obj1 };
for (const key in obj2) {
if (Object.prototype.hasOwnProperty.call(obj2, key)) {
if (typeof obj2[key] === 'object' && !Array.isArray(obj2[key]) && obj1[key]) {
output[key] = deepMerge(obj1[key], obj2[key]);
}
else {
output[key] = obj2[key];
}
}
}
return output;
}
exports.deepMerge = deepMerge;

View File

@@ -1 +0,0 @@
export declare function ensureDirectoryExists(directory: any): void;

View File

@@ -1,18 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureDirectoryExists = void 0;
const fs_1 = __importDefault(require("fs"));
function ensureDirectoryExists(directory) {
try {
if (!fs_1.default.existsSync(directory)) {
fs_1.default.mkdirSync(directory, { recursive: true });
}
}
catch (error) {
console.error(`Error creating directory '${directory}': ${error.message}`);
}
}
exports.ensureDirectoryExists = ensureDirectoryExists;

View File

@@ -1,3 +0,0 @@
import type { JSX } from 'react';
import { I18n } from '../types';
export declare const getTranslation: (label: JSX.Element | Record<string, string> | string, i18n: Pick<I18n, 'fallbackLanguage' | 'language'>) => string;

View File

@@ -1,21 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTranslation = void 0;
const getTranslation = (label, i18n) => {
if (typeof label === 'object') {
if (label[i18n.language]) {
return label[i18n.language];
}
let fallbacks = [];
if (typeof i18n.fallbackLanguage === 'string') {
fallbacks = [i18n.fallbackLanguage];
}
else if (Array.isArray(i18n.fallbackLanguage)) {
fallbacks = i18n.fallbackLanguage;
}
const fallbackLang = fallbacks.find((language) => label[language]);
return fallbackLang && label[fallbackLang] ? fallbackLang : label[Object.keys(label)[0]];
}
return label;
};
exports.getTranslation = getTranslation;

View File

@@ -1,30 +0,0 @@
import { Translations, InitI18n } from '../types';
/**
* @function getTranslationString
*
* Gets a translation string from a translations object
*
* @returns string
*/
export declare const getTranslationString: ({ count, key, translations, }: {
count?: number;
key: string;
translations: Translations[0];
}) => string;
/**
* @function t
*
* Merges config defined translations with translations passed in as an argument
* returns a function that can be used to translate a string
*
* @returns string
*/
type TFunctionConstructor = ({ key, translations, vars, }: {
key: string;
translations?: Translations[0];
vars?: Record<string, any>;
}) => string;
export declare const t: TFunctionConstructor;
export declare function matchLanguage(header: string): string | undefined;
export declare const initI18n: InitI18n;
export {};

View File

@@ -1,180 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initI18n = exports.matchLanguage = exports.t = exports.getTranslationString = void 0;
const deepMerge_1 = require("./deepMerge");
/**
* @function getTranslationString
*
* Gets a translation string from a translations object
*
* @returns string
*/
const getTranslationString = ({ count, key, translations, }) => {
const keys = key.split(':');
let keySuffix = '';
const translation = keys.reduce((acc, key, index) => {
if (typeof acc === 'string')
return acc;
if (typeof count === 'number') {
if (count === 0 && `${key}_zero` in acc) {
keySuffix = '_zero';
}
else if (count === 1 && `${key}_one` in acc) {
keySuffix = '_one';
}
else if (count === 2 && `${key}_two` in acc) {
keySuffix = '_two';
}
else if (count > 5 && `${key}_many` in acc) {
keySuffix = '_many';
}
else if (count > 2 && count <= 5 && `${key}_few` in acc) {
keySuffix = '_few';
}
else if (`${key}_other` in acc) {
keySuffix = '_other';
}
}
let keyToUse = key;
if (index === keys.length - 1 && keySuffix) {
keyToUse = `${key}${keySuffix}`;
}
if (acc && keyToUse in acc) {
return acc[keyToUse];
}
return undefined;
}, translations);
if (!translation) {
console.log('key not found: ', key);
}
return translation || key;
};
exports.getTranslationString = getTranslationString;
/**
* @function replaceVars
*
* Replaces variables in a translation string with values from an object
*
* @returns string
*/
const replaceVars = ({ translationString, vars, }) => {
const parts = translationString.split(/({{.*?}})/);
return parts
.map((part) => {
if (part.startsWith('{{') && part.endsWith('}}')) {
const placeholder = part.substring(2, part.length - 2).trim();
return vars[placeholder] || part;
}
else {
return part;
}
})
.join('');
};
const t = ({ key, translations, vars }) => {
let translationString = (0, exports.getTranslationString)({
count: typeof vars?.count === 'number' ? vars.count : undefined,
key,
translations,
});
if (vars) {
translationString = replaceVars({
translationString,
vars,
});
}
if (!translationString) {
translationString = key;
}
return translationString;
};
exports.t = t;
function parseAcceptLanguage(header) {
return header
.split(',')
.map((lang) => {
const [language, quality] = lang.trim().split(';q=');
return {
language,
quality: quality ? parseFloat(quality) : 1,
};
})
.sort((a, b) => b.quality - a.quality); // Sort by quality, highest to lowest
}
const acceptedLanguages = [
'ar',
'az',
'bg',
'cs',
'de',
'en',
'es',
'fa',
'fr',
'hr',
'hu',
'it',
'ja',
'ko',
'my',
'nb',
'nl',
'pl',
'pt',
'ro',
'rs',
'rsLatin',
'ru',
'sv',
'th',
'tr',
'ua',
'vi',
'zh',
'zhTw',
];
function matchLanguage(header) {
const parsedHeader = parseAcceptLanguage(header);
for (const { language } of parsedHeader) {
for (const acceptedLanguage of acceptedLanguages) {
if (language.startsWith(acceptedLanguage)) {
return acceptedLanguage;
}
}
}
return undefined;
}
exports.matchLanguage = matchLanguage;
const initTFunction = (args) => (key, vars) => {
const { config, language, translations } = args;
const mergedLanguages = (0, deepMerge_1.deepMerge)(config?.translations ?? {}, translations);
const languagePreference = matchLanguage(language);
return (0, exports.t)({
key,
translations: mergedLanguages[languagePreference],
vars,
});
};
function memoize(fn, keys) {
const cacheMap = new Map();
return function (args) {
const cacheKey = keys.reduce((acc, key) => acc + args[key], '');
if (!cacheMap.has(cacheKey)) {
const result = fn(args);
cacheMap.set(cacheKey, result);
}
return cacheMap.get(cacheKey);
};
}
exports.initI18n = memoize((({ config, language = 'en', translations, context }) => {
const i18n = {
fallbackLanguage: config.fallbackLanguage,
language: language || config.fallbackLanguage,
t: initTFunction({
config,
language: language || config.fallbackLanguage,
translations,
}),
};
return i18n;
}), ['language', 'context']);

1833
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import fetch from 'node-fetch'
import qs from 'qs'
import type { Config } from '../../packages/payload/src/config/types'