@nocode-factory/sanity-kit 2.65.0-rc.6 → 2.66.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,11 +6,8 @@ export interface TranslateService {
6
6
  projectKey: string
7
7
  }
8
8
 
9
- // Lots MODESTES (kit >= 2.65.0) : au-delà, la réponse de l'IA arrive parfois incomplète ou
10
- // mal formée (« bad_model_output », vu sur JAF avec 66 textes d'une page) et tout le lot
11
- // échouait. Un lot qui échoue est redécoupé en deux, jusqu'au texte seul.
12
- const MAX_TEXTS = 30
13
- const MAX_CHARS = 6_000
9
+ const MAX_TEXTS = 250
10
+ const MAX_CHARS = 30_000
14
11
 
15
12
  const MESSAGES: Record<string, string> = {
16
13
  daily_limit: 'Daily AI translation limit reached for this project.',
@@ -18,19 +15,6 @@ const MESSAGES: Record<string, string> = {
18
15
  bad_key: 'This project is not registered in the NCF kit (npx ncf-kit setup).',
19
16
  not_configured: 'AI translation is not configured on the NCF kit service.',
20
17
  too_long: 'Text too long to translate at once.',
21
- bad_model_output: 'The AI returned an unreadable answer.',
22
- }
23
-
24
- /** Erreurs qui ne se règlent pas en redécoupant le lot (inutile de réessayer texte par texte). */
25
- const FATAL = new Set(['daily_limit', 'project_inactive', 'bad_key', 'not_configured'])
26
-
27
- class TranslateError extends Error {
28
- constructor(
29
- message: string,
30
- readonly code: string,
31
- ) {
32
- super(message)
33
- }
34
18
  }
35
19
 
36
20
  async function call(service: TranslateService, from: string, to: string, texts: string[]): Promise<string[]> {
@@ -40,52 +24,24 @@ async function call(service: TranslateService, from: string, to: string, texts:
40
24
  body: JSON.stringify({key: service.projectKey, from, to, texts}),
41
25
  })
42
26
  const body = (await response.json().catch(() => ({}))) as {texts?: string[]; error?: string}
43
- if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) {
44
- const code = body.error ?? (response.ok ? 'bad_model_output' : String(response.status))
45
- throw new TranslateError(MESSAGES[code] ?? `AI translation failed (${code}).`, code)
46
- }
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}).`)
47
29
  return body.texts
48
30
  }
49
31
 
50
32
  /**
51
- * Traduit un lot ; s'il échoue (réponse mal formée, texte trop long...), le redécoupe en
52
- * deux jusqu'au texte seul. Rend une traduction par texte, ou null pour un texte raté.
53
- */
54
- async function translateBatch(service: TranslateService, from: string, to: string, texts: string[], errors: string[]): Promise<(string | null)[]> {
55
- try {
56
- return await call(service, from, to, texts)
57
- } catch (cause) {
58
- const error = cause instanceof TranslateError ? cause : new TranslateError(cause instanceof Error ? cause.message : String(cause), 'unknown')
59
- if (FATAL.has(error.code)) throw error
60
- if (texts.length === 1) {
61
- errors.push(error.message)
62
- return [null]
63
- }
64
- const half = Math.ceil(texts.length / 2)
65
- return [...(await translateBatch(service, from, to, texts.slice(0, half), errors)), ...(await translateBatch(service, from, to, texts.slice(half), errors))]
66
- }
67
- }
68
-
69
- /**
70
- * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to`, en lots,
71
- * SANS tout perdre si une partie échoue : rend les valeurs traduites, les rangs des
72
- * valeurs ratées (laissées telles quelles) et la raison de l'échec.
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.
73
35
  */
