@nocode-factory/sanity-kit 2.27.1 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/ncf-kit.mjs CHANGED
@@ -34,6 +34,7 @@ function usage(code = 0) {
34
34
  npx ncf-kit setup --types page,homePage [options] active le projet, clé du journal, webhook
35
35
  npx ncf-kit doctor [--web <dossier>] [--offline] vérifie que le projet est complet
36
36
  npx ncf-kit check-environments [--page <chemin>] test prod / préprod, BLOQUANT (postbuild du site)
37
+ npx ncf-kit check-deploy avant sanity deploy : l'appId est bien le Studio de CE projet
37
38
  npx ncf-kit translations [export] [--out <fichier>] champs « À traduire » → JSON (texte source et actuel)
38
39
  npx ncf-kit translations apply <fichier> écrit les traductions dans les brouillons
39
40
 
@@ -422,6 +423,13 @@ async function doctor() {
422
423
 
423
424
  /* En ligne */
424
425
  if (!offline) {
426
+ {
427
+ const r = await checkDeploy({quiet: true})
428
+ const msg = r.level === 'ko' ? `${r.detail} Le kit a besoin que chaque projet déploie SON Studio ; le projet ne le garantit pas : corriger studio/.env, et \"deploy\": \"ncf-kit check-deploy && sanity deploy\" dans studio/package.json.` : r.detail
429
+ ;({ok, warn, ko})[r.level]('Studio à déployer', msg)
430
+ const studioPkg = read(join(studio, 'package.json'))
431
+ if (studioPkg && !/ncf-kit check-deploy/.test(studioPkg)) warn('Studio à déployer', "le kit a besoin d'un contrôle avant chaque déploiement du Studio ; le projet ne l'a pas : \"deploy\": \"ncf-kit check-deploy && sanity deploy\" dans studio/package.json, et toujours `npm run deploy`.")
432
+ }
425
433
  // Purge du cache à la publication : webhook Sanity vers la PRODUCTION
426
434
  // (/api/revalidate), qui relaie à la préprod. Sans lui, rien ne se met à jour
427
435
  // sur le site avant le prochain build.
@@ -608,10 +616,45 @@ async function translations() {
608
616
  fail(`translations : sous-commande inconnue « ${sub} » (export | apply <fichier>)`)
609
617
  }
610
618
 
619
+ // ─── check-deploy : ne jamais écraser le Studio d'un autre projet ───
620
+ // `sanity deploy` publie sur le Studio désigné par SANITY_STUDIO_APP_ID. Un dépôt
621
+ // dupliqué qui garde l'appId d'origine écrase le Studio de l'autre projet (vécu :
622
+ // Studio Circet France remplacé par celui d'un pays). Vérifie, avant de déployer,
623
+ // que l'appId est un Studio de CE projet Sanity et qu'il porte le nom d'hôte du .env.
624
+ async function checkDeploy({quiet = false} = {}) {
625
+ const dir = resolve(flag('dir') ?? process.cwd())
626
+ const env = {
627
+ ...parseEnv(read(join(dir, '.env'))),
628
+ ...parseEnv(read(join(dir, '.env.production.local'))),
629
+ }
630
+ const projectId = env.SANITY_STUDIO_PROJECT_ID
631
+ const appId = env.SANITY_STUDIO_APP_ID
632
+ const hostname = env.SANITY_STUDIO_HOSTNAME
633
+ if (!projectId) return {level: 'ko', detail: 'SANITY_STUDIO_PROJECT_ID absent du .env du studio.'}
634
+ if (!appId) return {level: 'ok', detail: `pas d'appId : premier déploiement (${hostname ?? 'nom choisi au déploiement'})`}
635
+ const token = sanityToken()
636
+ if (!token) return {level: 'warn', detail: 'non vérifié : aucun jeton Sanity (npx sanity login).'}
637
+ const r = await request(`${SANITY_API}/v2024-08-01/projects/${projectId}/user-applications`, {headers: {authorization: `Bearer ${token}`}})
638
+ if (!r.ok) return {level: 'warn', detail: `Studios du projet illisibles (${r.status}).`}
639
+ const apps = Array.isArray(r.body) ? r.body : []
640
+ const app = apps.find((a) => a.id === appId)
641
+ if (!app) return {level: 'ko', detail: `SANITY_STUDIO_APP_ID=${appId} n'est pas un Studio du projet ${projectId} : il vient sans doute d'un autre projet (dépôt dupliqué). Le vider pour créer le Studio de ce projet au déploiement.`}
642
+ if (hostname && app.appHost && app.appHost !== hostname) return {level: 'ko', detail: `SANITY_STUDIO_APP_ID=${appId} est le Studio « ${app.appHost} », pas « ${hostname} » : déployer l'écraserait. Mettre l'appId de ${hostname} (ou le vider).`}
643
+ return {level: 'ok', detail: `${app.appHost ?? appId}.sanity.studio`}
644
+ }
645
+
611
646
  if (command === 'setup') {
612
647
  setup().catch((error) => fail(error?.message ?? String(error)))
613
648
  } else if (command === 'doctor') {
614
649
  doctor().catch((error) => fail(error?.message ?? String(error)))
650
+ } else if (command === 'check-deploy') {
651
+ checkDeploy()
652
+ .then((r) => {
653
+ const icon = {ok: '✔', warn: '⚠', ko: '✖'}[r.level]
654
+ console.log(`${icon} Studio à déployer : ${r.detail}`)
655
+ if (r.level === 'ko') process.exit(1)
656
+ })
657
+ .catch((error) => fail(error?.message ?? String(error)))
615
658
  } else if (command === 'translations') {
616
659
  translations().catch((error) => fail(error?.message ?? String(error)))
617
660
  } else if (command === 'check-environments') {
package/dist/index.d.ts CHANGED
@@ -1348,7 +1348,7 @@ export declare function ActorName(props: {
1348
1348
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1349
1349
  * le vérifie.
1350
1350
  */
1351
- export declare const KIT_VERSION = "2.27.1";
1351
+ export declare const KIT_VERSION = "2.29.0";
1352
1352
  /**
1353
1353
  * Données de la page proposées comme colonnes.
1354
1354
  *
package/dist/index.js CHANGED
@@ -1420,7 +1420,7 @@ function explainGrantError(error) {
1420
1420
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1421
1421
  * le vérifie.
1422
1422
  */
1423
- const KIT_VERSION = "2.27.1";
1423
+ const KIT_VERSION = "2.29.0";
1424
1424
  /**
1425
1425
  * Signale ce Studio au service du kit, une fois par montage.
1426
1426
  *
@@ -1763,7 +1763,7 @@ function useKitUpdate() {
1763
1763
  !controller.signal.aborted && body?.version && setLatest(body.version);
1764
1764
  }).catch(() => {}), () => controller.abort();
1765
1765
  }, []);
1766
- let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.27.1") > 0);
1766
+ let available = !!(latest && !isPrerelease(latest) && compareVersions(latest, "2.29.0") > 0);
1767
1767
  return {
1768
1768
  current: KIT_VERSION,
1769
1769
  latest,
@@ -8243,16 +8243,35 @@ function fieldPathKey(path) {
8243
8243
  */
8244
8244
  function withTranslationTodo(Inner, config) {
8245
8245
  function TranslationTodoInput(props) {
8246
- let id = useFormValue(["_id"]), client = useKitClient(), todo = useTranslationTodo(client, config.i18n ? id : void 0), [busy, setBusy] = useState(!1), [error, setError] = useState(null), language = useFormValue([config.i18n?.field ?? "language"]), key = fieldPathKey(props.path), inner = createElement(Inner, props), show = !!todo?.paths?.includes(key), done = () => {
8246
+ let id = useFormValue(["_id"]), client = useKitClient(), todo = useTranslationTodo(client, config.i18n ? id : void 0), [busy, setBusy] = useState(!1), [error, setError] = useState(null), language = useFormValue([config.i18n?.field ?? "language"]), key = fieldPathKey(props.path), inner = createElement(Inner, props), show = !!todo?.paths?.includes(key), [master, setMaster] = useState(null), sourceId = show ? todo?.sourceId : void 0;
8247
+ useEffect(() => {
8248
+ if (!sourceId) return;
8249
+ let alive = !0;
8250
+ return client.getDocument(sourceId).then((doc) => {
8251
+ if (!alive) return;
8252
+ let text = collectTexts$1(valueAtKey(doc, key)).join("").trim();
8253
+ setMaster(text || "(empty: follows the component default)");
8254
+ }).catch(() => alive && setMaster(null)), () => {
8255
+ alive = !1;
8256
+ };
8257
+ }, [
8258
+ client,
8259
+ sourceId,
8260
+ key
8261
+ ]);
8262
+ let done = () => {
8247
8263
  todo && (setBusy(!0), client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit().finally(() => setBusy(!1)));
8248
8264
  }, translate = async () => {
8249
8265
  if (todo?.sourceId && todo.sourceLanguage && language && config.history) {
8250
8266
  setBusy(!0), setError(null);
8251
8267
  try {
8252
8268
  let value = valueAtKey(await client.getDocument(todo.sourceId) ?? await client.getDocument(`drafts.${todo.sourceId}`), key);
8253
- if (value === void 0) throw Error("Source text not found.");
8254
- let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
8255
- props.onChange(set(translated)), await client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit();
8269
+ if (!collectTexts$1(value).some((t) => t.trim())) props.onChange(unset());
8270
+ else {
8271
+ let [translated] = await translateValues(config.history, todo.sourceLanguage, language, [value]);
8272
+ props.onChange(set(translated));
8273
+ }
8274
+ await client.patch(todo._id).set({ paths: (todo.paths ?? []).filter((p) => p !== key) }).commit();
8256
8275
  } catch (cause) {
8257
8276
  setError(cause instanceof Error ? cause.message : String(cause));
8258
8277
  } finally {
@@ -8267,44 +8286,60 @@ function withTranslationTodo(Inner, config) {
8267
8286
  padding: 2,
8268
8287
  radius: 2,
8269
8288
  border: !0,
8270
- children: [/* @__PURE__ */ jsxs(Flex, {
8271
- align: "center",
8272
- gap: 2,
8273
- children: [
8274
- /* @__PURE__ */ jsxs(Text, {
8275
- size: 1,
8276
- style: { flex: 1 },
8277
- children: [
8278
- "To translate: changed in the ",
8279
- (todo?.sourceLanguage ?? "").toUpperCase(),
8280
- " version."
8281
- ]
8282
- }),
8283
- config.history && !props.readOnly && /* @__PURE__ */ jsx(Button, {
8284
- tone: "primary",
8285
- fontSize: 1,
8286
- padding: 2,
8287
- text: busy ? "Translating…" : "Translate with AI",
8288
- disabled: busy,
8289
- onClick: () => void translate()
8290
- }),
8291
- /* @__PURE__ */ jsx(Button, {
8292
- mode: "ghost",
8293
- fontSize: 1,
8294
- padding: 2,
8295
- text: "Mark as translated",
8296
- disabled: busy,
8297
- onClick: done
8298
- })
8299
- ]
8300
- }), error && /* @__PURE__ */ jsx(Text, {
8301
- size: 1,
8302
- style: {
8303
- marginTop: 8,
8304
- color: "var(--card-badge-critical-fg-color, #c00)"
8305
- },
8306
- children: error
8307
- })]
8289
+ children: [
8290
+ /* @__PURE__ */ jsxs(Flex, {
8291
+ align: "center",
8292
+ gap: 2,
8293
+ children: [
8294
+ /* @__PURE__ */ jsxs(Text, {
8295
+ size: 1,
8296
+ style: { flex: 1 },
8297
+ children: [
8298
+ "To translate: changed in the ",
8299
+ (todo?.sourceLanguage ?? "").toUpperCase(),
8300
+ " version."
8301
+ ]
8302
+ }),
8303
+ config.history && !props.readOnly && /* @__PURE__ */ jsx(Button, {
8304
+ tone: "primary",
8305
+ fontSize: 1,
8306
+ padding: 2,
8307
+ text: busy ? "Translating…" : "Translate with AI",
8308
+ disabled: busy,
8309
+ onClick: () => void translate()
8310
+ }),
8311
+ /* @__PURE__ */ jsx(Button, {
8312
+ mode: "ghost",
8313
+ fontSize: 1,
8314
+ padding: 2,
8315
+ text: "Mark as translated",
8316
+ disabled: busy,
8317
+ onClick: done
8318
+ })
8319
+ ]
8320
+ }),
8321
+ master && /* @__PURE__ */ jsxs(Text, {
8322
+ size: 1,
8323
+ muted: !0,
8324
+ style: {
8325
+ marginTop: 8,
8326
+ whiteSpace: "pre-wrap"
8327
+ },
8328
+ children: [
8329
+ (todo?.sourceLanguage ?? "").toUpperCase(),
8330
+ ": ",
8331
+ master.length > 600 ? `${master.slice(0, 600)}…` : master
8332
+ ]
8333
+ }),
8334
+ error && /* @__PURE__ */ jsx(Text, {
8335
+ size: 1,
8336
+ style: {
8337
+ marginTop: 8,
8338
+ color: "var(--card-badge-critical-fg-color, #c00)"
8339
+ },
8340
+ children: error
8341
+ })
8342
+ ]
8308
8343
  })]
8309
8344
  });
8310
8345
  }
@@ -8548,37 +8583,58 @@ function propagate(target, before, after, documentType) {
8548
8583
  function hasChanges(r) {
8549
8584
  return r.toTranslate.length > 0 || r.copied.length > 0 || r.added > 0 || r.removed > 0 || r.moved;
8550
8585
  }
8551
- /**
8552
- * Publier la version PRINCIPALE d'une page qui a des traductions : la publication
8553
- * part normalement, puis « Propager aux autres langues ? » propose d'appliquer aux
8554
- * BROUILLONS des traductions la structure (sections ajoutées, supprimées, déplacées)
8555
- * et les valeurs non textuelles (images, liens, options…). Les textes traduits ne
8556
- * sont jamais écrasés à la main : les textes modifiés sont traduits par l'IA
8557
- * (« Translate with AI », service du kit, coché par défaut) ou marqués « à
8558
- * traduire ». Rien n'est publié dans les autres langues : on relit, on publie.
8586
+ /** Slug d'URL depuis un titre : sans accents, minuscules, tirets. */
8587
+ function slugify(input, maxLength = 96) {
8588
+ return input.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLength).replace(/-+$/g, "");
8589
+ }
8590
+ /**
8591
+ * Publier la version PRINCIPALE d'une page :
8592
+ * - page déjà publiée qui a des traductions : « Propagate to other languages? »
8593
+ * applique la structure (sections ajoutées, supprimées, déplacées) et les valeurs
8594
+ * non textuelles (images, liens, options…) ;
8595
+ * - PREMIÈRE publication : « Create the other language versions? » crée la page dans
8596
+ * chaque langue cochée, reliée à ses traductions (hreflang, bascule de langue).
8597
+ * Avec « Translate with AI » (service du kit, coché par défaut) : textes traduits
8598
+ * par l'IA et versions PUBLIÉES directement (aucun clic de plus). Sans, ou si l'IA
8599
+ * échoue : brouillons, textes marqués « To translate ». Une modification d'une autre
8600
+ * langue ne remonte jamais à la version principale.
8559
8601
  * `masterLocale` : langue source (défaut : langue principale du site ; les valeurs
8560
- * par défaut des composants ont la leur, `i18n.defaultsSourceLocale`).
8602
+ * par défaut des composants ont la leur, `i18n.defaultsSourceLocale`). `allowCreate` :
8603
+ * propose la création des autres versions (types de pages seulement).
8561
8604
  */
8562
- function withPropagation(Publish, config, masterLocale) {
8605
+ function withPropagation(Publish, config, masterLocale, options = {}) {
8563
8606
  let i18n = config.i18n, master = masterLocale ?? i18n?.defaultLocale, Wrapped = (props) => {
8564
8607
  let base = Publish(props), client = useKitClient(), schema = useSchema(), [run, setRun] = useState(null), current = props.draft ?? props.published;
8565
8608
  return !base || !i18n || current?.[i18n.field] !== master ? base : {
8566
8609
  ...base,
8567
8610
  onHandle: () => {
8568
8611
  let before = props.published, after = props.draft;
8569
- if (base.onHandle?.(), !before || !after) return;
8570
- let documentType = schema.get(props.type);
8571
- findTargets(client, props.id, String(after[i18n.field] ?? ""), before, after, documentType).then((targets) => {
8612
+ if (base.onHandle?.(), !after) return;
8613
+ let documentType = schema.get(props.type), source = String(after[i18n.field] ?? "");
8614
+ before ? findTargets(client, props.id, source, before, after, documentType).then((targets) => {
8572
8615
  targets.some((t) => hasChanges(t.result)) && setRun({
8573
- before,
8616
+ mode: "update",
8574
8617
  after,
8575
8618
  targets
8576
8619
  });
8620
+ }).catch(() => {}) : options.allowCreate && findMissing(client, props.id, source, i18n.locales).then((missing) => {
8621
+ if (!missing.length) return;
8622
+ let result = propagate({}, {}, after, documentType);
8623
+ setRun({
8624
+ mode: "create",
8625
+ after,
8626
+ targets: missing.map((language) => ({
8627
+ language,
8628
+ id: null,
8629
+ result,
8630
+ selected: !0
8631
+ }))
8632
+ });
8577
8633
  }).catch(() => {});
8578
8634
  },
8579
8635
  dialog: run ? {
8580
8636
  type: "dialog",
8581
- header: "Propagate to other languages?",
8637
+ header: run.mode === "create" ? "Create the other language versions?" : "Propagate to other languages?",
8582
8638
  width: "medium",
8583
8639
  onClose: () => {
8584
8640
  setRun(null), props.onComplete();
@@ -8587,7 +8643,7 @@ function withPropagation(Publish, config, masterLocale) {
8587
8643
  config,
8588
8644
  id: props.id,
8589
8645
  type: props.type,
8590
- before: run.before,
8646
+ mode: run.mode,
8591
8647
  after: run.after,
8592
8648
  targets: run.targets,
8593
8649
  onDone: () => {
@@ -8599,10 +8655,16 @@ function withPropagation(Publish, config, masterLocale) {
8599
8655
  };
8600
8656
  return Wrapped.action = Publish.action, Wrapped;
8601
8657
  }
8658
+ async function translationsOf(client, id) {
8659
+ return (await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"key\": _key, \"id\": value._ref}", { id }) ?? []).map((t) => ({
8660
+ language: t.language ?? t.key ?? "",
8661
+ id: t.id ?? ""
8662
+ })).filter((t) => t.language && t.id);
8663
+ }
8602
8664
  async function findTargets(client, id, source, before, after, documentType) {
8603
- let translations = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0].translations[]{language, \"id\": value._ref}", { id }), list = [];
8604
- for (let t of translations ?? []) {
8605
- if (!t?.id || t.id === id || t.language === source) continue;
8665
+ let list = [];
8666
+ for (let t of await translationsOf(client, id)) {
8667
+ if (t.id === id || t.language === source) continue;
8606
8668
  let target = await client.getDocument(`drafts.${t.id}`) ?? await client.getDocument(t.id) ?? null;
8607
8669
  if (!target) continue;
8608
8670
  let result = propagate(target, before, after, documentType);
@@ -8615,45 +8677,93 @@ async function findTargets(client, id, source, before, after, documentType) {
8615
8677
  }
8616
8678
  return list;
8617
8679
  }
8680
+ async function findMissing(client, id, source, locales) {
8681
+ let existing = new Set((await translationsOf(client, id)).map((t) => t.language));
8682
+ return locales.filter((l) => l !== source && !existing.has(l));
8683
+ }
8684
+ const randomId = () => typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
8685
+ /** Relie les nouvelles versions à la page (translation.metadata de document-internationalization). */
8686
+ async function linkTranslations(client, sourceId, sourceLanguage, type, created) {
8687
+ if (!created.length) return;
8688
+ let item = (language, ref) => ({
8689
+ _key: language,
8690
+ _type: "internationalizedArrayReferenceValue",
8691
+ language,
8692
+ value: {
8693
+ _type: "reference",
8694
+ _ref: ref,
8695
+ _weak: !0,
8696
+ _strengthenOnPublish: { type }
8697
+ }
8698
+ }), meta = await client.fetch("*[_type == \"translation.metadata\" && references($id)][0]{_id}", { id: sourceId });
8699
+ meta ? await client.patch(meta._id).setIfMissing({ translations: [] }).append("translations", created.map((c) => item(c.language, c.id))).commit() : await client.create({
8700
+ _id: randomId(),
8701
+ _type: "translation.metadata",
8702
+ schemaTypes: [type],
8703
+ translations: [item(sourceLanguage, sourceId), ...created.map((c) => item(c.language, c.id))]
8704
+ });
8705
+ }
8618
8706
  function PropagateDialog(props) {
8619
- let { config, id, type, after, onDone } = props, client = useKitClient(), 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), apply = async () => {
8707
+ let { config, id, type, mode, after, onDone } = props, client = useKitClient(), field = config.i18n?.field ?? "language", source = String(after[field] ?? ""), pageType = config.pageTypes.find((t) => t.type === type), [targets, setTargets] = useState(props.targets), [busy, setBusy] = useState(!1), toast = useToast(), [error, setError] = useState(null), [ai, setAi] = useState(!!config.history), hasTexts = targets.some((t) => t.result.toTranslate.length), apply = async () => {
8620
8708
  setBusy(!0), setError(null);
8621
8709
  try {
8622
- let applied = [], translatedCount = 0, aiError = null;
8710
+ let published = [], drafted = [], created = [], aiError = null;
8623
8711
  for (let t of targets) {
8624
8712
  if (!t.selected) continue;
8625
- let { _rev, _createdAt, _updatedAt, ...doc } = t.result.document, remaining = t.result.toTranslate;
8713
+ let { _id, _rev, _createdAt, _updatedAt, ...doc } = structuredClone(t.result.document), targetId = t.id ?? randomId(), remaining = t.result.toTranslate, translatedOk = !remaining.length;
8626
8714
  if (ai && config.history && remaining.length) try {
8627
- let values = remaining.map((path) => valueAtKey(after, path)), translated = await translateValues(config.history, source, t.language, values);
8628
- remaining = remaining.filter((path, n) => values[n] === void 0 || !setAtKey(doc, path, translated[n])), translatedCount += t.result.toTranslate.length - remaining.length;
8715
+ let toSend = remaining.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 ?? ""));
8716
+ remaining = remaining.filter((path, n) => !setAtKey(doc, path, toSend[n] === void 0 ? void 0 : translated[n])), translatedOk = !remaining.length;
8629
8717
  } catch (cause) {
8630
8718
  aiError = cause instanceof Error ? cause.message : String(cause);
8631
8719
  }
8632
- if (await client.createOrReplace({
8720
+ if (mode === "create") {
8721
+ doc[field] = t.language;
8722
+ let slugField = pageType?.slugField, titleField = pageType?.titleField ?? "title", title = typeof doc[titleField] == "string" ? doc[titleField] : "", sourceSlug = slugField ? after[slugField]?.current : void 0;
8723
+ if (slugField && (title || sourceSlug)) {
8724
+ let base = slugify(title) || String(sourceSlug), slug = base;
8725
+ for (let n = 2; await client.fetch(`count(*[_type == $type && ${slugField}.current == $slug && ${field} == $language && !(_id in path("drafts.**"))]) > 0`, {
8726
+ type,
8727
+ slug,
8728
+ language: t.language
8729
+ }); n++) slug = `${base}-${n}`;
8730
+ doc[slugField] = {
8731
+ _type: "slug",
8732
+ current: slug
8733
+ };
8734
+ }
8735
+ }
8736
+ let publish = ai && translatedOk, tx = client.transaction();
8737
+ publish ? (tx.createOrReplace({
8633
8738
  ...doc,
8634
- _id: `drafts.${t.id}`,
8739
+ _id: targetId,
8635
8740
  _type: type
8636
- }), remaining.length) {
8637
- let todoId = translationTodoId(t.id), existing = await client.fetch("*[_id == $todoId][0].paths", { todoId });
8638
- await client.createOrReplace({
8639
- _id: todoId,
8640
- _type: TRANSLATION_TODO_TYPE,
8641
- documentId: t.id,
8642
- sourceId: id,
8643
- sourceLanguage: source,
8644
- paths: [.../* @__PURE__ */ new Set([...existing ?? [], ...remaining])]
8645
- });
8646
- }
8647
- applied.push(t.language.toUpperCase());
8741
+ }), t.id && tx.delete(`drafts.${t.id}`)) : tx.createOrReplace({
8742
+ ...doc,
8743
+ _id: `drafts.${targetId}`,
8744
+ _type: type
8745
+ }), await tx.commit();
8746
+ let todoId = translationTodoId(targetId), existing = await client.fetch("*[_id == $todoId][0].paths", { todoId }) ?? [], done = new Set(t.result.toTranslate.filter((p) => !remaining.includes(p))), paths = [.../* @__PURE__ */ new Set([...existing.filter((p) => !done.has(p)), ...remaining])];
8747
+ (paths.length || existing.length) && await client.createOrReplace({
8748
+ _id: todoId,
8749
+ _type: TRANSLATION_TODO_TYPE,
8750
+ documentId: targetId,
8751
+ sourceId: id,
8752
+ sourceLanguage: source,
8753
+ paths
8754
+ }), t.id || created.push({
8755
+ language: t.language,
8756
+ id: targetId
8757
+ }), (publish ? published : drafted).push(t.language.toUpperCase());
8648
8758
  }
8649
- toast.push({
8759
+ await linkTranslations(client, id, source, type, created), toast.push({
8650
8760
  status: aiError ? "warning" : "success",
8651
- title: `Drafts updated: ${applied.join(", ")}`,
8652
- description: aiError ? `AI translation failed (${aiError}): the changed texts are marked "To translate".` : translatedCount ? `${translatedCount} text${translatedCount > 1 ? "s" : ""} translated with AI. Review, then publish each language.` : "Translate the fields marked \"To translate\", then publish each language.",
8761
+ title: [published.length ? `Published: ${published.join(", ")}` : "", drafted.length ? `Drafts: ${drafted.join(", ")}` : ""].filter(Boolean).join(" · "),
8762
+ 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.",
8653
8763
  duration: 8e3
8654
8764
  }), onDone();
8655
8765
  } catch (cause) {
8656
- setError(`Propagation failed, nothing was published. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 140)})`);
8766
+ setError(`Failed. (${(cause instanceof Error ? cause.message : String(cause)).slice(0, 160)})`);
8657
8767
  } finally {
8658
8768
  setBusy(!1);
8659
8769
  }
@@ -8665,14 +8775,12 @@ function PropagateDialog(props) {
8665
8775
  /* @__PURE__ */ jsxs(Text, {
8666
8776
  size: 1,
8667
8777
  children: [
8668
- "The ",
8669
- source.toUpperCase(),
8670
- " version is published. Apply its changes to the drafts of the other languages? Changed texts are ",
8671
- ai ? "translated with AI" : "marked \"To translate\"",
8672
- ". Nothing is published."
8778
+ 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?`,
8779
+ " ",
8780
+ ai ? "Texts are translated with AI and each language is published." : "Each language is saved as a draft, texts marked \"To translate\"."
8673
8781
  ]
8674
8782
  }),
8675
- config.history && targets.some((t) => t.result.toTranslate.length) && /* @__PURE__ */ jsxs(Flex, {
8783
+ config.history && hasTexts && /* @__PURE__ */ jsxs(Flex, {
8676
8784
  as: "label",
8677
8785
  align: "center",
8678
8786
  gap: 2,
@@ -8681,7 +8789,7 @@ function PropagateDialog(props) {
8681
8789
  onChange: () => setAi(!ai)
8682
8790
  }), /* @__PURE__ */ jsx(Text, {
8683
8791
  size: 1,
8684
- children: "Translate changed texts with AI"
8792
+ children: "Translate with AI and publish"
8685
8793
  })]
8686
8794
  }),
8687
8795
  /* @__PURE__ */ jsx(Stack, {
@@ -8695,7 +8803,7 @@ function PropagateDialog(props) {
8695
8803
  align: "flex-start",
8696
8804
  children: [/* @__PURE__ */ jsx(Checkbox, {
8697
8805
  checked: t.selected,
8698
- disabled: !hasChanges(t.result),
8806
+ disabled: mode === "update" && !hasChanges(t.result),
8699
8807
  onChange: () => setTargets(targets.map((x, i) => i === index ? {
8700
8808
  ...x,
8701
8809
  selected: !x.selected
@@ -8711,12 +8819,12 @@ function PropagateDialog(props) {
8711
8819
  }), /* @__PURE__ */ jsx(Text, {
8712
8820
  size: 1,
8713
8821
  muted: !0,
8714
- children: summary(t.result)
8822
+ children: mode === "create" ? `New version (${t.result.toTranslate.length} texts)` : summary(t.result)
8715
8823
  })]
8716
8824
  })
8717
8825
  })]
8718
8826
  })
8719
- }, t.id))
8827
+ }, `${t.language}-${t.id ?? "new"}`))
8720
8828
  }),
8721
8829
  error && /* @__PURE__ */ jsx(Card, {
8722
8830
  tone: "critical",
@@ -8736,7 +8844,7 @@ function PropagateDialog(props) {
8736
8844
  onClick: onDone,
8737
8845
  disabled: busy
8738
8846
  }), /* @__PURE__ */ jsx(Button, {
8739
- text: busy ? "Propagating…" : "Propagate",
8847
+ text: busy ? "Working…" : mode === "create" ? "Create" : "Propagate",
8740
8848
  tone: "primary",
8741
8849
  onClick: () => void apply(),
8742
8850
  disabled: busy || !targets.some((t) => t.selected)
@@ -9059,7 +9167,7 @@ const ncfKit = definePlugin((options) => {
9059
9167
  },
9060
9168
  document: {
9061
9169
  newDocumentOptions: (prev) => prev.filter((option) => option.templateId !== BOARD_LAYOUT_TYPE),
9062
- actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action) : prev
9170
+ actions: (prev, context) => config.pageTypeNames.includes(context.schemaType) ? prev.map((action) => action.action === "unpublish" ? RemoveFromSiteAction : action.action === "publish" && config.i18n ? withPropagation(action, config, void 0, { allowCreate: !0 }) : action) : context.schemaType === config.componentPreview.defaultsType && config.i18n ? prev.map((action) => action.action === "publish" ? withPropagation(action, config, config.i18n?.defaultsSourceLocale) : action) : prev
9063
9171
  },
9064
9172
  studio: { components: { toolMenu: createPreviewLauncher(config, issues) } },
9065
9173
  form: { components: { input: createKitInput(config) } }