@nocode-factory/sanity-kit 2.65.0-rc.2 → 2.65.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -21,6 +21,24 @@
21
21
  - **Réessayer marche** : une version restée inachevée (textes « To translate » après un
22
22
  échec) est détectée et reprise par « Unfinished translations, retry » (seulement ses
23
23
  textes à traduire). Avant, elle « existait » en brouillon et relancer ne faisait rien.
24
+ - **Grosses pages traduites par petits lots** : jusqu'ici jusqu'à 250 textes partaient en
25
+ une requête, et une réponse de l'IA mal formée (« bad_model_output ») faisait échouer
26
+ toute la page (vu sur JAF : « Élémentaire », 66 textes, 2 échecs sur 2). Lots de 30
27
+ textes, un lot refusé est redécoupé jusqu'au texte seul, et les textes traduits sont
28
+ GARDÉS : seuls les ratés restent « To translate » (création, reprise, propagation,
29
+ valeurs par défaut). Une erreur sans remède (quota, clé du kit) s'arrête tout de suite.
30
+ - **Slug jamais « traduit » comme un texte** : une reprise le vidait (vu sur JAF, page
31
+ sans adresse). Il est recalculé depuis le titre traduit, unique dans la langue.
32
+ - **Ancres et valeurs techniques jamais envoyées à l'IA** : ancre d'une section (même sans
33
+ `options.instanceOnly`), ancre de la page visée par un lien, adresse, email, téléphone,
34
+ jeton de couleur, code, chemin ou couleur hexadécimale sont recopiés tels quels. Avant,
35
+ l'IA écrivait « start of school year » dans une ancre (liens du sommaire cassés) et
36
+ envoyait couleur, téléphone et email à traduire (vu sur JAF).
37
+ - **Textes alternatifs des images traduits** (`alt`, légende d'une image qui déclare ses
38
+ champs) : avant, l'image était recopiée entière, alt dans la langue principale.
39
+ - **Source affichée sous un slug « To translate »** : le slug de la version principale (il
40
+ s'affichait « vide »).
41
+ - **`doctor` nomme les pages** sans version ou seulement en brouillon (5 au plus).
24
42
  - **Textes rendus à l'identique par l'IA** (noms propres, marques) : comptés comme
25
43
  traduits, plus reproposés sans fin, et signalés « à vérifier » (vu sur JAF : 12 textes).
26
44
  - **`doctor`, « Langues : contenus »** : une langue ne compte que si sa version est
package/bin/ncf-kit.mjs CHANGED
@@ -648,19 +648,23 @@ async function doctor() {
648
648
  const refs = m.refs ?? []
649
649
  for (const r of refs) langsOf.set(r.id, refs)
650
650
  }
651
+ // Pages nommées dans le message (vu sur JAF : « 1 en brouillon seulement », sans dire laquelle).
652
+ const titled = (await q(`*[_id in $ids]{_id, "title": coalesce(title, name, slug.current, _id)}`, {ids: sources})) ?? []
653
+ const titles = new Map(titled.map((d) => [d._id, d.title]))
654
+ const names = (ids) => `${ids.slice(0, 5).map((id) => `« ${titles.get(id) ?? id} »`).join(', ')}${ids.length > 5 ? `, +${ids.length - 5}` : ''}`
651
655
  const status = (id, l) => {
652
656
  const ref = (langsOf.get(id) ?? []).find((r) => r.lang === l)
653
657
  return !ref ? 'missing' : published.has(ref.id) ? 'online' : 'draft'
654
658
  }
655
659
  const gaps = locales
656
660
  .slice(1)
657
- .map((l) => [l, sources.filter((id) => status(id, l) === 'missing').length, sources.filter((id) => status(id, l) === 'draft').length])
658
- .filter(([, missing, drafts]) => missing || drafts)
661
+ .map((l) => [l, sources.filter((id) => status(id, l) === 'missing'), sources.filter((id) => status(id, l) === 'draft')])
662
+ .filter(([, missing, drafts]) => missing.length || drafts.length)
659
663
  gaps.length
660
664
  ? ko(
661
665
  'Langues : contenus',
662
666
  `le kit a besoin que chaque langue ait EN LIGNE toutes les pages de la langue principale (${main.toUpperCase()}) ; ${gaps
663
- .map(([l, missing, drafts]) => `${l.toUpperCase()} : ${[missing ? `${missing} document(s) sans version` : '', drafts ? `${drafts} en brouillon seulement (à relire puis publier)` : ''].filter(Boolean).join(', ')}`)
667
+ .map(([l, missing, drafts]) => `${l.toUpperCase()} : ${[missing.length ? `${missing.length} document(s) sans version (${names(missing)})` : '', drafts.length ? `${drafts.length} en brouillon seulement, à relire puis publier (${names(drafts)})` : ''].filter(Boolean).join(', ')}`)
664
668
  .join(' ; ')} : Studio → Pages → Languages (« Translate with AI », brouillons à relire), puis publier chaque version.`,
665
669
  )
666
670
  : ok('Langues : contenus', `${sources.length} document(s) ${main.toUpperCase()}, chacun publié dans ${locales.length - 1} autre(s) langue(s)`)
package/dist/index.d.ts CHANGED
@@ -1483,7 +1483,7 @@ export declare function ActorName(props: {
1483
1483
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1484
1484
  * le vérifie.
1485
1485
  */
1486
- export declare const KIT_VERSION = "2.65.0-rc.2";
1486
+ export declare const KIT_VERSION = "2.65.0-rc.4";
1487
1487
  /**
1488
1488
  * Données de la page proposées comme colonnes.
1489
1489
  *
package/dist/index.js CHANGED
@@ -1423,7 +1423,7 @@ function explainGrantError(error) {
1423
1423
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1424
1424
  * le vérifie.
1425
1425
  */
1426
- const KIT_VERSION = "2.65.0-rc.2";
1426
+ const KIT_VERSION = "2.65.0-rc.4";
1427
1427
  /**
1428
1428
  * Signale ce Studio au service du kit, une fois par montage.
1429
1429
  *
@@ -1931,7 +1931,7 @@ function useKitUpdate() {
1931
1931
  !controller.signal.aborted && body?.version && setLatest(body.version);
1932
1932
  }).catch(() => {}), () => controller.abort();
1933
1933
  }, []);
1934
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.65.0-rc.2") > 0);
1934
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.65.0-rc.4") > 0);
1935
1935
  return {
1936
1936
  current: KIT_VERSION,
1937
1937
  latest,
@@ -3941,7 +3941,18 @@ const MESSAGES = {
3941
3941
  project_inactive: "This project is not active in the NCF kit.",
3942
3942
  bad_key: "This project is not registered in the NCF kit (npx ncf-kit setup).",
3943
3943
  not_configured: "AI translation is not configured on the NCF kit service.",
3944
- too_long: "Text too long to translate at once."
3944
+ too_long: "Text too long to translate at once.",
3945
+ bad_model_output: "The AI returned an unreadable answer."
3946
+ }, FATAL = /* @__PURE__ */ new Set([
3947
+ "daily_limit",
3948
+ "project_inactive",
3949
+ "bad_key",
3950
+ "not_configured"
3951
+ ]);
3952
+ var TranslateError = class extends Error {
3953
+ constructor(message, code) {
3954
+ super(message), this.code = code;
3955
+ }
3945
3956
  };
3946
3957
  async function call(service, from, to, texts) {
3947
3958
  let response = await fetch(`${service.endpoint}/translate`, {
@@ -3954,24 +3965,56 @@ async function call(service, from, to, texts) {
3954
3965
  texts
3955
3966
  })
3956
3967
  }), body = await response.json().catch(() => ({}));
3957
- if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) throw Error(MESSAGES[body.error ?? ""] ?? `AI translation failed (${body.error ?? response.status}).`);
3968
+ if (!response.ok || !Array.isArray(body.texts) || body.texts.length !== texts.length) {
3969
+ let code = body.error ?? (response.ok ? "bad_model_output" : String(response.status));
3970
+ throw new TranslateError(MESSAGES[code] ?? `AI translation failed (${code}).`, code);
3971
+ }
3958
3972
  return body.texts;
3959
3973
  }
3960
3974
  /**
3961
- * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
3962
- * mêmes valeurs, textes traduits. Découpe en lots si besoin.
3975
+ * Traduit un lot ; s'il échoue (réponse mal formée, texte trop long...), le redécoupe en
3976
+ * deux jusqu'au texte seul. Rend une traduction par texte, ou null pour un texte raté.
3963
3977
  */
3964
- async function translateValues(service, from, to, values) {
3965
- let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], batch = [], size = 0, flush = async () => {
3966
- batch.length && (translated.push(...await call(service, from, to, batch)), batch = [], size = 0);
3978
+ async function translateBatch(service, from, to, texts, errors) {
3979
+ try {
3980
+ return await call(service, from, to, texts);
3981
+ } catch (cause) {
3982
+ let error = cause instanceof TranslateError ? cause : new TranslateError(cause instanceof Error ? cause.message : String(cause), "unknown");
3983
+ if (FATAL.has(error.code)) throw error;
3984
+ if (texts.length === 1) return errors.push(error.message), [null];
3985
+ let half = Math.ceil(texts.length / 2);
3986
+ return [...await translateBatch(service, from, to, texts.slice(0, half), errors), ...await translateBatch(service, from, to, texts.slice(half), errors)];
3987
+ }
3988
+ }
3989
+ /**
3990
+ * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to`, en lots,
3991
+ * SANS tout perdre si une partie échoue : rend les valeurs traduites, les rangs des
3992
+ * valeurs ratées (laissées telles quelles) et la raison de l'échec.
3993
+ */
3994
+ async function translateValuesSettled(service, from, to, values) {
3995
+ let perValue = values.map((v) => collectTexts$1(v)), all = perValue.flat(), translated = [], errors = [], batch = [], size = 0, flush = async () => {
3996
+ batch.length && (translated.push(...await translateBatch(service, from, to, batch, errors)), batch = [], size = 0);
3967
3997
  };
3968
- for (let text of all) (batch.length >= 250 || size + text.length > 3e4) && await flush(), batch.push(text), size += text.length;
3998
+ for (let text of all) (batch.length >= 30 || size + text.length > 6e3) && await flush(), batch.push(text), size += text.length;
3969
3999
  await flush();
3970
- let offset = 0;
3971
- return values.map((value, n) => {
3972
- let count = perValue[n].length, slice = translated.slice(offset, offset + count);
3973
- return offset += count, count ? replaceTexts(value, slice) : value;
3974
- });
4000
+ let offset = 0, failed = [];
4001
+ return {
4002
+ values: values.map((value, n) => {
4003
+ let count = perValue[n].length, slice = translated.slice(offset, offset + count);
4004
+ return offset += count, count ? slice.some((t) => t === null) ? (failed.push(n), value) : replaceTexts(value, slice) : value;
4005
+ }),
4006
+ failed,
4007
+ error: failed.length ? `${failed.length} text(s) not translated: ${[...new Set(errors)].join(" ")}` : null
4008
+ };
4009
+ }
4010
+ /**
4011
+ * Traduit des valeurs de champs (chaînes ou textes riches) de `from` vers `to` :
4012
+ * mêmes valeurs, textes traduits. Échoue si une valeur n'a pas pu être traduite.
4013
+ */
4014
+ async function translateValues(service, from, to, values) {
4015
+ let result = await translateValuesSettled(service, from, to, values);
4016
+ if (result.error) throw Error(result.error);
4017
+ return result.values;
3975
4018
  }
3976
4019
  const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
3977
4020
  "image",
@@ -3986,7 +4029,13 @@ const VALUE_TYPE_NAMES = /* @__PURE__ */ new Set([
3986
4029
  "datetime",
3987
4030
  "number",
3988
4031
  "boolean"
3989
- ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), isObj$2 = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$2 = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed$1 = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj$2(i) && typeof i._key == "string");
4032
+ ]), SKIP_KEYS = /* @__PURE__ */ new Set(["language", "slug"]), 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, NON_TEXT_VALUE = /^(?:[\w.+-]+@[\w-]+\.[\w.-]+|\+?[\d\s().-]{6,}|(?:https?:|mailto:|tel:)\S*|[/#]\S*|#[0-9a-f]{3,8})$/i;
4033
+ /** Un texte libre qui n'est pas à traduire (nom du champ, ou valeur technique). */
4034
+ function isNonTextValue(name, value) {
4035
+ return name && NON_TEXT_NAMES.test(name) ? !0 : typeof value == "string" && NON_TEXT_VALUE.test(value.trim());
4036
+ }
4037
+ /** Dernier nom de champ d'un chemin lisible (« sections[k].cta.anchor » → « anchor »). */
4038
+ const lastName = (path) => path.split(".").pop()?.replace(/\[.*$/, ""), isObj$2 = (v) => typeof v == "object" && !!v && !Array.isArray(v), same$2 = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null), keyed$1 = (v) => Array.isArray(v) && v.length > 0 && v.every((i) => isObj$2(i) && typeof i._key == "string");
3990
4039
  function typeNames(t) {
3991
4040
  let out = [];
3992
4041
  for (let c = t; c; c = c.type) c.name && out.push(c.name);
@@ -3996,7 +4045,9 @@ function typeNames(t) {
3996
4045
  function kindOf(t, value) {
3997
4046
  if (t) {
3998
4047
  let names = typeNames(t);
3999
- if (t.options?.instanceOnly || names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
4048
+ if (t.options?.instanceOnly) return "value";
4049
+ if (names.includes("image") && hasOwnFields(t)) return "object";
4050
+ if (names.some((n) => VALUE_TYPE_NAMES.has(n)) || t.to) return "value";
4000
4051
  if (t.jsonType === "array") {
4001
4052
  let of = t.of ?? [];
4002
4053
  if (of.some((m) => typeNames(m).includes("block"))) return "text";
@@ -4008,6 +4059,15 @@ function kindOf(t, value) {
4008
4059
  }
4009
4060
  return keyed$1(value) ? "list" : isObj$2(value) ? "object" : "value";
4010
4061
  }
4062
+ function hasOwnFields(t) {
4063
+ for (let c = t; c; c = c.type) if (c.fields?.some((f) => ![
4064
+ "asset",
4065
+ "hotspot",
4066
+ "crop",
4067
+ "media"
4068
+ ].includes(f.name))) return !0;
4069
+ return !1;
4070
+ }
4011
4071
  function fieldType(t, name) {
4012
4072
  for (let c = t; c; c = c.type) {
4013
4073
  let f = c.fields?.find((x) => x.name === name);
@@ -4022,15 +4082,17 @@ function itemType(t, item) {
4022
4082
  /** Tous les textes d'un élément ajouté : à traduire. */
4023
4083
  function collectTexts(value, t, path, acc) {
4024
4084
  let kind = kindOf(t, value);
4025
- if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
4026
- else if (kind === "object" && isObj$2(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
4027
- else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$2(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
4085
+ if (!(kind === "text" && typeof value == "string" && isNonTextValue(lastName(path), value))) {
4086
+ if (kind === "text") value != null && value !== "" && acc.toTranslate.push(path);
4087
+ else if (kind === "object" && isObj$2(value)) for (let [k, v] of Object.entries(value)) k.startsWith("_") || collectTexts(v, fieldType(t, k), `${path}.${k}`, acc);
4088
+ else if (kind === "list" && Array.isArray(value)) for (let item of value) isObj$2(item) && collectTexts(item, itemType(t, item), `${path}[${String(item._key)}]`, acc);
4089
+ }
4028
4090
  }
4029
4091
  const ABSENT$1 = Symbol("absent");
4030
4092
  function merge(target, before, after, t, path, acc) {
4031
4093
  if (same$2(before, after)) return target === void 0 ? ABSENT$1 : target;
4032
4094
  let kind = kindOf(t, after ?? before);
4033
- if (kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT$1 : target) : (acc.toTranslate.push(path), target == null || target === "" || same$2(target, before) ? after : target);
4095
+ if (kind === "text" && typeof (after ?? before) == "string" && isNonTextValue(lastName(path), after ?? before) && (kind = "value"), kind === "text") return after == null || after === "" ? (target != null && target !== "" && acc.toTranslate.push(path), target === void 0 ? ABSENT$1 : target) : (acc.toTranslate.push(path), target == null || target === "" || same$2(target, before) ? after : target);
4034
4096
  if (kind === "value") return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
4035
4097
  if (kind === "object") {
4036
4098
  if (!isObj$2(after)) return acc.copied.push(path), after === void 0 ? ABSENT$1 : after;
@@ -4183,12 +4245,36 @@ async function linkTranslations(client, sourceId, sourceLanguage, type, created)
4183
4245
  * traduits par l'IA si `ai` (service du kit), slug traduit et unique, publiée si
4184
4246
  * tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
4185
4247
  */
4248
+ /** Champ slug d'un type (registre des pages du kit, sinon « slug » s'il est rempli). */
4249
+ function slugFieldOf(config, type, source) {
4250
+ let field = config.pageTypes.find((t) => t.type === type)?.slugField ?? (source.slug?.current ? "slug" : null);
4251
+ return field && source[field]?.current ? field : null;
4252
+ }
4253
+ /**
4254
+ * Slug d'une version traduite : tiré de son titre (déjà traduit), unique dans la langue
4255
+ * (-2, -3...) ; à défaut de titre, le slug de la version source. JAMAIS « traduit » comme
4256
+ * un texte (vu sur JAF : une reprise avait vidé le slug d'une page).
4257
+ */
4258
+ async function translatedSlug(client, config, type, doc, source, language) {
4259
+ let field = config.i18n?.field ?? "language", pageType = config.pageTypes.find((t) => t.type === type), slugField = slugFieldOf(config, type, source) ?? "slug", titleField = pageType?.titleField ?? "title", base = slugify(typeof doc[titleField] == "string" ? doc[titleField] : "") || String(source[slugField].current), id = typeof doc._id == "string" ? doc._id.replace(/^drafts\./, "") : "", slug = base;
4260
+ for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**")) && _id != $id]) > 0`, {
4261
+ type,
4262
+ slug,
4263
+ language,
4264
+ id
4265
+ }); n++) slug = `${base}-${n}`;
4266
+ return {
4267
+ _type: "slug",
4268
+ current: slug
4269
+ };
4270
+ }
4186
4271
  async function createTranslatedVersion(opts) {
4187
4272
  let { client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai, publish = !1 } = opts, field = config.i18n?.field ?? "language", result = propagate({}, {}, source, schemaType), { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(result.document), id = translationIdFor(sourceId, sourceLanguage, language), remaining = result.toTranslate, aiError = null, written = [];
4188
4273
  if (ai && config.history && remaining.length) try {
4189
- let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, sourceLanguage, language, toSend.map((v) => v ?? ""));
4190
- remaining = remaining.filter((path, n) => {
4191
- let value = toSend[n] === void 0 ? void 0 : translated[n], ok = setAtKey(doc, path, value);
4274
+ let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, sourceLanguage, language, toSend.map((v) => v ?? "")), failed = new Set(result.failed);
4275
+ result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4276
+ if (failed.has(n)) return !0;
4277
+ let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4192
4278
  return ok && value !== void 0 && written.push({
4193
4279
  path,
4194
4280
  value
@@ -4198,20 +4284,8 @@ async function createTranslatedVersion(opts) {
4198
4284
  aiError = cause instanceof Error ? cause.message : String(cause);
4199
4285
  }
4200
4286
  doc[field] = language, Object.assign(doc, await localizeReferences(client, doc, language));
4201
- let pageType = config.pageTypes.find((t) => t.type === type), slugField = pageType?.slugField ?? (source.slug?.current ? "slug" : null);
4202
- if (slugField && source[slugField]?.current) {
4203
- let titleField = pageType?.titleField ?? "title", base = slugify(typeof doc[titleField] == "string" ? doc[titleField] : "") || String(source[slugField].current), slug = base;
4204
- for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {
4205
- type,
4206
- slug,
4207
- language
4208
- }); n++) slug = `${base}-${n}`;
4209
- doc[slugField] = {
4210
- _type: "slug",
4211
- current: slug
4212
- };
4213
- }
4214
- slugField && remaining.includes(pageType?.titleField ?? "title") && !remaining.includes(slugField) && (remaining = [...remaining, slugField]);
4287
+ let pageType = config.pageTypes.find((t) => t.type === type), slugField = slugFieldOf(config, type, source);
4288
+ slugField && (doc[slugField] = await translatedSlug(client, config, type, doc, source, language)), slugField && remaining.includes(pageType?.titleField ?? "title") && !remaining.includes(slugField) && (remaining = [...remaining, slugField]);
4215
4289
  let complete = ai && !remaining.length && !aiError, published = complete && publish;
4216
4290
  await client.createOrReplace({
4217
4291
  ...doc,
@@ -4247,24 +4321,28 @@ async function createTranslatedVersion(opts) {
4247
4321
  * Rend le document complété et le nombre de textes traduits.
4248
4322
  */
4249
4323
  async function fillTranslation(opts) {
4250
- let { config, schemaType, source, sourceLanguage, language } = opts, document = structuredClone(opts.target);
4324
+ let { config, schemaType, source, sourceLanguage, language, trace } = opts, document = structuredClone(opts.target);
4251
4325
  for (let [key, value] of Object.entries(source)) key.startsWith("_") || key === (config.i18n?.field ?? "language") || (document[key] === void 0 || document[key] === null) && (document[key] = structuredClone(value));
4252
- let paths = untranslatedPaths(source, document, schemaType);
4326
+ let paths = untranslatedPaths(source, document, schemaType, trace);
4253
4327
  if (!paths.length || !config.history) return {
4254
4328
  document,
4255
4329
  translated: 0,
4256
- written: []
4330
+ written: [],
4331
+ failed: 0,
4332
+ error: null
4257
4333
  };
4258
- let translated = await translateValues(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), written = [];
4334
+ let result = await translateValuesSettled(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), failed = new Set(result.failed), written = [];
4259
4335
  return paths.forEach((p, n) => {
4260
- setAtKey(document, p, translated[n]) && written.push({
4336
+ !failed.has(n) && setAtKey(document, p, result.values[n]) && written.push({
4261
4337
  path: p,
4262
- value: translated[n]
4338
+ value: result.values[n]
4263
4339
  });
4264
4340
  }), {
4265
4341
  document,
4266
4342
  translated: written.length,
4267
- written
4343
+ written,
4344
+ failed: failed.size,
4345
+ error: result.error
4268
4346
  };
4269
4347
  }
4270
4348
  /**
@@ -4297,11 +4375,12 @@ async function retryTranslatedVersion(opts) {
4297
4375
  remaining: todo.paths,
4298
4376
  aiError: "AI translation is not configured (kit project key missing)"
4299
4377
  };
4300
- let { _rev, _createdAt, _updatedAt, ...doc } = structuredClone(current), remaining = todo.paths, aiError = null, written = [];
4378
+ let { _rev, _createdAt, _updatedAt, ...doc } = structuredClone(current), type = String(current._type), slugField = slugFieldOf(config, type, source), nameOf = (path) => path.split(".").pop()?.replace(/\[.*$/, ""), technical = (path) => isNonTextValue(nameOf(path), valueAtKey(source, path)), slugPending = !!(slugField && todo.paths.includes(slugField)), remaining = todo.paths.filter((p) => p !== slugField && !technical(p)), aiError = null, written = [];
4301
4379
  try {
4302
- let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, todo.sourceLanguage, language, toSend.map((v) => v ?? ""));
4303
- remaining = remaining.filter((path, n) => {
4304
- let value = toSend[n] === void 0 ? void 0 : translated[n], ok = setAtKey(doc, path, value);
4380
+ let toSend = remaining.map((path) => valueAtKey(source, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, todo.sourceLanguage, language, toSend.map((v) => v ?? "")), failed = new Set(result.failed);
4381
+ result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4382
+ if (failed.has(n)) return !0;
4383
+ let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4305
4384
  return ok && value !== void 0 && written.push({
4306
4385
  path,
4307
4386
  value
@@ -4310,6 +4389,10 @@ async function retryTranslatedVersion(opts) {
4310
4389
  } catch (cause) {
4311
4390
  aiError = cause instanceof Error ? cause.message : String(cause);
4312
4391
  }
4392
+ if (slugPending && slugField) {
4393
+ let titleField = config.pageTypes.find((t) => t.type === type)?.titleField ?? "title";
4394
+ remaining.includes(titleField) ? remaining = [...remaining, slugField] : doc[slugField] = await translatedSlug(client, config, type, doc, source, language);
4395
+ }
4313
4396
  let published = publish && !remaining.length && !aiError, tx = client.transaction();
4314
4397
  return published ? (tx.createOrReplace({
4315
4398
  ...doc,
@@ -4512,7 +4595,8 @@ function LanguagesSync() {
4512
4595
  source: src,
4513
4596
  target: base,
4514
4597
  sourceLanguage: d.from,
4515
- language: d.language
4598
+ language: d.language,
4599
+ trace: await readTrace(client, id)
4516
4600
  }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction();
4517
4601
  publishNow ? (tx.createOrReplace({
4518
4602
  ...doc,
@@ -4525,7 +4609,7 @@ function LanguagesSync() {
4525
4609
  sourceLanguage: d.from
4526
4610
  });
4527
4611
  let unchanged = filled.written.filter((w) => JSON.stringify(w.value) === JSON.stringify(valueAtKey(src, w.path))).length;
4528
- lines.push({
4612
+ filled.error && fail(what, `${filled.error} The other texts were kept; retry to translate the rest.`), lines.push({
4529
4613
  tone: publishNow ? "positive" : "caution",
4530
4614
  text: `${what}: ${filled.translated} text(s) translated${publishNow ? " and published" : " in the draft, to review then publish"}${unchanged ? ` (${unchanged} kept identical by the AI: names, brands... check them)` : ""}`
4531
4615
  });
@@ -11821,7 +11905,7 @@ function withTranslationTodo(Inner, config) {
11821
11905
  let alive = !0;
11822
11906
  return client.getDocument(sourceId).then((doc) => {
11823
11907
  if (!alive) return;
11824
- let text = collectTexts$1(valueAtKey(doc, key)).join("").trim();
11908
+ let value = valueAtKey(doc, key), text = (value && typeof value == "object" && typeof value.current == "string" ? value.current : "") || (typeof value == "string" ? value : collectTexts$1(value).join("").trim());
11825
11909
  setMaster(text || "(empty: follows the component default)");
11826
11910
  }).catch(() => alive && setMaster(null)), () => {
11827
11911
  alive = !1;
@@ -12170,9 +12254,12 @@ function PropagateDialog(props) {
12170
12254
  if (ai && config.history && remaining.length) {
12171
12255
  let toDo = remaining.filter((p) => !kept.includes(p));
12172
12256
  try {
12173
- let toSend = toDo.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), translated = await translateValues(config.history, source, t.language, toSend.map((v) => v ?? "")), done = /* @__PURE__ */ new Set();
12257
+ let toSend = toDo.map((path) => valueAtKey(after, path)).map((v) => collectTexts$1(v).some((s) => s.trim()) ? v : void 0), result = await translateValuesSettled(config.history, source, t.language, toSend.map((v) => v ?? "")), missed = new Set(result.failed);
12258
+ result.error && (failed = !0, aiError = result.error);
12259
+ let done = /* @__PURE__ */ new Set();
12174
12260
  toDo.forEach((path, n) => {
12175
- let value = toSend[n] === void 0 ? void 0 : translated[n];
12261
+ if (missed.has(n)) return;
12262
+ let value = toSend[n] === void 0 ? void 0 : result.values[n];
12176
12263
  setAtKey(doc, path, value) && (done.add(path), value !== void 0 && written.push({
12177
12264
  path,
12178
12265
  value