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

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,12 @@
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.
24
30
  - **Textes rendus à l'identique par l'IA** (noms propres, marques) : comptés comme
25
31
  traduits, plus reproposés sans fin, et signalés « à vérifier » (vu sur JAF : 12 textes).
26
32
  - **`doctor`, « Langues : contenus »** : une langue ne compte que si sa version est
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.1";
1486
+ export declare const KIT_VERSION = "2.65.0-rc.3";
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.1";
1426
+ const KIT_VERSION = "2.65.0-rc.3";
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.1") > 0);
1934
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.65.0-rc.3") > 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",
@@ -4186,9 +4229,10 @@ async function linkTranslations(client, sourceId, sourceLanguage, type, created)
4186
4229
  async function createTranslatedVersion(opts) {
4187
4230
  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
4231
  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);
4232
+ 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);
4233
+ result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4234
+ if (failed.has(n)) return !0;
4235
+ let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4192
4236
  return ok && value !== void 0 && written.push({
4193
4237
  path,
4194
4238
  value
@@ -4247,24 +4291,28 @@ async function createTranslatedVersion(opts) {
4247
4291
  * Rend le document complété et le nombre de textes traduits.
4248
4292
  */
4249
4293
  async function fillTranslation(opts) {
4250
- let { config, schemaType, source, sourceLanguage, language } = opts, document = structuredClone(opts.target);
4294
+ let { config, schemaType, source, sourceLanguage, language, trace } = opts, document = structuredClone(opts.target);
4251
4295
  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);
4296
+ let paths = untranslatedPaths(source, document, schemaType, trace);
4253
4297
  if (!paths.length || !config.history) return {
4254
4298
  document,
4255
4299
  translated: 0,
4256
- written: []
4300
+ written: [],
4301
+ failed: 0,
4302
+ error: null
4257
4303
  };
4258
- let translated = await translateValues(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), written = [];
4304
+ let result = await translateValuesSettled(config.history, sourceLanguage, language, paths.map((p) => valueAtKey(source, p))), failed = new Set(result.failed), written = [];
4259
4305
  return paths.forEach((p, n) => {
4260
- setAtKey(document, p, translated[n]) && written.push({
4306
+ !failed.has(n) && setAtKey(document, p, result.values[n]) && written.push({
4261
4307
  path: p,
4262
- value: translated[n]
4308
+ value: result.values[n]
4263
4309
  });
4264
4310
  }), {
4265
4311
  document,
4266
4312
  translated: written.length,
4267
- written
4313
+ written,
4314
+ failed: failed.size,
4315
+ error: result.error
4268
4316
  };
4269
4317
  }
4270
4318
  /**
@@ -4299,9 +4347,10 @@ async function retryTranslatedVersion(opts) {
4299
4347
  };
4300
4348
  let { _rev, _createdAt, _updatedAt, ...doc } = structuredClone(current), remaining = todo.paths, aiError = null, written = [];
4301
4349
  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);
4350
+ 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);
4351
+ result.error && (aiError = result.error), remaining = remaining.filter((path, n) => {
4352
+ if (failed.has(n)) return !0;
4353
+ let value = toSend[n] === void 0 ? void 0 : result.values[n], ok = setAtKey(doc, path, value);
4305
4354
  return ok && value !== void 0 && written.push({
4306
4355
  path,
4307
4356
  value
@@ -4370,8 +4419,8 @@ function LanguagesSync() {
4370
4419
  language,
4371
4420
  docs: sources.filter((d) => !langsOf.get(d._id)?.has(language))
4372
4421
  })), unfinished = await client.fetch(`*[_type == $todo && count(paths) > 0]{documentId, sourceId, sourceLanguage, paths,
4373
- "language": coalesce(*[_id == "drafts." + ^.documentId][0].${field}, *[_id == ^.documentId][0].${field}),
4374
- "title": coalesce(*[_id == "drafts." + ^.documentId][0].${TITLE}, *[_id == ^.documentId][0].${TITLE})}`, { todo: TRANSLATION_TODO_TYPE }), draftOnly = await client.fetch(`*[_id in path("drafts.**") && ${field} in $others && !(_type in $excluded) && !defined(*[_id == string::split(^._id, "drafts.")[1]][0]._id)]{"language": ${field}}`, {
4422
+ "version": coalesce(*[_id == "drafts." + ^.documentId][0], *[_id == ^.documentId][0]){"language": ${field}, "title": ${TITLE}}}
4423
+ {documentId, sourceId, sourceLanguage, paths, "language": version.language, "title": version.title}`, { todo: TRANSLATION_TODO_TYPE }), draftOnly = await client.fetch(`*[_id in path("drafts.**") && ${field} in $others && !(_type in $excluded) && !defined(*[_id == string::split(^._id, "drafts.")[1]][0]._id)]{"language": ${field}}`, {
4375
4424
  others,
4376
4425
  excluded: EXCLUDED
4377
4426
  }), drafts = others.map((language) => ({
@@ -4512,7 +4561,8 @@ function LanguagesSync() {
4512
4561
  source: src,
4513
4562
  target: base,
4514
4563
  sourceLanguage: d.from,
4515
- language: d.language
4564
+ language: d.language,
4565
+ trace: await readTrace(client, id)
4516
4566
  }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction();
4517
4567
  publishNow ? (tx.createOrReplace({
4518
4568
  ...doc,
@@ -4525,7 +4575,7 @@ function LanguagesSync() {
4525
4575
  sourceLanguage: d.from
4526
4576
  });
4527
4577
  let unchanged = filled.written.filter((w) => JSON.stringify(w.value) === JSON.stringify(valueAtKey(src, w.path))).length;
4528
- lines.push({
4578
+ filled.error && fail(what, `${filled.error} The other texts were kept; retry to translate the rest.`), lines.push({
4529
4579
  tone: publishNow ? "positive" : "caution",
4530
4580
  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
4581
  });
@@ -12170,9 +12220,12 @@ function PropagateDialog(props) {
12170
12220
  if (ai && config.history && remaining.length) {
12171
12221
  let toDo = remaining.filter((p) => !kept.includes(p));
12172
12222
  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();
12223
+ 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);
12224
+ result.error && (failed = !0, aiError = result.error);
12225
+ let done = /* @__PURE__ */ new Set();
12174
12226
  toDo.forEach((path, n) => {
12175
- let value = toSend[n] === void 0 ? void 0 : translated[n];
12227
+ if (missed.has(n)) return;
12228
+ let value = toSend[n] === void 0 ? void 0 : result.values[n];
12176
12229
  setAtKey(doc, path, value) && (done.add(path), value !== void 0 && written.push({
12177
12230
  path,
12178
12231
  value