@nocode-factory/sanity-kit 2.56.0 → 2.59.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.
Files changed (47) hide show
  1. package/README.md +45 -8
  2. package/bin/item-types.mjs +131 -0
  3. package/bin/ncf-kit.mjs +121 -2
  4. package/dist/{finalUrl-IXF3zbT9.js → finalUrl-DYyjKCjh.js} +2 -1
  5. package/dist/finalUrl-DYyjKCjh.js.map +1 -0
  6. package/dist/{fixCrossLanguageReferences-CDczoic9.js → fixCrossLanguageReferences-C4A61VWW.js} +2 -2
  7. package/dist/{fixCrossLanguageReferences-CDczoic9.js.map → fixCrossLanguageReferences-C4A61VWW.js.map} +1 -1
  8. package/dist/{fixCrossLanguageReferences-C1VsmGsJ.d.ts → fixCrossLanguageReferences-CfFDSTD5.d.ts} +8 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +7240 -7011
  11. package/dist/index.js.map +1 -1
  12. package/dist/inherited-DZvM35P6.js +101 -0
  13. package/dist/inherited-DZvM35P6.js.map +1 -0
  14. package/dist/jsonld.js +1 -1
  15. package/dist/protocol-Bl7Yj2Ro.js +31 -0
  16. package/dist/protocol-Bl7Yj2Ro.js.map +1 -0
  17. package/dist/schema.d.ts +1 -1
  18. package/dist/schema.js +2 -2
  19. package/dist/web-edit.d.ts +192 -0
  20. package/dist/web-edit.js +144 -0
  21. package/dist/web-edit.js.map +1 -0
  22. package/dist/web-editing.d.ts +51 -0
  23. package/dist/web-editing.js +693 -0
  24. package/dist/web-editing.js.map +1 -0
  25. package/package.json +22 -2
  26. package/scripts/use-client.mjs +1 -1
  27. package/src/config/resolve.ts +1 -0
  28. package/src/config/types.ts +7 -1
  29. package/src/form/AssetSourceBrowser.tsx +68 -39
  30. package/src/index.ts +12 -5
  31. package/src/lib/i18nTemplates.ts +38 -4
  32. package/src/tools/collections/CollectionTable.tsx +116 -89
  33. package/src/tools/presentation/PagesNavigator.tsx +150 -56
  34. package/src/ui/PreviewEditBridge.tsx +74 -0
  35. package/src/version.ts +1 -1
  36. package/src/web/edit/ImageReplaceLayer.tsx +174 -0
  37. package/src/web/edit/InlineTextEditor.tsx +365 -0
  38. package/src/web/edit/InlineTextOverlay.tsx +43 -0
  39. package/src/web/edit/PreviewEditing.tsx +191 -0
  40. package/src/web/edit/index.ts +18 -0
  41. package/src/web/edit/inherited.ts +174 -0
  42. package/src/web/edit/labels.ts +37 -0
  43. package/src/web/edit/protocol.ts +47 -0
  44. package/src/web/edit/store.ts +98 -0
  45. package/src/web/edit/targets.ts +186 -0
  46. package/src/web/editing.ts +18 -0
  47. package/dist/finalUrl-IXF3zbT9.js.map +0 -1
package/README.md CHANGED
@@ -35,7 +35,8 @@ reste d'avant la 2.0.0 (figé en 1.8.0) : le retirer.
35
35
  | Site, rendu des sections | `applyDefaults(section, defaults, isDraft ? reattributeTo(source, section._key) : undefined)` ; défauts lus avec `componentDefaultsQuery(types, projection)` |
