@nocode-factory/sanity-kit 2.29.2 → 2.30.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/bin/ncf-kit.mjs CHANGED
@@ -35,6 +35,7 @@ function usage(code = 0) {
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
37
  npx ncf-kit check-deploy avant sanity deploy : l'appId est bien le Studio de CE projet
38
+ npx ncf-kit translate-json [--apply] textes du site (messages/<langue>.json, titres du registre) traduits par IA
38
39
  npx ncf-kit translations [export] [--out <fichier>] champs « À traduire » → JSON (texte source et actuel)
39
40
  npx ncf-kit translations apply <fichier> écrit les traductions dans les brouillons
40
41
 
@@ -378,6 +379,37 @@ async function doctor() {
378
379
  config.includes('ncfMainDocuments(')
379
380
  ? ok('Langues : panneau de Presentation', 'ncfMainDocuments')
380
381
  : ko('Langues : panneau de Presentation', need('ncfMainDocuments dans presentationTool', 'en changeant de langue dans l\'aperçu, le panneau de droite doit éditer le document de cette langue', 'resolve: {mainDocuments: defineDocuments(ncfMainDocuments(ncfOptions, {siteRoutes: routes}))} (voir sanity.config.ts du starter).'))
382
+ // Textes du site par langue : un fichier de messages et un titre de registre par
383
+ // langue (sinon une langue s'afficherait dans la langue principale sans le dire).
384
+ if (webPkg) {
385
+ const webEnv = parseEnv(read(join(web, '.env.local')))
386
+ const webLocales = String(webEnv.NEXT_PUBLIC_LOCALES || '').split(',').map((l) => l.trim()).filter(Boolean)
387
+ if (webLocales.length && webLocales.join(',') !== locales.join(','))
388
+ ko('Langues : studio = site', `studio ${locales.join(',')} ≠ site (web/.env.local) ${webLocales.join(',')} : mêmes langues, même ordre (la 1re est la langue principale), aussi dans Vercel.`)
389
+ const messagesDir = join(web, 'i18n', 'messages')
390
+ if (existsSync(messagesDir)) {
391
+ const missingFiles = locales.filter((l) => !existsSync(join(messagesDir, `${l}.json`)))
392
+ missingFiles.length
393
+ ? ko('Langues : textes du site', need(`un fichier de textes par langue (${missingFiles.map((l) => `messages/${l}.json`).join(', ')})`, 'sinon la langue s\'affiche dans la langue principale', 'npx ncf-kit translate-json --apply (depuis studio/), puis relire et committer.'))
394
+ : ok('Langues : textes du site', `messages/{${locales.join(',')}}.json`)
395
+ }
396
+ const routesFile = join(web, 'app', 'lib', 'site-routes.json')
397
+ if (existsSync(routesFile)) {
398
+ let missingTitles = 0
399
+ const visit = (v) => {
400
+ if (Array.isArray(v)) v.forEach(visit)
401
+ else if (v && typeof v === 'object') {
402
+ const keys = Object.keys(v)
403
+ if (keys.length && keys.includes(locales[0]) && keys.every((k) => /^[a-z]{2}(-[A-Za-z]{2})?$/.test(k))) missingTitles += locales.filter((l) => v[l] === undefined).length
404
+ else Object.values(v).forEach(visit)
405
+ }
406
+ }
407
+ visit(JSON.parse(read(routesFile) || '{}'))
408
+ missingTitles
409
+ ? ko('Langues : titres du registre', need('un titre par langue dans site-routes.json', `${missingTitles} manquant(s)`, 'npx ncf-kit translate-json --apply.'))
410
+ : ok('Langues : titres du registre', 'complets')
411
+ }
412
+ }
381
413
  const rules = read(join(root, 'CLAUDE.md'))
382
414
  rules && !/trois règles/i.test(rules) && warn('Langues : consignes', need('les trois règles des langues dans CLAUDE.md', 'Claude ne les connaîtrait pas dans ce projet', 'recopier le bloc « LANGUES » du CLAUDE.md du starter.'))
383
415
  }
@@ -420,6 +452,22 @@ async function doctor() {
420
452
  const workflows = walk(join(root, '.github', 'workflows'))
421
453
  const captures = workflows.find((f) => /public\/sections/.test(read(f)))
422
454
  captures ? ok('Captures des composants', captures.replace(root + '/', '')) : warn('Captures des composants', "aucun workflow ne produit public/sections/<bloc>.png : l'onglet Composants affichera « Pas de capture ». Reprendre .github/workflows/section-screenshots.yml du starter.")
455
+ // Chaque section a SA vraie capture (jamais un dessin), tenue à jour chaque nuit.
456
+ {
457
+ const options = read(join(web, 'app', 'lib', 'section-options.json'))
458
+ if (options) {
459
+ const expected = (JSON.parse(options).sections ?? []).map((x) => String(x.type).replace(/^section\./, ''))
460
+ const missing = expected.filter((name) => !existsSync(join(web, 'public', 'sections', `${name}.png`)))
461
+ missing.length
462
+ ? ko('Captures des sections', `le kit a besoin d'une vraie capture par section (menu d'insertion, onglet Composants) ; le projet n'en a pas pour : ${missing.join(', ')}. Pousser une modification de section (le workflow les génère) ou lancer « Captures des sections » dans GitHub Actions.`)
463
+ : ok('Captures des sections', `${expected.length} section(s), une capture chacune`)
464
+ if (captures && !/schedule:/.test(read(captures)))
465
+ warn('Captures des sections', "le workflow ne tourne pas chaque nuit : une valeur par défaut changée dans le Studio ne se verrait pas dans la capture. Ajouter `schedule: - cron: \"0 3 * * *\"` (voir le starter).")
466
+ }
467
+ const studioFiles2 = walk(studio)
468
+ const drawn = studioFiles2.find((f) => /data:image\/svg\+xml/.test(read(f)) && /previewImageUrl|blockPreview|blockThumb/.test(read(f)))
469
+ if (drawn) warn('Captures des sections', `${drawn.replace(root + '/', '')} dessine des vignettes (SVG) : le Studio doit montrer la vraie capture (${'${SITE}'}/sections/<type>.png).`)
470
+ }
423
471
 
424
472
  /* En ligne */
425
473
  if (!offline) {
@@ -430,6 +478,45 @@ async function doctor() {
430
478
  const studioPkg = read(join(studio, 'package.json'))
431
479
  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
480
  }
481
+ // Contenus par langue : chaque document de la langue principale a sa version dans
482
+ // chaque langue, et les valeurs par défaut des composants existent par langue.
483
+ {
484
+ const locales = String(env.SANITY_STUDIO_LOCALES || '').split(',').map((l) => l.trim()).filter(Boolean)
485
+ const projectId = env.SANITY_STUDIO_PROJECT_ID
486
+ const dataset = env.SANITY_STUDIO_DATASET || 'production'
487
+ const token = sanityToken()
488
+ if (locales.length > 1 && projectId && token) {
489
+ const q = async (query, params = {}) => {
490
+ const url = new URL(`https://${projectId}.api.sanity.io/v2025-02-19/data/query/${dataset}`)
491
+ url.searchParams.set('query', query)
492
+ url.searchParams.set('perspective', 'raw')
493
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(`$${k}`, JSON.stringify(v))
494
+ const r = await request(url, {headers: {authorization: `Bearer ${token}`}})
495
+ return r.ok ? r.body.result : null
496
+ }
497
+ const main = locales[0]
498
+ const excluded = ['translation.metadata', 'ncfBoardLayout', 'ncfTranslationTodo', 'componentDefaults']
499
+ const sources = await q(`*[language == $main && !(_id in path("drafts.**")) && !(_type in $excluded)]._id`, {main, excluded})
500
+ const metas = await q(`*[_type == "translation.metadata"]{"refs": translations[]{"lang": coalesce(language, _key), "id": value._ref}}`)
501
+ if (Array.isArray(sources) && Array.isArray(metas)) {
502
+ const langsOf = new Map()
503
+ for (const m of metas) {
504
+ const langs = new Set((m.refs ?? []).map((r) => r.lang))
505
+ for (const r of m.refs ?? []) langsOf.set(r.id, langs)
506
+ }
507
+ const gaps = locales.slice(1).map((l) => [l, sources.filter((id) => !langsOf.get(id)?.has(l)).length]).filter(([, n]) => n)
508
+ gaps.length
509
+ ? ko('Langues : contenus', `le kit a besoin que chaque langue ait toutes les pages de la langue principale (${main.toUpperCase()}) ; ${gaps.map(([l, n]) => `${l.toUpperCase()} : ${n} document(s) sans version`).join(', ')} : Studio → Pages → Languages → « Translate with AI and publish ».`)
510
+ : ok('Langues : contenus', `${sources.length} document(s) ${main.toUpperCase()}, chacun dans ${locales.length - 1} autre(s) langue(s)`)
511
+ const defaultsLangs = (await q(`*[_type == "componentDefaults" && !(_id in path("drafts.**"))].language`)) ?? []
512
+ const noDefaults = locales.filter((l) => !defaultsLangs.includes(l))
513
+ if (defaultsLangs.length)
514
+ noDefaults.length
515
+ ? ko('Langues : valeurs par défaut', `valeurs par défaut des composants absentes en ${noDefaults.join(', ').toUpperCase()} : Studio → Pages → Languages (crée et traduit). Après un nouveau composant : npm run defaults:fill -- --apply, puis Languages.`)
516
+ : ok('Langues : valeurs par défaut', `une par langue (${locales.join(', ')})`)
517
+ }
518
+ }
519
+ }
433
520
  // Purge du cache à la publication : webhook Sanity vers la PRODUCTION
434
521
  // (/api/revalidate), qui relaie à la préprod. Sans lui, rien ne se met à jour
435
522
  // sur le site avant le prochain build.
@@ -643,6 +730,109 @@ async function checkDeploy({quiet = false} = {}) {
643
730
  return {level: 'ok', detail: `${app.appHost ?? appId}.sanity.studio`}
644
731
  }
645
732
 
733
+ // ─── translate-json : textes du site (fichiers de messages, titres du registre) ───
734
+ // Complète par IA (service du kit, même clé de projet que le Studio) ce qui manque
735
+ // dans une langue, depuis la langue PRINCIPALE (1re de SANITY_STUDIO_LOCALES) :
736
+ // - web/i18n/messages/<langue>.json : clés absentes (les valeurs existantes ne sont
737
+ // jamais modifiées) ; fichier créé s'il n'existe pas ;
738
+ // - web/app/lib/site-routes.json : chaque objet par langue ({fr, en}) reçoit les
739
+ // langues manquantes.
740
+ // Par défaut : simulation ; --apply écrit. Depuis studio/ (lit son .env).
741
+ async function translateJson() {
742
+ const studioDir = resolve(flag('dir') ?? process.cwd())
743
+ const root = dirname(studioDir)
744
+ const web = resolve(flag('web') ?? join(root, 'web'))
745
+ const env = {...parseEnv(read(join(studioDir, '.env'))), ...parseEnv(read(join(studioDir, '.env.production.local')))}
746
+ const locales = String(flag('locales') ?? env.SANITY_STUDIO_LOCALES ?? '').split(',').map((l) => l.trim()).filter(Boolean)
747
+ const main = flag('main') ?? locales[0]
748
+ const apply = has('apply')
749
+ if (locales.length < 2 || !main) fail('Site monolingue (SANITY_STUDIO_LOCALES) : rien à traduire.')
750
+ const key = env.SANITY_STUDIO_NCF_PROJECT_KEY
751
+ if (!key) fail('SANITY_STUDIO_NCF_PROJECT_KEY absent : `npx ncf-kit setup` d\'abord (clé du service du kit).')
752
+ const endpoint = (flag('endpoint') ?? env.SANITY_STUDIO_NCF_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/$/, '')
753
+ const translate = async (to, texts) => {
754
+ const out = []
755
+ for (let i = 0; i < texts.length; i += 200) {
756
+ const r = await request(`${endpoint}/translate`, {
757
+ method: 'POST',
758
+ headers: {'content-type': 'application/json'},
759
+ body: JSON.stringify({key, from: main, to, texts: texts.slice(i, i + 200)}),
760
+ })
761
+ if (!r.ok || !Array.isArray(r.body.texts)) fail(`Traduction refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 200)}`)
762
+ out.push(...r.body.texts)
763
+ }
764
+ return out
765
+ }
766
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v)
767
+ let changes = 0
768
+
769
+ // 1. Fichiers de messages.
770
+ const messagesDir = join(web, 'i18n', 'messages')
771
+ const mainFile = join(messagesDir, `${main}.json`)
772
+ if (existsSync(mainFile)) {
773
+ const source = JSON.parse(readFileSync(mainFile, 'utf8'))
774
+ for (const locale of locales.filter((l) => l !== main)) {
775
+ const file = join(messagesDir, `${locale}.json`)
776
+ const target = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}
777
+ const missing = []
778
+ const walk = (src, tgt, path) => {
779
+ for (const [k, v] of Object.entries(src)) {
780
+ if (isObj(v)) {
781
+ if (!isObj(tgt[k])) tgt[k] = {}
782
+ walk(v, tgt[k], [...path, k])
783
+ } else if (Array.isArray(v)) {
784
+ if (!Array.isArray(tgt[k])) missing.push({holder: tgt, key: k, value: v})
785
+ } else if (tgt[k] === undefined) missing.push({holder: tgt, key: k, value: v})
786
+ }
787
+ }
788
+ walk(source, target, [])
789
+ if (!missing.length) continue
790
+ // Chaînes traduites ; tableaux de chaînes traduits élément par élément ; le reste recopié.
791
+ const strings = []
792
+ for (const m of missing) {
793
+ if (typeof m.value === 'string') strings.push(m.value)
794
+ else if (Array.isArray(m.value)) for (const x of m.value) if (typeof x === 'string') strings.push(x)
795
+ }
796
+ const translated = apply ? await translate(locale, strings) : strings
797
+ let n = 0
798
+ for (const m of missing) {
799
+ if (typeof m.value === 'string') m.holder[m.key] = translated[n++]
800
+ else if (Array.isArray(m.value)) m.holder[m.key] = m.value.map((x) => (typeof x === 'string' ? translated[n++] : x))
801
+ else m.holder[m.key] = m.value
802
+ }
803
+ changes += missing.length
804
+ console.log(`${apply ? '✔' : '•'} messages/${locale}.json : ${missing.length} texte(s) ${apply ? 'traduit(s)' : 'à traduire'}`)
805
+ if (apply) writeFileSync(file, `${JSON.stringify(target, null, 2)}\n`)
806
+ }
807
+ } else console.log(`(pas de ${mainFile.replace(root + '/', '')} : fichiers de messages ignorés)`)
808
+
809
+ // 2. Titres par langue du registre des pages.
810
+ const routesFile = join(web, 'app', 'lib', 'site-routes.json')
811
+ if (existsSync(routesFile)) {
812
+ const routes = JSON.parse(readFileSync(routesFile, 'utf8'))
813
+ const maps = []
814
+ const visit = (v) => {
815
+ if (Array.isArray(v)) v.forEach(visit)
816
+ else if (isObj(v)) {
817
+ const keys = Object.keys(v)
818
+ if (keys.length && keys.includes(main) && keys.every((k) => /^[a-z]{2}(-[A-Za-z]{2})?$/.test(k)) && typeof v[main] === 'string') maps.push(v)
819
+ else Object.values(v).forEach(visit)
820
+ }
821
+ }
822
+ visit(routes)
823
+ for (const locale of locales.filter((l) => l !== main)) {
824
+ const todo = maps.filter((m) => m[locale] === undefined)
825
+ if (!todo.length) continue
826
+ const translated = apply ? await translate(locale, todo.map((m) => m[main])) : todo.map((m) => m[main])
827
+ todo.forEach((m, i) => (m[locale] = translated[i]))
828
+ changes += todo.length
829
+ console.log(`${apply ? '✔' : '•'} site-routes.json : ${todo.length} titre(s) ${locale} ${apply ? 'traduit(s)' : 'à traduire'}`)
830
+ }
831
+ if (apply && changes) writeFileSync(routesFile, `${JSON.stringify(routes, null, 2)}\n`)
832
+ }
833
+ console.log(changes ? (apply ? '\nRelire le diff, puis committer.' : '\nSimulation : relancer avec --apply pour traduire et écrire.') : 'Rien à traduire : chaque langue est complète.')
834
+ }
835
+
646
836
  if (command === 'setup') {
647
837
  setup().catch((error) => fail(error?.message ?? String(error)))
648
838
  } else if (command === 'doctor') {
@@ -655,6 +845,8 @@ if (command === 'setup') {
655
845
  if (r.level === 'ko') process.exit(1)
656
846
  })
657
847
  .catch((error) => fail(error?.message ?? String(error)))
848
+ } else if (command === 'translate-json') {
849
+ translateJson().catch((error) => fail(error?.message ?? String(error)))
658
850
  } else if (command === 'translations') {
659
851
  translations().catch((error) => fail(error?.message ?? String(error)))
660
852
  } else if (command === 'check-environments') {
package/dist/index.d.ts CHANGED
@@ -418,6 +418,19 @@ export declare const kitSchemaTypes: ({
418
418
  type: "string";
419
419
  }[];
420
420
  readOnly: true;
421
+ } | {
422
+ name: "machine";
423
+ title: string;
424
+ type: "array";
425
+ readOnly: true;
426
+ of: {
427
+ type: "object";
428
+ name: string;
429
+ fields: {
430
+ name: string;
431
+ type: "string";
432
+ }[];
433
+ }[];
421
434
  })[];
422
435
  preview: {
423
436
  select: {
@@ -1348,7 +1361,7 @@ export declare function ActorName(props: {
1348
1361
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
1349
1362
  * le vérifie.
1350
1363
  */
1351
- export declare const KIT_VERSION = "2.29.2";
1364
+ export declare const KIT_VERSION = "2.30.1";
1352
1365
  /**
1353
1366
  * Données de la page proposées comme colonnes.
1354
1367
  *