@pigment/auto-translate 1.5.0 → 1.6.0
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/README.md +13 -2
- package/dist/components/LockTranslation/index.js +1 -3
- package/dist/components/LockTranslation/index.js.map +1 -1
- package/dist/components/OpenAiModelField.d.ts +2 -0
- package/dist/components/OpenAiModelField.js +93 -0
- package/dist/components/OpenAiModelField.js.map +1 -0
- package/dist/endpoints/listOpenAiModels.d.ts +5 -0
- package/dist/endpoints/listOpenAiModels.js +93 -0
- package/dist/endpoints/listOpenAiModels.js.map +1 -0
- package/dist/exports/client.d.ts +1 -0
- package/dist/exports/client.js +1 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/globals/translationSettings.js +14 -3
- package/dist/globals/translationSettings.js.map +1 -1
- package/dist/services/translationService.js +13 -10
- package/dist/services/translationService.js.map +1 -1
- package/package.json +54 -25
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ A powerful auto-translation plugin for [Payload CMS](https://payloadcms.com) tha
|
|
|
9
9
|
- 🎯 **Smart Translation**: Preserves excluded fields when updating default language content
|
|
10
10
|
- 🔧 **Flexible Configuration**: Configure per-collection settings and global exclusions
|
|
11
11
|
- 🔐 **Protected Settings**: Lock/unlock translation settings to prevent accidental changes
|
|
12
|
-
- 🤖 **OpenAI Integration**:
|
|
12
|
+
- 🤖 **OpenAI Integration**: Translate with OpenAI (model selectable in Translation Settings)
|
|
13
13
|
- 📦 **Zero UI Overhead**: Seamlessly integrates with Payload's admin panel
|
|
14
14
|
- ⚡ **Performance Optimized**: 10-15x faster translation with smart extraction and deduplication
|
|
15
15
|
|
|
@@ -75,6 +75,16 @@ OPENAI_BASE_URL=https://api.openai.com/v1
|
|
|
75
75
|
|
|
76
76
|
> **⚠️ Important:** Restart your server after updating `.env` or plugin settings.
|
|
77
77
|
|
|
78
|
+
### Translation Settings (Admin)
|
|
79
|
+
|
|
80
|
+
After install, open **Auto-Translate Settings → Translation Settings** in the Payload admin:
|
|
81
|
+
|
|
82
|
+
- **Model** — live OpenAI model dropdown (requires `OPENAI_API_KEY`). This value is what translation calls use.
|
|
83
|
+
- **Temperature** — hidden for GPT-5+ / o-series (those models reject custom temperature).
|
|
84
|
+
- **System prompt / rules / max tokens** — editable after unlocking settings.
|
|
85
|
+
|
|
86
|
+
`provider.model` in plugin config is only a fallback when the global has no model set.
|
|
87
|
+
|
|
78
88
|
---
|
|
79
89
|
|
|
80
90
|
## 🔧 Advanced Configuration
|
|
@@ -103,7 +113,8 @@ export default buildConfig({
|
|
|
103
113
|
// Optional: Translation provider settings
|
|
104
114
|
provider: {
|
|
105
115
|
type: 'openai', // or 'custom'
|
|
106
|
-
|
|
116
|
+
// Fallback only — prefer Admin → Translation Settings → Model
|
|
117
|
+
model: 'gpt-4o',
|
|
107
118
|
apiKey: process.env.OPENAI_API_KEY,
|
|
108
119
|
baseURL: process.env.OPENAI_BASE_URL,
|
|
109
120
|
|
|
@@ -15,17 +15,15 @@ import './style.css';
|
|
|
15
15
|
const { dispatchFields } = useForm();
|
|
16
16
|
const isLocked = Boolean(lockField?.value ?? true);
|
|
17
17
|
const [isLoading, setIsLoading] = useState(false);
|
|
18
|
-
//
|
|
18
|
+
// Model select uses form lock state in OpenAiModelField (react-select).
|
|
19
19
|
const applyLockStateToFields = useCallback((locked)=>{
|
|
20
20
|
const fieldsToLock = [
|
|
21
21
|
'systemPrompt',
|
|
22
22
|
'translationRules',
|
|
23
|
-
'model',
|
|
24
23
|
'temperature',
|
|
25
24
|
'maxTokens'
|
|
26
25
|
];
|
|
27
26
|
fieldsToLock.forEach((fieldPath)=>{
|
|
28
|
-
// Find the input/textarea elements for this field
|
|
29
27
|
const inputs = document.querySelectorAll(`[name="${fieldPath}"], textarea[id*="${fieldPath}"], input[id*="${fieldPath}"]`);
|
|
30
28
|
inputs.forEach((input)=>{
|
|
31
29
|
if (locked) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/LockTranslation/index.tsx"],"sourcesContent":["'use client'\n\nimport { useForm, useFormFields } from '@payloadcms/ui'\nimport React, { useCallback, useEffect, useState } from 'react'\n\nimport { updateLockTranslationSettingsField } from './actions/lockTranslations.js'\nimport './style.css'\n\n/**\n * Component that provides lock/unlock functionality for translation settings\n * - Fields are locked by default (read-only)\n * - User must click \"Unlock\" to edit\n * - After saving, fields automatically lock again\n * - Updates the hidden lockTranslationSettings checkbox field to enable server-side access control\n */\nexport const LockTranslation: React.FC = () => {\n const lockField = useFormFields(([fields]) => fields?.lockTranslationSettings)\n const { dispatchFields } = useForm()\n const isLocked = Boolean(lockField?.value ?? true)\n const [isLoading, setIsLoading] = useState(false)\n\n //
|
|
1
|
+
{"version":3,"sources":["../../../src/components/LockTranslation/index.tsx"],"sourcesContent":["'use client'\n\nimport { useForm, useFormFields } from '@payloadcms/ui'\nimport React, { useCallback, useEffect, useState } from 'react'\n\nimport { updateLockTranslationSettingsField } from './actions/lockTranslations.js'\nimport './style.css'\n\n/**\n * Component that provides lock/unlock functionality for translation settings\n * - Fields are locked by default (read-only)\n * - User must click \"Unlock\" to edit\n * - After saving, fields automatically lock again\n * - Updates the hidden lockTranslationSettings checkbox field to enable server-side access control\n */\nexport const LockTranslation: React.FC = () => {\n const lockField = useFormFields(([fields]) => fields?.lockTranslationSettings)\n const { dispatchFields } = useForm()\n const isLocked = Boolean(lockField?.value ?? true)\n const [isLoading, setIsLoading] = useState(false)\n\n // Model select uses form lock state in OpenAiModelField (react-select).\n const applyLockStateToFields = useCallback((locked: boolean) => {\n const fieldsToLock = ['systemPrompt', 'translationRules', 'temperature', 'maxTokens']\n\n fieldsToLock.forEach((fieldPath) => {\n const inputs = document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(\n `[name=\"${fieldPath}\"], textarea[id*=\"${fieldPath}\"], input[id*=\"${fieldPath}\"]`,\n )\n\n inputs.forEach((input) => {\n if (locked) {\n input.setAttribute('disabled', 'true')\n } else {\n input.removeAttribute('disabled')\n }\n })\n })\n }, [])\n\n // Apply initial lock state when component mounts or lock state changes\n useEffect(() => {\n // Small delay to ensure form fields are rendered\n const timer = setTimeout(() => {\n applyLockStateToFields(isLocked)\n }, 100)\n\n return () => clearTimeout(timer)\n }, [isLocked, applyLockStateToFields])\n\n const toggleLock = useCallback(async () => {\n const newLockState = !isLocked\n setIsLoading(true)\n\n try {\n const result = await updateLockTranslationSettingsField(newLockState)\n\n if (result.success) {\n // Update the lockTranslationSettings field value\n dispatchFields({\n type: 'UPDATE',\n path: 'lockTranslationSettings',\n value: result.isLocked,\n })\n\n // Apply lock state to fields\n applyLockStateToFields(result.isLocked)\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[LockTranslation] Error:', error)\n } finally {\n setIsLoading(false)\n }\n }, [isLocked, dispatchFields, applyLockStateToFields])\n\n return (\n <div className=\"translation-settings-lock-container\">\n <button\n className={`translation-settings-lock-button ${isLocked ? 'locked' : 'unlocked'}`}\n disabled={isLoading}\n onClick={toggleLock}\n title={\n isLocked\n ? '🔒 Settings are locked to prevent accidental changes. Click to unlock and edit.'\n : '🔓 Settings are unlocked. Click to lock after saving your changes.'\n }\n type=\"button\"\n >\n <span className=\"translation-settings-lock-icon\">\n {isLoading ? '⏳' : isLocked ? '🔒' : '🔓'}\n </span>\n <span className=\"translation-settings-lock-label\">\n {isLoading ? 'Updating...' : isLocked ? 'Unlock Settings' : 'Lock Settings'}\n </span>\n </button>\n </div>\n )\n}\n"],"names":["useForm","useFormFields","React","useCallback","useEffect","useState","updateLockTranslationSettingsField","LockTranslation","lockField","fields","lockTranslationSettings","dispatchFields","isLocked","Boolean","value","isLoading","setIsLoading","applyLockStateToFields","locked","fieldsToLock","forEach","fieldPath","inputs","document","querySelectorAll","input","setAttribute","removeAttribute","timer","setTimeout","clearTimeout","toggleLock","newLockState","result","success","type","path","error","console","div","className","button","disabled","onClick","title","span"],"mappings":"AAAA;;AAEA,SAASA,OAAO,EAAEC,aAAa,QAAQ,iBAAg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;YACxC;QACF,EAAE,OAAOyB,OAAO;YACd,sCAAsC;YACtCC,QAAQD,KAAK,CAAC,4BAA4BA;QAC5C,SAAU;YACRrB,aAAa;QACf;IACF,GAAG;QAACJ;QAAUD;QAAgBM;KAAuB;IAErD,qBACE,KAACsB;QAAIC,WAAU;kBACb,cAAA,MAACC;YACCD,WAAW,CAAC,iCAAiC,EAAE5B,WAAW,WAAW,YAAY;YACjF8B,UAAU3B;YACV4B,SAASZ;YACTa,OACEhC,WACI,oFACA;YAENuB,MAAK;;8BAEL,KAACU;oBAAKL,WAAU;8BACbzB,YAAY,MAAMH,WAAW,OAAO;;8BAEvC,KAACiC;oBAAKL,WAAU;8BACbzB,YAAY,gBAAgBH,WAAW,oBAAoB;;;;;AAKtE,EAAC"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { FieldDescription, FieldLabel, SelectInput, useField, useFormFields } from '@payloadcms/ui';
|
|
4
|
+
import React, { useEffect, useMemo, useState } from 'react';
|
|
5
|
+
const MODELS_URL = '/payload/api/globals/translation-settings/openai-models';
|
|
6
|
+
export const OpenAiModelField = ({ field, path, readOnly })=>{
|
|
7
|
+
const { value, setValue, showError, errorMessage } = useField({
|
|
8
|
+
path
|
|
9
|
+
});
|
|
10
|
+
const lockField = useFormFields(([fields])=>fields?.lockTranslationSettings);
|
|
11
|
+
const isLocked = lockField === undefined ? Boolean(readOnly) : Boolean(lockField.value);
|
|
12
|
+
const [options, setOptions] = useState([]);
|
|
13
|
+
const [loading, setLoading] = useState(true);
|
|
14
|
+
const [loadError, setLoadError] = useState(null);
|
|
15
|
+
useEffect(()=>{
|
|
16
|
+
const controller = new AbortController();
|
|
17
|
+
const load = async ()=>{
|
|
18
|
+
setLoading(true);
|
|
19
|
+
setLoadError(null);
|
|
20
|
+
try {
|
|
21
|
+
const res = await fetch(MODELS_URL, {
|
|
22
|
+
credentials: 'include',
|
|
23
|
+
signal: controller.signal
|
|
24
|
+
});
|
|
25
|
+
const data = await res.json();
|
|
26
|
+
if (!res.ok) {
|
|
27
|
+
throw new Error(data.error || `Failed to load models (${res.status})`);
|
|
28
|
+
}
|
|
29
|
+
setOptions(Array.isArray(data.models) ? data.models : []);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (err instanceof Error && err.name === 'AbortError') return;
|
|
32
|
+
setLoadError(err instanceof Error ? err.message : 'Failed to load models');
|
|
33
|
+
} finally{
|
|
34
|
+
if (!controller.signal.aborted) setLoading(false);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
void load();
|
|
38
|
+
return ()=>controller.abort();
|
|
39
|
+
}, []);
|
|
40
|
+
const optionsWithCurrent = useMemo(()=>{
|
|
41
|
+
if (!value || options.some((option)=>option.value === value)) return options;
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
label: value,
|
|
45
|
+
value
|
|
46
|
+
},
|
|
47
|
+
...options
|
|
48
|
+
];
|
|
49
|
+
}, [
|
|
50
|
+
options,
|
|
51
|
+
value
|
|
52
|
+
]);
|
|
53
|
+
const description = typeof field.admin?.description === 'string' ? field.admin.description : undefined;
|
|
54
|
+
const disabled = isLocked || loading;
|
|
55
|
+
return /*#__PURE__*/ _jsxs("div", {
|
|
56
|
+
className: "field-type select",
|
|
57
|
+
children: [
|
|
58
|
+
/*#__PURE__*/ _jsx(FieldLabel, {
|
|
59
|
+
label: field.label,
|
|
60
|
+
path: path,
|
|
61
|
+
required: field.required
|
|
62
|
+
}),
|
|
63
|
+
/*#__PURE__*/ _jsx(SelectInput, {
|
|
64
|
+
description: description,
|
|
65
|
+
Error: showError && errorMessage ? /*#__PURE__*/ _jsx("div", {
|
|
66
|
+
className: "field-error",
|
|
67
|
+
children: errorMessage
|
|
68
|
+
}) : null,
|
|
69
|
+
isClearable: false,
|
|
70
|
+
name: path,
|
|
71
|
+
onChange: (option)=>{
|
|
72
|
+
if (disabled || !option || Array.isArray(option)) return;
|
|
73
|
+
if ('value' in option && typeof option.value === 'string') {
|
|
74
|
+
setValue(option.value);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
options: optionsWithCurrent,
|
|
78
|
+
path: path,
|
|
79
|
+
placeholder: loading ? 'Loading models…' : 'Select a model',
|
|
80
|
+
readOnly: disabled,
|
|
81
|
+
required: field.required,
|
|
82
|
+
showError: showError,
|
|
83
|
+
value: value ?? ''
|
|
84
|
+
}),
|
|
85
|
+
loadError ? /*#__PURE__*/ _jsx(FieldDescription, {
|
|
86
|
+
description: `Could not load OpenAI models: ${loadError}`,
|
|
87
|
+
path: path
|
|
88
|
+
}) : null
|
|
89
|
+
]
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=OpenAiModelField.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/OpenAiModelField.tsx"],"sourcesContent":["'use client'\n\nimport type { TextFieldClientComponent, OptionObject } from 'payload'\nimport { FieldDescription, FieldLabel, SelectInput, useField, useFormFields } from '@payloadcms/ui'\nimport React, { useEffect, useMemo, useState } from 'react'\n\nconst MODELS_URL = '/payload/api/globals/translation-settings/openai-models'\n\nexport const OpenAiModelField: TextFieldClientComponent = ({ field, path, readOnly }) => {\n const { value, setValue, showError, errorMessage } = useField<string>({ path })\n const lockField = useFormFields(([fields]) => fields?.lockTranslationSettings)\n const isLocked = lockField === undefined ? Boolean(readOnly) : Boolean(lockField.value)\n const [options, setOptions] = useState<OptionObject[]>([])\n const [loading, setLoading] = useState(true)\n const [loadError, setLoadError] = useState<string | null>(null)\n\n useEffect(() => {\n const controller = new AbortController()\n\n const load = async () => {\n setLoading(true)\n setLoadError(null)\n try {\n const res = await fetch(MODELS_URL, {\n credentials: 'include',\n signal: controller.signal,\n })\n const data = (await res.json()) as { models?: OptionObject[]; error?: string }\n if (!res.ok) {\n throw new Error(data.error || `Failed to load models (${res.status})`)\n }\n setOptions(Array.isArray(data.models) ? data.models : [])\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') return\n setLoadError(err instanceof Error ? err.message : 'Failed to load models')\n } finally {\n if (!controller.signal.aborted) setLoading(false)\n }\n }\n\n void load()\n return () => controller.abort()\n }, [])\n\n const optionsWithCurrent = useMemo(() => {\n if (!value || options.some((option) => option.value === value)) return options\n return [{ label: value, value }, ...options]\n }, [options, value])\n\n const description =\n typeof field.admin?.description === 'string' ? field.admin.description : undefined\n\n const disabled = isLocked || loading\n\n return (\n <div className=\"field-type select\">\n <FieldLabel label={field.label} path={path} required={field.required} />\n <SelectInput\n description={description}\n Error={showError && errorMessage ? <div className=\"field-error\">{errorMessage}</div> : null}\n isClearable={false}\n name={path}\n onChange={(option) => {\n if (disabled || !option || Array.isArray(option)) return\n if ('value' in option && typeof option.value === 'string') {\n setValue(option.value)\n }\n }}\n options={optionsWithCurrent}\n path={path}\n placeholder={loading ? 'Loading models…' : 'Select a model'}\n readOnly={disabled}\n required={field.required}\n showError={showError}\n value={value ?? ''}\n />\n {loadError ? (\n <FieldDescription description={`Could not load OpenAI models: ${loadError}`} path={path} />\n ) : null}\n </div>\n )\n}\n"],"names":["FieldDescription","FieldLabel","SelectInput","useField","useFormFields","React","useEffect","useMemo","useState","MODELS_URL","OpenAiModelField","field","path","readOnly","value","setValue","showError","errorMessage","lockField","fields","lockTranslationSettings","isLocked","undefined","Boolean","options","setOptions","loading","setLoading","loadError","setLoadError","controller","AbortController","load","res","fetch","credentials","signal","data","json","ok","Error","error","status","Array","isArray","models","err","name","message","aborted","abort","optionsWithCurrent","some","option","label","description","admin","disabled","div","className","required","isClearable","onChange","placeholder"],"mappings":"AAAA;;AAGA,SAASA,gBAAgB,EAAEC,UAAU,EAAEC,WAAW,EAAEC,QAAQ,EAAEC,aAAa,QAAQ,iBAAgB;AACnG,OAAOC,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAE3D,MAAMC,aAAa;AAEn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I,CAACO,SAASU,QAAQ4B,IAAI,CAAC,CAACC,SAAWA,OAAOvC,KAAK,KAAKA,QAAQ,OAAOU;QACvE,OAAO;YAAC;gBAAE8B,OAAOxC;gBAAOA;YAAM;eAAMU;SAAQ;IAC9C,GAAG;QAACA;QAASV;KAAM;IAEnB,MAAMyC,cACJ,OAAO5C,MAAM6C,KAAK,EAAED,gBAAgB,WAAW5C,MAAM6C,KAAK,CAACD,WAAW,GAAGjC;IAE3E,MAAMmC,WAAWpC,YAAYK;IAE7B,qBACE,MAACgC;QAAIC,WAAU;;0BACb,KAAC1D;gBAAWqD,OAAO3C,MAAM2C,KAAK;gBAAE1C,MAAMA;gBAAMgD,UAAUjD,MAAMiD,QAAQ;;0BACpE,KAAC1D;gBACCqD,aAAaA;gBACbf,OAAOxB,aAAaC,6BAAe,KAACyC;oBAAIC,WAAU;8BAAe1C;qBAAsB;gBACvF4C,aAAa;gBACbd,MAAMnC;gBACNkD,UAAU,CAACT;oBACT,IAAII,YAAY,CAACJ,UAAUV,MAAMC,OAAO,CAACS,SAAS;oBAClD,IAAI,WAAWA,UAAU,OAAOA,OAAOvC,KAAK,KAAK,UAAU;wBACzDC,SAASsC,OAAOvC,KAAK;oBACvB;gBACF;gBACAU,SAAS2B;gBACTvC,MAAMA;gBACNmD,aAAarC,UAAU,oBAAoB;gBAC3Cb,UAAU4C;gBACVG,UAAUjD,MAAMiD,QAAQ;gBACxB5C,WAAWA;gBACXF,OAAOA,SAAS;;YAEjBc,0BACC,KAAC5B;gBAAiBuD,aAAa,CAAC,8BAA8B,EAAE3B,WAAW;gBAAEhB,MAAMA;iBACjF;;;AAGV,EAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Endpoint } from 'payload';
|
|
2
|
+
export declare function isChatCapableModel(id: string): boolean;
|
|
3
|
+
/** GPT-5+ and o-series only accept the default temperature (1). */
|
|
4
|
+
export declare function supportsCustomTemperature(model: string): boolean;
|
|
5
|
+
export declare const listOpenAiModelsEndpoint: Endpoint;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const OPENAI_MODELS_CACHE_TTL_MS = 10 * 60 * 1000;
|
|
2
|
+
const NON_CHAT_MODEL = /(embedding|whisper|tts|dall-e|realtime|audio|image|moderation|transcribe|search-preview|codex|sora|babbage|davinci|computer-use|deep-research|gpt-oss|omni-moderation)/i;
|
|
3
|
+
let modelsCache = null;
|
|
4
|
+
let modelsInflight = null;
|
|
5
|
+
export function isChatCapableModel(id) {
|
|
6
|
+
if (!id || NON_CHAT_MODEL.test(id)) return false;
|
|
7
|
+
return /^(gpt-|o[1-9]|chatgpt-)/i.test(id);
|
|
8
|
+
}
|
|
9
|
+
/** GPT-5+ and o-series only accept the default temperature (1). */ export function supportsCustomTemperature(model) {
|
|
10
|
+
if (!model) return true;
|
|
11
|
+
if (/^o[1-9]/i.test(model)) return false;
|
|
12
|
+
if (/^gpt-5/i.test(model)) return false;
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
async function fetchChatCapableModels(apiKey) {
|
|
16
|
+
const openaiRes = await fetch('https://api.openai.com/v1/models', {
|
|
17
|
+
headers: {
|
|
18
|
+
Authorization: `Bearer ${apiKey}`
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
if (!openaiRes.ok) {
|
|
22
|
+
const errText = await openaiRes.text();
|
|
23
|
+
throw new Error(`OpenAI API ${openaiRes.status}: ${errText.slice(0, 200)}`);
|
|
24
|
+
}
|
|
25
|
+
const body = await openaiRes.json();
|
|
26
|
+
return (body.data ?? []).filter((model)=>typeof model?.id === 'string' && isChatCapableModel(model.id)).sort((a, b)=>(b.created ?? 0) - (a.created ?? 0) || a.id.localeCompare(b.id)).map((model)=>({
|
|
27
|
+
label: model.id,
|
|
28
|
+
value: model.id
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
async function getCachedChatCapableModels(apiKey) {
|
|
32
|
+
const now = Date.now();
|
|
33
|
+
if (modelsCache && modelsCache.expiresAt > now) {
|
|
34
|
+
return modelsCache.models;
|
|
35
|
+
}
|
|
36
|
+
if (modelsInflight) return modelsInflight;
|
|
37
|
+
modelsInflight = fetchChatCapableModels(apiKey).then((models)=>{
|
|
38
|
+
modelsCache = {
|
|
39
|
+
models,
|
|
40
|
+
expiresAt: Date.now() + OPENAI_MODELS_CACHE_TTL_MS
|
|
41
|
+
};
|
|
42
|
+
return models;
|
|
43
|
+
}).finally(()=>{
|
|
44
|
+
modelsInflight = null;
|
|
45
|
+
});
|
|
46
|
+
return modelsInflight;
|
|
47
|
+
}
|
|
48
|
+
export const listOpenAiModelsEndpoint = {
|
|
49
|
+
path: '/openai-models',
|
|
50
|
+
method: 'get',
|
|
51
|
+
handler: async (req)=>{
|
|
52
|
+
if (!req.user) {
|
|
53
|
+
return Response.json({
|
|
54
|
+
error: 'Unauthorized'
|
|
55
|
+
}, {
|
|
56
|
+
status: 401
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const apiKey = process.env.OPENAI_API_KEY;
|
|
60
|
+
if (!apiKey) {
|
|
61
|
+
return Response.json({
|
|
62
|
+
error: 'OPENAI_API_KEY is not set'
|
|
63
|
+
}, {
|
|
64
|
+
status: 500
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const models = await getCachedChatCapableModels(apiKey);
|
|
69
|
+
return Response.json({
|
|
70
|
+
models
|
|
71
|
+
});
|
|
72
|
+
} catch (err) {
|
|
73
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
74
|
+
if (message.startsWith('OpenAI API ')) {
|
|
75
|
+
return Response.json({
|
|
76
|
+
error: message
|
|
77
|
+
}, {
|
|
78
|
+
status: 502
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
req.payload.logger.error({
|
|
82
|
+
err
|
|
83
|
+
}, '[auto-translate] Failed to list OpenAI models');
|
|
84
|
+
return Response.json({
|
|
85
|
+
error: message
|
|
86
|
+
}, {
|
|
87
|
+
status: 500
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=listOpenAiModels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/endpoints/listOpenAiModels.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\ntype OpenAIModel = {\n id: string\n created?: number\n object?: string\n owned_by?: string\n}\n\ntype ModelOption = { label: string; value: string }\n\nconst OPENAI_MODELS_CACHE_TTL_MS = 10 * 60 * 1000\n\nconst NON_CHAT_MODEL =\n /(embedding|whisper|tts|dall-e|realtime|audio|image|moderation|transcribe|search-preview|codex|sora|babbage|davinci|computer-use|deep-research|gpt-oss|omni-moderation)/i\n\nlet modelsCache: { models: ModelOption[]; expiresAt: number } | null = null\nlet modelsInflight: Promise<ModelOption[]> | null = null\n\nexport function isChatCapableModel(id: string): boolean {\n if (!id || NON_CHAT_MODEL.test(id)) return false\n return /^(gpt-|o[1-9]|chatgpt-)/i.test(id)\n}\n\n/** GPT-5+ and o-series only accept the default temperature (1). */\nexport function supportsCustomTemperature(model: string): boolean {\n if (!model) return true\n if (/^o[1-9]/i.test(model)) return false\n if (/^gpt-5/i.test(model)) return false\n return true\n}\n\nasync function fetchChatCapableModels(apiKey: string): Promise<ModelOption[]> {\n const openaiRes = await fetch('https://api.openai.com/v1/models', {\n headers: { Authorization: `Bearer ${apiKey}` },\n })\n\n if (!openaiRes.ok) {\n const errText = await openaiRes.text()\n throw new Error(`OpenAI API ${openaiRes.status}: ${errText.slice(0, 200)}`)\n }\n\n const body = (await openaiRes.json()) as { data?: OpenAIModel[] }\n return (body.data ?? [])\n .filter((model) => typeof model?.id === 'string' && isChatCapableModel(model.id))\n .sort((a, b) => (b.created ?? 0) - (a.created ?? 0) || a.id.localeCompare(b.id))\n .map((model) => ({\n label: model.id,\n value: model.id,\n }))\n}\n\nasync function getCachedChatCapableModels(apiKey: string): Promise<ModelOption[]> {\n const now = Date.now()\n if (modelsCache && modelsCache.expiresAt > now) {\n return modelsCache.models\n }\n\n if (modelsInflight) return modelsInflight\n\n modelsInflight = fetchChatCapableModels(apiKey)\n .then((models) => {\n modelsCache = { models, expiresAt: Date.now() + OPENAI_MODELS_CACHE_TTL_MS }\n return models\n })\n .finally(() => {\n modelsInflight = null\n })\n\n return modelsInflight\n}\n\nexport const listOpenAiModelsEndpoint: Endpoint = {\n path: '/openai-models',\n method: 'get',\n handler: async (req) => {\n if (!req.user) {\n return Response.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const apiKey = process.env.OPENAI_API_KEY\n if (!apiKey) {\n return Response.json({ error: 'OPENAI_API_KEY is not set' }, { status: 500 })\n }\n\n try {\n const models = await getCachedChatCapableModels(apiKey)\n return Response.json({ models })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n if (message.startsWith('OpenAI API ')) {\n return Response.json({ error: message }, { status: 502 })\n }\n req.payload.logger.error({ err }, '[auto-translate] Failed to list OpenAI models')\n return Response.json({ error: message }, { status: 500 })\n }\n },\n}\n"],"names":["OPENAI_MODELS_CACHE_TTL_MS","NON_CHAT_MODEL","modelsCache","modelsInflight","isChatCapableModel","id","test","supportsCustomTemperature","model","fetchChatCapableModels","apiKey","openaiRes","fetch","headers","Authorization","ok","errText","text","Error","status","slice","body","json","data","filter","sort","a","b","created","localeCompare","map","label","value","getCachedChatCapableModels","now","Date","expiresAt","models","then","finally","listOpenAiModelsEndpoint","path","method","handler","req","user","Response","error","process","env","OPENAI_API_KEY","err","message","String","startsWith","payload","logger"],"mappings":"AAWA,MAAMA,6BAA6B,KAAK,KAAK;AAE7C,MAAMC,iBACJ;AAEF,IAAIC,cAAmE;AACvE,IAAIC,iBAAgD;AAEpD,OAAO,SAASC,mBAAmBC,EAAU;IAC3C,IAAI,CAACA,MAAMJ,eAAeK,IAAI,CAACD,KAAK,OAAO;IAC3C,OAAO,2BAA2BC,IAAI,CAACD;AACzC;AAEA,iEAAiE,GACjE,OAAO,SAASE,0BAA0B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AAKlC;QAA2B;QAC3E,OAAOqC;IACT,GACCE,OAAO,CAAC;QACPpC,iBAAiB;IACnB;IAEF,OAAOA;AACT;AAEA,OAAO,MAAMqC,2BAAqC;IAChDC,MAAM;IACNC,QAAQ;IACRC,SAAS,OAAOC;QACd,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAOC,SAASxB,IAAI,CAAC;gBAAEyB,OAAO;YAAe,GAAG;gBAAE5B,QAAQ;YAAI;QAChE;QAEA,MAAMT,SAASsC,QAAQC,GAAG,CAACC,cAAc;QACzC,IAAI,CAACxC,QAAQ;YACX,OAAOoC,SAASxB,IAAI,CAAC;gBAAEyB,OAAO;YAA4B,GAAG;gBAAE5B,QAAQ;YAAI;QAC7E;QAEA,IAAI;YACF,MAAMkB,SAAS,MAAMJ,2BAA2BvB;YAChD,OAAOoC,SAASxB,IAAI,CAAC;gBAAEe;YAAO;QAChC,EAAE,OAAOc,KAAK;YACZ,MAAMC,UAAUD,eAAejC,QAAQiC,IAAIC,OAAO,GAAGC,OAAOF;YAC5D,IAAIC,QAAQE,UAAU,CAAC,gBAAgB;gBACrC,OAAOR,SAASxB,IAAI,CAAC;oBAAEyB,OAAOK;gBAAQ,GAAG;oBAAEjC,QAAQ;gBAAI;YACzD;YACAyB,IAAIW,OAAO,CAACC,MAAM,CAACT,KAAK,CAAC;gBAAEI;YAAI,GAAG;YAClC,OAAOL,SAASxB,IAAI,CAAC;gBAAEyB,OAAOK;YAAQ,GAAG;gBAAEjC,QAAQ;YAAI;QACzD;IACF;AACF,EAAC"}
|
package/dist/exports/client.d.ts
CHANGED
package/dist/exports/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { LockTranslation } from '../components/LockTranslation/index.js'\nexport { TranslationControl } from '../components/TranslationControl.js'\nexport type * from '../types/index.js'\n"],"names":["LockTranslation","TranslationControl"],"mappings":"AAAA,SAASA,eAAe,QAAQ,yCAAwC;AACxE,SAASC,kBAAkB,QAAQ,sCAAqC"}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { LockTranslation } from '../components/LockTranslation/index.js'\nexport { OpenAiModelField } from '../components/OpenAiModelField.js'\nexport { TranslationControl } from '../components/TranslationControl.js'\nexport type * from '../types/index.js'\n"],"names":["LockTranslation","OpenAiModelField","TranslationControl"],"mappings":"AAAA,SAASA,eAAe,QAAQ,yCAAwC;AACxE,SAASC,gBAAgB,QAAQ,oCAAmC;AACpE,SAASC,kBAAkB,QAAQ,sCAAqC"}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { listOpenAiModelsEndpoint, supportsCustomTemperature } from '../endpoints/listOpenAiModels.js';
|
|
1
2
|
export const getTranslationSettingsGlobal = (slug = 'translation-settings')=>({
|
|
2
3
|
slug,
|
|
3
4
|
admin: {
|
|
4
5
|
description: 'Configure translation settings including the system prompt and model parameters',
|
|
5
6
|
group: 'Auto-Translate Settings'
|
|
6
7
|
},
|
|
8
|
+
endpoints: [
|
|
9
|
+
listOpenAiModelsEndpoint
|
|
10
|
+
],
|
|
7
11
|
fields: [
|
|
8
12
|
{
|
|
9
13
|
name: 'settingsLock',
|
|
@@ -73,7 +77,10 @@ export const getTranslationSettingsGlobal = (slug = 'translation-settings')=>({
|
|
|
73
77
|
}
|
|
74
78
|
},
|
|
75
79
|
admin: {
|
|
76
|
-
|
|
80
|
+
components: {
|
|
81
|
+
Field: '@pigment/auto-translate/client#OpenAiModelField'
|
|
82
|
+
},
|
|
83
|
+
description: 'The OpenAI model to use for translations'
|
|
77
84
|
},
|
|
78
85
|
defaultValue: 'gpt-4o',
|
|
79
86
|
label: 'Model',
|
|
@@ -89,8 +96,12 @@ export const getTranslationSettingsGlobal = (slug = 'translation-settings')=>({
|
|
|
89
96
|
}
|
|
90
97
|
},
|
|
91
98
|
admin: {
|
|
92
|
-
description: 'Controls randomness in translation (0.0-2.0). Lower values are more deterministic.',
|
|
93
|
-
step: 0.1
|
|
99
|
+
description: 'Controls randomness in translation (0.0-2.0). Lower values are more deterministic. Not applied for GPT-5+ or o-series models.',
|
|
100
|
+
step: 0.1,
|
|
101
|
+
condition: (_data, siblingData)=>{
|
|
102
|
+
const model = typeof siblingData?.model === 'string' ? siblingData.model : '';
|
|
103
|
+
return supportsCustomTemperature(model);
|
|
104
|
+
}
|
|
94
105
|
},
|
|
95
106
|
defaultValue: 0.3,
|
|
96
107
|
label: 'Temperature',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/globals/translationSettings.ts"],"sourcesContent":["import type { GlobalConfig } from 'payload'\n\nexport const getTranslationSettingsGlobal = (\n slug: string = 'translation-settings',\n): GlobalConfig => ({\n slug,\n admin: {\n description: 'Configure translation settings including the system prompt and model parameters',\n group: 'Auto-Translate Settings',\n },\n fields: [\n {\n name: 'settingsLock',\n type: 'ui',\n admin: {\n components: {\n Field: '@pigment/auto-translate/client#LockTranslation',\n },\n position: 'sidebar',\n },\n },\n {\n name: 'lockTranslationSettings',\n type: 'checkbox',\n admin: {\n hidden: true,\n },\n defaultValue: true,\n },\n {\n name: 'systemPrompt',\n type: 'textarea',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description:\n 'The main instruction for the AI translator. Use {fromLocale} and {toLocale} as placeholders.',\n rows: 3,\n },\n defaultValue: `You are a professional translator. Translate the JSON object values from {fromLocale} to {toLocale}.`,\n label: 'System Prompt',\n required: true,\n },\n {\n name: 'translationRules',\n type: 'textarea',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description:\n \"⚠️ Do not edit if you don't know what you are doing. These rules ensure proper JSON translation behavior.\",\n rows: 8,\n },\n defaultValue: `Rules:\n- Only translate the values, never the keys\n- Preserve the exact JSON structure\n- Do not translate field names like 'id', 'createdAt', 'updatedAt', etc.\n- Maintain formatting, HTML tags, and special characters\n- Return only valid JSON without any markdown formatting or code blocks\n- If a value is already in the target language or is a proper noun, keep it as is`,\n label: 'Translation Rules',\n required: true,\n },\n {\n name: 'model',\n type: 'text',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description: 'The OpenAI model to use for translations
|
|
1
|
+
{"version":3,"sources":["../../src/globals/translationSettings.ts"],"sourcesContent":["import type { GlobalConfig } from 'payload'\n\nimport { listOpenAiModelsEndpoint, supportsCustomTemperature } from '../endpoints/listOpenAiModels.js'\n\nexport const getTranslationSettingsGlobal = (\n slug: string = 'translation-settings',\n): GlobalConfig => ({\n slug,\n admin: {\n description: 'Configure translation settings including the system prompt and model parameters',\n group: 'Auto-Translate Settings',\n },\n endpoints: [listOpenAiModelsEndpoint],\n fields: [\n {\n name: 'settingsLock',\n type: 'ui',\n admin: {\n components: {\n Field: '@pigment/auto-translate/client#LockTranslation',\n },\n position: 'sidebar',\n },\n },\n {\n name: 'lockTranslationSettings',\n type: 'checkbox',\n admin: {\n hidden: true,\n },\n defaultValue: true,\n },\n {\n name: 'systemPrompt',\n type: 'textarea',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description:\n 'The main instruction for the AI translator. Use {fromLocale} and {toLocale} as placeholders.',\n rows: 3,\n },\n defaultValue: `You are a professional translator. Translate the JSON object values from {fromLocale} to {toLocale}.`,\n label: 'System Prompt',\n required: true,\n },\n {\n name: 'translationRules',\n type: 'textarea',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description:\n \"⚠️ Do not edit if you don't know what you are doing. These rules ensure proper JSON translation behavior.\",\n rows: 8,\n },\n defaultValue: `Rules:\n- Only translate the values, never the keys\n- Preserve the exact JSON structure\n- Do not translate field names like 'id', 'createdAt', 'updatedAt', etc.\n- Maintain formatting, HTML tags, and special characters\n- Return only valid JSON without any markdown formatting or code blocks\n- If a value is already in the target language or is a proper noun, keep it as is`,\n label: 'Translation Rules',\n required: true,\n },\n {\n name: 'model',\n type: 'text',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n components: {\n Field: '@pigment/auto-translate/client#OpenAiModelField',\n },\n description: 'The OpenAI model to use for translations',\n },\n defaultValue: 'gpt-4o',\n label: 'Model',\n required: true,\n },\n {\n name: 'temperature',\n type: 'number',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description:\n 'Controls randomness in translation (0.0-2.0). Lower values are more deterministic. Not applied for GPT-5+ or o-series models.',\n step: 0.1,\n condition: (_data, siblingData) => {\n const model = typeof siblingData?.model === 'string' ? siblingData.model : ''\n return supportsCustomTemperature(model)\n },\n },\n defaultValue: 0.3,\n label: 'Temperature',\n max: 2,\n min: 0,\n required: true,\n },\n {\n name: 'maxTokens',\n type: 'number',\n access: {\n read: () => true,\n update: ({ data }) => {\n return !data?.lockTranslationSettings\n },\n },\n admin: {\n description: 'Maximum tokens for the response. Leave empty for automatic.',\n },\n label: 'Max Tokens',\n min: 1,\n },\n ],\n hooks: {\n afterChange: [\n async ({ data, req }) => {\n if (!data?.lockTranslationSettings) {\n const result = await req.payload.updateGlobal({\n slug: 'translation-settings',\n data: { lockTranslationSettings: true },\n req,\n })\n\n return result\n }\n },\n ],\n },\n label: 'Translation Settings',\n})\n"],"names":["listOpenAiModelsEndpoint","supportsCustomTemperature","getTranslationSettingsGlobal","slug","admin","description","group","endpoints","fields","name","type","components","Field","position","hidden","defaultValue","access","read","update","data","lockTranslationSettings","rows","label","required","step","condition","_data","siblingData","model","max","min","hooks","afterChange","req","result","payload","updateGlobal"],"mappings":"AAEA,SAASA,wBAAwB,EAAEC,yBAAyB,QAAQ,mCAAkC;AAEtG,OAAO,MAAMC,+BAA+B,CAC1CC,OAAe,sBAAsB,GACnB,CAAA;QAClBA;QACAC,OAAO;YACLC,aAAa;YACbC,OAAO;QACT;QACAC,WAAW;YAACP;SAAyB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U,WAAWD,YAAYC,KAAK,GAAG;wBAC3E,OAAO3B,0BAA0B2B;oBACnC;gBACF;gBACAb,cAAc;gBACdO,OAAO;gBACPO,KAAK;gBACLC,KAAK;gBACLP,UAAU;YACZ;YACA;gBACEd,MAAM;gBACNC,MAAM;gBACNM,QAAQ;oBACNC,MAAM,IAAM;oBACZC,QAAQ,CAAC,EAAEC,IAAI,EAAE;wBACf,OAAO,CAACA,MAAMC;oBAChB;gBACF;gBACAhB,OAAO;oBACLC,aAAa;gBACf;gBACAiB,OAAO;gBACPQ,KAAK;YACP;SACD;QACDC,OAAO;YACLC,aAAa;gBACX,OAAO,EAAEb,IAAI,EAAEc,GAAG,EAAE;oBAClB,IAAI,CAACd,MAAMC,yBAAyB;wBAClC,MAAMc,SAAS,MAAMD,IAAIE,OAAO,CAACC,YAAY,CAAC;4BAC5CjC,MAAM;4BACNgB,MAAM;gCAAEC,yBAAyB;4BAAK;4BACtCa;wBACF;wBAEA,OAAOC;oBACT;gBACF;aACD;QACH;QACAZ,OAAO;IACT,CAAA,EAAE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import OpenAI from 'openai';
|
|
2
|
+
import { supportsCustomTemperature } from '../endpoints/listOpenAiModels.js';
|
|
2
3
|
import { filterExcludedPaths, overlayNonTranslatableValues } from '../utilities/fieldHelpers.js';
|
|
3
4
|
export class TranslationService {
|
|
4
5
|
client;
|
|
@@ -340,12 +341,13 @@ export class TranslationService {
|
|
|
340
341
|
response_format: {
|
|
341
342
|
type: 'json_object'
|
|
342
343
|
},
|
|
343
|
-
|
|
344
|
+
...supportsCustomTemperature(settings.model) ? {
|
|
345
|
+
temperature: settings.temperature
|
|
346
|
+
} : {},
|
|
347
|
+
...settings.maxTokens ? {
|
|
348
|
+
max_tokens: settings.maxTokens
|
|
349
|
+
} : {}
|
|
344
350
|
};
|
|
345
|
-
// Add maxTokens if specified
|
|
346
|
-
if (settings.maxTokens) {
|
|
347
|
-
requestParams.max_tokens = settings.maxTokens;
|
|
348
|
-
}
|
|
349
351
|
const response = await client.chat.completions.create(requestParams, {
|
|
350
352
|
timeout
|
|
351
353
|
});
|
|
@@ -529,12 +531,13 @@ export class TranslationService {
|
|
|
529
531
|
response_format: {
|
|
530
532
|
type: 'json_object'
|
|
531
533
|
},
|
|
532
|
-
|
|
534
|
+
...supportsCustomTemperature(settings.model) ? {
|
|
535
|
+
temperature: settings.temperature
|
|
536
|
+
} : {},
|
|
537
|
+
...settings.maxTokens ? {
|
|
538
|
+
max_tokens: settings.maxTokens
|
|
539
|
+
} : {}
|
|
533
540
|
};
|
|
534
|
-
// Add maxTokens if specified
|
|
535
|
-
if (settings.maxTokens) {
|
|
536
|
-
requestParams.max_tokens = settings.maxTokens;
|
|
537
|
-
}
|
|
538
541
|
const response = await client.chat.completions.create(requestParams, {
|
|
539
542
|
timeout
|
|
540
543
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/translationService.ts"],"sourcesContent":["import type { CollectionSlug, Field, GlobalSlug, Payload } from 'payload'\n\nimport OpenAI from 'openai'\n\nimport type { AutoTranslateConfig, TranslateOptions } from '../types/index.js'\n\nimport { filterExcludedPaths, overlayNonTranslatableValues } from '../utilities/fieldHelpers.js'\n\nexport class TranslationService {\n private client?: OpenAI\n private config: AutoTranslateConfig\n\n constructor(config: AutoTranslateConfig) {\n this.config = config\n }\n\n /**\n * Extracts translatable text from lexical editor nodes\n */\n private extractFromLexicalNode(\n node: any,\n path: string,\n strings: Map<string, string>,\n deduplicationMap: Map<string, string[]>,\n ): any {\n const enableDeduplication = this.config.enableDeduplication !== false // Default to true\n\n // Handle text nodes - skip whitespace-only or very short text\n if (node.type === 'text' && node.text && typeof node.text === 'string') {\n const trimmed = node.text.trim()\n\n // Skip if empty, whitespace-only, or too short\n if (trimmed.length === 0 || this.shouldSkipString(node.text, `${path}.text`)) {\n return node\n }\n\n const textPath = `${path}.text`\n\n if (enableDeduplication) {\n // Check for deduplication\n if (deduplicationMap.has(trimmed)) {\n // This string already exists, just store the path mapping\n const existingPaths = deduplicationMap.get(trimmed)!\n existingPaths.push(textPath)\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n } else {\n // New unique string\n strings.set(textPath, node.text)\n deduplicationMap.set(trimmed, [textPath])\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n }\n } else {\n // No deduplication - add every string\n strings.set(textPath, node.text)\n deduplicationMap.set(trimmed, [textPath])\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n }\n }\n\n // Handle nodes with children\n if (node.children && Array.isArray(node.children)) {\n return {\n ...node,\n children: node.children.map((child: any, index: number) =>\n this.extractFromLexicalNode(\n child,\n `${path}.children[${index}]`,\n strings,\n deduplicationMap,\n ),\n ),\n }\n }\n\n return node\n }\n\n /**\n * Extracts translatable strings from data structure\n * Returns a map of paths to translatable values and metadata for reconstruction\n */\n private extractTranslatableStrings(\n data: any,\n path: string = '',\n ): { deduplicationMap: Map<string, string[]>; metadata: any; strings: Map<string, string> } {\n const strings = new Map<string, string>()\n const deduplicationMap = new Map<string, string[]>() // value -> [paths]\n const enableDeduplication = this.config.enableDeduplication !== false // Default to true\n\n const extract = (obj: any, currentPath: string): any => {\n if (obj === null || obj === undefined) {\n return obj\n }\n\n // Handle lexical editor format\n if (this.isLexicalEditorNode(obj)) {\n return this.extractFromLexicalNode(obj, currentPath, strings, deduplicationMap)\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item, index) => extract(item, `${currentPath}[${index}]`))\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {}\n for (const [key, value] of Object.entries(obj)) {\n const newPath = currentPath ? `${currentPath}.${key}` : key\n result[key] = extract(value, newPath)\n }\n return result\n }\n\n // Handle strings\n if (typeof obj === 'string' && obj.trim().length > 0) {\n // Skip IDs and other non-translatable strings\n if (!this.shouldSkipString(obj, currentPath)) {\n if (enableDeduplication) {\n // Check for deduplication\n const trimmedValue = obj.trim()\n if (deduplicationMap.has(trimmedValue)) {\n // This string already exists, just store the path mapping\n const existingPaths = deduplicationMap.get(trimmedValue)!\n existingPaths.push(currentPath)\n return `__TRANSLATE_${currentPath}__`\n } else {\n // New unique string\n strings.set(currentPath, obj)\n deduplicationMap.set(trimmedValue, [currentPath])\n return `__TRANSLATE_${currentPath}__`\n }\n } else {\n // No deduplication - add every string\n strings.set(currentPath, obj)\n deduplicationMap.set(obj.trim(), [currentPath])\n return `__TRANSLATE_${currentPath}__`\n }\n }\n }\n\n return obj\n }\n\n const metadata = extract(data, path)\n return { deduplicationMap, metadata, strings }\n }\n\n /**\n * Lazily initialize OpenAI client only when needed\n */\n private getOpenAIClient(): OpenAI {\n if (!this.client) {\n const apiKey = this.config.provider?.apiKey || process.env.OPENAI_API_KEY\n if (!apiKey) {\n throw new Error(\n 'OpenAI API key is required. Set OPENAI_API_KEY environment variable or provide it in plugin config.',\n )\n }\n\n this.client = new OpenAI({\n apiKey,\n baseURL: this.config.provider?.baseURL || process.env.OPENAI_BASE_URL,\n })\n }\n return this.client\n }\n\n /**\n * Gets the original value at a path in metadata (helper for deduplication)\n */\n private getOriginalValue(metadata: any, path: string): null | string {\n try {\n const parts = path.split(/[.[\\]]/).filter(Boolean)\n let current = metadata\n for (const part of parts) {\n if (current === null || current === undefined) {\n return null\n }\n current = current[part]\n }\n return typeof current === 'string' ? current : null\n } catch {\n return null\n }\n }\n\n /**\n * Gets translation settings from the global or returns defaults\n */\n private async getTranslationSettings(payload: Payload): Promise<{\n maxTokens?: number\n model: string\n systemPrompt: string\n temperature: number\n translationRules: string\n }> {\n const settingsSlug = this.config.translationSettingsSlug || 'translation-settings'\n\n // Default values\n const defaults = {\n maxTokens: undefined,\n model: this.config.provider?.model || 'gpt-4o',\n systemPrompt:\n 'You are a professional translator. Translate the JSON object values from {fromLocale} to {toLocale}.',\n temperature: 0.3,\n translationRules: `Rules:\n - Only translate the values, never the keys\n - Preserve the exact JSON structure\n - Maintain formatting, HTML tags, and special characters\n - Return only valid JSON without any markdown formatting or code blocks\n - If a value is already in the target language or is a proper noun, keep it as is`,\n }\n\n try {\n const settings = await payload.findGlobal({\n slug: settingsSlug as GlobalSlug,\n })\n\n if (settings) {\n return {\n maxTokens: settings.maxTokens || defaults.maxTokens,\n model: settings.model || defaults.model,\n systemPrompt: settings.systemPrompt || defaults.systemPrompt,\n temperature:\n typeof settings.temperature === 'number' ? settings.temperature : defaults.temperature,\n translationRules: settings.translationRules || defaults.translationRules,\n }\n }\n } catch (error) {\n if (this.config.debugging) {\n console.warn(\n '[Auto-Translate] Could not fetch translation settings, using defaults:',\n error,\n )\n }\n }\n\n return defaults\n }\n\n /**\n * Checks if an object is a lexical editor node\n */\n private isLexicalEditorNode(obj: any): boolean {\n return (\n obj &&\n typeof obj === 'object' &&\n 'type' in obj &&\n 'version' in obj &&\n ('children' in obj || 'text' in obj)\n )\n }\n\n /**\n * Reconstructs data with translated strings, applying deduplicated translations\n */\n private reconstructWithTranslations(\n metadata: any,\n translations: Map<string, string>,\n deduplicationMap: Map<string, string[]>,\n ): any {\n // Build a comprehensive translation map including deduplicated paths\n const fullTranslations = new Map<string, string>()\n\n // For each unique string that was translated\n translations.forEach((translatedValue, originalPath) => {\n fullTranslations.set(originalPath, translatedValue)\n\n // Find all paths that had the same original value\n const originalValue = this.getOriginalValue(metadata, originalPath)\n if (originalValue) {\n const trimmed = originalValue.replace(/^__TRANSLATE_(.+)__$/, '$1')\n // Look through deduplication map to find all paths with same value\n for (const [value, paths] of deduplicationMap.entries()) {\n if (paths.includes(originalPath)) {\n // Apply the same translation to all paths with this value\n paths.forEach((path) => {\n fullTranslations.set(path, translatedValue)\n })\n break\n }\n }\n }\n })\n\n const reconstruct = (obj: any): any => {\n if (obj === null || obj === undefined) {\n return obj\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => reconstruct(item))\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {}\n for (const [key, value] of Object.entries(obj)) {\n result[key] = reconstruct(value)\n }\n return result\n }\n\n // Replace translation placeholders\n if (typeof obj === 'string' && obj.startsWith('__TRANSLATE_')) {\n const path = obj.slice(12, -2) // Remove __TRANSLATE_ prefix and __ suffix\n return fullTranslations.get(path) || obj\n }\n\n return obj\n }\n\n return reconstruct(metadata)\n }\n\n /**\n * Determines if a string should be skipped from translation\n */\n private shouldSkipString(str: string, path: string): boolean {\n // Skip IDs (MongoDB ObjectIds and similar)\n if (/^[a-f0-9]{24}$/i.test(str)) {\n return true\n }\n\n // Skip URLs\n if (/^https?:\\/\\//.test(str)) {\n return true\n }\n\n // Skip file paths\n if (/^\\/\\S*\\.(jpg|jpeg|png|gif|webp|svg|pdf|mp4|webm|ogg|mp3|wav)$/i.test(str)) {\n return true\n }\n\n // Skip email addresses\n if (/^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/.test(str)) {\n return true\n }\n\n // Skip ISO date strings\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(str)) {\n return true\n }\n\n // Skip date-time strings like \"2019-01-31 12:05:04\"\n if (/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(str)) {\n return true\n }\n\n // Skip percentages like \"100%\"\n if (/^\\d+%$/.test(str)) {\n return true\n }\n\n // Skip pure numbers\n if (/^\\d+$/.test(str)) {\n return true\n }\n\n // Skip whitespace-only strings (including single spaces)\n if (str.trim().length === 0) {\n return true\n }\n\n // Skip very short strings based on config (default: 3 characters)\n const minLength = this.config.minStringLength !== undefined ? this.config.minStringLength : 3\n if (str.trim().length < minLength) {\n return true\n }\n\n // Skip status values\n if (['archived', 'draft', 'pending', 'published'].includes(str.toLowerCase())) {\n return true\n }\n\n // Skip paths ending with id, createdAt, updatedAt, etc.\n const pathLower = path.toLowerCase()\n if (\n pathLower.endsWith('id') ||\n pathLower.endsWith('_id') ||\n pathLower.includes('createdat') ||\n pathLower.includes('updatedat')\n ) {\n return true\n }\n\n return false\n }\n\n /**\n * Legacy translation method (sends entire structure)\n */\n private async translateWithOpenAILegacy(\n data: any,\n fromLocale: string,\n toLocale: string,\n payload: Payload,\n ): Promise<any> {\n const client = this.getOpenAIClient()\n const timeout = this.config.provider?.timeout || 30000\n\n try {\n // Get translation settings from global\n const settings = await this.getTranslationSettings(payload)\n\n // Build system message from settings\n const systemPrompt = settings.systemPrompt\n .replace('{fromLocale}', fromLocale)\n .replace('{toLocale}', toLocale)\n\n const systemMessage = `${systemPrompt}\\n\\n${settings.translationRules}`\n\n const requestParams: any = {\n messages: [\n {\n content: systemMessage,\n role: 'system',\n },\n {\n content: JSON.stringify(data, null, 2),\n role: 'user',\n },\n ],\n model: settings.model,\n response_format: { type: 'json_object' },\n temperature: settings.temperature,\n }\n\n // Add maxTokens if specified\n if (settings.maxTokens) {\n requestParams.max_tokens = settings.maxTokens\n }\n\n const response = await client.chat.completions.create(requestParams, { timeout })\n\n const translatedText = response.choices[0]?.message?.content\n\n if (!translatedText) {\n throw new Error('No translation received from OpenAI')\n }\n\n return JSON.parse(translatedText)\n } catch (error) {\n console.error('[Auto-Translate] Translation error:', error)\n throw error\n }\n }\n\n /**\n * Gets global and collection-specific excluded fields\n */\n getConfigExcludedFields(collection: string): string[] {\n const globalExclusions = this.config.excludeFields || []\n const collectionConfig = this.config.collections?.[collection as CollectionSlug]\n\n if (typeof collectionConfig === 'object' && collectionConfig.excludeFields) {\n return [...globalExclusions, ...collectionConfig.excludeFields]\n }\n\n return globalExclusions\n }\n\n /**\n * Gets translation exclusions for a document\n */\n async getExclusions(\n payload: Payload,\n collection: string,\n documentId: string,\n locale: string,\n ): Promise<string[]> {\n const exclusionsSlug = (this.config.translationExclusionsSlug ||\n 'translation-exclusions') as CollectionSlug\n\n try {\n const result = await payload.find({\n collection: exclusionsSlug,\n limit: 1,\n where: {\n and: [\n { collectionSlug: { equals: collection } },\n { documentId: { equals: documentId } },\n { locale: { equals: locale } },\n ],\n },\n })\n\n if (result.docs.length > 0) {\n const exclusion = result.docs[0] as any\n return exclusion.excludedPaths?.map((item: any) => item.path) || []\n }\n\n return []\n } catch (error) {\n if (this.config.debugging) {\n payload.logger.error(`[Auto-Translate] Error fetching exclusions: ${error}`)\n }\n return []\n }\n }\n\n /**\n * Main translation method\n */\n async translate(options: TranslateOptions): Promise<any> {\n const { collection, data, excludedPaths = [], fromLocale, payload, toLocale } = options\n\n // Filter out excluded paths before translation\n const dataToTranslate = filterExcludedPaths(data, excludedPaths)\n\n if (this.config.debugging) {\n payload.logger.info(\n `[Auto-Translate] Translating from ${fromLocale} to ${toLocale} for collection ${collection}`,\n )\n payload.logger.info(`[Auto-Translate] Excluded paths: ${excludedPaths.join(', ')}`)\n }\n\n // Run the configured translation strategy\n let translated: any\n if (this.config.provider?.customTranslate) {\n // Use custom translator if provided\n translated = await this.config.provider.customTranslate(options)\n } else {\n // Use OpenAI by default\n translated = await this.translateWithOpenAI(dataToTranslate, fromLocale, toLocale, payload)\n }\n\n // Restore canonical values for enum-backed fields (select/radio). The Postgres\n // adapter stores these as native enum columns, so a translated option value\n // (e.g. \"narrow\" -> \"schmal\") is rejected with `invalid input value for enum`.\n //\n // When `translateLocalizedFieldsOnly` is enabled, also restore every field that\n // is not localized (directly or via a localized ancestor container) so only\n // localized fields are translated.\n const fields = this.getDocumentFields(payload, collection)\n if (fields) {\n overlayNonTranslatableValues(translated, data, fields, {\n localizedOnly: this.config.translateLocalizedFieldsOnly === true,\n })\n }\n\n return translated\n }\n\n /**\n * Resolves the field schema for a collection or global slug so translation can\n * be made schema-aware (e.g. to avoid translating enum-backed select/radio\n * field values).\n */\n private getDocumentFields(payload: Payload, slug: string): Field[] | undefined {\n const collectionConfig = (payload as any).collections?.[slug]?.config\n if (collectionConfig && Array.isArray(collectionConfig.fields)) {\n return collectionConfig.fields\n }\n\n const globalConfig = (payload.config as any)?.globals?.find((g: any) => g.slug === slug)\n if (globalConfig && Array.isArray(globalConfig.fields)) {\n return globalConfig.fields\n }\n\n return undefined\n }\n\n /**\n * Translates using OpenAI API (optimized version)\n * This method is now public and can be used directly in your application\n */\n async translateWithOpenAI(\n data: any,\n fromLocale: string,\n toLocale: string,\n payload: Payload,\n ): Promise<any> {\n const client = this.getOpenAIClient()\n\n // Use optimization by default (can be disabled via config)\n const useOptimization = this.config.optimizeTranslation !== false\n\n if (!useOptimization) {\n // Use legacy approach: send entire structure\n return this.translateWithOpenAILegacy(data, fromLocale, toLocale, payload)\n }\n\n // Extract only translatable strings with deduplication\n const { deduplicationMap, metadata, strings } = this.extractTranslatableStrings(data)\n\n if (strings.size === 0) {\n // Nothing to translate\n return data\n }\n\n // Create a simple object with just the strings to translate\n const stringsToTranslate: Record<string, string> = {}\n strings.forEach((value, key) => {\n stringsToTranslate[key] = value\n })\n\n if (this.config.debugging) {\n const originalSize = JSON.stringify(data).length\n const optimizedSize = JSON.stringify(stringsToTranslate).length\n const reduction = ((1 - optimizedSize / originalSize) * 100).toFixed(1)\n\n // Calculate deduplication stats\n let totalPaths = 0\n deduplicationMap.forEach((paths) => {\n totalPaths += paths.length\n })\n const deduplicationSavings = totalPaths - strings.size\n const deduplicationPercent =\n totalPaths > 0 ? ((deduplicationSavings / totalPaths) * 100).toFixed(1) : '0'\n\n console.log('[Auto-Translate] ✨ Optimization Stats:')\n console.log(` 📊 Unique strings to translate: ${strings.size}`)\n console.log(` 🔄 Total string instances: ${totalPaths}`)\n console.log(\n ` 💾 Deduplication savings: ${deduplicationSavings} strings (${deduplicationPercent}%)`,\n )\n console.log(` 📦 Original JSON size: ${originalSize.toLocaleString()} bytes`)\n console.log(` 📦 Optimized JSON size: ${optimizedSize.toLocaleString()} bytes`)\n console.log(` 🎯 Total size reduction: ${reduction}%`)\n }\n\n try {\n // Get translation settings from global\n const settings = await this.getTranslationSettings(payload)\n\n // Add timeout configuration (default 30 seconds, configurable via plugin options)\n const timeout = this.config.provider?.timeout || 30000\n\n if (this.config.debugging) {\n console.log(\n `[Auto-Translate] Calling OpenAI API (timeout: ${timeout}ms, model: ${settings.model})`,\n )\n console.log(\n `[Auto-Translate] Payload size: ${JSON.stringify(stringsToTranslate).length} bytes`,\n )\n }\n\n // Build system message from settings\n const systemPrompt = settings.systemPrompt\n .replace('{fromLocale}', fromLocale)\n .replace('{toLocale}', toLocale)\n\n const systemMessage = `${systemPrompt}\\n\\n${settings.translationRules}`\n\n const requestParams: any = {\n messages: [\n {\n content: systemMessage,\n role: 'system',\n },\n {\n content: JSON.stringify(stringsToTranslate, null, 2),\n role: 'user',\n },\n ],\n model: settings.model,\n response_format: { type: 'json_object' },\n temperature: settings.temperature,\n }\n\n // Add maxTokens if specified\n if (settings.maxTokens) {\n requestParams.max_tokens = settings.maxTokens\n }\n\n const response = await client.chat.completions.create(requestParams, { timeout })\n\n const translatedText = response.choices[0]?.message?.content\n\n if (!translatedText) {\n throw new Error('No translation received from OpenAI')\n }\n\n if (this.config.debugging) {\n console.log(\n `[Auto-Translate] Received response from OpenAI (${translatedText.length} chars)`,\n )\n }\n\n let translatedStrings: any\n try {\n translatedStrings = JSON.parse(translatedText)\n } catch (parseError) {\n console.error('[Auto-Translate] Failed to parse OpenAI response as JSON')\n console.error('[Auto-Translate] Response text:', translatedText.substring(0, 500))\n throw new Error(\n `Invalid JSON response from OpenAI: ${parseError instanceof Error ? parseError.message : String(parseError)}`,\n )\n }\n\n // Convert back to Map\n const translationsMap = new Map<string, string>()\n for (const [key, value] of Object.entries(translatedStrings)) {\n if (typeof value === 'string') {\n translationsMap.set(key, value)\n }\n }\n\n // Reconstruct the full data structure with translations, applying deduplication\n return this.reconstructWithTranslations(metadata, translationsMap, deduplicationMap)\n } catch (error) {\n console.error('[Auto-Translate] Translation error:', error)\n\n // Provide more context about the error\n if (error && typeof error === 'object') {\n const err = error as any\n if (err.status) {\n console.error(`[Auto-Translate] OpenAI API status: ${err.status}`)\n }\n if (err.code) {\n console.error(`[Auto-Translate] Error code: ${err.code}`)\n }\n if (err.message) {\n console.error(`[Auto-Translate] Error message: ${err.message}`)\n }\n }\n\n // Add context to the error before re-throwing\n const contextualError = new Error(\n `Translation failed from ${fromLocale} to ${toLocale}: ${error instanceof Error ? error.message : String(error)}`,\n )\n contextualError.cause = error\n throw contextualError\n }\n }\n\n /**\n * Updates translation exclusions for a document\n */\n async updateExclusions(\n payload: Payload,\n collection: string,\n documentId: string,\n locale: string,\n excludedPaths: string[],\n ): Promise<void> {\n const exclusionsSlug = (this.config.translationExclusionsSlug ||\n 'translation-exclusions') as CollectionSlug\n\n try {\n const existing = await payload.find({\n collection: exclusionsSlug,\n limit: 1,\n where: {\n and: [\n { collectionSlug: { equals: collection } },\n { documentId: { equals: documentId } },\n { locale: { equals: locale } },\n ],\n },\n })\n\n const exclusionsData = {\n collectionSlug: collection,\n documentId,\n excludedPaths: excludedPaths.map((path) => ({ path })),\n locale,\n }\n\n if (existing.docs.length > 0) {\n await payload.update({\n id: existing.docs[0].id,\n collection: exclusionsSlug,\n data: exclusionsData,\n })\n } else {\n await payload.create({\n collection: exclusionsSlug,\n data: exclusionsData,\n })\n }\n\n if (this.config.debugging) {\n payload.logger.info(\n `[Auto-Translate] Updated exclusions for ${collection}:${documentId}:${locale}`,\n )\n }\n } catch (error) {\n if (this.config.debugging) {\n payload.logger.error(`[Auto-Translate] Error updating exclusions: ${error}`)\n }\n }\n }\n}\n"],"names":["OpenAI","filterExcludedPaths","overlayNonTranslatableValues","TranslationService","client","config","extractFromLexicalNode","node","path","strings","deduplicationMap","enableDeduplication","type","text","trimmed","trim","length","shouldSkipString","textPath","has","existingPaths","get","push","set","children","Array","isArray","map","child","index","extractTranslatableStrings","data","Map","extract","obj","currentPath","undefined","isLexicalEditorNode","item","result","key","value","Object","entries","newPath","trimmedValue","metadata","getOpenAIClient","apiKey","provider","process","env","OPENAI_API_KEY","Error","baseURL","OPENAI_BASE_URL","getOriginalValue","parts","split","filter","Boolean","current","part","getTranslationSettings","payload","settingsSlug","translationSettingsSlug","defaults","maxTokens","model","systemPrompt","temperature","translationRules","settings","findGlobal","slug","error","debugging","console","warn","reconstructWithTranslations","translations","fullTranslations","forEach","translatedValue","originalPath","originalValue","replace","paths","includes","reconstruct","startsWith","slice","str","test","minLength","minStringLength","toLowerCase","pathLower","endsWith","translateWithOpenAILegacy","fromLocale","toLocale","timeout","systemMessage","requestParams","messages","content","role","JSON","stringify","response_format","max_tokens","response","chat","completions","create","translatedText","choices","message","parse","getConfigExcludedFields","collection","globalExclusions","excludeFields","collectionConfig","collections","getExclusions","documentId","locale","exclusionsSlug","translationExclusionsSlug","find","limit","where","and","collectionSlug","equals","docs","exclusion","excludedPaths","logger","translate","options","dataToTranslate","info","join","translated","customTranslate","translateWithOpenAI","fields","getDocumentFields","localizedOnly","translateLocalizedFieldsOnly","globalConfig","globals","g","useOptimization","optimizeTranslation","size","stringsToTranslate","originalSize","optimizedSize","reduction","toFixed","totalPaths","deduplicationSavings","deduplicationPercent","log","toLocaleString","translatedStrings","parseError","substring","String","translationsMap","err","status","code","contextualError","cause","updateExclusions","existing","exclusionsData","update","id"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAI3B,SAASC,mBAAmB,EAAEC,4BAA4B,QAAQ,+BAA8B;AAEhG,OAAO,MAAMC;IACHC,OAAe;IACfC,OAA2B;IAEnC,YAAYA,MAA2B,CAAE;QACvC,IAAI,CAACA,MAAM,GAAGA;IAChB;IAEA;;GAEC,GACD,AAAQC,uBACNC,IAAS,EACTC,IAAY,EACZC,OAA4B,EAC5BC,gBAAuC,EAClC;QACL,MAAMC,sBAAsB,IAAI,CAACN,MAAM,CAACM,mBAAmB,KAAK,MAAM,kBAAkB;;QAExF,8DAA8D;QAC9D,IAAIJ,KAAKK,IAAI,KAAK,UAAUL,KAAKM,IAAI,IAAI,OAAON,KAAKM,IAAI,KAAK,UAAU;YACtE,MAAMC,UAAUP,KAAKM,IAAI,CAACE,IAAI;YAE9B,+CAA+C;YAC/C,IAAID,QAAQE,MAAM,KAAK,KAAK,IAAI,CAACC,gBAAgB,CAACV,KAAKM,IAAI,EAAE,GAAGL,KAAK,KAAK,CAAC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SAAS3C,IAAI,CAAC1H,MAAM,GAAG,GAAG;gBAC5B,MAAMgD,QAAQuH,MAAM,CAAC;oBACnBC,IAAIH,SAAS3C,IAAI,CAAC,EAAE,CAAC8C,EAAE;oBACvB9D,YAAYQ;oBACZnG,MAAMuJ;gBACR;YACF,OAAO;gBACL,MAAMtH,QAAQoD,MAAM,CAAC;oBACnBM,YAAYQ;oBACZnG,MAAMuJ;gBACR;YACF;YAEA,IAAI,IAAI,CAACjL,MAAM,CAACwE,SAAS,EAAE;gBACzBb,QAAQ6E,MAAM,CAACI,IAAI,CACjB,CAAC,wCAAwC,EAAEvB,WAAW,CAAC,EAAEM,WAAW,CAAC,EAAEC,QAAQ;YAEnF;QACF,EAAE,OAAOrD,OAAO;YACd,IAAI,IAAI,CAACvE,MAAM,CAACwE,SAAS,EAAE;gBACzBb,QAAQ6E,MAAM,CAACjE,KAAK,CAAC,CAAC,4CAA4C,EAAEA,OAAO;YAC7E;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/services/translationService.ts"],"sourcesContent":["import type { CollectionSlug, Field, GlobalSlug, Payload } from 'payload'\n\nimport OpenAI from 'openai'\n\nimport type { AutoTranslateConfig, TranslateOptions } from '../types/index.js'\n\nimport { supportsCustomTemperature } from '../endpoints/listOpenAiModels.js'\nimport { filterExcludedPaths, overlayNonTranslatableValues } from '../utilities/fieldHelpers.js'\n\nexport class TranslationService {\n private client?: OpenAI\n private config: AutoTranslateConfig\n\n constructor(config: AutoTranslateConfig) {\n this.config = config\n }\n\n /**\n * Extracts translatable text from lexical editor nodes\n */\n private extractFromLexicalNode(\n node: any,\n path: string,\n strings: Map<string, string>,\n deduplicationMap: Map<string, string[]>,\n ): any {\n const enableDeduplication = this.config.enableDeduplication !== false // Default to true\n\n // Handle text nodes - skip whitespace-only or very short text\n if (node.type === 'text' && node.text && typeof node.text === 'string') {\n const trimmed = node.text.trim()\n\n // Skip if empty, whitespace-only, or too short\n if (trimmed.length === 0 || this.shouldSkipString(node.text, `${path}.text`)) {\n return node\n }\n\n const textPath = `${path}.text`\n\n if (enableDeduplication) {\n // Check for deduplication\n if (deduplicationMap.has(trimmed)) {\n // This string already exists, just store the path mapping\n const existingPaths = deduplicationMap.get(trimmed)!\n existingPaths.push(textPath)\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n } else {\n // New unique string\n strings.set(textPath, node.text)\n deduplicationMap.set(trimmed, [textPath])\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n }\n } else {\n // No deduplication - add every string\n strings.set(textPath, node.text)\n deduplicationMap.set(trimmed, [textPath])\n return { ...node, text: `__TRANSLATE_${textPath}__` }\n }\n }\n\n // Handle nodes with children\n if (node.children && Array.isArray(node.children)) {\n return {\n ...node,\n children: node.children.map((child: any, index: number) =>\n this.extractFromLexicalNode(\n child,\n `${path}.children[${index}]`,\n strings,\n deduplicationMap,\n ),\n ),\n }\n }\n\n return node\n }\n\n /**\n * Extracts translatable strings from data structure\n * Returns a map of paths to translatable values and metadata for reconstruction\n */\n private extractTranslatableStrings(\n data: any,\n path: string = '',\n ): { deduplicationMap: Map<string, string[]>; metadata: any; strings: Map<string, string> } {\n const strings = new Map<string, string>()\n const deduplicationMap = new Map<string, string[]>() // value -> [paths]\n const enableDeduplication = this.config.enableDeduplication !== false // Default to true\n\n const extract = (obj: any, currentPath: string): any => {\n if (obj === null || obj === undefined) {\n return obj\n }\n\n // Handle lexical editor format\n if (this.isLexicalEditorNode(obj)) {\n return this.extractFromLexicalNode(obj, currentPath, strings, deduplicationMap)\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item, index) => extract(item, `${currentPath}[${index}]`))\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {}\n for (const [key, value] of Object.entries(obj)) {\n const newPath = currentPath ? `${currentPath}.${key}` : key\n result[key] = extract(value, newPath)\n }\n return result\n }\n\n // Handle strings\n if (typeof obj === 'string' && obj.trim().length > 0) {\n // Skip IDs and other non-translatable strings\n if (!this.shouldSkipString(obj, currentPath)) {\n if (enableDeduplication) {\n // Check for deduplication\n const trimmedValue = obj.trim()\n if (deduplicationMap.has(trimmedValue)) {\n // This string already exists, just store the path mapping\n const existingPaths = deduplicationMap.get(trimmedValue)!\n existingPaths.push(currentPath)\n return `__TRANSLATE_${currentPath}__`\n } else {\n // New unique string\n strings.set(currentPath, obj)\n deduplicationMap.set(trimmedValue, [currentPath])\n return `__TRANSLATE_${currentPath}__`\n }\n } else {\n // No deduplication - add every string\n strings.set(currentPath, obj)\n deduplicationMap.set(obj.trim(), [currentPath])\n return `__TRANSLATE_${currentPath}__`\n }\n }\n }\n\n return obj\n }\n\n const metadata = extract(data, path)\n return { deduplicationMap, metadata, strings }\n }\n\n /**\n * Lazily initialize OpenAI client only when needed\n */\n private getOpenAIClient(): OpenAI {\n if (!this.client) {\n const apiKey = this.config.provider?.apiKey || process.env.OPENAI_API_KEY\n if (!apiKey) {\n throw new Error(\n 'OpenAI API key is required. Set OPENAI_API_KEY environment variable or provide it in plugin config.',\n )\n }\n\n this.client = new OpenAI({\n apiKey,\n baseURL: this.config.provider?.baseURL || process.env.OPENAI_BASE_URL,\n })\n }\n return this.client\n }\n\n /**\n * Gets the original value at a path in metadata (helper for deduplication)\n */\n private getOriginalValue(metadata: any, path: string): null | string {\n try {\n const parts = path.split(/[.[\\]]/).filter(Boolean)\n let current = metadata\n for (const part of parts) {\n if (current === null || current === undefined) {\n return null\n }\n current = current[part]\n }\n return typeof current === 'string' ? current : null\n } catch {\n return null\n }\n }\n\n /**\n * Gets translation settings from the global or returns defaults\n */\n private async getTranslationSettings(payload: Payload): Promise<{\n maxTokens?: number\n model: string\n systemPrompt: string\n temperature: number\n translationRules: string\n }> {\n const settingsSlug = this.config.translationSettingsSlug || 'translation-settings'\n\n // Default values\n const defaults = {\n maxTokens: undefined,\n model: this.config.provider?.model || 'gpt-4o',\n systemPrompt:\n 'You are a professional translator. Translate the JSON object values from {fromLocale} to {toLocale}.',\n temperature: 0.3,\n translationRules: `Rules:\n - Only translate the values, never the keys\n - Preserve the exact JSON structure\n - Maintain formatting, HTML tags, and special characters\n - Return only valid JSON without any markdown formatting or code blocks\n - If a value is already in the target language or is a proper noun, keep it as is`,\n }\n\n try {\n const settings = await payload.findGlobal({\n slug: settingsSlug as GlobalSlug,\n })\n\n if (settings) {\n return {\n maxTokens: settings.maxTokens || defaults.maxTokens,\n model: settings.model || defaults.model,\n systemPrompt: settings.systemPrompt || defaults.systemPrompt,\n temperature:\n typeof settings.temperature === 'number' ? settings.temperature : defaults.temperature,\n translationRules: settings.translationRules || defaults.translationRules,\n }\n }\n } catch (error) {\n if (this.config.debugging) {\n console.warn(\n '[Auto-Translate] Could not fetch translation settings, using defaults:',\n error,\n )\n }\n }\n\n return defaults\n }\n\n /**\n * Checks if an object is a lexical editor node\n */\n private isLexicalEditorNode(obj: any): boolean {\n return (\n obj &&\n typeof obj === 'object' &&\n 'type' in obj &&\n 'version' in obj &&\n ('children' in obj || 'text' in obj)\n )\n }\n\n /**\n * Reconstructs data with translated strings, applying deduplicated translations\n */\n private reconstructWithTranslations(\n metadata: any,\n translations: Map<string, string>,\n deduplicationMap: Map<string, string[]>,\n ): any {\n // Build a comprehensive translation map including deduplicated paths\n const fullTranslations = new Map<string, string>()\n\n // For each unique string that was translated\n translations.forEach((translatedValue, originalPath) => {\n fullTranslations.set(originalPath, translatedValue)\n\n // Find all paths that had the same original value\n const originalValue = this.getOriginalValue(metadata, originalPath)\n if (originalValue) {\n const trimmed = originalValue.replace(/^__TRANSLATE_(.+)__$/, '$1')\n // Look through deduplication map to find all paths with same value\n for (const [value, paths] of deduplicationMap.entries()) {\n if (paths.includes(originalPath)) {\n // Apply the same translation to all paths with this value\n paths.forEach((path) => {\n fullTranslations.set(path, translatedValue)\n })\n break\n }\n }\n }\n })\n\n const reconstruct = (obj: any): any => {\n if (obj === null || obj === undefined) {\n return obj\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => reconstruct(item))\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {}\n for (const [key, value] of Object.entries(obj)) {\n result[key] = reconstruct(value)\n }\n return result\n }\n\n // Replace translation placeholders\n if (typeof obj === 'string' && obj.startsWith('__TRANSLATE_')) {\n const path = obj.slice(12, -2) // Remove __TRANSLATE_ prefix and __ suffix\n return fullTranslations.get(path) || obj\n }\n\n return obj\n }\n\n return reconstruct(metadata)\n }\n\n /**\n * Determines if a string should be skipped from translation\n */\n private shouldSkipString(str: string, path: string): boolean {\n // Skip IDs (MongoDB ObjectIds and similar)\n if (/^[a-f0-9]{24}$/i.test(str)) {\n return true\n }\n\n // Skip URLs\n if (/^https?:\\/\\//.test(str)) {\n return true\n }\n\n // Skip file paths\n if (/^\\/\\S*\\.(jpg|jpeg|png|gif|webp|svg|pdf|mp4|webm|ogg|mp3|wav)$/i.test(str)) {\n return true\n }\n\n // Skip email addresses\n if (/^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/.test(str)) {\n return true\n }\n\n // Skip ISO date strings\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(str)) {\n return true\n }\n\n // Skip date-time strings like \"2019-01-31 12:05:04\"\n if (/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(str)) {\n return true\n }\n\n // Skip percentages like \"100%\"\n if (/^\\d+%$/.test(str)) {\n return true\n }\n\n // Skip pure numbers\n if (/^\\d+$/.test(str)) {\n return true\n }\n\n // Skip whitespace-only strings (including single spaces)\n if (str.trim().length === 0) {\n return true\n }\n\n // Skip very short strings based on config (default: 3 characters)\n const minLength = this.config.minStringLength !== undefined ? this.config.minStringLength : 3\n if (str.trim().length < minLength) {\n return true\n }\n\n // Skip status values\n if (['archived', 'draft', 'pending', 'published'].includes(str.toLowerCase())) {\n return true\n }\n\n // Skip paths ending with id, createdAt, updatedAt, etc.\n const pathLower = path.toLowerCase()\n if (\n pathLower.endsWith('id') ||\n pathLower.endsWith('_id') ||\n pathLower.includes('createdat') ||\n pathLower.includes('updatedat')\n ) {\n return true\n }\n\n return false\n }\n\n /**\n * Legacy translation method (sends entire structure)\n */\n private async translateWithOpenAILegacy(\n data: any,\n fromLocale: string,\n toLocale: string,\n payload: Payload,\n ): Promise<any> {\n const client = this.getOpenAIClient()\n const timeout = this.config.provider?.timeout || 30000\n\n try {\n // Get translation settings from global\n const settings = await this.getTranslationSettings(payload)\n\n // Build system message from settings\n const systemPrompt = settings.systemPrompt\n .replace('{fromLocale}', fromLocale)\n .replace('{toLocale}', toLocale)\n\n const systemMessage = `${systemPrompt}\\n\\n${settings.translationRules}`\n\n const requestParams = {\n messages: [\n {\n content: systemMessage,\n role: 'system' as const,\n },\n {\n content: JSON.stringify(data, null, 2),\n role: 'user' as const,\n },\n ],\n model: settings.model,\n response_format: { type: 'json_object' as const },\n ...(supportsCustomTemperature(settings.model)\n ? { temperature: settings.temperature }\n : {}),\n ...(settings.maxTokens ? { max_tokens: settings.maxTokens } : {}),\n }\n\n const response = await client.chat.completions.create(requestParams, { timeout })\n\n const translatedText = response.choices[0]?.message?.content\n\n if (!translatedText) {\n throw new Error('No translation received from OpenAI')\n }\n\n return JSON.parse(translatedText)\n } catch (error) {\n console.error('[Auto-Translate] Translation error:', error)\n throw error\n }\n }\n\n /**\n * Gets global and collection-specific excluded fields\n */\n getConfigExcludedFields(collection: string): string[] {\n const globalExclusions = this.config.excludeFields || []\n const collectionConfig = this.config.collections?.[collection as CollectionSlug]\n\n if (typeof collectionConfig === 'object' && collectionConfig.excludeFields) {\n return [...globalExclusions, ...collectionConfig.excludeFields]\n }\n\n return globalExclusions\n }\n\n /**\n * Gets translation exclusions for a document\n */\n async getExclusions(\n payload: Payload,\n collection: string,\n documentId: string,\n locale: string,\n ): Promise<string[]> {\n const exclusionsSlug = (this.config.translationExclusionsSlug ||\n 'translation-exclusions') as CollectionSlug\n\n try {\n const result = await payload.find({\n collection: exclusionsSlug,\n limit: 1,\n where: {\n and: [\n { collectionSlug: { equals: collection } },\n { documentId: { equals: documentId } },\n { locale: { equals: locale } },\n ],\n },\n })\n\n if (result.docs.length > 0) {\n const exclusion = result.docs[0] as any\n return exclusion.excludedPaths?.map((item: any) => item.path) || []\n }\n\n return []\n } catch (error) {\n if (this.config.debugging) {\n payload.logger.error(`[Auto-Translate] Error fetching exclusions: ${error}`)\n }\n return []\n }\n }\n\n /**\n * Main translation method\n */\n async translate(options: TranslateOptions): Promise<any> {\n const { collection, data, excludedPaths = [], fromLocale, payload, toLocale } = options\n\n // Filter out excluded paths before translation\n const dataToTranslate = filterExcludedPaths(data, excludedPaths)\n\n if (this.config.debugging) {\n payload.logger.info(\n `[Auto-Translate] Translating from ${fromLocale} to ${toLocale} for collection ${collection}`,\n )\n payload.logger.info(`[Auto-Translate] Excluded paths: ${excludedPaths.join(', ')}`)\n }\n\n // Run the configured translation strategy\n let translated: any\n if (this.config.provider?.customTranslate) {\n // Use custom translator if provided\n translated = await this.config.provider.customTranslate(options)\n } else {\n // Use OpenAI by default\n translated = await this.translateWithOpenAI(dataToTranslate, fromLocale, toLocale, payload)\n }\n\n // Restore canonical values for enum-backed fields (select/radio). The Postgres\n // adapter stores these as native enum columns, so a translated option value\n // (e.g. \"narrow\" -> \"schmal\") is rejected with `invalid input value for enum`.\n //\n // When `translateLocalizedFieldsOnly` is enabled, also restore every field that\n // is not localized (directly or via a localized ancestor container) so only\n // localized fields are translated.\n const fields = this.getDocumentFields(payload, collection)\n if (fields) {\n overlayNonTranslatableValues(translated, data, fields, {\n localizedOnly: this.config.translateLocalizedFieldsOnly === true,\n })\n }\n\n return translated\n }\n\n /**\n * Resolves the field schema for a collection or global slug so translation can\n * be made schema-aware (e.g. to avoid translating enum-backed select/radio\n * field values).\n */\n private getDocumentFields(payload: Payload, slug: string): Field[] | undefined {\n const collectionConfig = (payload as any).collections?.[slug]?.config\n if (collectionConfig && Array.isArray(collectionConfig.fields)) {\n return collectionConfig.fields\n }\n\n const globalConfig = (payload.config as any)?.globals?.find((g: any) => g.slug === slug)\n if (globalConfig && Array.isArray(globalConfig.fields)) {\n return globalConfig.fields\n }\n\n return undefined\n }\n\n /**\n * Translates using OpenAI API (optimized version)\n * This method is now public and can be used directly in your application\n */\n async translateWithOpenAI(\n data: any,\n fromLocale: string,\n toLocale: string,\n payload: Payload,\n ): Promise<any> {\n const client = this.getOpenAIClient()\n\n // Use optimization by default (can be disabled via config)\n const useOptimization = this.config.optimizeTranslation !== false\n\n if (!useOptimization) {\n // Use legacy approach: send entire structure\n return this.translateWithOpenAILegacy(data, fromLocale, toLocale, payload)\n }\n\n // Extract only translatable strings with deduplication\n const { deduplicationMap, metadata, strings } = this.extractTranslatableStrings(data)\n\n if (strings.size === 0) {\n // Nothing to translate\n return data\n }\n\n // Create a simple object with just the strings to translate\n const stringsToTranslate: Record<string, string> = {}\n strings.forEach((value, key) => {\n stringsToTranslate[key] = value\n })\n\n if (this.config.debugging) {\n const originalSize = JSON.stringify(data).length\n const optimizedSize = JSON.stringify(stringsToTranslate).length\n const reduction = ((1 - optimizedSize / originalSize) * 100).toFixed(1)\n\n // Calculate deduplication stats\n let totalPaths = 0\n deduplicationMap.forEach((paths) => {\n totalPaths += paths.length\n })\n const deduplicationSavings = totalPaths - strings.size\n const deduplicationPercent =\n totalPaths > 0 ? ((deduplicationSavings / totalPaths) * 100).toFixed(1) : '0'\n\n console.log('[Auto-Translate] ✨ Optimization Stats:')\n console.log(` 📊 Unique strings to translate: ${strings.size}`)\n console.log(` 🔄 Total string instances: ${totalPaths}`)\n console.log(\n ` 💾 Deduplication savings: ${deduplicationSavings} strings (${deduplicationPercent}%)`,\n )\n console.log(` 📦 Original JSON size: ${originalSize.toLocaleString()} bytes`)\n console.log(` 📦 Optimized JSON size: ${optimizedSize.toLocaleString()} bytes`)\n console.log(` 🎯 Total size reduction: ${reduction}%`)\n }\n\n try {\n // Get translation settings from global\n const settings = await this.getTranslationSettings(payload)\n\n // Add timeout configuration (default 30 seconds, configurable via plugin options)\n const timeout = this.config.provider?.timeout || 30000\n\n if (this.config.debugging) {\n console.log(\n `[Auto-Translate] Calling OpenAI API (timeout: ${timeout}ms, model: ${settings.model})`,\n )\n console.log(\n `[Auto-Translate] Payload size: ${JSON.stringify(stringsToTranslate).length} bytes`,\n )\n }\n\n // Build system message from settings\n const systemPrompt = settings.systemPrompt\n .replace('{fromLocale}', fromLocale)\n .replace('{toLocale}', toLocale)\n\n const systemMessage = `${systemPrompt}\\n\\n${settings.translationRules}`\n\n const requestParams = {\n messages: [\n {\n content: systemMessage,\n role: 'system' as const,\n },\n {\n content: JSON.stringify(stringsToTranslate, null, 2),\n role: 'user' as const,\n },\n ],\n model: settings.model,\n response_format: { type: 'json_object' as const },\n ...(supportsCustomTemperature(settings.model)\n ? { temperature: settings.temperature }\n : {}),\n ...(settings.maxTokens ? { max_tokens: settings.maxTokens } : {}),\n }\n\n const response = await client.chat.completions.create(requestParams, { timeout })\n\n const translatedText = response.choices[0]?.message?.content\n\n if (!translatedText) {\n throw new Error('No translation received from OpenAI')\n }\n\n if (this.config.debugging) {\n console.log(\n `[Auto-Translate] Received response from OpenAI (${translatedText.length} chars)`,\n )\n }\n\n let translatedStrings: any\n try {\n translatedStrings = JSON.parse(translatedText)\n } catch (parseError) {\n console.error('[Auto-Translate] Failed to parse OpenAI response as JSON')\n console.error('[Auto-Translate] Response text:', translatedText.substring(0, 500))\n throw new Error(\n `Invalid JSON response from OpenAI: ${parseError instanceof Error ? parseError.message : String(parseError)}`,\n )\n }\n\n // Convert back to Map\n const translationsMap = new Map<string, string>()\n for (const [key, value] of Object.entries(translatedStrings)) {\n if (typeof value === 'string') {\n translationsMap.set(key, value)\n }\n }\n\n // Reconstruct the full data structure with translations, applying deduplication\n return this.reconstructWithTranslations(metadata, translationsMap, deduplicationMap)\n } catch (error) {\n console.error('[Auto-Translate] Translation error:', error)\n\n // Provide more context about the error\n if (error && typeof error === 'object') {\n const err = error as any\n if (err.status) {\n console.error(`[Auto-Translate] OpenAI API status: ${err.status}`)\n }\n if (err.code) {\n console.error(`[Auto-Translate] Error code: ${err.code}`)\n }\n if (err.message) {\n console.error(`[Auto-Translate] Error message: ${err.message}`)\n }\n }\n\n // Add context to the error before re-throwing\n const contextualError = new Error(\n `Translation failed from ${fromLocale} to ${toLocale}: ${error instanceof Error ? error.message : String(error)}`,\n )\n contextualError.cause = error\n throw contextualError\n }\n }\n\n /**\n * Updates translation exclusions for a document\n */\n async updateExclusions(\n payload: Payload,\n collection: string,\n documentId: string,\n locale: string,\n excludedPaths: string[],\n ): Promise<void> {\n const exclusionsSlug = (this.config.translationExclusionsSlug ||\n 'translation-exclusions') as CollectionSlug\n\n try {\n const existing = await payload.find({\n collection: exclusionsSlug,\n limit: 1,\n where: {\n and: [\n { collectionSlug: { equals: collection } },\n { documentId: { equals: documentId } },\n { locale: { equals: locale } },\n ],\n },\n })\n\n const exclusionsData = {\n collectionSlug: collection,\n documentId,\n excludedPaths: excludedPaths.map((path) => ({ path })),\n locale,\n }\n\n if (existing.docs.length > 0) {\n await payload.update({\n id: existing.docs[0].id,\n collection: exclusionsSlug,\n data: exclusionsData,\n })\n } else {\n await payload.create({\n collection: exclusionsSlug,\n data: exclusionsData,\n })\n }\n\n if (this.config.debugging) {\n payload.logger.info(\n `[Auto-Translate] Updated exclusions for ${collection}:${documentId}:${locale}`,\n )\n }\n } catch (error) {\n if (this.config.debugging) {\n payload.logger.error(`[Auto-Translate] Error updating exclusions: ${error}`)\n }\n }\n }\n}\n"],"names":["OpenAI","supportsCustomTemperature","filterExcludedPaths","overlayNonTranslatableValues","TranslationService","client","config","extractFromLexicalNode","node","path","strings","deduplicationMap","enableDeduplication","type","text","trimmed","trim","length","shouldSkipString","textPath","has","existingPaths","get","push","set","children","Array","isArray","map","child","index","extractTranslatableStrings","data","Map","extract","obj","currentPath","undefined","isLexicalEditorNode","item","result","key","value","Object","entries","newPath","trimmedValue","metadata","getOpenAIClient","apiKey","provider","process","env","OPENAI_API_KEY","Error","baseURL","OPENAI_BASE_URL","getOriginalValue","parts","split","filter","Boolean","current","part","getTranslationSettings","payload","settingsSlug","translationSettingsSlug","defaults","maxTokens","model","systemPrompt","temperature","translationRules","settings","findGlobal","slug","error","debugging","console","warn","reconstructWithTranslations","translations","fullTranslations","forEach","translatedValue","originalPath","originalValue","replace","paths","includes","reconstruct","startsWith","slice","str","test","minLength","minStringLength","toLowerCase","pathLower","endsWith","translateWithOpenAILegacy","fromLocale","toLocale","timeout","systemMessage","requestParams","messages","content","role","JSON","stringify","response_format","max_tokens","response","chat","completions","create","translatedText","choices","message","parse","getConfigExcludedFields","collection","globalExclusions","excludeFields","collectionConfig","collections","getExclusions","documentId","locale","exclusionsSlug","translationExclusionsSlug","find","limit","where","and","collectionSlug","equals","docs","exclusion","excludedPaths","logger","translate","options","dataToTranslate","info","join","translated","customTranslate","translateWithOpenAI","fields","getDocumentFields","localizedOnly","translateLocalizedFieldsOnly","globalConfig","globals","g","useOptimization","optimizeTranslation","size","stringsToTranslate","originalSize","optimizedSize","reduction","toFixed","totalPaths","deduplicationSavings","deduplicationPercent","log","toLocaleString","translatedStrings","parseError","substring","String","translationsMap","err","status","code","contextualError","cause","updateExclusions","existing","exclusionsData","update","id"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAI3B,SAASC,yBAAyB,QAAQ,mCAAkC;AAC5E,SAASC,mBAAmB,EAAEC,4BAA4B,QAAQ,+BAA8B;AAEhG,OAAO,MAAMC;IACHC,OAAe;IACfC,OAA2B;IAEnC,YAAYA,MAA2B,CAAE;QACvC,IAAI,CAACA,MAAM,GAAGA;IAChB;IAEA;;GAEC,GACD,AAAQC,uBACNC,IAAS,EACTC,IAAY,EACZC,OAA4B,EAC5BC,gBAAuC,EAClC;QACL,MAAMC,sBAAsB,IAAI,CAACN,MAAM,CAACM,mBAAmB,KAAK,MAAM,kBAAkB;;QAExF,8DAA8D;QAC9D,IAAIJ,KAAKK,IAAI,KAAK,UAAUL,KAAKM,IAAI,IAAI,OAAON,KAAKM,IAA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C,QAAQf;4BAAW;wBAAE;wBACzC;4BAAEM,YAAY;gCAAES,QAAQT;4BAAW;wBAAE;wBACrC;4BAAEC,QAAQ;gCAAEQ,QAAQR;4BAAO;wBAAE;qBAC9B;gBACH;YACF;YAEA,MAAMqD,iBAAiB;gBACrB9C,gBAAgBd;gBAChBM;gBACAY,eAAeA,cAAcjH,GAAG,CAAC,CAACnB,OAAU,CAAA;wBAAEA;oBAAK,CAAA;gBACnDyH;YACF;YAEA,IAAIoD,SAAS3C,IAAI,CAAC1H,MAAM,GAAG,GAAG;gBAC5B,MAAMgD,QAAQuH,MAAM,CAAC;oBACnBC,IAAIH,SAAS3C,IAAI,CAAC,EAAE,CAAC8C,EAAE;oBACvB9D,YAAYQ;oBACZnG,MAAMuJ;gBACR;YACF,OAAO;gBACL,MAAMtH,QAAQoD,MAAM,CAAC;oBACnBM,YAAYQ;oBACZnG,MAAMuJ;gBACR;YACF;YAEA,IAAI,IAAI,CAACjL,MAAM,CAACwE,SAAS,EAAE;gBACzBb,QAAQ6E,MAAM,CAACI,IAAI,CACjB,CAAC,wCAAwC,EAAEvB,WAAW,CAAC,EAAEM,WAAW,CAAC,EAAEC,QAAQ;YAEnF;QACF,EAAE,OAAOrD,OAAO;YACd,IAAI,IAAI,CAACvE,MAAM,CAACwE,SAAS,EAAE;gBACzBb,QAAQ6E,MAAM,CAACjE,KAAK,CAAC,CAAC,4CAA4C,EAAEA,OAAO;YAC7E;QACF;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pigment/auto-translate",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Automatic translation plugin for Payload CMS with field-level exclusion controls and performance optimizations",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload",
|
|
@@ -47,6 +47,30 @@
|
|
|
47
47
|
"files": [
|
|
48
48
|
"dist"
|
|
49
49
|
],
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
52
|
+
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
|
53
|
+
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
54
|
+
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
55
|
+
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
56
|
+
"dev": "next dev dev",
|
|
57
|
+
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
|
|
58
|
+
"dev:generate-types": "pnpm dev:payload generate:types",
|
|
59
|
+
"dev:migrate": "pnpm dev:payload migrate",
|
|
60
|
+
"dev:migrate:create": "pnpm dev:payload migrate:create",
|
|
61
|
+
"dev:migrate:down": "pnpm dev:payload migrate:down",
|
|
62
|
+
"dev:migrate:fresh": "pnpm dev:payload migrate:fresh",
|
|
63
|
+
"dev:migrate:status": "pnpm dev:payload migrate:status",
|
|
64
|
+
"dev:payload": "dotenv -e ./dev/.env -- cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload",
|
|
65
|
+
"generate:importmap": "pnpm dev:generate-importmap",
|
|
66
|
+
"generate:types": "pnpm dev:generate-types",
|
|
67
|
+
"lint": "eslint",
|
|
68
|
+
"lint:fix": "eslint ./src --fix",
|
|
69
|
+
"prepublishOnly": "pnpm clean && pnpm build",
|
|
70
|
+
"test": "pnpm test:int && pnpm test:e2e",
|
|
71
|
+
"test:e2e": "playwright test",
|
|
72
|
+
"test:int": "vitest"
|
|
73
|
+
},
|
|
50
74
|
"devDependencies": {
|
|
51
75
|
"@eslint/eslintrc": "^3.2.0",
|
|
52
76
|
"@payloadcms/db-mongodb": "3.85.0",
|
|
@@ -91,31 +115,36 @@
|
|
|
91
115
|
"node": "^20.9.0 || >=22",
|
|
92
116
|
"pnpm": "^9 || ^10"
|
|
93
117
|
},
|
|
118
|
+
"publishConfig": {
|
|
119
|
+
"exports": {
|
|
120
|
+
".": {
|
|
121
|
+
"types": "./dist/index.d.ts",
|
|
122
|
+
"import": "./dist/index.js",
|
|
123
|
+
"default": "./dist/index.js"
|
|
124
|
+
},
|
|
125
|
+
"./client": {
|
|
126
|
+
"types": "./dist/exports/client.d.ts",
|
|
127
|
+
"import": "./dist/exports/client.js",
|
|
128
|
+
"default": "./dist/exports/client.js"
|
|
129
|
+
},
|
|
130
|
+
"./rsc": {
|
|
131
|
+
"types": "./dist/exports/rsc.d.ts",
|
|
132
|
+
"import": "./dist/exports/rsc.js",
|
|
133
|
+
"default": "./dist/exports/rsc.js"
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
"main": "./dist/index.js",
|
|
137
|
+
"types": "./dist/index.d.ts"
|
|
138
|
+
},
|
|
139
|
+
"pnpm": {
|
|
140
|
+
"onlyBuiltDependencies": [
|
|
141
|
+
"sharp",
|
|
142
|
+
"esbuild",
|
|
143
|
+
"unrs-resolver"
|
|
144
|
+
]
|
|
145
|
+
},
|
|
94
146
|
"registry": "https://registry.npmjs.org/",
|
|
95
147
|
"dependencies": {
|
|
96
148
|
"openai": "^6.8.0"
|
|
97
|
-
},
|
|
98
|
-
"scripts": {
|
|
99
|
-
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
100
|
-
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
|
101
|
-
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
102
|
-
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
103
|
-
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
104
|
-
"dev": "next dev dev",
|
|
105
|
-
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
|
|
106
|
-
"dev:generate-types": "pnpm dev:payload generate:types",
|
|
107
|
-
"dev:migrate": "pnpm dev:payload migrate",
|
|
108
|
-
"dev:migrate:create": "pnpm dev:payload migrate:create",
|
|
109
|
-
"dev:migrate:down": "pnpm dev:payload migrate:down",
|
|
110
|
-
"dev:migrate:fresh": "pnpm dev:payload migrate:fresh",
|
|
111
|
-
"dev:migrate:status": "pnpm dev:payload migrate:status",
|
|
112
|
-
"dev:payload": "dotenv -e ./dev/.env -- cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload",
|
|
113
|
-
"generate:importmap": "pnpm dev:generate-importmap",
|
|
114
|
-
"generate:types": "pnpm dev:generate-types",
|
|
115
|
-
"lint": "eslint",
|
|
116
|
-
"lint:fix": "eslint ./src --fix",
|
|
117
|
-
"test": "pnpm test:int && pnpm test:e2e",
|
|
118
|
-
"test:e2e": "playwright test",
|
|
119
|
-
"test:int": "vitest"
|
|
120
149
|
}
|
|
121
|
-
}
|
|
150
|
+
}
|