36
36
  | Site, design system | page `/design-system/composant?type=<nom>` (rendu réel d'un composant, voir le starter) |
37
37
  | Studio, redirections | structure : `redirectsStructure(S, {icon})` (sous-dossiers Manual / Slug changes / Languages) ; type `redirect` : `const c = redirectConflicts({siteRoutes, i18n: {defaultLocale}})`, `from` → `rule.custom(c.from)`, `to` → `rule.custom(c.to)` (publication refusée en cas de conflit) |
38
- | Studio, collections | structure : vue table (tri, filtres par colonne, export CSV) — `.child(ncfCollectionTable(S, options, type))` sur une entrée de collection, ou `...ncfCollections(S, context, options)` pour la découverte auto |
38
+ | Studio, collections | structure : vue table (tri, recherche, export CSV) + switch vue liste — `.child(ncfCollectionTable(S, options, type))` sur une entrée de collection, ou `...ncfCollections(S, context, options)` pour la découverte auto |
39
+ | Site, édition sur place (aperçu) | `<VisualEditing components={ncfOverlayComponents} …/>` + `<NcfPreviewEditing labels={…} />` (`/web/editing`) ; requêtes en brouillon : `annotateImageEditTargets(data, sourceMap, {studioUrl})` ; sections : `withPreviewEditTargets(reattributeTo(…), source, key, collected, {studioUrl})`, `rekeyOwnImageTargets`, `<script {...inheritedEditScriptProps(entry)} />` ; images : `imageEditAttributes(image)`, `imageAlt(image)` (`/web/edit`). Voir « Édition sur place dans l'aperçu ». |
39
40
 
40
41
  Puis, depuis `studio/` :
41
42
 
@@ -50,13 +51,13 @@ Zéro ✖ = projet complet. Sortie 1 sinon (utilisable en CI).
50
51
  Cliquer une collection dans l'onglet **Structure** ouvre une **table** plutôt que
51
52
  la liste native : une colonne par champ du CMS (texte, nombre, booléen, date et
52
53
  **références** résolues en titre), ajout/masquage des colonnes, colonnes
53
- **redimensionnables** (poignée) et **déplaçables** (glisser l'en-tête), **tri** et
54
- **filtre** par colonne, recherche globale, **export CSV** de la vue courante et un
55
- bouton **« + »** de création. Un **switch Liste / Table** en haut bascule entre la
56
- vue dense et une liste compacte (titre + sous-titre, façon liste native). Lecture
57
- seule sur les lignes : cliquer une ligne ouvre le document **en volet enfant** (à
58
- droite ; les volets précédents se réduisent sans se fermer). Les colonnes sont
59
- tirées du schéma — rien à déclarer.
54
+ **redimensionnables** (poignée) et **déplaçables** (glisser l'en-tête), **tri** par
55
+ colonne, **recherche globale**, **export CSV** de la vue courante et un bouton
56
+ **« + »** de création. Un **switch Liste / Table** en haut bascule entre la table
57
+ dense et une **vue liste façon Sanity** (vignette du type, titre, chemin et pastille
58
+ de statut publié/brouillon). Lecture seule sur les lignes : cliquer une ligne ouvre
59
+ le document **en volet enfant** (à droite ; les volets précédents se réduisent sans
60
+ se fermer). Les colonnes sont tirées du schéma — rien à déclarer.
60
61
 
61
62
  Trois façons de la brancher dans le résolveur de structure :
62
63
 
@@ -167,6 +168,42 @@ Les outils de schéma sont aussi dans l'entrée `@nocode-factory/sanity-kit/sche
167
168
 
168
169
  `npx ncf-kit doctor` vérifie chaque branchement.
169
170
 
171
+ ## Édition sur place dans l'aperçu (Presentation)
172
+
173
+ Dans l'aperçu du Studio, en **Edit mode** :
174
+
175
+ - **Texte** (champ chaîne, ligne ou passage en italique d'un titre en texte riche) : crayon
176
+ au survol ; au clic, un champ de saisie prend la place exacte du texte, dans sa
177
+ typographie. Entrée ou clic ailleurs = enregistré dans le **brouillon** (patch du seul
178
+ champ), Échap = annulé. Rien n'est publié.
179
+ - **Texte hérité** des valeurs par défaut du composant : l'éditeur part de la valeur par
180
+ défaut EXACTE (jamais du texte affiché, que le composant met en forme). Une liste
181
+ héritée (lignes d'un titre, titre en texte riche sans lien) est recopiée dans la page au
182
+ premier enregistrement ; la valeur par défaut ne change jamais.
183
+ - **Image** (alt rempli ou non, même sous un dégradé ou un titre en plein cadre) :
184
+ « Replace this image » au survol ; au clic, le Studio ouvre la médiathèque en quasi plein
185
+ écran (masonry, dossiers, recherche). Cadrage et point focal retirés.
186
+ - **Browse mode** : un clic suit les liens, comme sur le site. Interrupteur du kit en bas
187
+ à gauche de l'aperçu (mémorisé) ; un projet peut brancher le sien :
188
+ `<NcfPreviewEditing editMode={() => …} />`.
189
+
190
+ **Dépendances du site** : `@sanity/visual-editing` et `@sanity/mutate` déclarés dans
191
+ `web/package.json`, à la MÊME version que celle de next-sanity, puis `npm dedupe` : deux
192
+ copies = deux connexions au Studio, l'éditeur enregistrerait dans le vide. `doctor` le
193
+ vérifie.
194
+
195
+ Libellés anglais par défaut : passer ceux du projet (`labels`). Couleurs : variables CSS
196
+ `--ncf-edit-accent`, `--ncf-edit-chip`, `--ncf-edit-font`.
197
+
198
+ Le pont côté Studio (message de l'aperçu, médiathèque) est monté par le plugin : rien à
199
+ brancher. Seules les origines des environnements du kit (`environments`, `previewUrl`)
200
+ sont écoutées, depuis une fenêtre affichée par le Studio.
201
+
202
+ **Éléments de liste sans `_type`** (écrits par script) : le site les affiche, mais le
203
+ formulaire du Studio plante en les ouvrant et l'aperçu ne peut pas les éditer.
204
+ `npx ncf-kit item-types` les liste (sortie 1), `--apply` les corrige par patch ciblé ;
205
+ `doctor` le vérifie.
206
+
170
207
  ## Test prod / préprod (bloquant)
171
208
 
172
209
  Le kit livre le test qui garantit que la production n'affiche **jamais** de brouillon
@@ -0,0 +1,131 @@
1
+ // ÉLÉMENTS DE LISTE SANS `_type` : tout élément d'une liste d'objets (cartes,
2
+ // lieux, chiffres clés, lignes de tableau...) porte le `_type` que le schéma
3
+ // déclare pour la liste. Le Studio le pose toujours lui-même ; un élément écrit
4
+ // par SCRIPT sans `_type` passe inaperçu sur le site (qui ne lit que les champs),
5
+ // mais casse l'édition :
6
+ // - formulaire : « Could not render the document editor » dès qu'on ouvre
7
+ // l'élément ;
8
+ // - Presentation : l'élément n'est plus relié au schéma (pas d'édition sur place).
9
+ //
10
+ // Module pur (sans dépendance) : parcourt un document avec le schéma EXTRAIT
11
+ // (`sanity schema extract`, format TypeGen) et liste les éléments sans `_type`,
12
+ // avec le `_type` attendu quand il n'y a pas d'ambiguïté. Utilisé par
13
+ // `npx ncf-kit item-types` et par `doctor` ; testé (test/itemTypes.test.ts).
14
+
15
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v)
16
+
17
+ export function createTypeIndex(schema) {
18
+ const byName = new Map()
19
+ for (const entry of schema) byName.set(entry.name, entry.type === 'document' ? {type: 'object', attributes: entry.attributes} : entry.value)
20
+
21
+ // Résout un nœud jusqu'à un objet / tableau / union / scalaire (références
22
+ // « inline » et attributs hérités par `rest` fusionnés).
23
+ function resolve(node, seen = new Set()) {
24
+ if (!node) return undefined
25
+ if (node.type === 'inline' && node.name) {
26
+ if (seen.has(node.name)) return undefined
27
+ seen.add(node.name)
28
+ return resolve(byName.get(node.name), seen)
29
+ }
30
+ if (node.type === 'object' && node.rest) {
31
+ const rest = resolve(node.rest, seen)
32
+ return {type: 'object', attributes: {...(rest?.attributes ?? {}), ...(node.attributes ?? {})}}
33
+ }
34
+ return node
35
+ }
36
+
37
+ const literalType = (node) => {
38
+ const t = node?.attributes?._type?.value
39
+ return t && t.type === 'string' && typeof t.value === 'string' ? t.value : null
40
+ }
41
+
42
+ function objectMembers(arrayNode) {
43
+ const out = []
44
+ const add = (n) => {
45
+ const r = resolve(n)
46
+ if (!r) return
47
+ if (r.type === 'union') for (const m of r.of) add(m)
48
+ else if (r.type === 'object') out.push(r)
49
+ }
50
+ add(arrayNode.of)
51
+ return out
52
+ }
53
+
54
+ function pickObject(node, value) {
55
+ const r = resolve(node)
56
+ if (!r) return undefined
57
+ if (r.type === 'object') return r
58
+ if (r.type === 'union') {
59
+ const members = r.of.map((m) => resolve(m)).filter((m) => m?.type === 'object')
60
+ return members.find((m) => literalType(m) === value._type) ?? (members.length === 1 ? members[0] : undefined)
61
+ }
62
+ return undefined
63
+ }
64
+ function pickArray(node) {
65
+ const r = resolve(node)
66
+ if (!r) return undefined
67
+ if (r.type === 'array') return r
68
+ if (r.type === 'union') return r.of.map((m) => resolve(m)).find((m) => m?.type === 'array')
69
+ return undefined
70
+ }
71
+
72
+ function walk(value, node, path, out) {
73
+ if (Array.isArray(value)) {
74
+ const arr = pickArray(node)
75
+ if (!arr) return
76
+ const members = objectMembers(arr)
77
+ value.forEach((item, index) => {
78
+ if (!isObj(item)) return
79
+ const key = typeof item._key === 'string' ? item._key : null
80
+ const itemPath = key ? `${path}[_key=="${key}"]` : `${path}[${index}]`
81
+ let member
82
+ if (typeof item._type === 'string') member = members.find((m) => literalType(m) === item._type)
83
+ else if (members.length > 0) {
84
+ // Un élément sans `_ref` n'est pas une référence (liste « carte OU carte liée »).
85
+ const candidates = members.filter((m) => (literalType(m) === 'reference') === (typeof item._ref === 'string'))
86
+ const expected = candidates.length === 1 ? literalType(candidates[0]) : null
87
+ out.push({path: itemPath, expected, ...(key ? {} : {noKey: true})})
88
+ member = candidates.length === 1 ? candidates[0] : undefined
89
+ }
90
+ if (member) walkObject(item, member, itemPath, out)
91
+ })
92
+ return
93
+ }
94
+ if (!isObj(value)) return
95
+ const obj = pickObject(node, value)
96
+ if (obj) walkObject(value, obj, path, out)
97
+ }
98
+
99
+ function walkObject(value, node, path, out) {
100
+ for (const [k, child] of Object.entries(value)) {
101
+ if (k.startsWith('_')) continue
102
+ const attr = node.attributes?.[k]
103
+ if (attr) walk(child, attr.value, path ? `${path}.${k}` : k, out)
104
+ }
105
+ }
106
+
107
+ /** Éléments de liste sans `_type` d'un document : [{path, expected, noKey?}]. */
108
+ function missingTypes(doc) {
109
+ const root = byName.get(String(doc._type))
110
+ if (!root) return []
111
+ const out = []
112
+ walkObject(doc, resolve(root) ?? root, '', out)
113
+ return out
114
+ }
115
+
116
+ return {missingTypes}
117
+ }
118
+
119
+ /**
120
+ * Patch CIBLÉ d'un document : `set` du seul `_type` de chaque élément (et d'un
121
+ * `_key` quand il manque aussi), verrouillé sur la révision lue. Null si rien à faire.
122
+ */
123
+ export function itemTypesPatch(doc, missing, newKey) {
124
+ const set = {}
125
+ for (const m of missing) {
126
+ if (!m.expected) continue
127
+ set[`${m.path}._type`] = m.expected
128
+ if (m.noKey) set[`${m.path}._key`] = newKey()
129
+ }
130
+ return Object.keys(set).length ? {patch: {id: doc._id, ifRevisionID: doc._rev, set}} : null
131
+ }
package/bin/ncf-kit.mjs CHANGED
@@ -14,6 +14,8 @@
14
14
  import {readFileSync, writeFileSync, existsSync, readdirSync, statSync} from 'node:fs'
15
15
  import {dirname, join, resolve} from 'node:path'
16
16
  import {homedir} from 'node:os'
17
+ import {createRequire} from 'node:module'
18
+ const require_child = () => createRequire(import.meta.url)('node:child_process')
17
19
 
18
20
  const DEFAULT_ENDPOINT = 'https://dkoxgivytgsmvqmjvmjt.supabase.co/functions/v1'
19
21
  const SANITY_API = 'https://api.sanity.io'
@@ -34,10 +36,11 @@ function usage(code = 0) {
34
36
  npx ncf-kit setup --types page,homePage [options] active le projet, clé du journal, webhook
35
37
  npx ncf-kit doctor [--web <dossier>] [--offline] vérifie que le projet est complet
36
38
  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
39
+ npx ncf-kit check-deploy [--skip-data] avant sanity deploy : l'appId est bien le Studio de CE projet, alerte _type
38
40
  npx ncf-kit translate-json [--from <langue>] [--apply] textes du site (messages/<langue>.json, titres du registre) traduits par IA
39
41
  npx ncf-kit translations [export] [--out <fichier>] champs « À traduire » → JSON (texte source et actuel)
40
42
  npx ncf-kit translations apply <fichier> écrit les traductions dans les brouillons
43
+ npx ncf-kit item-types [--apply] éléments de liste sans _type (écrits par script) ; --apply corrige
41
44
 
42
45
  Depuis le dossier du studio (celui de sanity.config.ts et de .env).
43
46
 
@@ -337,6 +340,16 @@ async function doctor() {
337
340
  if (!config.includes('ncfPresentationComponents('))
338
341
  warn('Presentation : liste des pages', "le kit a besoin de ncfPresentationComponents dans presentationTool pour afficher la liste des pages à gauche de l'aperçu ; le projet ne l'a pas : presentationTool({components: ncfPresentationComponents(ncfOptions), ...}).")
339
342
  else ok('Presentation : liste des pages', 'ncfPresentationComponents')
343
+ // Vue TABLEUR des collections (kit >= 2.54) : elle se branche dans la structure du
344
+ // Studio du projet (le kit ne peut pas modifier une structure écrite par le projet).
345
+ // Une mise à jour du kit ne l'apporte donc pas à un projet créé avant : on le dit.
346
+ {
347
+ const studioSources = walk(studio).filter((f) => /\.(m?[jt]sx?)$/.test(f))
348
+ const wired = studioSources.some((f) => /\bncfCollectionTable\(|\bncfCollections\(/.test(read(f)))
349
+ wired
350
+ ? ok('Collections : vue tableur', 'ncfCollectionTable / ncfCollections dans la structure')
351
+ : warn('Collections : vue tableur', "le kit propose une vue tableur des collections (tri, recherche, colonnes, export CSV, création) ; le projet ne la branche pas : dans la structure du Studio, .child(ncfCollectionTable(S, ncfOptions, type, {id, title})) sur chaque collection (voir collectionTable et byLanguage(..., asTable) dans studio/sanity.config.ts du starter). Les pages gardent la liste native.")
352
+ }
340
353
  if (!config.includes('ncfAllowedOrigins')) ko('Origines autorisées', "presentationTool sans allowOrigins: ncfAllowedOrigins(options) : l'aperçu de la préproduction s'affiche mais reste muet.")
341
354
  else ok('Origines autorisées', 'ncfAllowedOrigins')
342
355
  if (/preprodUrl\s*:\s*false/.test(config)) ko('Préproduction désactivée', "sanity.config contient preprodUrl: false : la préproduction conventionnelle est retirée. À n'utiliser que si le projet n'en a vraiment pas.")
@@ -530,6 +543,27 @@ async function doctor() {
530
543
  }
531
544
 
532
545
  /* En ligne */
546
+ // Édition sur place (/web/editing) : le kit doit voir le MÊME @sanity/visual-editing que
547
+ // next-sanity. Deux copies = deux connexions au Studio : l'éditeur enregistrerait dans
548
+ // le vide (aucune erreur visible).
549
+ {
550
+ const usesEditing = (() => {
551
+ try {
552
+ const {execFileSync} = require_child()
553
+ return execFileSync('grep', ['-rl', '--include=*.tsx', '--include=*.ts', 'sanity-kit/web/editing', join(web, 'components'), join(web, 'app')], {encoding: 'utf8'}).trim().length > 0
554
+ } catch {
555
+ return false
556
+ }
557
+ })()
558
+ if (usesEditing) {
559
+ const top = read(join(web, 'node_modules', '@sanity', 'visual-editing', 'package.json'))
560
+ const nested = read(join(web, 'node_modules', 'next-sanity', 'node_modules', '@sanity', 'visual-editing', 'package.json'))
561
+ const declared = /"@sanity\/visual-editing"\s*:/.test(read(join(web, 'package.json'))) && /"@sanity\/mutate"\s*:/.test(read(join(web, 'package.json')))
562
+ if (!top || !declared) ko('Édition sur place', "le kit a besoin de @sanity/visual-editing et @sanity/mutate déclarés dans web/package.json (même version que next-sanity) : npm install @sanity/visual-editing @sanity/mutate, puis npm dedupe.")
563
+ else if (nested) ko('Édition sur place', `deux copies de @sanity/visual-editing (${JSON.parse(top).version} et ${JSON.parse(nested).version} dans next-sanity) : l'éditeur de l'aperçu enregistrerait dans le vide. Dans web/ : npm dedupe.`)
564
+ else ok('Édition sur place', `@sanity/visual-editing ${JSON.parse(top).version}, une seule copie (partagée avec next-sanity)`)
565
+ }
566
+ }
533
567
  if (!offline) {
534
568
  {
535
569
  const r = await checkDeploy({quiet: true})
@@ -577,6 +611,14 @@ async function doctor() {
577
611
  }
578
612
  }
579
613
  }
614
+ // Éléments de liste sans _type (écrits par script) : le formulaire du Studio plante
615
+ // dès qu'on les ouvre et l'aperçu ne peut pas les éditer sur place.
616
+ {
617
+ const scan = sanityToken() ? await scanItemTypes(studio, {quiet: true}) : null
618
+ if (!scan) warn('Éléments de liste typés', 'non vérifié : jeton Sanity, SANITY_STUDIO_PROJECT_ID ou `sanity schema extract` indisponible.')
619
+ else if (scan.count) ko('Éléments de liste typés', `${scan.count} élément(s) de liste sans _type dans ${scan.todo.length} document(s) (écrits par script) : le formulaire du Studio plante en les ouvrant (« Could not render the document editor »). npx ncf-kit item-types pour la liste, --apply pour corriger.`)
620
+ else ok('Éléments de liste typés', `tous les éléments de liste ont leur _type (${scan.docs} documents)`)
621
+ }
580
622
  // Purge du cache à la publication : webhook Sanity vers la PRODUCTION
581
623
  // (/api/revalidate), qui relaie à la préprod. Sans lui, rien ne se met à jour
582
624
  // sur le site avant le prochain build.
@@ -671,6 +713,69 @@ function patchPath(doc, path) {
671
713
  return out
672
714
  }
673
715
 
716
+ /**
717
+ * Éléments de liste sans `_type` (bin/item-types.mjs) dans TOUS les documents
718
+ * (brouillons et versions compris). Schéma extrait par `sanity schema extract`
719
+ * dans node_modules/.cache (jamais versionné). Renvoie null si impossible.
720
+ */
721
+ async function scanItemTypes(dir, {quiet = false} = {}) {
722
+ const env = {...parseEnv(read(join(dir, '.env'))), ...parseEnv(read(join(dir, '.env.production.local')))}
723
+ const projectId = env.SANITY_STUDIO_PROJECT_ID ?? process.env.SANITY_STUDIO_PROJECT_ID
724
+ const dataset = flag('dataset') ?? env.SANITY_STUDIO_DATASET ?? process.env.SANITY_STUDIO_DATASET ?? 'production'
725
+ const token = sanityToken()
726
+ if (!projectId || !token) return null
727
+ const {spawnSync} = await import('node:child_process')
728
+ const {mkdirSync} = await import('node:fs')
729
+ const rel = join('node_modules', '.cache', 'ncf-kit', 'schema.json')
730
+ mkdirSync(join(dir, dirname(rel)), {recursive: true})
731
+ const extract = spawnSync('npx', ['--no-install', 'sanity', 'schema', 'extract', '--force', '--path', rel], {cwd: dir, encoding: 'utf8', stdio: quiet ? 'pipe' : ['ignore', 'ignore', 'inherit']})
732
+ if (extract.status !== 0 || !existsSync(join(dir, rel))) return null
733
+ const {createTypeIndex} = await import('./item-types.mjs')
734
+ const {missingTypes} = createTypeIndex(JSON.parse(readFileSync(join(dir, rel), 'utf8')))
735
+ const api = `https://${projectId}.api.sanity.io/v2025-02-19/data`
736
+ const url = new URL(`${api}/query/${dataset}`)
737
+ url.searchParams.set('query', '*[!(_type match "system.*") && !(_type match "sanity.*") && !(_id in path("_.**"))]')
738
+ url.searchParams.set('perspective', 'raw')
739
+ const r = await request(url, {headers: {authorization: `Bearer ${token}`}})
740
+ if (!r.ok) return null
741
+ const docs = r.body.result ?? []
742
+ const todo = docs.map((doc) => ({doc, missing: missingTypes(doc)})).filter((x) => x.missing.length)
743
+ return {api, dataset, token, docs: docs.length, todo, count: todo.reduce((n, x) => n + x.missing.length, 0)}
744
+ }
745
+
746
+ async function itemTypes() {
747
+ const dir = resolve(flag('dir') ?? process.cwd())
748
+ if (!existsSync(join(dir, 'package.json'))) fail(`Pas de package.json dans ${dir} : lance la commande depuis le dossier du studio, ou passe --dir.`)
749
+ if (!sanityToken()) fail('Aucun jeton Sanity : lance `npx sanity login`, ou exporte SANITY_AUTH_TOKEN.')
750
+ const scan = await scanItemTypes(dir)
751
+ if (!scan) fail('Contrôle impossible : SANITY_STUDIO_PROJECT_ID absent, `sanity schema extract` en échec, ou lecture Sanity refusée.')
752
+ if (!scan.count) {
753
+ console.log(`✓ Éléments de liste : tous ont leur _type (${scan.docs} documents).`)
754
+ return
755
+ }
756
+ for (const {doc, missing} of scan.todo) {
757
+ console.log(`${doc._id} (${doc._type}) : ${missing.length} élément(s) sans _type`)
758
+ for (const m of missing) console.log(` ${m.path} -> ${m.expected ?? '? (plusieurs types possibles)'}`)
759
+ }
760
+ if (!has('apply')) {
761
+ console.error(`\n✖ ${scan.count} élément(s) de liste sans _type dans ${scan.todo.length} document(s).`)
762
+ console.error(' Correction : npx ncf-kit item-types --apply (patch ciblé), puis corriger le script qui les a écrits.')
763
+ process.exit(1)
764
+ }
765
+ const {itemTypesPatch} = await import('./item-types.mjs')
766
+ const {randomBytes} = await import('node:crypto')
767
+ const mutations = scan.todo.map(({doc, missing}) => itemTypesPatch(doc, missing, () => randomBytes(6).toString('hex'))).filter(Boolean)
768
+ const headers = {authorization: `Bearer ${scan.token}`, 'content-type': 'application/json'}
769
+ const r = await request(`${scan.api}/mutate/${scan.dataset}`, {method: 'POST', headers, body: JSON.stringify({mutations})})
770
+ if (!r.ok) fail(`Écriture Sanity refusée (${r.status}) : ${JSON.stringify(r.body).slice(0, 300)}`)
771
+ const manual = scan.todo.flatMap(({doc, missing}) => missing.filter((m) => !m.expected).map((m) => `${doc._id} ${m.path}`))
772
+ console.log(`\n✓ ${scan.count - manual.length} _type ajouté(s) par patch ciblé.`)
773
+ if (manual.length) {
774
+ console.error(`✖ Plusieurs types possibles, à corriger dans le Studio :\n ${manual.join('\n ')}`)
775
+ process.exit(1)
776
+ }
777
+ }
778
+
674
779
  async function translations() {
675
780
  const sub = args[1] && !args[1].startsWith('--') ? args[1] : 'export'
676
781
  const dir = resolve(flag('dir') ?? process.cwd())
@@ -927,14 +1032,28 @@ if (command === 'setup') {
927
1032
  doctor().catch((error) => fail(error?.message ?? String(error)))
928
1033
  } else if (command === 'check-deploy') {
929
1034
  checkDeploy()
930
- .then((r) => {
1035
+ .then(async (r) => {
931
1036
  const icon = {ok: '✔', warn: '⚠', ko: '✖'}[r.level]
932
1037
  console.log(`${icon} Studio à déployer : ${r.detail}`)
933
1038
  if (r.level === 'ko') process.exit(1)
1039
+ // Avant chaque déploiement du Studio : éléments de liste sans _type (le formulaire
1040
+ // planterait en les ouvrant). ALERTE seulement : un déploiement livre du code, il
1041
+ // ne réécrit jamais des données sans qu'on le voie ; la correction reste un geste
1042
+ // volontaire (npx ncf-kit item-types --apply). `--skip-data` pour la sauter.
1043
+ if (has('skip-data')) return
1044
+ const scan = await scanItemTypes(resolve(flag('dir') ?? process.cwd()), {quiet: true}).catch(() => null)
1045
+ if (!scan) console.log('⚠ Éléments de liste typés : non vérifié (jeton Sanity ou `sanity schema extract` indisponible).')
1046
+ else if (scan.count)
1047
+ console.log(
1048
+ `⚠ Éléments de liste typés : ${scan.count} élément(s) sans _type dans ${scan.todo.length} document(s) : le formulaire du Studio plantera en les ouvrant. Corriger : npx ncf-kit item-types (liste), puis --apply. Le déploiement continue.`,
1049
+ )
1050
+ else console.log(`✔ Éléments de liste typés : aucun écart (${scan.docs} documents).`)
934
1051
  })
935
1052
  .catch((error) => fail(error?.message ?? String(error)))
936
1053
  } else if (command === 'translate-json') {
937
1054
  translateJson().catch((error) => fail(error?.message ?? String(error)))
1055
+ } else if (command === 'item-types') {
1056
+ itemTypes().catch((error) => fail(error?.message ?? String(error)))
938
1057
  } else if (command === 'translations') {
939
1058
  translations().catch((error) => fail(error?.message ?? String(error)))
940
1059
  } else if (command === 'check-environments') {
@@ -101,6 +101,7 @@ function resolveConfig(input) {
101
101
  path: normalizePath(f.path),
102
102
  localized: f.localized ?? null
103
103
  })),
104
+ collectionLabels: Object.fromEntries((input.siteRoutes?.collections ?? []).filter((c) => c.type && c.section).map((c) => [c.type, c.section])),
104
105
  redirectType: input.redirectType?.trim() || "redirect",
105
106
  pageTypeNames: pageTypes.map((p) => p.type).filter(Boolean),
106
107
  pageBuilderField: input.pageBuilderField?.trim() || "sections",
@@ -276,4 +277,4 @@ function finalPath(input, pageType, config, redirects) {
276
277
  }
277
278
  export { DEFAULT_PAGE_BUILDER_FIELD as _, depth as a, segments as c, normalizePath as d, resolveConfig as f, DEFAULT_INTERNAL_FIELDS as g, DEFAULT_I18N as h, redirectMapOf as i, toPath as l, DEFAULT_COMPONENT_PREVIEW as m, followRedirects as n, pageTypeFor as o, DEFAULT_BOARD_TAGS as p, redirectKey as r, parentPath as s, finalPath as t, toUrl as u, DEFAULT_SLUG_FIELD as v, DEFAULT_TITLE_FIELD as y };
278
279
 
279
- //# sourceMappingURL=finalUrl-IXF3zbT9.js.map
280
+ //# sourceMappingURL=finalUrl-DYyjKCjh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"finalUrl-DYyjKCjh.js","names":[],"sources":["../src/config/defaults.ts","../src/config/resolve.ts","../src/lib/paths.ts","../src/lib/finalUrl.ts"],"sourcesContent":["import type {\n NcfBoardTag,\n NcfInternalField,\n NcfComponentPreviewConfig,\n NcfI18nConfig,\n NcfToolsConfig,\n} from './types'\n\nexport const DEFAULT_PAGE_BUILDER_FIELD = 'sections'\nexport const DEFAULT_SLUG_FIELD = 'slug'\nexport const DEFAULT_TITLE_FIELD = 'title'\nexport const DEFAULT_BLOCK_NAMESPACE = ''\n\n/**\n * Chemins essayés pour savoir si une page est indexable. Le premier\n * correspond à la convention du starter (`seo.noindex`), le second couvre les\n * schémas qui portent le drapeau à la racine.\n */\nexport const DEFAULT_NOINDEX_FIELDS = ['seo.noindex', 'noindex']\n\n// Aucune langue par défaut : la langue principale (master) vient TOUJOURS du projet\n// (`defaultLocale`, sinon la première de `locales`). Un site peut avoir le français,\n// l'anglais ou toute autre langue comme master.\nexport const DEFAULT_I18N: Omit<Required<NcfI18nConfig>, 'defaultsSourceLocale' | 'defaultLocale'> = {\n field: 'language',\n locales: [],\n}\n\n/**\n * Convention NoCode Factory : page `/design-system` dans le front, captures\n * dans `/sections/<nom>.png` générées au push par GitHub Actions.\n */\nexport const DEFAULT_COMPONENT_PREVIEW: Required<NcfComponentPreviewConfig> = {\n provider: 'designSystemPage',\n path: '/design-system',\n anchor: '{name}',\n thumbnail: '/sections/{name}.png',\n defaultsType: 'componentDefaults',\n live: '/design-system/composant?type={name}',\n}\n\nexport const DEFAULT_TOOLS: Required<NcfToolsConfig> = {\n pages: true,\n components: true,\n history: true,\n designSystem: true,\n assets: true,\n}\n\n/**\n * Outils rangés dans « Plus » : Vision (console GROQ) et la planification\n * (« Scheduled drafts » quand les Releases sont désactivées, « Releases » sinon :\n * le même outil, nommé `releases` ; `schedules` couvre les anciennes versions).\n */\nexport const DEFAULT_TOOLBAR_MORE = ['vision', 'releases', 'schedules']\n\n/**\n * Étiquettes de suivi par défaut : l'avancement d'une refonte, pas un statut\n * de publication. Elles vivent dans le document de disposition du kit, donc\n * aucun schéma client n'est modifié.\n */\nexport const DEFAULT_BOARD_TAGS: NcfBoardTag[] = [\n {id: 'en-cours', label: 'In progress', color: '#f5a623'},\n {id: 'fait', label: 'Done', color: '#43d675'},\n {id: 'a-relire', label: 'To review', color: '#2276fc'},\n {id: 'a-refondre', label: 'To rework', color: '#f03e3e'},\n]\n\n/**\n * Colonnes de gestion interne par défaut. Volontairement peu nombreuses : ce\n * sont celles qu'on redemande sur tous les projets. `internalFields` les\n * remplace entièrement.\n */\nexport const DEFAULT_INTERNAL_FIELDS: NcfInternalField[] = [\n {id: 'owner', label: 'Owner', type: 'text'},\n {id: 'audience', label: 'Audience', type: 'text'},\n {id: 'role', label: 'Page role', type: 'text'},\n]\n\n/**\n * Service du kit, hébergé par NoCode Factory.\n *\n * Renseigné d'office pour qu'un Studio n'ait rien à configurer : il se\n * signale au démarrage, et c'est ce qui permet de savoir quels projets\n * utilisent le kit. `endpoint` le remplace pour une instance privée.\n */\nexport const DEFAULT_SERVICE_ENDPOINT = 'https://dkoxgivytgsmvqmjvmjt.supabase.co/functions/v1'\n","import {\n DEFAULT_BLOCK_NAMESPACE,\n DEFAULT_BOARD_TAGS,\n DEFAULT_INTERNAL_FIELDS,\n DEFAULT_SERVICE_ENDPOINT,\n DEFAULT_COMPONENT_PREVIEW,\n DEFAULT_I18N,\n DEFAULT_NOINDEX_FIELDS,\n DEFAULT_PAGE_BUILDER_FIELD,\n DEFAULT_SLUG_FIELD,\n DEFAULT_TITLE_FIELD,\n DEFAULT_TOOLBAR_MORE, DEFAULT_TOOLS,\n} from './defaults'\nimport type {\n NcfEnvironment,\n NcfKitConfig,\n NcfPageTypeConfig,\n ResolvedKitConfig,\n ResolvedPageType,\n} from './types'\n\nconst trimTrailingSlash = (url: string) => url.replace(/\\/+$/, '')\n\n/** Garantit un chemin absolu ('accueil' -> '/accueil', '' -> '/'). */\nexport const normalizePath = (path: string): string => {\n const trimmed = path.trim()\n if (!trimmed || trimmed === '/') return '/'\n const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n return withSlash.length > 1 ? trimTrailingSlash(withSlash) : withSlash\n}\n\nfunction resolvePageType(\n entry: NcfPageTypeConfig,\n defaults: {slugField: string; titleField: string},\n): ResolvedPageType {\n if (typeof entry === 'string') {\n return {\n type: entry.trim(),\n slugField: defaults.slugField,\n path: null,\n pathPrefix: null,\n localizedPrefixes: null,\n titleField: defaults.titleField,\n }\n }\n\n // `path` gagne sur `slugField` : une page à chemin fixe (l'accueil) n'a pas\n // de slug à lire, même si le type en porte un par ailleurs.\n const path = typeof entry.path === 'string' ? normalizePath(entry.path) : null\n const slugField =\n entry.slugField === null ? null : (entry.slugField?.trim() || defaults.slugField)\n\n // Un préfixe vide ou '/' vaut « à la racine » : pas de préfixe.\n const prefix = typeof entry.pathPrefix === 'string' ? normalizePath(entry.pathPrefix) : '/'\n\n return {\n type: (entry.type ?? '').trim(),\n slugField: path ? null : slugField,\n path,\n // Conservé même avec `path` (qui gagne au calcul du chemin) : la validation\n // peut ainsi signaler le préfixe inutile.\n pathPrefix: prefix === '/' ? null : prefix,\n localizedPrefixes: entry.localizedPrefixes\n ? Object.fromEntries(Object.entries(entry.localizedPrefixes).map(([l, p]) => [l, normalizePath(p) === '/' ? '' : normalizePath(p)]))\n : null,\n titleField: entry.titleField?.trim() || defaults.titleField,\n }\n}\n\n/** Applique les valeurs par défaut. Ne valide rien : voir `validateConfig`. */\nexport function resolveConfig(input: NcfKitConfig): ResolvedKitConfig {\n const slugField = input.slugField?.trim() || DEFAULT_SLUG_FIELD\n const titleField = input.titleField?.trim() || DEFAULT_TITLE_FIELD\n\n const pageTypes = (Array.isArray(input.pageTypes) ? input.pageTypes : []).map((entry) =>\n resolvePageType(entry, {slugField, titleField}),\n )\n\n const i18n =\n input.i18n === false || input.i18n === undefined\n ? null\n : (() => {\n const locales = (input.i18n.locales ?? DEFAULT_I18N.locales).map((l) => l.trim()).filter(Boolean)\n // Master : `defaultLocale`, sinon la première langue. Jamais une langue écrite\n // dans le kit (absente : signalé par validateConfig).\n const defaultLocale = input.i18n.defaultLocale?.trim() || locales[0] || ''\n return {\n field: input.i18n.field?.trim() || DEFAULT_I18N.field,\n defaultLocale,\n locales,\n // Valeurs par défaut des composants : écrites dans la langue master,\n // traduites vers les autres (sauf choix explicite du projet).\n defaultsSourceLocale: input.i18n.defaultsSourceLocale?.trim() || defaultLocale,\n }\n })()\n\n return {\n pageTypes,\n codedPages: (input.siteRoutes?.fixed ?? [])\n .filter((f) => f.pageSlug && !f.homePage && !f.system && !f.notFound)\n .map((f) => ({pageSlug: f.pageSlug as string, path: normalizePath(f.path), localized: f.localized ?? null})),\n collectionLabels: Object.fromEntries((input.siteRoutes?.collections ?? []).filter((c) => c.type && c.section).map((c) => [c.type as string, c.section as string])),\n redirectType: input.redirectType?.trim() || 'redirect',\n pageTypeNames: pageTypes.map((p) => p.type).filter(Boolean),\n pageBuilderField: input.pageBuilderField?.trim() || DEFAULT_PAGE_BUILDER_FIELD,\n blockNamespace: input.blockNamespace ?? DEFAULT_BLOCK_NAMESPACE,\n noindexFields: input.noindexField\n ? [input.noindexField].flat().map((field) => field.trim()).filter(Boolean)\n : DEFAULT_NOINDEX_FIELDS,\n previewUrl: input.previewUrl ? trimTrailingSlash(input.previewUrl.trim()) : null,\n environments: resolveEnvironments(input),\n pageThumbnail: input.pageThumbnail?.trim() || null,\n i18n,\n componentPreview: {\n provider: input.componentPreview?.provider ?? DEFAULT_COMPONENT_PREVIEW.provider,\n path: input.componentPreview?.path ?? DEFAULT_COMPONENT_PREVIEW.path,\n anchor: input.componentPreview?.anchor ?? DEFAULT_COMPONENT_PREVIEW.anchor,\n thumbnail: input.componentPreview?.thumbnail ?? DEFAULT_COMPONENT_PREVIEW.thumbnail,\n defaultsType: input.componentPreview?.defaultsType ?? DEFAULT_COMPONENT_PREVIEW.defaultsType,\n live: input.componentPreview?.live ?? DEFAULT_COMPONENT_PREVIEW.live,\n },\n serviceEndpoint:\n input.serviceEndpoint === false\n ? null\n : trimTrailingSlash((input.serviceEndpoint || DEFAULT_SERVICE_ENDPOINT).trim()),\n history: input.history?.projectKey?.trim()\n ? {\n projectKey: input.history.projectKey.trim(),\n endpoint: trimTrailingSlash(\n (input.history.endpoint || input.serviceEndpoint || DEFAULT_SERVICE_ENDPOINT).trim(),\n ),\n }\n : null,\n // Le JSON-LD IA s'appuie sur le même service que la traduction : sans\n // `history.projectKey`, il n'y a pas d'IA à brancher.\n jsonLd:\n input.jsonLd?.enabled && input.history?.projectKey?.trim()\n ? {field: input.jsonLd.field?.trim() || 'jsonLd'}\n : null,\n tools: {...DEFAULT_TOOLS, ...input.tools},\n moreTools: input.moreTools === false ? [] : (input.moreTools ?? DEFAULT_TOOLBAR_MORE),\n boardTags: input.boardTags?.length ? input.boardTags : DEFAULT_BOARD_TAGS,\n internalFields: input.internalFields?.length\n ? input.internalFields\n : DEFAULT_INTERNAL_FIELDS,\n // Additif : le schéma du client fournit déjà l'essentiel, ceci ne sert\n // qu'à ce qu'un parcours de schéma ne sait pas exprimer.\n documentColumns: (input.documentColumns ?? []).map((column) => ({\n key: column.key.trim(),\n label: column.label?.trim() || column.key.trim(),\n paths: [column.path].flat().map((path) => path.trim()).filter(Boolean),\n type: column.type ?? 'text',\n })),\n collections: {\n include: (input.collections?.include ?? []).map((name) => name.trim()).filter(Boolean),\n exclude: (input.collections?.exclude ?? []).map((name) => name.trim()).filter(Boolean),\n labels: input.collections?.labels ?? {},\n },\n }\n}\n\n\n/**\n * Préproduction déduite de la production, par convention.\n *\n * NoCode Factory assigne à chaque projet un domaine Vercel **fixe** pour la\n * branche `preprod`, de la forme `preview-<projet>.vercel.app`. Fixe parce\n * qu'un lien de partage doit survivre au commit suivant : une URL de\n * déploiement change à chaque poussée, un domaine assigné non.\n *\n * La déduire évite de la déclarer neuf fois. Elle n'est proposée que pour un\n * hôte Vercel — ailleurs la convention ne s'applique pas — et `environments`\n * la remplace dès qu'on la déclare explicitement.\n */\nexport function conventionalPreprodUrl(previewUrl: string | null): string | null {\n if (!previewUrl) return null\n try {\n const url = new URL(previewUrl)\n if (!url.hostname.endsWith('.vercel.app')) return null\n // Une préproduction ne se dérive pas d'une préproduction.\n if (url.hostname.startsWith('preview-')) return null\n return `${url.protocol}//preview-${url.hostname}`\n } catch {\n return null\n }\n}\n\n/**\n * Environnements d'aperçu.\n *\n * `previewUrl` en fournit toujours un, nommé « Production » : un projet qui\n * n'en déclare pas d'autres doit quand même pouvoir basculer entre brouillons\n * et contenu en ligne.\n *\n * Quand `environments` mentionne déjà `previewUrl`, on ne le double pas.\n */\nfunction resolveEnvironments(input: NcfKitConfig): NcfEnvironment[] {\n const declared = (input.environments ?? [])\n .map((environment) => ({\n id: environment.id.trim(),\n label: environment.label?.trim() || environment.id.trim(),\n url: trimTrailingSlash((environment.url ?? '').trim()),\n }))\n .filter((environment) => environment.id && environment.url)\n\n const preview = input.previewUrl ? trimTrailingSlash(input.previewUrl.trim()) : null\n if (!preview) return declared\n\n const production = declared.some((environment) => environment.url === preview)\n ? []\n : [{id: 'production', label: 'Production', url: preview}]\n\n // La préproduction conventionnelle complète la liste, sauf si le projet en\n // a déjà déclaré une — sa déclaration explicite fait foi.\n //\n // On compare l'identifiant autant que l'URL : un projet dont le domaine ne\n // suit pas exactement la convention déclare bien un `preprod`, à une autre\n // adresse. En n'écartant que par l'URL, on en ajoutait un second portant le\n // même identifiant, et la configuration devenait invalide.\n const conventional = conventionalPreprodUrl(preview)\n const hasPreprod =\n declared.some(\n (environment) => environment.url === conventional || environment.id === 'preprod',\n ) || input.preprodUrl === false\n\n const preprod =\n conventional && !hasPreprod\n ? [{id: 'preprod', label: 'Staging', url: conventional}]\n : []\n\n return [...production, ...preprod, ...declared]\n}\n","import {normalizePath} from '../config/resolve'\nimport type {ResolvedI18n, ResolvedPageType} from '../config/types'\n\nexport interface PathInput {\n /** Valeur du champ slug (`slug.current`). Peut contenir des `/`. */\n slug?: string | null\n /** Chemin fixe du type de page, s'il en a un. */\n path?: string | null\n /** Préfixe d'URL du type de page ('/blog'), devant le slug. */\n pathPrefix?: string | null\n /** Préfixe par langue (dossiers traduits) : celui de `locale` gagne sur `pathPrefix`. */\n localizedPrefixes?: Record<string, string> | null\n /** Langue du document. */\n locale?: string | null\n}\n\n/**\n * Chemin d'une page sur le site. Le chemin fixe l'emporte sur le slug, le\n * préfixe du type se place devant le slug ('/blog' + 'mon-article'), et la\n * langue par défaut n'est pas préfixée (convention Next.js du starter).\n */\nexport function toPath(input: PathInput, i18n: ResolvedI18n | null): string | null {\n const localized = input.locale ? input.localizedPrefixes?.[input.locale] : undefined\n const raw = localized !== undefined ? localized : input.pathPrefix\n const prefix = typeof raw === 'string' && raw ? normalizePath(raw) : '/'\n const base =\n typeof input.path === 'string' && input.path\n ? normalizePath(input.path)\n : input.slug\n ? normalizePath(prefix === '/' ? input.slug : `${prefix}/${input.slug.replace(/^\\/+/, '')}`)\n : null\n\n if (base === null) return null\n if (!i18n || !input.locale || input.locale === i18n.defaultLocale) return base\n return base === '/' ? `/${input.locale}` : `/${input.locale}${base}`\n}\n\n/** URL absolue d'une page, ou `null` si le front n'est pas configuré. */\nexport function toUrl(previewUrl: string | null, path: string | null): string | null {\n if (!previewUrl || path === null) return null\n return path === '/' ? previewUrl : `${previewUrl}${path}`\n}\n\n/** Segments d'un chemin : '/services/plomberie' -> ['services', 'plomberie']. */\nexport function segments(path: string): string[] {\n return path.split('/').filter(Boolean)\n}\n\n/** Profondeur dans l'arborescence. '/' vaut 0. */\nexport function depth(path: string): number {\n return segments(path).length\n}\n\n/**\n * Chemin du parent, ou `null` à la racine. Sert au placement automatique du\n * board : '/services/plomberie' -> '/services'.\n */\nexport function parentPath(path: string): string | null {\n const parts = segments(path)\n if (parts.length === 0) return null\n if (parts.length === 1) return '/'\n return `/${parts.slice(0, -1).join('/')}`\n}\n\n/** Le type de page correspondant à un document. */\nexport function pageTypeFor(\n type: string,\n pageTypes: ResolvedPageType[],\n): ResolvedPageType | undefined {\n return pageTypes.find((p) => p.type === type)\n}\n","import type {ResolvedKitConfig, ResolvedPageType} from '../config/types'\nimport {toPath} from './paths'\n\n/** Clé de comparaison des redirections (comme le site) : minuscules, sans « / » final, sans ? ni #. */\nexport const redirectKey = (path: string) => {\n const clean = (path.trim().split(/[?#]/)[0] ?? '').toLowerCase()\n return clean.length > 1 ? clean.replace(/\\/+$/, '') : clean\n}\n\n/** Table des redirections du Studio : départ (normalisé) -> destination. */\nexport type RedirectMap = Map<string, string>\n\nexport function redirectMapOf(rows: readonly {from?: string | null; to?: string | null}[]): RedirectMap {\n const map: RedirectMap = new Map()\n for (const r of rows) {\n if (!r.from?.startsWith('/') || !r.to) continue\n const key = redirectKey(r.from)\n if (key !== redirectKey(r.to) && !map.has(key)) map.set(key, r.to.trim())\n }\n return map\n}\n\n/** Destination finale d'une adresse (chaîne de redirections suivie, boucles ignorées). */\nexport function followRedirects(path: string, redirects: RedirectMap | null | undefined): string {\n if (!redirects?.size) return path\n let current = path\n const seen = new Set<string>()\n for (let hop = 0; hop < 5; hop++) {\n const next = redirects.get(redirectKey(current))\n if (!next || seen.has(next)) break\n seen.add(next)\n current = next\n }\n return current\n}\n\n/**\n * URL FINALE d'une page (celle qui répond 200, sans redirection) : adresse réelle\n * d'une page codée (registre `siteRoutes`, dossier de la langue), sinon dossier et\n * slug de la langue ; puis destination si l'adresse est le départ d'une redirection\n * du Studio. Affichée partout dans le kit (onglet Pages, board, Presentation, slug).\n */\nexport function finalPath(\n input: {slug: string | null; locale: string | null},\n pageType: ResolvedPageType | null | undefined,\n config: Pick<ResolvedKitConfig, 'i18n' | 'codedPages'>,\n redirects?: RedirectMap | null,\n): string | null {\n if (!pageType) return null\n const atRoot = !pageType.path && !pageType.pathPrefix && !pageType.localizedPrefixes\n const coded = atRoot && input.slug ? config.codedPages.find((c) => c.pageSlug === input.slug) : undefined\n const path = coded\n ? toPath({path: (input.locale && coded.localized?.[input.locale]) || coded.path, locale: input.locale}, config.i18n)\n : toPath(\n {slug: input.slug, path: pageType.path, pathPrefix: pageType.pathPrefix, localizedPrefixes: pageType.localizedPrefixes, locale: input.locale},\n config.i18n,\n )\n return path === null ? null : followRedirects(path, redirects)\n}\n"],"mappings":"AAQA,MAAa,6BAA6B,YAC7B,qBAAqB,QACrB,sBAAsB,SAQtB,yBAAyB,CAAC,eAAe,SAAS,GAKlD,eAAwF;CACnG,OAAO;CACP,SAAS,CAAC;AACZ,GAMa,4BAAiE;CAC5E,UAAU;CACV,MAAM;CACN,QAAQ;CACR,WAAW;CACX,cAAc;CACd,MAAM;AACR,GAEa,gBAA0C;CACrD,OAAO;CACP,YAAY;CACZ,SAAS;CACT,cAAc;CACd,QAAQ;AACV,GAOa,uBAAuB;CAAC;CAAU;CAAY;AAAW,GAOzD,qBAAoC;CAC/C;EAAC,IAAI;EAAY,OAAO;EAAe,OAAO;CAAS;CACvD;EAAC,IAAI;EAAQ,OAAO;EAAQ,OAAO;CAAS;CAC5C;EAAC,IAAI;EAAY,OAAO;EAAa,OAAO;CAAS;CACrD;EAAC,IAAI;EAAc,OAAO;EAAa,OAAO;CAAS;AACzD,GAOa,0BAA8C;CACzD;EAAC,IAAI;EAAS,OAAO;EAAS,MAAM;CAAM;CAC1C;EAAC,IAAI;EAAY,OAAO;EAAY,MAAM;CAAM;CAChD;EAAC,IAAI;EAAQ,OAAO;EAAa,MAAM;CAAM;AAC/C,GCxDM,qBAAqB,QAAgB,IAAI,QAAQ,QAAQ,EAAE,GAGpD,iBAAiB,SAAyB;CACrD,IAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,WAAW,YAAY,KAAK,OAAO;CACxC,IAAM,YAAY,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI;CAC1D,OAAO,UAAU,SAAS,IAAI,kBAAkB,SAAS,IAAI;AAC/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,IAAI,IAAI,GAAG,KAAG,IAAI,IAAI,KAAK,EAAE,GAAG,KAAK,CAAC;CAC1E;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAc,WAAmD;CAC/F,IAAI,CAAC,WAAW,MAAM,OAAO;CAC7B,IAAI,UAAU,MACR,uBAAO,IAAI,IAAY;CAC7B,KAAK,IAAI,MAAM,GAAG,MAAM,GAAG,OAAO;EAChC,IAAM,OAAO,UAAU,IAAI,YAAY,OAAO,CAAC;EAC/C,IAAI,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG;EAE7B,AADA,KAAK,IAAI,IAAI,GACb,UAAU;CACZ;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,UACd,OACA,UACA,QACA,WACe;CACf,IAAI,CAAC,UAAU,OAAO;CAEtB,IAAM,QADS,CAAC,SAAS,QAAQ,CAAC,SAAS,cAAc,CAAC,SAAS,qBAC3C,MAAM,OAAO,OAAO,WAAW,MAAM,MAAM,EAAE,aAAa,MAAM,IAAI,IAAI,KAAA,GAC1F,OACF,OADS,QACF;EAAC,MAAO,MAAM,UAAU,MAAM,YAAY,MAAM,WAAY,MAAM;EAAM,QAAQ,MAAM;CAAM,IAEjG;EAAC,MAAM,MAAM;EAAM,MAAM,SAAS;EAAM,YAAY,SAAS;EAAY,mBAAmB,SAAS;EAAmB,QAAQ,MAAM;CAAM,GAFxC,OAAO,IAI7G;CACJ,OAAO,SAAS,OAAO,OAAO,gBAAgB,MAAM,SAAS;AAC/D"}
@@ -1,4 +1,4 @@
1
- import { l as toPath } from "./finalUrl-IXF3zbT9.js";
1
+ import { l as toPath } from "./finalUrl-DYyjKCjh.js";
2
2
  import { defineField, defineType } from "sanity";
3
3
  /** Identifiant stable de la redirection d'une version (mise à jour, jamais dupliquée). */
4
4
  const translationRedirectId = (versionId) => `redirect-translation-${versionId.replace(/^drafts\./, "").replace(/[^A-Za-z0-9_-]/g, "-")}`;
@@ -340,4 +340,4 @@ async function fixCrossLanguageReferences(client, options) {
340
340
  }
341
341
  export { componentDefaultsMainDocument as a, defineComponentDefaults as c, syncTranslationRedirects as d, translationRedirectId as f, DEFAULT_COMPONENT_DEFAULTS_TYPE as i, requiredUnlessDefault as l, withSameLanguageReferences as n, componentDefaultsMainDocuments as o, translationRedirectOptions as p, pageTypesFromSiteRoutes as r, defaultsFieldName as s, fixCrossLanguageReferences as t, requiredUnlessDefaultFor as u };
342
342
 
343
- //# sourceMappingURL=fixCrossLanguageReferences-CDczoic9.js.map
343
+ //# sourceMappingURL=fixCrossLanguageReferences-C4A61VWW.js.map