@nocode-factory/sanity-kit 2.64.0-rc.3 → 2.65.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.
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.64.0-rc.3";
1426
+ const KIT_VERSION = "2.65.0-rc.1";
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.64.0-rc.3") > 0);
1934
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.65.0-rc.1") > 0);
1935
1935
  return {
1936
1936
  current: KIT_VERSION,
1937
1937
  latest,
@@ -4184,7 +4184,7 @@ async function linkTranslations(client, sourceId, sourceLanguage, type, created)
4184
4184
  * tout est traduit (sinon brouillon et textes « To translate »). Relie la version.
4185
4185
  */
4186
4186
  async function createTranslatedVersion(opts) {
4187
- let { client, config, type, schemaType, source, sourceId, sourceLanguage, language, ai } = 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 = [];
4187
+ 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
4188
  if (ai && config.history && remaining.length) try {
4189
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
4190
  remaining = remaining.filter((path, n) => {
@@ -4212,7 +4212,7 @@ async function createTranslatedVersion(opts) {
4212
4212
  };
4213
4213
  }
4214
4214
  slugField && remaining.includes(pageType?.titleField ?? "title") && !remaining.includes(slugField) && (remaining = [...remaining, slugField]);
4215
- let published = ai && !remaining.length && !aiError;
4215
+ let complete = ai && !remaining.length && !aiError, published = complete && publish;
4216
4216
  await client.createOrReplace({
4217
4217
  ...doc,
4218
4218
  _id: published ? id : `drafts.${id}`,
@@ -4235,7 +4235,9 @@ async function createTranslatedVersion(opts) {
4235
4235
  return redirects && await syncTranslationRedirects(client, redirects, [sourceId]).catch(() => {}), {
4236
4236
  id,
4237
4237
  published,
4238
- aiError
4238
+ complete,
4239
+ aiError,
4240
+ remaining
4239
4241
  };
4240
4242
  }
4241
4243
  /**
@@ -4269,35 +4271,94 @@ async function fillTranslation(opts) {
4269
4271
  * Textes de `source` absents ou non traduits dans `target` (vides, ou identiques au
4270
4272
  * texte source). Un texte déjà traduit, même à la main, n'y figure jamais.
4271
4273
  */
4272
- function untranslatedPaths(source, target, schemaType) {
4274
+ function untranslatedPaths(source, target, schemaType, trace) {
4273
4275
  return propagate({}, {}, source, schemaType).toTranslate.filter((path) => {
4274
4276
  let src = valueAtKey(source, path);
4275
4277
  if (!collectTexts$1(src).some((t) => t.trim())) return !1;
4276
4278
  let cur = target ? valueAtKey(target, path) : void 0;
4277
- return !collectTexts$1(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src);
4279
+ return !collectTexts$1(cur).some((t) => t.trim()) || JSON.stringify(cur) === JSON.stringify(src) && trace?.get(path) !== hashValue(cur);
4278
4280
  });
4279
4281
  }
4282
+ /**
4283
+ * Reprend une version traduite restée INACHEVÉE (textes « To translate » après un échec de
4284
+ * l'IA) : retraduit seulement ces textes depuis la version source publiée, dans le
4285
+ * brouillon (créé depuis la version publiée s'il n'existe pas). Publie si tout est traduit
4286
+ * et `publish` demandé. Rend ce qui reste et l'erreur de l'IA, pour le dire à l'équipe.
4287
+ */
4288
+ async function retryTranslatedVersion(opts) {
4289
+ let { client, config, todo, language, publish = !1 } = opts, id = todo.documentId.replace(/^drafts\./, ""), source = await client.getDocument(todo.sourceId), current = await client.getDocument(`drafts.${id}`) ?? await client.getDocument(id);
4290
+ if (!source || !current) return {
4291
+ published: !1,
4292
+ remaining: todo.paths,
4293
+ aiError: source ? "translated version not found" : "source version not found (unpublished or deleted)"
4294
+ };
4295
+ if (!config.history) return {
4296
+ published: !1,
4297
+ remaining: todo.paths,
4298
+ aiError: "AI translation is not configured (kit project key missing)"
4299
+ };
4300
+ let { _rev, _createdAt, _updatedAt, ...doc } = structuredClone(current), remaining = todo.paths, aiError = null, written = [];
4301
+ 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);
4305
+ return ok && value !== void 0 && written.push({
4306
+ path,
4307
+ value
4308
+ }), !ok;
4309
+ });
4310
+ } catch (cause) {
4311
+ aiError = cause instanceof Error ? cause.message : String(cause);
4312
+ }
4313
+ let published = publish && !remaining.length && !aiError, tx = client.transaction();
4314
+ return published ? (tx.createOrReplace({
4315
+ ...doc,
4316
+ _id: id
4317
+ }), tx.delete(`drafts.${id}`)) : tx.createOrReplace({
4318
+ ...doc,
4319
+ _id: `drafts.${id}`
4320
+ }), tx.patch(translationTodoId(id), (p) => p.set({ paths: remaining })), await tx.commit(), await recordTrace(client, id, written, {
4321
+ sourceId: todo.sourceId,
4322
+ sourceLanguage: todo.sourceLanguage
4323
+ }), {
4324
+ published,
4325
+ remaining,
4326
+ aiError
4327
+ };
4328
+ }
4280
4329
  const EXCLUDED = [
4281
4330
  "translation.metadata",
4282
4331
  BOARD_LAYOUT_TYPE,
4283
4332
  TRANSLATION_TODO_TYPE
4284
- ];
4333
+ ], TITLE = "coalesce(title, name, heading, internalName, slug.current, _id)";
4334
+ /** Erreur lisible pour l'équipe (le service renvoie parfois un message technique). */
4335
+ function explain$1(error) {
4336
+ let e = error.toLowerCase();
4337
+ return /401|403|unauthori|forbidden|key/.test(e) ? `${error} (kit project key: run \`npx ncf-kit setup\`)` : /429|rate|quota|limit/.test(e) ? `${error} (AI service busy or quota reached: retry in a few minutes)` : /timeout|timed out|network|fetch|50\d/.test(e) ? `${error} (AI service unreachable: retry in a few minutes)` : /too (long|large)|length|token/.test(e) ? `${error} (text too long for one request: translate this field by hand)` : error;
4338
+ }
4285
4339
  /**
4286
4340
  * Langues du site : met chaque langue au niveau de la langue principale, en UN clic
4287
- * explicite (jamais tout seul). Utile à l'ajout d'une langue (« de » : toutes les
4288
- * pages en allemand) et après l'ajout d'un composant (valeurs par défaut traduites
4289
- * dans chaque langue).
4290
- * - Documents : chaque document publié de la langue principale sans version dans
4291
- * une langue reçoit sa version, traduite par l'IA, publiée et reliée.
4292
- * - Valeurs par défaut des composants : langue source (anglais en général), puis
4293
- * chaque langue ; un document absent est créé ; seuls les textes vides ou restés
4294
- * identiques au texte source sont traduits (jamais un texte traduit à la main).
4341
+ * explicite (jamais tout seul). Utile à l'ajout d'une langue et après l'ajout d'un
4342
+ * composant (valeurs par défaut traduites dans chaque langue).
4343
+ * - On choisit ce qu'on traduit (documents manquants, traductions inachevées, valeurs
4344
+ * par défaut des composants) et, par défaut, tout est enregistré en BROUILLON à relire
4345
+ * (kit >= 2.65.0) : une traduction de l'IA n'est publiée sans relecture que si on coche
4346
+ * « Publish right away ».
4347
+ * - Chaque échec est listé avec sa raison ; une version inachevée (échec de l'IA) est
4348
+ * détectée et reprise par « Retry » (seulement ses textes à traduire).
4349
+ * - Valeurs par défaut : seuls les textes vides ou restés identiques au texte source sont
4350
+ * traduits (jamais un texte traduit à la main) ; un texte que l'IA a rendu à l'identique
4351
+ * (nom propre, marque) n'est plus reproposé.
4295
4352
  */
4296
4353
  function LanguagesSync() {
4297
- let config = useKitConfig(), client = useKitClient(), schema = useSchema(), [open, setOpen] = useState(!1), [plan, setPlan] = useState(null), [busy, setBusy] = useState(!1), [progress, setProgress] = useState(null), [report, setReport] = useState(null), i18n = config.i18n, field = i18n?.field ?? "language", defaultsType = config.componentPreview.defaultsType, typeOf = (name) => schema.get(name), analyse = useCallback(async () => {
4354
+ let config = useKitConfig(), client = useKitClient(), schema = useSchema(), [open, setOpen] = useState(!1), [plan, setPlan] = useState(null), [busy, setBusy] = useState(!1), [progress, setProgress] = useState(null), [report, setReport] = useState(null), [pick, setPick] = useState({
4355
+ missing: !0,
4356
+ unfinished: !0,
4357
+ defaults: !0
4358
+ }), [publishNow, setPublishNow] = useState(!1), i18n = config.i18n, field = i18n?.field ?? "language", defaultsType = config.componentPreview.defaultsType, typeOf = (name) => schema.get(name), analyse = useCallback(async () => {
4298
4359
  if (!i18n) return;
4299
- setPlan(null), setReport(null);
4300
- let main = i18n.defaultLocale, sources = await client.fetch(`*[defined(${field}) && ${field} == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]{_id, _type}`, {
4360
+ setPlan(null);
4361
+ let main = i18n.defaultLocale, others = i18n.locales.filter((l) => l !== main), sources = await client.fetch(`*[defined(${field}) && ${field} == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]{_id, _type, "title": ${TITLE}}`, {
4301
4362
  main,
4302
4363
  excluded: [...EXCLUDED, defaultsType]
4303
4364
  }), metas = await client.fetch("*[_type == \"translation.metadata\"]{\"refs\": translations[]{\"lang\": coalesce(language, _key), \"id\": value._ref}}"), langsOf = /* @__PURE__ */ new Map();
@@ -4305,12 +4366,20 @@ function LanguagesSync() {
4305
4366
  let langs = new Set((m.refs ?? []).map((r) => r.lang ?? ""));
4306
4367
  for (let r of m.refs ?? []) r.id && langsOf.set(r.id, langs);
4307
4368
  }
4308
- let missing = i18n.locales.filter((l) => l !== main).map((language) => ({
4369
+ let missing = others.map((language) => ({
4309
4370
  language,
4310
4371
  docs: sources.filter((d) => !langsOf.get(d._id)?.has(language))
4311
- })), defaultsDocs = await client.fetch("*[_type == $type && !(_id in path(\"drafts.**\"))]", { type: defaultsType }), byLang = (lang) => defaultsDocs.find((d) => d[field] === lang) ?? null, sourceLang = byLang(i18n.defaultsSourceLocale) ? i18n.defaultsSourceLocale : main, sourceDoc = byLang(sourceLang), mainDoc = byLang(main), defaults = [];
4372
+ })), 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}}`, {
4375
+ others,
4376
+ excluded: EXCLUDED
4377
+ }), drafts = others.map((language) => ({
4378
+ language,
4379
+ count: draftOnly.filter((d) => d.language === language).length
4380
+ })).filter((d) => d.count), defaultsDocs = await client.fetch("*[_type == $type && !(_id in path(\"drafts.**\"))]", { type: defaultsType }), byLang = (lang) => defaultsDocs.find((d) => d[field] === lang) ?? null, sourceLang = byLang(i18n.defaultsSourceLocale) ? i18n.defaultsSourceLocale : main, sourceDoc = byLang(sourceLang), mainDoc = byLang(main), defaults = [];
4312
4381
  if (sourceDoc && mainDoc && sourceLang !== main) {
4313
- let texts = untranslatedPaths(mainDoc, sourceDoc, typeOf(defaultsType)).length;
4382
+ let trace = await readTrace(client, String(sourceDoc._id)), texts = untranslatedPaths(mainDoc, sourceDoc, typeOf(defaultsType), trace).length;
4314
4383
  texts && defaults.push({
4315
4384
  language: sourceLang,
4316
4385
  exists: !0,
@@ -4319,16 +4388,18 @@ function LanguagesSync() {
4319
4388
  });
4320
4389
  }
4321
4390
  if (sourceDoc) for (let language of i18n.locales.filter((l) => l !== sourceLang)) {
4322
- let doc = byLang(language);
4391
+ let doc = byLang(language), trace = doc ? await readTrace(client, String(doc._id)) : void 0;
4323
4392
  defaults.push({
4324
4393
  language,
4325
4394
  exists: !!doc,
4326
- texts: untranslatedPaths(sourceDoc, doc, typeOf(defaultsType)).length,
4395
+ texts: untranslatedPaths(sourceDoc, doc, typeOf(defaultsType), trace).length,
4327
4396
  from: sourceLang
4328
4397
  });
4329
4398
  }
4330
4399
  setPlan({
4331
4400
  missing,
4401
+ unfinished,
4402
+ drafts,
4332
4403
  defaults
4333
4404
  });
4334
4405
  }, [
@@ -4338,92 +4409,157 @@ function LanguagesSync() {
4338
4409
  i18n
4339
4410
  ]), run = async () => {
4340
4411
  if (!plan || !i18n) return;
4341
- setBusy(!0);
4342
- let lines = [];
4412
+ setBusy(!0), setReport(null);
4413
+ let lines = [], fail = (what, error) => lines.push({
4414
+ tone: "critical",
4415
+ text: `${what}: ${explain$1(error)}`
4416
+ });
4343
4417
  try {
4344
- let total = plan.missing.reduce((n, m) => n + m.docs.length, 0), n = 0;
4345
- for (let m of plan.missing) {
4346
- let ok = 0, drafts = 0;
4347
- for (let d of m.docs) {
4348
- n++, setProgress(`Documents ${n}/${total} (${m.language.toUpperCase()})`);
4349
- let source = await client.getDocument(d._id);
4350
- if (source) try {
4351
- (await createTranslatedVersion({
4352
- client,
4353
- config,
4354
- type: d._type,
4355
- schemaType: typeOf(d._type),
4356
- source,
4357
- sourceId: d._id,
4358
- sourceLanguage: i18n.defaultLocale,
4359
- language: m.language,
4360
- ai: !0
4361
- })).published ? ok++ : drafts++;
4362
- } catch (cause) {
4363
- lines.push(`${m.language.toUpperCase()} ${d._id}: ${cause instanceof Error ? cause.message : String(cause)}`);
4418
+ if (pick.missing) {
4419
+ let total = plan.missing.reduce((n, m) => n + m.docs.length, 0), n = 0;
4420
+ for (let m of plan.missing) {
4421
+ let published = 0, review = 0;
4422
+ for (let d of m.docs) {
4423
+ n++, setProgress(`Documents ${n}/${total} (${m.language.toUpperCase()})`);
4424
+ let what = `${m.language.toUpperCase()} « ${d.title ?? d._id} »`;
4425
+ try {
4426
+ let source = await client.getDocument(d._id);
4427
+ if (!source) {
4428
+ fail(what, "source version not found");
4429
+ continue;
4430
+ }
4431
+ let created = await createTranslatedVersion({
4432
+ client,
4433
+ config,
4434
+ type: d._type,
4435
+ schemaType: typeOf(d._type),
4436
+ source,
4437
+ sourceId: d._id,
4438
+ sourceLanguage: i18n.defaultLocale,
4439
+ language: m.language,
4440
+ ai: !0,
4441
+ publish: publishNow
4442
+ });
4443
+ created.published ? published++ : created.complete ? review++ : created.aiError ? fail(what, `AI translation failed, saved as a draft with ${created.remaining.length} text(s) to translate. ${created.aiError}`) : fail(what, `${created.remaining.length} text(s) not translated, saved as a draft (marked "To translate")`);
4444
+ } catch (cause) {
4445
+ fail(what, cause instanceof Error ? cause.message : String(cause));
4446
+ }
4364
4447
  }
4448
+ published && lines.push({
4449
+ tone: "positive",
4450
+ text: `${m.language.toUpperCase()}: ${published} document(s) translated and published`
4451
+ }), review && lines.push({
4452
+ tone: "caution",
4453
+ text: `${m.language.toUpperCase()}: ${review} document(s) translated as drafts, to review then publish`
4454
+ });
4365
4455
  }
4366
- m.docs.length && lines.unshift(`${m.language.toUpperCase()}: ${ok} published${drafts ? `, ${drafts} saved as drafts (texts to translate)` : ""}`);
4367
4456
  }
4368
- for (let d of plan.defaults) {
4369
- if (d.exists && !d.texts) continue;
4370
- let src = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4371
- type: defaultsType,
4372
- lang: d.from
4373
- });
4374
- if (!src) continue;
4375
- let sourceLang = d.from;
4376
- if (setProgress(`Component defaults (${d.language.toUpperCase()})`), !d.exists) {
4377
- await createTranslatedVersion({
4378
- client,
4379
- config,
4380
- type: defaultsType,
4381
- schemaType: typeOf(defaultsType),
4382
- source: src,
4383
- sourceId: String(src._id),
4384
- sourceLanguage: sourceLang,
4385
- language: d.language,
4386
- ai: !0
4387
- }), lines.push(`Component defaults ${d.language.toUpperCase()}: created`);
4457
+ if (pick.unfinished) for (let [n, t] of plan.unfinished.entries()) {
4458
+ setProgress(`Unfinished translations ${n + 1}/${plan.unfinished.length}`);
4459
+ let what = `${(t.language ?? "").toUpperCase()} « ${t.title ?? t.documentId} »`;
4460
+ if (!t.language) {
4461
+ fail(what, "language of the translated version unknown");
4388
4462
  continue;
4389
4463
  }
4390
- let target = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4391
- type: defaultsType,
4392
- lang: d.language
4393
- });
4394
- if (!target) continue;
4395
- let filled = await fillTranslation({
4464
+ let r = await retryTranslatedVersion({
4465
+ client,
4396
4466
  config,
4397
- schemaType: typeOf(defaultsType),
4398
- source: src,
4399
- target,
4400
- sourceLanguage: sourceLang,
4401
- language: d.language
4402
- }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction().createOrReplace(doc), draft = await client.getDocument(`drafts.${String(target._id)}`);
4403
- if (draft) {
4404
- let { _rev: r2, _updatedAt: u2, _createdAt: c2, ...dd } = (await fillTranslation({
4467
+ todo: t,
4468
+ language: t.language,
4469
+ publish: publishNow
4470
+ });
4471
+ r.aiError ? fail(what, `still ${r.remaining.length} text(s) to translate. ${r.aiError}`) : r.remaining.length ? fail(what, `${r.remaining.length} text(s) could not be placed (field changed since): translate them by hand`) : lines.push({
4472
+ tone: r.published ? "positive" : "caution",
4473
+ text: `${what}: completed${r.published ? " and published" : ", draft to review then publish"}`
4474
+ });
4475
+ }
4476
+ if (pick.defaults) for (let d of plan.defaults) {
4477
+ if (d.exists && !d.texts) continue;
4478
+ let what = `Component defaults ${d.language.toUpperCase()}`;
4479
+ try {
4480
+ let src = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4481
+ type: defaultsType,
4482
+ lang: d.from
4483
+ });
4484
+ if (!src) continue;
4485
+ if (setProgress(`${what}`), !d.exists) {
4486
+ let created = await createTranslatedVersion({
4487
+ client,
4488
+ config,
4489
+ type: defaultsType,
4490
+ schemaType: typeOf(defaultsType),
4491
+ source: src,
4492
+ sourceId: String(src._id),
4493
+ sourceLanguage: d.from,
4494
+ language: d.language,
4495
+ ai: !0,
4496
+ publish: publishNow
4497
+ });
4498
+ created.aiError ? fail(what, `AI translation failed, created as a draft. ${created.aiError}`) : lines.push({
4499
+ tone: created.published ? "positive" : "caution",
4500
+ text: `${what}: created${created.published ? " and published" : " as a draft, to review then publish"}`
4501
+ });
4502
+ continue;
4503
+ }
4504
+ let published = await client.fetch(`*[_type == $type && ${field} == $lang && !(_id in path("drafts.**"))][0]`, {
4505
+ type: defaultsType,
4506
+ lang: d.language
4507
+ });
4508
+ if (!published) continue;
4509
+ let id = String(published._id), base = await client.getDocument(`drafts.${id}`) ?? published, filled = await fillTranslation({
4405
4510
  config,
4406
4511
  schemaType: typeOf(defaultsType),
4407
4512
  source: src,
4408
- target: draft,
4409
- sourceLanguage: sourceLang,
4513
+ target: base,
4514
+ sourceLanguage: d.from,
4410
4515
  language: d.language
4411
- })).document;
4412
- tx.createOrReplace(dd);
4516
+ }), { _rev, _updatedAt, _createdAt, ...doc } = filled.document, tx = client.transaction();
4517
+ publishNow ? (tx.createOrReplace({
4518
+ ...doc,
4519
+ _id: id
4520
+ }), tx.delete(`drafts.${id}`)) : tx.createOrReplace({
4521
+ ...doc,
4522
+ _id: `drafts.${id}`
4523
+ }), await tx.commit(), await recordTrace(client, id, filled.written, {
4524
+ sourceId: String(src._id),
4525
+ sourceLanguage: d.from
4526
+ });
4527
+ let unchanged = filled.written.filter((w) => JSON.stringify(w.value) === JSON.stringify(valueAtKey(src, w.path))).length;
4528
+ lines.push({
4529
+ tone: publishNow ? "positive" : "caution",
4530
+ 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
+ });
4532
+ } catch (cause) {
4533
+ fail(what, cause instanceof Error ? cause.message : String(cause));
4413
4534
  }
4414
- await tx.commit(), await recordTrace(client, String(target._id), filled.written, {
4415
- sourceId: String(src._id),
4416
- sourceLanguage: sourceLang
4417
- }), lines.push(`Component defaults ${d.language.toUpperCase()}: ${filled.translated} text${filled.translated > 1 ? "s" : ""} translated`);
4418
4535
  }
4419
4536
  } catch (cause) {
4420
- lines.push(`Stopped: ${cause instanceof Error ? cause.message : String(cause)}`);
4537
+ fail("Stopped", cause instanceof Error ? cause.message : String(cause));
4421
4538
  } finally {
4422
- setBusy(!1), setProgress(null), setReport(lines.length ? lines : ["Everything was already up to date."]), analyse();
4539
+ setBusy(!1), setProgress(null), setReport(lines.length ? lines : [{
4540
+ tone: "positive",
4541
+ text: "Everything was already up to date."
4542
+ }]), analyse();
4423
4543
  }
4424
4544
  };
4425
4545
  if (!i18n || !config.history) return null;
4426
- let pendingDocs = plan?.missing.reduce((n, m) => n + m.docs.length, 0) ?? 0, pendingDefaults = plan?.defaults.filter((d) => !d.exists || d.texts).length ?? 0;
4546
+ let pendingDocs = plan?.missing.reduce((n, m) => n + m.docs.length, 0) ?? 0, pendingDefaults = plan?.defaults.filter((d) => !d.exists || d.texts).length ?? 0, pendingUnfinished = plan?.unfinished.length ?? 0, selected = pick.missing && pendingDocs || pick.unfinished && pendingUnfinished || pick.defaults && pendingDefaults, failures = report?.filter((l) => l.tone === "critical").length ?? 0, option = (key, label, count) => /* @__PURE__ */ jsxs(Flex, {
4547
+ as: "label",
4548
+ align: "center",
4549
+ gap: 2,
4550
+ children: [/* @__PURE__ */ jsx(Checkbox, {
4551
+ checked: pick[key] && count > 0,
4552
+ disabled: !count || busy,
4553
+ onChange: () => setPick({
4554
+ ...pick,
4555
+ [key]: !pick[key]
4556
+ })
4557
+ }), /* @__PURE__ */ jsx(Text, {
4558
+ size: 1,
4559
+ muted: !count,
4560
+ children: label
4561
+ })]
4562
+ });
4427
4563
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
4428
4564
  icon: TranslateIcon,
4429
4565
  text: "Languages",
@@ -4431,7 +4567,7 @@ function LanguagesSync() {
4431
4567
  fontSize: 1,
4432
4568
  padding: 2,
4433
4569
  onClick: () => {
4434
- setOpen(!0), analyse();
4570
+ setOpen(!0), setReport(null), analyse();
4435
4571
  }
4436
4572
  }), open && /* @__PURE__ */ jsx(Dialog, {
4437
4573
  id: "ncf-languages",
@@ -4448,43 +4584,120 @@ function LanguagesSync() {
4448
4584
  children: [
4449
4585
  "Brings every language to the level of the main language (",
4450
4586
  i18n.defaultLocale.toUpperCase(),
4451
- "): missing pages and documents are created, translated with AI and published; component defaults are translated from",
4452
- " ",
4453
- i18n.defaultsSourceLocale.toUpperCase(),
4454
- ". Texts already translated (even by hand) are never changed."
4587
+ ") with AI translation. Translations are saved as drafts to review, unless you choose to publish them right away. Texts already translated (even by hand) are never changed."
4455
4588
  ]
4456
4589
  }),
4457
4590
  plan ? /* @__PURE__ */ jsxs(Stack, {
4458
4591
  gap: 3,
4459
- children: [plan.missing.map((m) => /* @__PURE__ */ jsx(Card, {
4460
- padding: 3,
4461
- radius: 2,
4462
- border: !0,
4463
- tone: m.docs.length ? "caution" : "positive",
4464
- children: /* @__PURE__ */ jsxs(Text, {
4465
- size: 1,
4466
- children: [
4467
- m.language.toUpperCase(),
4468
- ": ",
4469
- m.docs.length ? `${m.docs.length} document${m.docs.length > 1 ? "s" : ""} without a version` : "all documents have a version"
4470
- ]
4471
- })
4472
- }, m.language)), plan.defaults.map((d) => /* @__PURE__ */ jsx(Card, {
4473
- padding: 3,
4474
- radius: 2,
4475
- border: !0,
4476
- tone: !d.exists || d.texts ? "caution" : "positive",
4477
- children: /* @__PURE__ */ jsxs(Text, {
4478
- size: 1,
4592
+ children: [
4593
+ plan.missing.map((m) => /* @__PURE__ */ jsx(Card, {
4594
+ padding: 3,
4595
+ radius: 2,
4596
+ border: !0,
4597
+ tone: m.docs.length ? "caution" : "positive",
4598
+ children: /* @__PURE__ */ jsxs(Text, {
4599
+ size: 1,
4600
+ children: [
4601
+ m.language.toUpperCase(),
4602
+ ": ",
4603
+ m.docs.length ? `${m.docs.length} document${m.docs.length > 1 ? "s" : ""} without a version` : "all documents have a version"
4604
+ ]
4605
+ })
4606
+ }, m.language)),
4607
+ plan.unfinished.length > 0 && /* @__PURE__ */ jsx(Card, {
4608
+ padding: 3,
4609
+ radius: 2,
4610
+ border: !0,
4611
+ tone: "critical",
4612
+ children: /* @__PURE__ */ jsxs(Stack, {
4613
+ gap: 2,
4614
+ children: [/* @__PURE__ */ jsxs(Text, {
4615
+ size: 1,
4616
+ weight: "semibold",
4617
+ children: [
4618
+ plan.unfinished.length,
4619
+ " unfinished translation",
4620
+ plan.unfinished.length > 1 ? "s" : "",
4621
+ " (texts still to translate)"
4622
+ ]
4623
+ }), plan.unfinished.slice(0, 8).map((t) => /* @__PURE__ */ jsxs(Text, {
4624
+ size: 1,
4625
+ muted: !0,
4626
+ children: [
4627
+ (t.language ?? "").toUpperCase(),
4628
+ " « ",
4629
+ t.title ?? t.documentId,
4630
+ " »: ",
4631
+ t.paths.length,
4632
+ " text",
4633
+ t.paths.length > 1 ? "s" : ""
4634
+ ]
4635
+ }, t.documentId))]
4636
+ })
4637
+ }),
4638
+ plan.drafts.map((d) => /* @__PURE__ */ jsx(Card, {
4639
+ padding: 3,
4640
+ radius: 2,
4641
+ border: !0,
4642
+ tone: "caution",
4643
+ children: /* @__PURE__ */ jsxs(Text, {
4644
+ size: 1,
4645
+ children: [
4646
+ d.language.toUpperCase(),
4647
+ ": ",
4648
+ d.count,
4649
+ " translated version",
4650
+ d.count > 1 ? "s" : "",
4651
+ " only in draft, not online yet (review then publish)"
4652
+ ]
4653
+ })
4654
+ }, `dr-${d.language}`)),
4655
+ plan.defaults.map((d) => /* @__PURE__ */ jsx(Card, {
4656
+ padding: 3,
4657
+ radius: 2,
4658
+ border: !0,
4659
+ tone: !d.exists || d.texts ? "caution" : "positive",
4660
+ children: /* @__PURE__ */ jsxs(Text, {
4661
+ size: 1,
4662
+ children: [
4663
+ "Component defaults ",
4664
+ d.language.toUpperCase(),
4665
+ ":",
4666
+ " ",
4667
+ d.exists ? d.texts ? `${d.texts} text${d.texts > 1 ? "s" : ""} to translate` : "translated" : "missing (will be created)"
4668
+ ]
4669
+ })
4670
+ }, `d-${d.language}`)),
4671
+ /* @__PURE__ */ jsxs(Stack, {
4672
+ gap: 2,
4479
4673
  children: [
4480
- "Component defaults ",
4481
- d.language.toUpperCase(),
4482
- ":",
4483
- " ",
4484
- d.exists ? d.texts ? `${d.texts} text${d.texts > 1 ? "s" : ""} to translate` : "translated" : "missing (will be created)"
4674
+ /* @__PURE__ */ jsx(Text, {
4675
+ size: 1,
4676
+ weight: "semibold",
4677
+ children: "Translate"
4678
+ }),
4679
+ option("missing", `Missing documents (${pendingDocs})`, pendingDocs),
4680
+ option("unfinished", `Unfinished translations, retry (${pendingUnfinished})`, pendingUnfinished),
4681
+ option("defaults", `Component defaults (${pendingDefaults} language${pendingDefaults > 1 ? "s" : ""})`, pendingDefaults),
4682
+ /* @__PURE__ */ jsx(Box, {
4683
+ paddingTop: 2,
4684
+ children: /* @__PURE__ */ jsxs(Flex, {
4685
+ as: "label",
4686
+ align: "center",
4687
+ gap: 2,
4688
+ children: [/* @__PURE__ */ jsx(Checkbox, {
4689
+ checked: publishNow,
4690
+ disabled: busy,
4691
+ onChange: () => setPublishNow(!publishNow)
4692
+ }), /* @__PURE__ */ jsx(Text, {
4693
+ size: 1,
4694
+ children: "Publish right away, without review (otherwise: drafts to review then publish)"
4695
+ })]
4696
+ })
4697
+ })
4485
4698
  ]
4486
4699
  })
4487
- }, `d-${d.language}`))]
4700
+ ]
4488
4701
  }) : /* @__PURE__ */ jsxs(Flex, {
4489
4702
  align: "center",
4490
4703
  gap: 2,
@@ -4502,17 +4715,26 @@ function LanguagesSync() {
4502
4715
  children: progress
4503
4716
  })]
4504
4717
  }),
4505
- report && /* @__PURE__ */ jsx(Card, {
4506
- padding: 3,
4507
- radius: 2,
4508
- tone: "primary",
4509
- children: /* @__PURE__ */ jsx(Stack, {
4510
- gap: 2,
4511
- children: report.map((line, i) => /* @__PURE__ */ jsx(Text, {
4718
+ report && /* @__PURE__ */ jsxs(Stack, {
4719
+ gap: 2,
4720
+ children: [failures > 0 && /* @__PURE__ */ jsxs(Text, {
4721
+ size: 1,
4722
+ weight: "semibold",
4723
+ children: [
4724
+ failures,
4725
+ " item",
4726
+ failures > 1 ? "s" : "",
4727
+ " failed: the reason is given for each. Fix it if needed, then retry (unfinished translations are kept and listed above)."
4728
+ ]
4729
+ }), report.map((line, i) => /* @__PURE__ */ jsx(Card, {
4730
+ padding: 3,
4731
+ radius: 2,
4732
+ tone: line.tone,
4733
+ children: /* @__PURE__ */ jsx(Text, {
4512
4734
  size: 1,
4513
- children: line
4514
- }, i))
4515
- })
4735
+ children: line.text
4736
+ })
4737
+ }, i))]
4516
4738
  }),
4517
4739
  /* @__PURE__ */ jsxs(Flex, {
4518
4740
  justify: "flex-end",
@@ -4522,12 +4744,12 @@ function LanguagesSync() {
4522
4744
  mode: "ghost",
4523
4745
  disabled: busy,
4524
4746
  onClick: () => setOpen(!1)
4525
- }), /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, {
4526
- tone: "primary",
4527
- text: busy ? "Working…" : "Translate with AI and publish",
4528
- disabled: busy || !plan || !pendingDocs && !pendingDefaults,
4747
+ }), /* @__PURE__ */ jsx(Button, {
4748
+ tone: publishNow ? "caution" : "primary",
4749
+ text: busy ? "Working…" : failures && pendingUnfinished ? "Retry" : publishNow ? "Translate with AI and publish" : "Translate with AI (drafts)",
4750
+ disabled: busy || !plan || !selected,
4529
4751
  onClick: () => void run()
4530
- }) })]
4752
+ })]
4531
4753
  })
4532
4754
  ]
4533
4755
  })
@@ -11922,7 +12144,7 @@ async function findMissing(client, id, source, locales) {
11922
12144
  return locales.filter((l) => l !== source && !existing.has(l));
11923
12145
  }
11924
12146
  function PropagateDialog(props) {
11925
- let { config, id, type, mode, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), [overwrite, setOverwrite] = useState(!1), editedCount = targets.reduce((n, t) => n + (t.selected ? t.edited.length : 0), 0), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
12147
+ let { config, id, type, mode, after, onDone } = props, client = useKitClient(), schema = useSchema(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), [publishNow, setPublishNow] = useState(!1), [overwrite, setOverwrite] = useState(!1), editedCount = targets.reduce((n, t) => n + (t.selected ? t.edited.length : 0), 0), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
11926
12148
  setBusy(!0), setError(null);
11927
12149
  try {
11928
12150
  let published = [], drafted = [], aiError = null;
@@ -11938,7 +12160,8 @@ function PropagateDialog(props) {
11938
12160
  sourceId: id,
11939
12161
  sourceLanguage: source,
11940
12162
  language: t.language,
11941
- ai
12163
+ ai,
12164
+ publish: publishNow
11942
12165
  });
11943
12166
  created.aiError && (aiError = created.aiError), (created.published ? published : drafted).push(t.language.toUpperCase());
11944
12167
  continue;
@@ -11959,7 +12182,7 @@ function PropagateDialog(props) {
11959
12182
  failed = !0, aiError = cause instanceof Error ? cause.message : String(cause);
11960
12183
  }
11961
12184
  }
11962
- let publish = ai && !failed && remaining.every((p) => kept.includes(p)), tx = client.transaction();
12185
+ let publish = publishNow && ai && !failed && remaining.every((p) => kept.includes(p)), tx = client.transaction();
11963
12186
  publish ? (tx.createOrReplace({
11964
12187
  ...doc,
11965
12188
  _id: targetId,
@@ -11985,7 +12208,7 @@ function PropagateDialog(props) {
11985
12208
  toast.push({
11986
12209
  status: aiError ? "warning" : "success",
11987
12210
  title: [published.length ? `Published: ${published.join(", ")}` : "", drafted.length ? `Drafts: ${drafted.join(", ")}` : ""].filter(Boolean).join(" · "),
11988
- description: aiError ? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate".` : drafted.length ? "Translate the fields marked \"To translate\", then publish each language." : "Translated with AI and published.",
12211
+ description: aiError ? `AI translation failed (${aiError}): saved as drafts, texts marked "To translate". Retry later from Pages → Languages (unfinished translations).` : drafted.length ? ai && !publishNow ? "Translated with AI as drafts: review each language, then publish it." : "Translate the fields marked \"To translate\", then publish each language." : "Translated with AI and published.",
11989
12212
  duration: 8e3
11990
12213
  }), onDone();
11991
12214
  } catch (cause) {
@@ -12003,7 +12226,7 @@ function PropagateDialog(props) {
12003
12226
  children: [
12004
12227
  mode === "create" ? `The ${source.toUpperCase()} page is published. Create it in the other languages?` : `The ${source.toUpperCase()} version is published. Apply its changes to the other languages?`,
12005
12228
  " ",
12006
- ai ? "Texts are translated with AI and each language is published." : "Each language is saved as a draft, texts marked \"To translate\"."
12229
+ ai ? publishNow ? "Texts are translated with AI and each language is published right away." : "Texts are translated with AI; each language is saved as a draft to review, then publish." : "Each language is saved as a draft, texts marked \"To translate\"."
12007
12230
  ]
12008
12231
  }),
12009
12232
  config.history && hasTexts && /* @__PURE__ */ jsxs(Flex, {
@@ -12015,7 +12238,19 @@ function PropagateDialog(props) {
12015
12238
  onChange: () => setAi(!ai)
12016
12239
  }), /* @__PURE__ */ jsx(Text, {
12017
12240
  size: 1,
12018
- children: "Translate with AI and publish"
12241
+ children: "Translate with AI"
12242
+ })]
12243
+ }),
12244
+ config.history && hasTexts && ai && /* @__PURE__ */ jsxs(Flex, {
12245
+ as: "label",
12246
+ align: "center",
12247
+ gap: 2,
12248
+ children: [/* @__PURE__ */ jsx(Checkbox, {
12249
+ checked: publishNow,
12250
+ onChange: () => setPublishNow(!publishNow)
12251
+ }), /* @__PURE__ */ jsx(Text, {
12252
+ size: 1,
12253
+ children: "Publish right away, without review"
12019
12254
  })]
12020
12255
  }),
12021
12256
  mode === "update" && editedCount > 0 && /* @__PURE__ */ jsxs(Flex, {