74
- export async function translateValuesSettled(
75
- service: TranslateService,
76
- from: string,
77
- to: string,
78
- values: readonly unknown[],
79
- ): Promise<{values: unknown[]; failed: number[]; error: string | null}> {
36
+ export async function translateValues(service: TranslateService, from: string, to: string, values: readonly unknown[]): Promise<unknown[]> {
80
37
  const perValue = values.map((v) => collectTexts(v))
81
38
  const all = perValue.flat()
82
- const translated: (string | null)[] = []
83
- const errors: string[] = []
39
+ const translated: string[] = []
84
40
  let batch: string[] = []
85
41
  let size = 0
86
42
  const flush = async () => {
87
43
  if (!batch.length) return
88
- translated.push(...(await translateBatch(service, from, to, batch, errors)))
44
+ translated.push(...(await call(service, from, to, batch)))
89
45
  batch = []
90
46
  size = 0
91
47
  }
@@ -96,27 +52,10 @@ export async function translateValuesSettled(
96
52
  }
97
53
  await flush()
98
54
  let offset = 0
99
- const failed: number[] = []
100
- const out = values.map((value, n) => {
55
+ return values.map((value, n) => {
101
56
  const count = perValue[n]!.length
102
57
  const slice = translated.slice(offset, offset + count)
103
58
  offset += count
104
- if (!count) return value
105
- if (slice.some((t) => t === null)) {
106
- failed.push(n)
107
- return value
108
- }
109
- return replaceTexts(value, slice as string[])
59
+ return count ? replaceTexts(value, slice) : value
110
60
  })
111
- return {values: out, failed, error: failed.length ? `${failed.length} text(s) not translated: ${[...new Set(errors)].join(' ')}` : null}
112
- }
113
-
114
- /**
115
- * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
116
- * mêmes valeurs, textes traduits. Échoue si une valeur n'a pas pu être traduite.
117
- */
118
- export async function translateValues(service: TranslateService, from: string, to: string, values: readonly unknown[]): Promise<unknown[]> {
119
- const result = await translateValuesSettled(service, from, to, values)
120
- if (result.error) throw new Error(result.error)
121
- return result.values
122
61
  }
@@ -44,23 +44,6 @@ export interface PropagationResult {
44
44
  const VALUE_TYPE_NAMES = new Set(['image', 'file', 'reference', 'crossDatasetReference', 'slug', 'geopoint', 'url', 'email', 'date', 'datetime', 'number', 'boolean'])
45
45
  const SKIP_KEYS = new Set(['language', 'slug'])
46
46
 
47
- // Champs texte qui ne se TRADUISENT pas (kit >= 2.65.0, vu sur JAF : ancres traduites en
48
- // « start of school year », couleur « sun », téléphone et email envoyés à l'IA) :
49
- // - par leur nom : ancres (d'une section ou de la page visée par un lien), adresses,
50
- // jetons de couleur, codes, icônes ;
51
- // - par leur valeur : email, téléphone, adresse web ou chemin, ancre, couleur hexadécimale.
52
- const NON_TEXT_NAMES = /^(anchor|pageAnchor|.*Anchor|href|url|link|email|mail|phone|tel|telephone|token|customHex|hex|color|colour|icon|code|key|id|slug|path|target|rel)$/i
53
- const NON_TEXT_VALUE = /^(?:[\w.+-]+@[\w-]+\.[\w.-]+|\+?[\d\s().-]{6,}|(?:https?:|mailto:|tel:)\S*|[/#]\S*|#[0-9a-f]{3,8})$/i
54
-
55
- /** Un texte libre qui n'est pas à traduire (nom du champ, ou valeur technique). */
56
- export function isNonTextValue(name: string | undefined, value: unknown): boolean {
57
- if (name && NON_TEXT_NAMES.test(name)) return true
58
- return typeof value === 'string' && NON_TEXT_VALUE.test(value.trim())
59
- }
60
-
61
- /** Dernier nom de champ d'un chemin lisible (« sections[k].cta.anchor » → « anchor »). */
62
- const lastName = (path: string) => path.split('.').pop()?.replace(/\[.*$/, '')
63
-
64
47
  const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
65
48
  const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
66
49
  const keyed = (v: unknown): v is Record<string, unknown>[] => Array.isArray(v) && v.length > 0 && v.every((i) => isObj(i) && typeof i._key === 'string')
@@ -78,9 +61,6 @@ export function kindOf(t: SchemaTypeLike | undefined, value: unknown): FieldKind
78
61
  // Champ propre à l'instance (options.instanceOnly, ex. ancre d'une section) :
79
62
  // une valeur recopiée telle quelle, jamais traduite.
80
63
  if (t.options?.instanceOnly) return 'value'
81
- // Image avec ses propres champs (alt, légende) : ses textes se traduisent, l'image
82
- // (asset, recadrage) est recopiée. Avant, l'image entière était recopiée, alt compris.
83
- if (names.includes('image') && hasOwnFields(t)) return 'object'
84
64
  if (names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return 'value'
85
65
  if (t.jsonType === 'array') {
86
66
  const of = t.of ?? []
@@ -98,11 +78,6 @@ export function kindOf(t: SchemaTypeLike | undefined, value: unknown): FieldKind
98
78
  return 'value'
99
79
  }
100
80
 
101
- function hasOwnFields(t: SchemaTypeLike | undefined): boolean {
102
- for (let c = t; c; c = c.type) if (c.fields?.some((f) => !['asset', 'hotspot', 'crop', 'media'].includes(f.name))) return true
103
- return false
104
- }
105
-
106
81
  function fieldType(t: SchemaTypeLike | undefined, name: string): SchemaTypeLike | undefined {
107
82
  for (let c = t; c; c = c.type) {
108
83
  const f = c.fields?.find((x) => x.name === name)
@@ -129,7 +104,6 @@ interface Acc {
129
104
  /** Tous les textes d'un élément ajouté : à traduire. */
130
105
  function collectTexts(value: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc) {
131
106
  const kind = kindOf(t, value)
132
- if (kind === 'text' && typeof value === 'string' && isNonTextValue(lastName(path), value)) return
133
107
  if (kind === 'text') {
134
108
  if (value !== undefined && value !== null && value !== '') acc.toTranslate.push(path)
135
109
  } else if (kind === 'object' && isObj(value)) {
@@ -143,9 +117,7 @@ const ABSENT = Symbol('absent')
143
117
 
144
118
  function merge(target: unknown, before: unknown, after: unknown, t: SchemaTypeLike | undefined, path: string, acc: Acc): unknown {
145
119
  if (same(before, after)) return target === undefined ? ABSENT : target
146
- let kind = kindOf(t, after ?? before)
147
- // Texte libre technique (ancre, email, téléphone, couleur...) : recopié, jamais traduit.
148
- if (kind === 'text' && typeof (after ?? before) === 'string' && isNonTextValue(lastName(path), after ?? before)) kind = 'value'
120
+ const kind = kindOf(t, after ?? before)
149
121
 
150
122
  if (kind === 'text') {
151
123
  if (after === undefined || after === null || after === '') {
@@ -4,10 +4,10 @@ import type {SanityClient} from 'sanity'
4
4
  import type {ResolvedKitConfig} from '../config/types'
5
5
  import {TRANSLATION_TODO_TYPE, translationTodoId} from '../schema/translationTodo'
6
6
  import {collectTexts, setAtKey, valueAtKey} from './aiTexts'
7
- import {translateValuesSettled} from './aiTranslate'
8
- import {isNonTextValue, propagate, type SchemaTypeLike} from './propagate'
7
+ import {translateValues} from './aiTranslate'
8
+ import {propagate, type SchemaTypeLike} from './propagate'
9
9
  import {slugify} from './slugify'
10
- import {hashValue, recordTrace} from './translationTrace'
10
+ import {recordTrace} from './translationTrace'
11
11
 
12
12
  type Doc = Record<string, unknown>
13
13
 
@@ -84,39 +84,6 @@ export async function linkTranslations(
84
84
  * traduits par l'IA si `ai` (service du kit), slug traduit et unique, publiée si
85
85
  * tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
86
86
  */
87
- /** Champ slug d'un type (registre des pages du kit, sinon « slug » s'il est rempli). */
88
- function slugFieldOf(config: ResolvedKitConfig, type: string, source: Doc): string | null {
89
- const pageType = config.pageTypes.find((t) => t.type === type)
90
- const field = pageType?.slugField ?? ((source.slug as {current?: string} | undefined)?.current ? 'slug' : null)
91
- return field && (source[field] as {current?: string} | undefined)?.current ? field : null
92
- }
93
-
94
- /**
95
- * Slug d'une version traduite : tiré de son titre (déjà traduit), unique dans la langue
96
- * (-2, -3...) ; à défaut de titre, le slug de la version source. JAMAIS « traduit » comme
97
- * un texte (vu sur JAF : une reprise avait vidé le slug d'une page).
98
- */
99
- async function translatedSlug(client: SanityClient, config: ResolvedKitConfig, type: string, doc: Doc, source: Doc, language: string): Promise<{_type: 'slug'; current: string}> {
100
- const field = config.i18n?.field ?? 'language'
101
- const pageType = config.pageTypes.find((t) => t.type === type)
102
- const slugField = slugFieldOf(config, type, source) ?? 'slug'
103
- const titleField = pageType?.titleField ?? 'title'
104
- const title = typeof doc[titleField] === 'string' ? (doc[titleField] as string) : ''
105
- const base = slugify(title) || String((source[slugField] as {current: string}).current)
106
- const id = typeof doc._id === 'string' ? doc._id.replace(/^drafts\./, '') : ''
107
- let slug = base
108
- for (
109
- let n = 2;
110
- await client.fetch<boolean>(
111
- `count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**")) && _id != $id]) > 0`,
112
- {type, slug, language, id},
113
- );
114
- n++
115
- )
116
- slug = `${base}-${n}`
117
- return {_type: 'slug', current: slug}
118
- }
119
-
120
87
  export async function createTranslatedVersion(opts: {
121
88
  client: SanityClient
122
89
  config: ResolvedKitConfig
@@ -127,14 +94,8 @@ export async function createTranslatedVersion(opts: {
127
94
  sourceLanguage: string
128
95
  language: string
129
96
  ai: boolean
130
- /**
131
- * Publier directement une version entièrement traduite (défaut : false, kit >= 2.65.0).
132
- * Sinon brouillon à relire : une traduction par l'IA n'est jamais mise en ligne sans
133
- * qu'un humain l'ait relue, sauf choix explicite.
134
- */
135
- publish?: boolean
136
- }): Promise<{id: string; published: boolean; complete: boolean; aiError: string | null; remaining: string[]}> {
137
- const {client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai, publish = false} = opts
97
+ }): Promise<{id: string; published: boolean; aiError: string | null}> {
98
+ const {client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai} = opts
138
99
  const field = config.i18n?.field ?? 'language'
139
100
  const result = propagate({}, {}, source, schemaType)
140
101
  const {_id, _rev, _createdAt, _updatedAt, ...doc} = structuredClone(result.document) as Doc
@@ -146,13 +107,9 @@ export async function createTranslatedVersion(opts: {
146
107
  try {
147
108
  const values = remaining.map((path) => valueAtKey(source, path))
148
109
  const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
149
- // Traduction partielle : un texte raté reste « To translate », les autres sont gardés.
150
- const result = await translateValuesSettled(config.history, sourceLanguage, language, toSend.map((v) => v ?? ''))
151
- const failed = new Set(result.failed)
152
- if (result.error) aiError = result.error
110
+ const translated = await translateValues(config.history, sourceLanguage, language, toSend.map((v) => v ?? ''))
153
111
  remaining = remaining.filter((path, n) => {
154
- if (failed.has(n)) return true
155
- const value = toSend[n] === undefined ? undefined : result.values[n]
112
+ const value = toSend[n] === undefined ? undefined : translated[n]
156
113
  const ok = setAtKey(doc, path, value)
157
114
  if (ok && value !== undefined) written.push({path, value})
158
115
  return !ok
@@ -166,13 +123,27 @@ export async function createTranslatedVersion(opts: {
166
123
  Object.assign(doc, await localizeReferences(client, doc, language))
167
124
  // Slug : traduit depuis le titre, unique dans la langue (-2, -3...).
168
125
  const pageType = config.pageTypes.find((t) => t.type === type)
169
- const slugField = slugFieldOf(config, type, source)
170
- if (slugField) doc[slugField] = await translatedSlug(client, config, type, doc, source, language)
126
+ const slugField = pageType?.slugField ?? ((source.slug as {current?: string} | undefined)?.current ? 'slug' : null)
127
+ if (slugField && (source[slugField] as {current?: string} | undefined)?.current) {
128
+ const titleField = pageType?.titleField ?? 'title'
129
+ const title = typeof doc[titleField] === 'string' ? (doc[titleField] as string) : ''
130
+ const base = slugify(title) || String((source[slugField] as {current: string}).current)
131
+ let slug = base
132
+ for (
133
+ let n = 2;
134
+ await client.fetch<boolean>(
135
+ `count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`,
136
+ {type, slug, language},
137
+ );
138
+ n++
139
+ )
140
+ slug = `${base}-${n}`
141
+ doc[slugField] = {_type: 'slug', current: slug}
142
+ }
171
143
  // Slug non traduit (titre resté dans la langue source) : marqué « To translate »
172
144
  // avec le titre, la règle d'or veut un slug dans la langue de la version.
173
145
  if (slugField && remaining.includes(pageType?.titleField ?? 'title') && !remaining.includes(slugField)) remaining = [...remaining, slugField]
174
- const complete = ai && !remaining.length && !aiError
175
- const published = complete && publish
146
+ const published = ai && !remaining.length && !aiError
176
147
  await client.createOrReplace({...doc, _id: published ? id : `drafts.${id}`, _type: type} as {_id: string; _type: string})
177
148
  if (remaining.length)
178
149
  await client.createOrReplace({
@@ -188,7 +159,7 @@ export async function createTranslatedVersion(opts: {
188
159
  // Version publiée : « slug d'origine dans cette langue » redirige vers elle.
189
160
  const redirects = published ? translationRedirectOptions(config) : null
190
161
  if (redirects) await syncTranslationRedirects(client, redirects, [sourceId]).catch(() => {})
191
- return {id, published, complete, aiError, remaining}
162
+ return {id, published, aiError}
192
163
  }
193
164
 
194
165
  /**
@@ -204,116 +175,38 @@ export async function fillTranslation(opts: {
204
175
  target: Doc
205
176
  sourceLanguage: string
206
177
  language: string
207
- /** Trace de l'IA (readTrace) : un texte déjà rendu à l'identique n'est pas renvoyé. */
208
- trace?: Map<string, string>
209
- }): Promise<{document: Doc; translated: number; written: {path: string; value: unknown}[]; failed: number; error: string | null}> {
210
- const {config, schemaType, source, sourceLanguage, language, trace} = opts
178
+ }): Promise<{document: Doc; translated: number; written: {path: string; value: unknown}[]}> {
179
+ const {config, schemaType, source, sourceLanguage, language} = opts
211
180
  const document = structuredClone(opts.target) as Doc
212
181
  // Blocs (champs de premier niveau) absents de la cible : recopiés tels quels.
213
182
  for (const [key, value] of Object.entries(source)) {
214
183
  if (key.startsWith('_') || key === (config.i18n?.field ?? 'language')) continue
215
184
  if (document[key] === undefined || document[key] === null) document[key] = structuredClone(value)
216
185
  }
217
- const paths = untranslatedPaths(source, document, schemaType, trace)
218
- if (!paths.length || !config.history) return {document, translated: 0, written: [], failed: 0, error: null}
219
- // Traduction partielle : un texte raté reste tel quel (reproposé au prochain passage).
220
- const result = await translateValuesSettled(
186
+ const paths = untranslatedPaths(source, document, schemaType)
187
+ if (!paths.length || !config.history) return {document, translated: 0, written: []}
188
+ const translated = await translateValues(
221
189
  config.history,
222
190
  sourceLanguage,
223
191
  language,
224
192
  paths.map((p) => valueAtKey(source, p)),
225
193
  )
226
- const failed = new Set(result.failed)
227
194
  const written: {path: string; value: unknown}[] = []
228
195
  paths.forEach((p, n) => {
229
- if (!failed.has(n) && setAtKey(document, p, result.values[n])) written.push({path: p, value: result.values[n]})
196
+ if (setAtKey(document, p, translated[n])) written.push({path: p, value: translated[n]})
230
197
  })
231
- return {document, translated: written.length, written, failed: failed.size, error: result.error}
198
+ return {document, translated: written.length, written}
232
199
  }
233
200
 
234
201
  /**
235
202
  * Textes de `source` absents ou non traduits dans `target` (vides, ou identiques au
236
203
  * texte source). Un texte déjà traduit, même à la main, n'y figure jamais.
237
204
  */
238
- export function untranslatedPaths(
239
- source: Doc,
240
- target: Doc | null,
241
- schemaType: SchemaTypeLike | undefined,
242
- /** Trace des textes écrits par l'IA (readTrace) : un texte que l'IA a rendu À L'IDENTIQUE
243
- * (nom propre, marque, « OK ») est traduit, il n'est plus reproposé sans fin. */
244
- trace?: Map<string, string>,
245
- ): string[] {
205
+ export function untranslatedPaths(source: Doc, target: Doc | null, schemaType: SchemaTypeLike | undefined): string[] {
246
206
  return propagate({}, {}, source, schemaType).toTranslate.filter((path) => {
247
207
  const src = valueAtKey(source, path)
248
208
  if (!collectTexts(src).some((t) => t.trim())) return false
249
209
  const cur = target ? valueAtKey(target, path) : undefined
250
- if (!collectTexts(cur).some((t) => t.trim())) return true
251
- if (JSON.stringify(cur) !== JSON.stringify(src)) return false
252
- return trace?.get(path) !== hashValue(cur)
210
+ return !collectTexts(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src)
253
211
  })
254
212
  }
255
-
256
- /**
257
- * Reprend une version traduite restée INACHEVÉE (textes « To translate » après un échec de
258
- * l'IA) : retraduit seulement ces textes depuis la version source publiée, dans le
259
- * brouillon (créé depuis la version publiée s'il n'existe pas). Publie si tout est traduit
260
- * et `publish` demandé. Rend ce qui reste et l'erreur de l'IA, pour le dire à l'équipe.
261
- */
262
- export async function retryTranslatedVersion(opts: {
263
- client: SanityClient
264
- config: ResolvedKitConfig
265
- todo: {documentId: string; sourceId: string; sourceLanguage: string; paths: string[]}
266
- language: string
267
- publish?: boolean
268
- }): Promise<{published: boolean; remaining: string[]; aiError: string | null}> {
269
- const {client, config, todo, language, publish = false} = opts
270
- const id = todo.documentId.replace(/^drafts\./, '')
271
- const source = await client.getDocument<Doc>(todo.sourceId)
272
- const current = (await client.getDocument<Doc>(`drafts.${id}`)) ?? (await client.getDocument<Doc>(id))
273
- if (!source || !current) return {published: false, remaining: todo.paths, aiError: !source ? 'source version not found (unpublished or deleted)' : 'translated version not found'}
274
- if (!config.history) return {published: false, remaining: todo.paths, aiError: 'AI translation is not configured (kit project key missing)'}
275
- const {_rev, _createdAt, _updatedAt, ...doc} = structuredClone(current) as Doc
276
- const type = String(current._type)
277
- // Slug : jamais traduit comme un texte, recalculé depuis le titre traduit (plus bas).
278
- // Valeurs techniques (ancre, email, téléphone, couleur) marquées par une version
279
- // antérieure du kit : retirées de la liste, gardées telles quelles.
280
- const slugField = slugFieldOf(config, type, source)
281
- const nameOf = (path: string) => path.split('.').pop()?.replace(/\[.*$/, '')
282
- const technical = (path: string) => isNonTextValue(nameOf(path), valueAtKey(source, path))
283
- const slugPending = Boolean(slugField && todo.paths.includes(slugField))
284
- let remaining = todo.paths.filter((p) => p !== slugField && !technical(p))
285
- let aiError: string | null = null
286
- const written: {path: string; value: unknown}[] = []
287
- try {
288
- const values = remaining.map((path) => valueAtKey(source, path))
289
- const toSend = values.map((v) => (collectTexts(v).some((s) => s.trim()) ? v : undefined))
290
- const result = await translateValuesSettled(config.history, todo.sourceLanguage, language, toSend.map((v) => v ?? ''))
291
- const failed = new Set(result.failed)
292
- if (result.error) aiError = result.error
293
- remaining = remaining.filter((path, n) => {
294
- if (failed.has(n)) return true
295
- const value = toSend[n] === undefined ? undefined : result.values[n]
296
- const ok = setAtKey(doc, path, value)
297
- if (ok && value !== undefined) written.push({path, value})
298
- return !ok
299
- })
300
- } catch (cause) {
301
- aiError = cause instanceof Error ? cause.message : String(cause)
302
- }
303
- if (slugPending && slugField) {
304
- const titleField = config.pageTypes.find((t) => t.type === type)?.titleField ?? 'title'
305
- // Titre traduit : slug recalculé depuis lui ; sinon le slug reste « To translate ».
306
- if (remaining.includes(titleField)) remaining = [...remaining, slugField]
307
- else doc[slugField] = await translatedSlug(client, config, type, doc, source, language)
308
- }
309
- const published = publish && !remaining.length && !aiError
310
- const tx = client.transaction()
311
- if (published) {
312
- tx.createOrReplace({...doc, _id: id} as {_id: string; _type: string})
313
- tx.delete(`drafts.${id}`)
314
- } else tx.createOrReplace({...doc, _id: `drafts.${id}`} as {_id: string; _type: string})
315
- tx.patch(translationTodoId(id), (p) => p.set({paths: remaining}))
316
- await tx.commit()
317
- await recordTrace(client, id, written, {sourceId: todo.sourceId, sourceLanguage: todo.sourceLanguage})
318
- return {published, remaining, aiError}
319
- }