@nocode-factory/sanity-kit 2.26.0 → 2.27.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/dist/index.d.ts +10 -2
- package/dist/index.js +247 -48
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/actions/PropagatePublish.tsx +40 -9
- package/src/config/defaults.ts +1 -1
- package/src/config/resolve.ts +3 -0
- package/src/config/types.ts +8 -0
- package/src/form/OverrideInput.tsx +62 -1
- package/src/form/TranslationTodoInput.tsx +36 -2
- package/src/hooks/useTranslationTodo.ts +2 -1
- package/src/index.ts +5 -1
- package/src/lib/aiTexts.ts +72 -0
- package/src/lib/aiTranslate.ts +61 -0
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -6,6 +6,8 @@ import type {ResolvedKitConfig} from '../config/types'
|
|
|
6
6
|
import {useKitClient} from '../hooks/useKitClient'
|
|
7
7
|
import {hasChanges, propagate, type PropagationResult, type SchemaTypeLike} from '../lib/propagate'
|
|
8
8
|
import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
|
|
9
|
+
import {setAtKey, valueAtKey} from '../lib/aiTexts'
|
|
10
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
9
11
|
|
|
10
12
|
type Doc = Record<string, unknown>
|
|
11
13
|
interface Target {
|
|
@@ -20,18 +22,22 @@ interface Target {
|
|
|
20
22
|
* part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
|
|
21
23
|
* BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
|
|
22
24
|
* et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
|
|
23
|
-
* sont jamais écrasés : les textes modifiés sont
|
|
24
|
-
*
|
|
25
|
+
* sont jamais écrasés à la main : les textes modifiés sont traduits par l'IA
|
|
26
|
+
* (« Translate with AI », service du kit, coché par défaut) ou marqués « à
|
|
27
|
+
* traduire ». Rien n'est publié dans les autres langues : on relit, on publie.
|
|
28
|
+
* `masterLocale` : langue source (défaut : langue principale du site ; les valeurs
|
|
29
|
+
* par défaut des composants ont la leur, `i18n.defaultsSourceLocale`).
|
|
25
30
|
*/
|
|
26
|
-
export function withPropagation(Publish: DocumentActionComponent, config: ResolvedKitConfig): DocumentActionComponent {
|
|
31
|
+
export function withPropagation(Publish: DocumentActionComponent, config: ResolvedKitConfig, masterLocale?: string): DocumentActionComponent {
|
|
27
32
|
const i18n = config.i18n
|
|
33
|
+
const master = masterLocale ?? i18n?.defaultLocale
|
|
28
34
|
const Wrapped: DocumentActionComponent = (props: DocumentActionProps) => {
|
|
29
35
|
const base = Publish(props)
|
|
30
36
|
const client = useKitClient()
|
|
31
37
|
const schema = useSchema()
|
|
32
38
|
const [run, setRun] = useState<{before: Doc; after: Doc; targets: Target[]} | null>(null)
|
|
33
39
|
const current = (props.draft ?? props.published) as Doc | null
|
|
34
|
-
if (!base || !i18n || current?.[i18n.field] !==
|
|
40
|
+
if (!base || !i18n || current?.[i18n.field] !== master) return base
|
|
35
41
|
return {
|
|
36
42
|
...base,
|
|
37
43
|
onHandle: () => {
|
|
@@ -119,17 +125,32 @@ function PropagateDialog(props: {
|
|
|
119
125
|
const [busy, setBusy] = useState(false)
|
|
120
126
|
const toast = useToast()
|
|
121
127
|
const [error, setError] = useState<string | null>(null)
|
|
128
|
+
// Textes modifiés : traduits par l'IA (service du kit) plutôt que marqués « à traduire ».
|
|
129
|
+
const [ai, setAi] = useState(Boolean(config.history))
|
|
122
130
|
|
|
123
131
|
const apply = async () => {
|
|
124
132
|
setBusy(true)
|
|
125
133
|
setError(null)
|
|
126
134
|
try {
|
|
127
135
|
const applied: string[] = []
|
|
136
|
+
let translatedCount = 0
|
|
137
|
+
let aiError: string | null = null
|
|
128
138
|
for (const t of targets) {
|
|
129
139
|
if (!t.selected) continue
|
|
130
140
|
const {_rev, _createdAt, _updatedAt, ...doc} = t.result.document
|
|
141
|
+
let remaining = t.result.toTranslate
|
|
142
|
+
if (ai && config.history && remaining.length) {
|
|
143
|
+
try {
|
|
144
|
+
const values = remaining.map((path) => valueAtKey(after, path))
|
|
145
|
+
const translated = await translateValues(config.history, source, t.language, values)
|
|
146
|
+
remaining = remaining.filter((path, n) => values[n] === undefined || !setAtKey(doc, path, translated[n]))
|
|
147
|
+
translatedCount += t.result.toTranslate.length - remaining.length
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
aiError = cause instanceof Error ? cause.message : String(cause)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
131
152
|
await client.createOrReplace({...doc, _id: `drafts.${t.id}`, _type: type} as {_id: string; _type: string})
|
|
132
|
-
if (
|
|
153
|
+
if (remaining.length) {
|
|
133
154
|
const todoId = translationTodoId(t.id)
|
|
134
155
|
const existing = await client.fetch<string[] | null>(`*[_id == $todoId][0].paths`, {todoId})
|
|
135
156
|
await client.createOrReplace({
|
|
@@ -138,16 +159,20 @@ function PropagateDialog(props: {
|
|
|
138
159
|
documentId: t.id,
|
|
139
160
|
sourceId: id,
|
|
140
161
|
sourceLanguage: source,
|
|
141
|
-
paths: [...new Set([...(existing ?? []), ...
|
|
162
|
+
paths: [...new Set([...(existing ?? []), ...remaining])],
|
|
142
163
|
})
|
|
143
164
|
}
|
|
144
165
|
applied.push(t.language.toUpperCase())
|
|
145
166
|
}
|
|
146
167
|
// Fini : la fenêtre se ferme seule, le résultat s'affiche en notification.
|
|
147
168
|
toast.push({
|
|
148
|
-
status: 'success',
|
|
169
|
+
status: aiError ? 'warning' : 'success',
|
|
149
170
|
title: `Drafts updated: ${applied.join(', ')}`,
|
|
150
|
-
description:
|
|
171
|
+
description: aiError
|
|
172
|
+
? `AI translation failed (${aiError}): the changed texts are marked "To translate".`
|
|
173
|
+
: translatedCount
|
|
174
|
+
? `${translatedCount} text${translatedCount > 1 ? 's' : ''} translated with AI. Review, then publish each language.`
|
|
175
|
+
: 'Translate the fields marked "To translate", then publish each language.',
|
|
151
176
|
duration: 8000,
|
|
152
177
|
})
|
|
153
178
|
onDone()
|
|
@@ -162,8 +187,14 @@ function PropagateDialog(props: {
|
|
|
162
187
|
<Stack gap={4} padding={4}>
|
|
163
188
|
<Text size={1}>
|
|
164
189
|
The {source.toUpperCase()} version is published. Apply its changes to the drafts of the other languages?
|
|
165
|
-
|
|
190
|
+
Changed texts are {ai ? 'translated with AI' : 'marked "To translate"'}. Nothing is published.
|
|
166
191
|
</Text>
|
|
192
|
+
{config.history && targets.some((t) => t.result.toTranslate.length) && (
|
|
193
|
+
<Flex as="label" align="center" gap={2}>
|
|
194
|
+
<Checkbox checked={ai} onChange={() => setAi(!ai)} />
|
|
195
|
+
<Text size={1}>Translate changed texts with AI</Text>
|
|
196
|
+
</Flex>
|
|
197
|
+
)}
|
|
167
198
|
<Stack gap={3}>
|
|
168
199
|
{targets.map((t, index) => (
|
|
169
200
|
<Card key={t.id} padding={3} radius={2} border>
|
package/src/config/defaults.ts
CHANGED
|
@@ -18,7 +18,7 @@ export const DEFAULT_BLOCK_NAMESPACE = ''
|
|
|
18
18
|
*/
|
|
19
19
|
export const DEFAULT_NOINDEX_FIELDS = ['seo.noindex', 'noindex']
|
|
20
20
|
|
|
21
|
-
export const DEFAULT_I18N: Required<NcfI18nConfig> = {
|
|
21
|
+
export const DEFAULT_I18N: Omit<Required<NcfI18nConfig>, 'defaultsSourceLocale'> = {
|
|
22
22
|
field: 'language',
|
|
23
23
|
defaultLocale: 'fr',
|
|
24
24
|
locales: [],
|
package/src/config/resolve.ts
CHANGED
|
@@ -79,6 +79,9 @@ export function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {
|
|
|
79
79
|
field: input.i18n.field?.trim() || DEFAULT_I18N.field,
|
|
80
80
|
defaultLocale: input.i18n.defaultLocale?.trim() || DEFAULT_I18N.defaultLocale,
|
|
81
81
|
locales: input.i18n.locales ?? DEFAULT_I18N.locales,
|
|
82
|
+
defaultsSourceLocale:
|
|
83
|
+
input.i18n.defaultsSourceLocale?.trim() ||
|
|
84
|
+
((input.i18n.locales ?? DEFAULT_I18N.locales).includes('en') ? 'en' : input.i18n.defaultLocale?.trim() || DEFAULT_I18N.defaultLocale),
|
|
82
85
|
}
|
|
83
86
|
|
|
84
87
|
return {
|
package/src/config/types.ts
CHANGED
|
@@ -37,6 +37,13 @@ export interface NcfI18nConfig {
|
|
|
37
37
|
defaultLocale?: string
|
|
38
38
|
/** Langues attendues. Vide = déduites des documents rencontrés. */
|
|
39
39
|
locales?: string[]
|
|
40
|
+
/**
|
|
41
|
+
* Langue SOURCE des valeurs par défaut des composants (défaut : `en` si le site
|
|
42
|
+
* l'a, sinon la langue principale). Publier ses valeurs par défaut propose de
|
|
43
|
+
* retraduire celles des autres langues ; un champ qui hérite d'une valeur par
|
|
44
|
+
* défaut non traduite propose « Translate default with AI ».
|
|
45
|
+
*/
|
|
46
|
+
defaultsSourceLocale?: string
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
/**
|
|
@@ -241,6 +248,7 @@ export interface ResolvedI18n {
|
|
|
241
248
|
field: string
|
|
242
249
|
defaultLocale: string
|
|
243
250
|
locales: string[]
|
|
251
|
+
defaultsSourceLocale: string
|
|
244
252
|
}
|
|
245
253
|
|
|
246
254
|
export interface ResolvedComponentPreview {
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import {useState, type ComponentType} from 'react'
|
|
2
2
|
import {set, unset, useFormValue, useSchema, type InputProps} from 'sanity'
|
|
3
3
|
import {useRouter} from 'sanity/router'
|
|
4
|
-
import {Box, Flex, Text} from '@sanity/ui'
|
|
4
|
+
import {Box, Button, Flex, Text} from '@sanity/ui'
|
|
5
5
|
import {Tooltip} from '@sanity/ui/tooltip'
|
|
6
6
|
import type {ResolvedKitConfig} from '../config/types'
|
|
7
7
|
import {blockName, componentIntentParams} from '../lib/blocks'
|
|
8
8
|
import {useKitClient} from '../hooks/useKitClient'
|
|
9
|
+
import {collectTexts} from '../lib/aiTexts'
|
|
10
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
9
11
|
import {useComponentDefaults} from '../hooks/useComponentDefaults'
|
|
10
12
|
import {
|
|
11
13
|
defaultValueAt,
|
|
@@ -59,6 +61,44 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
59
61
|
const defaults = useComponentDefaults(client, defaultsType, languageField, language)
|
|
60
62
|
const inherited = defaultValueAt(defaults, shortName, rel)
|
|
61
63
|
const field = rel[rel.length - 1] ?? ''
|
|
64
|
+
// Valeurs par défaut dans la langue SOURCE (anglais en général) : un champ qui
|
|
65
|
+
// hérite d'une valeur par défaut pas encore traduite dans cette langue (vide,
|
|
66
|
+
// ou identique au texte source) propose « Translate default with AI ».
|
|
67
|
+
const sourceLocale = config.i18n?.defaultsSourceLocale ?? null
|
|
68
|
+
const sourceDefaults = useComponentDefaults(client, defaultsType, languageField, sourceLocale)
|
|
69
|
+
const sourceDefault = defaultValueAt(sourceDefaults, shortName, rel)
|
|
70
|
+
const [translating, setTranslating] = useState(false)
|
|
71
|
+
const [translateError, setTranslateError] = useState<string | null>(null)
|
|
72
|
+
const untranslatedDefault =
|
|
73
|
+
Boolean(config.history && config.i18n && language && sourceLocale && language !== sourceLocale) &&
|
|
74
|
+
!inputProps.readOnly &&
|
|
75
|
+
isEmptyValue(inputProps.value) &&
|
|
76
|
+
collectTexts(sourceDefault).some((t) => t.trim()) &&
|
|
77
|
+
(isEmptyValue(inherited) || JSON.stringify(inherited) === JSON.stringify(sourceDefault))
|
|
78
|
+
const translateDefault = async () => {
|
|
79
|
+
const localeId = (defaults as {_id?: string} | null)?._id?.replace(/^drafts\./, '')
|
|
80
|
+
if (!config.history || !sourceLocale || !language) return
|
|
81
|
+
setTranslating(true)
|
|
82
|
+
setTranslateError(null)
|
|
83
|
+
try {
|
|
84
|
+
if (!localeId) throw new Error(`No ${language.toUpperCase()} component defaults document.`)
|
|
85
|
+
const [translated] = await translateValues(config.history, sourceLocale, language, [sourceDefault])
|
|
86
|
+
// Écrit dans le BROUILLON des valeurs par défaut de cette langue (à publier).
|
|
87
|
+
const published = await client.getDocument(localeId)
|
|
88
|
+
const path = [shortName, ...rel].map((seg, n) => (typeof seg === 'number' ? `[${seg}]` : n ? `.${seg}` : seg)).join('')
|
|
89
|
+
const tx = client.transaction()
|
|
90
|
+
if (published) {
|
|
91
|
+
const {_rev, _updatedAt, _createdAt, ...copy} = published
|
|
92
|
+
tx.createIfNotExists({...copy, _id: `drafts.${localeId}`} as {_id: string; _type: string})
|
|
93
|
+
}
|
|
94
|
+
tx.patch(`drafts.${localeId}`, (patch) => patch.set({[path]: translated}))
|
|
95
|
+
await tx.commit()
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
setTranslateError(cause instanceof Error ? cause.message : String(cause))
|
|
98
|
+
} finally {
|
|
99
|
+
setTranslating(false)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
62
102
|
|
|
63
103
|
const router = useRouter()
|
|
64
104
|
|
|
@@ -99,6 +139,27 @@ export function createOverrideInput(config: ResolvedKitConfig): ComponentType<In
|
|
|
99
139
|
<Flex align="flex-start" gap={2}>
|
|
100
140
|
<Box flex={1} style={{minWidth: 0}}>
|
|
101
141
|
{inputProps.renderDefault(shown)}
|
|
142
|
+
{untranslatedDefault && (
|
|
143
|
+
<Flex align="center" gap={2} marginTop={2} wrap="wrap">
|
|
144
|
+
<Text size={0} muted>
|
|
145
|
+
Default not translated to {String(language).toUpperCase()}.
|
|
146
|
+
</Text>
|
|
147
|
+
<Button
|
|
148
|
+
mode="ghost"
|
|
149
|
+
tone="primary"
|
|
150
|
+
fontSize={0}
|
|
151
|
+
padding={2}
|
|
152
|
+
text={translating ? 'Translating…' : 'Translate default with AI'}
|
|
153
|
+
disabled={translating}
|
|
154
|
+
onClick={() => void translateDefault()}
|
|
155
|
+
/>
|
|
156
|
+
{translateError && (
|
|
157
|
+
<Text size={0} style={{color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
158
|
+
{translateError}
|
|
159
|
+
</Text>
|
|
160
|
+
)}
|
|
161
|
+
</Flex>
|
|
162
|
+
)}
|
|
102
163
|
{inherits && placeholder === null && (
|
|
103
164
|
<Box marginTop={2}>
|
|
104
165
|
<Text size={0} muted>
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import {createElement, useState, type ComponentType} from 'react'
|
|
2
|
-
import {useFormValue, type InputProps} from 'sanity'
|
|
2
|
+
import {set, useFormValue, type InputProps} from 'sanity'
|
|
3
3
|
import {Button, Card, Flex, Stack, Text} from '@sanity/ui'
|
|
4
4
|
import type {ResolvedKitConfig} from '../config/types'
|
|
5
5
|
import {useKitClient} from '../hooks/useKitClient'
|
|
6
6
|
import {fieldPathKey, useTranslationTodo} from '../hooks/useTranslationTodo'
|
|
7
|
+
import {valueAtKey} from '../lib/aiTexts'
|
|
8
|
+
import {translateValues} from '../lib/aiTranslate'
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
11
|
* Sous un champ d'une traduction modifié dans la version principale (propagation) :
|
|
10
|
-
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste
|
|
12
|
+
* « À traduire », avec « Marquer comme traduit » qui le retire de la liste, et
|
|
13
|
+
* « Translate with AI » (service du kit) : traduit le texte de la version principale
|
|
14
|
+
* dans ce champ (brouillon de cette langue), puis le retire de la liste.
|
|
11
15
|
*/
|
|
12
16
|
export function withTranslationTodo(Inner: ComponentType<InputProps>, config: ResolvedKitConfig): ComponentType<InputProps> {
|
|
13
17
|
function TranslationTodoInput(props: InputProps) {
|
|
@@ -15,6 +19,8 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
15
19
|
const client = useKitClient()
|
|
16
20
|
const todo = useTranslationTodo(client, config.i18n ? id : undefined)
|
|
17
21
|
const [busy, setBusy] = useState(false)
|
|
22
|
+
const [error, setError] = useState<string | null>(null)
|
|
23
|
+
const language = useFormValue([config.i18n?.field ?? 'language']) as string | undefined
|
|
18
24
|
const key = fieldPathKey(props.path)
|
|
19
25
|
const inner = createElement(Inner, props)
|
|
20
26
|
const show = Boolean(todo?.paths?.includes(key))
|
|
@@ -27,6 +33,26 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
27
33
|
.commit()
|
|
28
34
|
.finally(() => setBusy(false))
|
|
29
35
|
}
|
|
36
|
+
const translate = async () => {
|
|
37
|
+
if (!todo?.sourceId || !todo.sourceLanguage || !language || !config.history) return
|
|
38
|
+
setBusy(true)
|
|
39
|
+
setError(null)
|
|
40
|
+
try {
|
|
41
|
+
const source = (await client.getDocument(todo.sourceId)) ?? (await client.getDocument(`drafts.${todo.sourceId}`))
|
|
42
|
+
const value = valueAtKey(source, key)
|
|
43
|
+
if (value === undefined) throw new Error('Source text not found.')
|
|
44
|
+
const [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value])
|
|
45
|
+
props.onChange(set(translated))
|
|
46
|
+
await client
|
|
47
|
+
.patch(todo._id)
|
|
48
|
+
.set({paths: (todo.paths ?? []).filter((p) => p !== key)})
|
|
49
|
+
.commit()
|
|
50
|
+
} catch (cause) {
|
|
51
|
+
setError(cause instanceof Error ? cause.message : String(cause))
|
|
52
|
+
} finally {
|
|
53
|
+
setBusy(false)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
30
56
|
// Même structure que la mention soit là ou non : le champ n'est jamais recréé.
|
|
31
57
|
return (
|
|
32
58
|
<Stack gap={2}>
|
|
@@ -37,8 +63,16 @@ export function withTranslationTodo(Inner: ComponentType<InputProps>, config: Re
|
|
|
37
63
|
<Text size={1} style={{flex: 1}}>
|
|
38
64
|
To translate: changed in the {(todo?.sourceLanguage ?? '').toUpperCase()} version.
|
|
39
65
|
</Text>
|
|
66
|
+
{config.history && !props.readOnly && (
|
|
67
|
+
<Button tone="primary" fontSize={1} padding={2} text={busy ? 'Translating…' : 'Translate with AI'} disabled={busy} onClick={() => void translate()} />
|
|
68
|
+
)}
|
|
40
69
|
<Button mode="ghost" fontSize={1} padding={2} text="Mark as translated" disabled={busy} onClick={done} />
|
|
41
70
|
</Flex>
|
|
71
|
+
{error && (
|
|
72
|
+
<Text size={1} style={{marginTop: 8, color: 'var(--card-badge-critical-fg-color, #c00)'}}>
|
|
73
|
+
{error}
|
|
74
|
+
</Text>
|
|
75
|
+
)}
|
|
42
76
|
</Card>
|
|
43
77
|
)}
|
|
44
78
|
</Stack>
|
|
@@ -8,6 +8,7 @@ import {translationTodoId} from '../schema/translationTodo'
|
|
|
8
8
|
*/
|
|
9
9
|
export interface TranslationTodo {
|
|
10
10
|
_id: string
|
|
11
|
+
sourceId?: string
|
|
11
12
|
sourceLanguage?: string
|
|
12
13
|
paths?: string[]
|
|
13
14
|
}
|
|
@@ -31,7 +32,7 @@ function entryFor(client: SanityClient, documentId: string): Entry {
|
|
|
31
32
|
if (!e.stop) {
|
|
32
33
|
const load = () =>
|
|
33
34
|
client
|
|
34
|
-
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceLanguage, paths}`, {id})
|
|
35
|
+
.fetch<TranslationTodo | null>(`*[_id == $id][0]{_id, sourceId, sourceLanguage, paths}`, {id})
|
|
35
36
|
.then((value) => {
|
|
36
37
|
e.value = value
|
|
37
38
|
e.listeners.forEach((l) => l())
|
package/src/index.ts
CHANGED
|
@@ -152,7 +152,11 @@ export const ncfKit = definePlugin<NcfKitConfig>((options) => {
|
|
|
152
152
|
? prev.map((action) =>
|
|
153
153
|
action.action === 'unpublish' ? RemoveFromSiteAction : action.action === 'publish' && config.i18n ? withPropagation(action, config) : action,
|
|
154
154
|
)
|
|
155
|
-
:
|
|
155
|
+
: // Valeurs par défaut des composants : publier celles de la langue source
|
|
156
|
+
// (anglais en général) propose de retraduire celles des autres langues.
|
|
157
|
+
context.schemaType === config.componentPreview.defaultsType && config.i18n
|
|
158
|
+
? prev.map((action) => (action.action === 'publish' ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action))
|
|
159
|
+
: prev,
|
|
156
160
|
},
|
|
157
161
|
|
|
158
162
|
// Le lanceur d'aperçu s'ajoute à droite des outils, dans la barre du haut
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textes d'une valeur de champ, pour la traduction par IA : une chaîne, ou les
|
|
3
|
+
* morceaux de texte (spans) d'un texte riche. La structure (styles, liens, marques,
|
|
4
|
+
* _key) n'est jamais envoyée ni modifiée : seuls les textes sont remplacés.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type Rec = Record<string, unknown>
|
|
8
|
+
const isObj = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
9
|
+
|
|
10
|
+
/** Textes d'une valeur, dans l'ordre. */
|
|
11
|
+
export function collectTexts(value: unknown): string[] {
|
|
12
|
+
if (typeof value === 'string') return [value]
|
|
13
|
+
if (!Array.isArray(value)) return []
|
|
14
|
+
const out: string[] = []
|
|
15
|
+
for (const item of value) {
|
|
16
|
+
if (typeof item === 'string') out.push(item)
|
|
17
|
+
else if (isObj(item) && Array.isArray(item.children))
|
|
18
|
+
for (const child of item.children) if (isObj(child) && typeof child.text === 'string') out.push(child.text)
|
|
19
|
+
}
|
|
20
|
+
return out
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** La même valeur avec ses textes remplacés (dans l'ordre de `collectTexts`). */
|
|
24
|
+
export function replaceTexts(value: unknown, texts: readonly string[]): unknown {
|
|
25
|
+
let i = 0
|
|
26
|
+
const next = () => texts[i++] ?? ''
|
|
27
|
+
if (typeof value === 'string') return next()
|
|
28
|
+
if (!Array.isArray(value)) return value
|
|
29
|
+
return value.map((item) => {
|
|
30
|
+
if (typeof item === 'string') return next()
|
|
31
|
+
if (isObj(item) && Array.isArray(item.children))
|
|
32
|
+
return {...item, children: item.children.map((child) => (isObj(child) && typeof child.text === 'string' ? {...child, text: next()} : child))}
|
|
33
|
+
return item
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `sections[a].title` → segments (`[x]` : clé d'élément de liste, ou rang). */
|
|
38
|
+
export function parsePathKey(path: string): ({field: string} | {item: string})[] {
|
|
39
|
+
const out: ({field: string} | {item: string})[] = []
|
|
40
|
+
for (const m of path.matchAll(/([^.[\]]+)|\[([^\]]+)\]/g)) out.push(m[1] !== undefined ? {field: m[1]} : {item: m[2]!})
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function itemOf(list: unknown[], key: string): unknown {
|
|
45
|
+
return list.find((i) => isObj(i) && i._key === key) ?? (/^\d+$/.test(key) ? list[Number(key)] : undefined)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Valeur d'un document au chemin `sections[a].title`. */
|
|
49
|
+
export function valueAtKey(doc: unknown, path: string): unknown {
|
|
50
|
+
let cur: unknown = doc
|
|
51
|
+
for (const seg of parsePathKey(path)) {
|
|
52
|
+
if (cur == null) return undefined
|
|
53
|
+
if ('field' in seg) cur = isObj(cur) ? cur[seg.field] : undefined
|
|
54
|
+
else cur = Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
55
|
+
}
|
|
56
|
+
return cur
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Écrit `value` au chemin dans `doc` (modifié sur place). Faux si le chemin n'existe pas. */
|
|
60
|
+
export function setAtKey(doc: Rec, path: string, value: unknown): boolean {
|
|
61
|
+
const segs = parsePathKey(path)
|
|
62
|
+
let cur: unknown = doc
|
|
63
|
+
for (let n = 0; n < segs.length - 1; n++) {
|
|
64
|
+
const seg = segs[n]!
|
|
65
|
+
cur = 'field' in seg ? (isObj(cur) ? cur[seg.field] : undefined) : Array.isArray(cur) ? itemOf(cur, seg.item) : undefined
|
|
66
|
+
if (cur == null) return false
|
|
67
|
+
}
|
|
68
|
+
const last = segs[segs.length - 1]
|
|
69
|
+
if (!last || !('field' in last) || !isObj(cur)) return false
|
|
70
|
+
cur[last.field] = value
|
|
71
|
+
return true
|
|
72
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {collectTexts, replaceTexts} from './aiTexts'
|
|
2
|
+
|
|
3
|
+
/** Service du kit (même clé de projet et même adresse que l'historique). */
|
|
4
|
+
export interface TranslateService {
|
|
5
|
+
endpoint: string
|
|
6
|
+
projectKey: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const MAX_TEXTS = 250
|
|
10
|
+
const MAX_CHARS = 30_000
|
|
11
|
+
|
|
12
|
+
const MESSAGES: Record<string, string> = {
|
|
13
|
+
daily_limit: 'Daily AI translation limit reached for this project.',
|
|
14
|
+
project_inactive: 'This project is not active in the NCF kit.',
|
|
15
|
+
bad_key: 'This project is not registered in the NCF kit (npx ncf-kit setup).',
|
|
16
|
+
not_configured: 'AI translation is not configured on the NCF kit service.',
|
|
17
|
+
too_long: 'Text too long to translate at once.',
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function call(service: TranslateService, from: string, to: string, texts: string[]): Promise<string[]> {
|
|
21
|
+
const response = await fetch(`${service.endpoint}/translate`, {
|
|
22
|
+
method: 'POST',
|
|
23
|
+
headers: {'content-type': 'application/json'},
|
|
24
|
+
body: JSON.stringify({key: service.projectKey, from, to, texts}),
|
|
25
|
+
})
|
|
26
|
+
const body = (await response.json().catch(() => ({}))) as {texts?: string[]; error?: string}
|
|
27
|
+
if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length)
|
|
28
|
+
throw new Error(MESSAGES[body.error ?? ''] ?? `AI translation failed (${body.error ?? response.status}).`)
|
|
29
|
+
return body.texts
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
|
|
34
|
+
* mêmes valeurs, textes traduits. Découpe en lots si besoin.
|
|
35
|
+
*/
|
|
36
|
+
export async function translateValues(service: TranslateService, from: string, to: string, values: readonly unknown[]): Promise<unknown[]> {
|
|
37
|
+
const perValue = values.map((v) => collectTexts(v))
|
|
38
|
+
const all = perValue.flat()
|
|
39
|
+
const translated: string[] = []
|
|
40
|
+
let batch: string[] = []
|
|
41
|
+
let size = 0
|
|
42
|
+
const flush = async () => {
|
|
43
|
+
if (!batch.length) return
|
|
44
|
+
translated.push(...(await call(service, from, to, batch)))
|
|
45
|
+
batch = []
|
|
46
|
+
size = 0
|
|
47
|
+
}
|
|
48
|
+
for (const text of all) {
|
|
49
|
+
if (batch.length >= MAX_TEXTS || size + text.length > MAX_CHARS) await flush()
|
|
50
|
+
batch.push(text)
|
|
51
|
+
size += text.length
|
|
52
|
+
}
|
|
53
|
+
await flush()
|
|
54
|
+
let offset = 0
|
|
55
|
+
return values.map((value, n) => {
|
|
56
|
+
const count = perValue[n]!.length
|
|
57
|
+
const slice = translated.slice(offset, offset + count)
|
|
58
|
+
offset += count
|
|
59
|
+
return count ? replaceTexts(value, slice) : value
|
|
60
|
+
})
|
|
61
|
+
}
|
package/src/version.ts
CHANGED