@nocode-factory/sanity-kit 2.43.0 → 2.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { a as componentDefaultsMainDocument, c as defineComponentDefaults, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as fixCrossLanguageReferences, o as componentDefaultsMainDocuments, r as withSameLanguageReferences, s as defaultsFieldName, t as CrossLanguageReport, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-j1qDJWic.js";
1
+ import { c as componentDefaultsMainDocuments, d as requiredUnlessDefault, f as requiredUnlessDefaultFor, i as SiteRoutesRegistry, l as defaultsFieldName, n as fixCrossLanguageReferences, o as DEFAULT_COMPONENT_DEFAULTS_TYPE, r as withSameLanguageReferences, s as componentDefaultsMainDocument, t as CrossLanguageReport, u as defineComponentDefaults } from "./fixCrossLanguageReferences-CFZax-Nb.js";
2
+ import { ComponentType } from "react";
2
3
  import { SanityClient } from "sanity";
4
+ import { ListItemBuilder, StructureBuilder } from "sanity/structure";
3
5
  /**
4
6
  * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
5
7
  *
@@ -78,5 +80,70 @@ export declare function syncTranslationRedirects(client: SanityClient, options:
78
80
  slug?: string | null;
79
81
  language?: string | null;
80
82
  }): Promise<TranslationRedirect[]>;
81
- export { type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type TranslationRedirect, type TranslationRedirectOptions, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, requiredUnlessDefault, requiredUnlessDefaultFor, withSameLanguageReferences };
83
+ /**
84
+ * RÈGLES DES REDIRECTIONS (embarquées par le kit, mêmes dans tous les projets) :
85
+ *
86
+ * 1. Trois familles, rangées chacune dans son sous-dossier du Studio (« Redirects ») :
87
+ * - manuelles : saisies par l'équipe ;
88
+ * - changements de slug : créées à la publication d'un nouveau slug
89
+ * (identifiant `redirect-auto-…`) ;
90
+ * - langues : adresse « slug d'origine » d'une version traduite vers son slug
91
+ * traduit (identifiant `redirect-translation-…`, syncTranslationRedirects).
92
+ * La famille vient de l'identifiant : rien à migrer, rien à saisir.
93
+ *
94
+ * 2. Une redirection EN CONFLIT ne peut pas être publiée (validation, erreur) :
95
+ * - même adresse de départ qu'une autre redirection ;
96
+ * - départ = adresse d'une page en ligne (elle deviendrait inaccessible) ;
97
+ * - destination = départ d'une autre redirection (chaîne : viser l'adresse finale) ;
98
+ * - boucle (la destination ramène au départ) ;
99
+ * - destination identique au départ.
100
+ */
101
+ type RedirectKind = 'manual' | 'slug' | 'translation';
102
+ export declare const TRANSLATION_REDIRECT_PREFIX = "redirect-translation-";
103
+ export declare const SLUG_REDIRECT_PREFIX = "redirect-auto-";
104
+ /** Famille d'une redirection, d'après son identifiant (brouillon compris). */
105
+ export declare function redirectKindOf(id: string | null | undefined): RedirectKind;
106
+ /** Filtre GROQ de chaque famille (à combiner avec `_type == $type`). */
107
+ export declare const REDIRECT_KIND_FILTERS: Record<RedirectKind, string>;
108
+ interface RedirectsStructureOptions {
109
+ /** Type des redirections. Défaut : `redirect`. */
110
+ redirectType?: string;
111
+ /** Titre de l'entrée. Défaut : « Redirects ». */
112
+ title?: string;
113
+ /** Icône de l'entrée (celle du projet). */
114
+ icon?: ComponentType;
115
+ /** Libellés des sous-dossiers (langue du Studio du projet). Défaut : anglais. */
116
+ labels?: Partial<Record<RedirectKind | 'all', string>>;
117
+ }
118
+ /**
119
+ * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création
120
+ * possible), changements de slug et langues (automatiques), puis toutes.
121
+ * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])
122
+ */
123
+ export declare function redirectsStructure(S: StructureBuilder, options?: RedirectsStructureOptions): ListItemBuilder;
124
+ interface RedirectConflictOptions {
125
+ /** Type des redirections. Défaut : `redirect`. */
126
+ redirectType?: string;
127
+ /** Registre des pages du site (site-routes.json) : adresses des pages en ligne. */
128
+ siteRoutes?: SiteRoutesRegistry | null;
129
+ /** Langues : langue principale (sans préfixe) et champ de langue. */
130
+ i18n?: {
131
+ defaultLocale: string;
132
+ field?: string;
133
+ } | null;
134
+ /** Champ slug des pages. Défaut : `slug`. */
135
+ slugField?: string;
136
+ }
137
+ /**
138
+ * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :
139
+ * la publication est bloquée, avec la raison et la redirection en cause).
140
+ * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})
141
+ * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})
142
+ * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})
143
+ */
144
+ export declare function redirectConflicts(options?: RedirectConflictOptions): {
145
+ from(value: unknown, context: unknown): Promise<true | string>;
146
+ to(value: unknown, context: unknown): Promise<true | string>;
147
+ };
148
+ export { type CrossLanguageReport, DEFAULT_COMPONENT_DEFAULTS_TYPE, type RedirectConflictOptions, type RedirectKind, type RedirectsStructureOptions, type TranslationRedirect, type TranslationRedirectOptions, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, requiredUnlessDefault, requiredUnlessDefaultFor, withSameLanguageReferences };
82
149
  //# sourceMappingURL=schema.d.ts.map
package/dist/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { T as DEFAULT_PAGE_BUILDER_FIELD, a as componentDefaultsMainDocuments, c as requiredUnlessDefault, d as translationRedirectId, i as componentDefaultsMainDocument, l as requiredUnlessDefaultFor, n as withSameLanguageReferences, o as defaultsFieldName, r as DEFAULT_COMPONENT_DEFAULTS_TYPE, s as defineComponentDefaults, t as fixCrossLanguageReferences, u as syncTranslationRedirects } from "./fixCrossLanguageReferences-DbkdPSMH.js";
1
+ import { A as DEFAULT_PAGE_BUILDER_FIELD, S as toPath, _ as redirectMapOf, a as componentDefaultsMainDocument, c as defineComponentDefaults, d as syncTranslationRedirects, f as translationRedirectId, g as redirectKey, h as followRedirects, i as DEFAULT_COMPONENT_DEFAULTS_TYPE, l as requiredUnlessDefault, n as withSameLanguageReferences, o as componentDefaultsMainDocuments, r as pageTypesFromSiteRoutes, s as defaultsFieldName, t as fixCrossLanguageReferences, u as requiredUnlessDefaultFor } from "./fixCrossLanguageReferences-DQ6bDuSZ.js";
2
2
  /**
3
3
  * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.
4
4
  *
@@ -74,6 +74,107 @@ function withNcfFormTabs(types, options = {}) {
74
74
  });
75
75
  });
76
76
  }
77
- export { DEFAULT_COMPONENT_DEFAULTS_TYPE, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, formTabOf, requiredUnlessDefault, requiredUnlessDefaultFor, syncTranslationRedirects, translationRedirectId, withNcfFormTabs, withSameLanguageReferences };
77
+ const TRANSLATION_REDIRECT_PREFIX = "redirect-translation-", SLUG_REDIRECT_PREFIX = "redirect-auto-";
78
+ /** Famille d'une redirection, d'après son identifiant (brouillon compris). */
79
+ function redirectKindOf(id) {
80
+ let clean = (id ?? "").replace(/^drafts\./, "");
81
+ return clean.startsWith("redirect-translation-") ? "translation" : clean.startsWith("redirect-auto-") ? "slug" : "manual";
82
+ }
83
+ const idIn = (prefix) => `(_id in path("${prefix}*") || _id in path("drafts.${prefix}*"))`, REDIRECT_KIND_FILTERS = {
84
+ translation: idIn(TRANSLATION_REDIRECT_PREFIX),
85
+ slug: idIn(SLUG_REDIRECT_PREFIX),
86
+ manual: `!${idIn(TRANSLATION_REDIRECT_PREFIX)} && !${idIn(SLUG_REDIRECT_PREFIX)}`
87
+ }, DEFAULT_LABELS = {
88
+ manual: "Manual",
89
+ slug: "Slug changes (automatic)",
90
+ translation: "Languages (automatic)",
91
+ all: "All redirects"
92
+ };
93
+ /**
94
+ * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création
95
+ * possible), changements de slug et langues (automatiques), puis toutes.
96
+ * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])
97
+ */
98
+ function redirectsStructure(S, options = {}) {
99
+ let type = options.redirectType ?? "redirect", title = options.title ?? "Redirects", labels = {
100
+ ...DEFAULT_LABELS,
101
+ ...options.labels
102
+ }, list = (kind, label) => S.listItem().id(`redirects-${kind}`).title(label).schemaType(type).child(S.documentList().id(`redirects-${kind}-list`).title(label).schemaType(type).apiVersion("2024-10-01").filter(`_type == $type && ${REDIRECT_KIND_FILTERS[kind]}`).params({ type }).defaultOrdering([{
103
+ field: "from",
104
+ direction: "asc"
105
+ }]).initialValueTemplates(kind === "manual" ? [S.initialValueTemplateItem(type)] : [])), item = S.listItem().id("redirects").title(title).child(S.list().id("redirects").title(title).items([
106
+ list("manual", labels.manual),
107
+ list("slug", labels.slug),
108
+ list("translation", labels.translation),
109
+ S.divider(),
110
+ S.listItem().id("redirects-all").title(labels.all).schemaType(type).child(S.documentTypeList(type).title(labels.all))
111
+ ]));
112
+ return options.icon ? item.icon(options.icon) : item;
113
+ }
114
+ const clean = (v) => typeof v == "string" ? v.trim() : "";
115
+ async function otherRedirects(ctx, type) {
116
+ let id = (ctx.document?._id ?? "").replace(/^drafts\./, ""), rows = await ctx.getClient({ apiVersion: "2024-10-01" }).withConfig({ perspective: "raw" }).fetch("*[_type == $type && !(_id in [$id, $draft])]{_id, from, to}", {
117
+ type,
118
+ id,
119
+ draft: `drafts.${id}`
120
+ }), byBase = /* @__PURE__ */ new Map();
121
+ for (let r of rows) {
122
+ let base = r._id.replace(/^drafts\./, "");
123
+ (!byBase.has(base) || r._id.startsWith("drafts.")) && byBase.set(base, r);
124
+ }
125
+ return [...byBase.values()];
126
+ }
127
+ const label = (r) => `${clean(r.from)} → ${clean(r.to)}`;
128
+ /**
129
+ * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :
130
+ * la publication est bloquée, avec la raison et la redirection en cause).
131
+ * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})
132
+ * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})
133
+ * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})
134
+ */
135
+ function redirectConflicts(options = {}) {
136
+ let type = options.redirectType ?? "redirect", field = options.i18n?.field ?? "language", slugField = options.slugField ?? "slug", pageTypes = options.siteRoutes ? pageTypesFromSiteRoutes(options.siteRoutes).filter((t) => !t.path) : [], i18n = options.i18n ? {
137
+ field,
138
+ defaultLocale: options.i18n.defaultLocale,
139
+ locales: [],
140
+ defaultsSourceLocale: options.i18n.defaultLocale
141
+ } : null;
142
+ async function pageAt(ctx, path) {
143
+ if (!pageTypes.length) return null;
144
+ let key = redirectKey(path), docs = await ctx.getClient({ apiVersion: "2024-10-01" }).withConfig({ perspective: "published" }).fetch(`*[_type in $types && defined(${slugField}.current)]{_type, title, "slug": ${slugField}.current, "lang": ${field}}`, { types: pageTypes.map((t) => t.type) });
145
+ for (let d of docs) {
146
+ let t = pageTypes.find((p) => p.type === d._type), p = t && toPath({
147
+ slug: d.slug,
148
+ pathPrefix: t.pathPrefix,
149
+ localizedPrefixes: t.localizedPrefixes,
150
+ locale: d.lang
151
+ }, i18n);
152
+ if (p && redirectKey(p) === key) return d.title || p;
153
+ }
154
+ return null;
155
+ }
156
+ return {
157
+ async from(value, context) {
158
+ let ctx = context, from = clean(value);
159
+ if (!from.startsWith("/")) return !0;
160
+ let same = (await otherRedirects(ctx, type)).find((r) => r.from && redirectKey(r.from) === redirectKey(from));
161
+ if (same) return `Conflict: another redirect already starts from this address (${label(same)}). Edit that one instead.`;
162
+ let page = await pageAt(ctx, from);
163
+ return !page || `Conflict: "${from}" is the address of a live page ("${page}"). Redirecting it would make that page unreachable.`;
164
+ },
165
+ async to(value, context) {
166
+ let ctx = context, to = clean(value), from = clean(ctx.document?.from);
167
+ if (!to.startsWith("/")) return !0;
168
+ if (from && redirectKey(from) === redirectKey(to)) return "Conflict: the new address is the same as the old one.";
169
+ let others = await otherRedirects(ctx, type), chained = others.find((r) => r.from && redirectKey(r.from) === redirectKey(to));
170
+ if (chained) {
171
+ let final = followRedirects(to, redirectMapOf(others));
172
+ return from && redirectKey(final) === redirectKey(from) ? `Conflict: loop. "${to}" already redirects back to "${from}" (${label(chained)}).` : `Conflict: "${to}" is itself redirected (${label(chained)}). Point directly to the final address: ${final}`;
173
+ }
174
+ return !0;
175
+ }
176
+ };
177
+ }
178
+ export { DEFAULT_COMPONENT_DEFAULTS_TYPE, REDIRECT_KIND_FILTERS, SLUG_REDIRECT_PREFIX, TRANSLATION_REDIRECT_PREFIX, componentDefaultsMainDocument, componentDefaultsMainDocuments, defaultsFieldName, defineComponentDefaults, fixCrossLanguageReferences, formTabOf, redirectConflicts, redirectKindOf, redirectsStructure, requiredUnlessDefault, requiredUnlessDefaultFor, syncTranslationRedirects, translationRedirectId, withNcfFormTabs, withSameLanguageReferences };
78
179
 
79
180
  //# sourceMappingURL=schema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../src/schema/formTabs.ts"],"sourcesContent":["/**\n * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.\n *\n * Un formulaire de page en une seule colonne mélange le contenu, le page builder et\n * les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un\n * document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.\n * - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,\n * comme l'option du même nom de ncfKit).\n * - SEO : `seo`, `structuredData` et les champs de métadonnées connus.\n * - Settings : réglages de page (`pageOptions`, `options`, `settings`...).\n * - Content : tout le reste (titre, slug, corps, image...).\n * Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son\n * `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.\n *\n * ```ts\n * schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}\n * ```\n */\n\nimport {DEFAULT_PAGE_BUILDER_FIELD} from '../config/defaults'\n\nconst SEO_FIELDS = new Set(['seo', 'structuredData', 'jsonld', 'noindex', 'metaTitle', 'metaDescription', 'ogImage', 'canonical', 'canonicalUrl'])\nconst SETTINGS_FIELDS = new Set(['pageOptions', 'options', 'settings', 'hideFromMenu', 'showInMenu', 'parent', 'publishedAt', 'redirects'])\n\nconst GROUPS = [\n {name: 'content', title: 'Content', default: true},\n {name: 'sections', title: 'Sections'},\n {name: 'seo', title: 'SEO'},\n {name: 'settings', title: 'Settings'},\n] as const\n\ntype Field = {name?: string; group?: unknown; hidden?: unknown}\ntype TypeLike = {type?: string; groups?: unknown; fields?: Field[]}\n\n/** Onglet d'un champ d'après son nom. */\nexport function formTabOf(name: string, pageBuilderField = DEFAULT_PAGE_BUILDER_FIELD): (typeof GROUPS)[number]['name'] {\n if (name === pageBuilderField) return 'sections'\n if (SEO_FIELDS.has(name)) return 'seo'\n if (SETTINGS_FIELDS.has(name)) return 'settings'\n return 'content'\n}\n\nexport function withNcfFormTabs<T>(types: readonly T[], options: {pageBuilderField?: string} = {}): T[] {\n return types.map((input) => {\n const type = input as unknown as TypeLike\n if (type.type !== 'document' || type.groups || !Array.isArray(type.fields)) return input\n // Champ toujours caché (hidden: true) : pas d'onglet (il n'en ferait naître un vide).\n const fields = type.fields.map((field) =>\n field.group || !field.name || field.hidden === true ? field : {...field, group: formTabOf(field.name, options.pageBuilderField)},\n )\n const used = new Set(fields.map((f) => f.group).flat())\n const groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({...g}))\n if (groups.length < 2) return input\n if (!groups.some((g) => 'default' in g && g.default)) (groups[0] as {default?: boolean}).default = true\n return {...type, groups, fields} as unknown as T\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAO;CAAkB;CAAU;CAAW;CAAa;CAAmB;CAAW;CAAa;AAAc,CAAC,GAC3I,kCAAkB,IAAI,IAAI;CAAC;CAAe;CAAW;CAAY;CAAgB;CAAc;CAAU;CAAe;AAAW,CAAC,GAEpI,SAAS;CACb;EAAC,MAAM;EAAW,OAAO;EAAW,SAAS;CAAI;CACjD;EAAC,MAAM;EAAY,OAAO;CAAU;CACpC;EAAC,MAAM;EAAO,OAAO;CAAK;CAC1B;EAAC,MAAM;EAAY,OAAO;CAAU;AACtC;;AAMA,SAAgB,UAAU,MAAc,mBAAmB,4BAA6D;CAItH,OAHI,SAAS,mBAAyB,aAClC,WAAW,IAAI,IAAI,IAAU,QAC7B,gBAAgB,IAAI,IAAI,IAAU,aAC/B;AACT;AAEA,SAAgB,gBAAmB,OAAqB,UAAuC,CAAC,GAAQ;CACtG,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAM,OAAO;EACb,IAAI,KAAK,SAAS,cAAc,KAAK,UAAU,CAAC,MAAM,QAAQ,KAAK,MAAM,GAAG,OAAO;EAEnF,IAAM,SAAS,KAAK,OAAO,KAAK,UAC9B,MAAM,SAAS,CAAC,MAAM,QAAQ,MAAM,WAAW,KAAO,QAAQ;GAAC,GAAG;GAAO,OAAO,UAAU,MAAM,MAAM,QAAQ,gBAAgB;EAAC,CACjI,GACM,OAAO,IAAI,IAAI,OAAO,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAChD,SAAS,OAAO,QAAQ,MAAM,KAAK,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,EAAC,GAAG,EAAC,EAAE;EAGzE,OAFI,OAAO,SAAS,IAAU,SACzB,OAAO,MAAM,MAAM,aAAa,KAAK,EAAE,OAAO,MAAG,OAAQ,EAAE,CAAyB,UAAU,KAC5F;GAAC,GAAG;GAAM;GAAQ;EAAM;CACjC,CAAC;AACH"}
1
+ {"version":3,"file":"schema.js","names":[],"sources":["../src/schema/formTabs.ts","../src/schema/redirects.ts"],"sourcesContent":["/**\n * Onglets du formulaire d'un document : Content, Sections, SEO, Settings.\n *\n * Un formulaire de page en une seule colonne mélange le contenu, le page builder et\n * les réglages SEO : on cherche, on se trompe de champ. Ici, chaque champ d'un\n * document va dans son onglet d'après son nom ; « Content » s'ouvre par défaut.\n * - Sections : le champ du page builder (`pageBuilderField`, défaut `sections`,\n * comme l'option du même nom de ncfKit).\n * - SEO : `seo`, `structuredData` et les champs de métadonnées connus.\n * - Settings : réglages de page (`pageOptions`, `options`, `settings`...).\n * - Content : tout le reste (titre, slug, corps, image...).\n * Un type qui déclare déjà ses `groups` n'est pas touché ; un champ qui a déjà son\n * `group` le garde. Pas d'onglets pour un document qui n'aurait qu'un onglet.\n *\n * ```ts\n * schema: {types: withNcfFormTabs(schemaTypes, {pageBuilderField: 'pageBuilder'})}\n * ```\n */\n\nimport {DEFAULT_PAGE_BUILDER_FIELD} from '../config/defaults'\n\nconst SEO_FIELDS = new Set(['seo', 'structuredData', 'jsonld', 'noindex', 'metaTitle', 'metaDescription', 'ogImage', 'canonical', 'canonicalUrl'])\nconst SETTINGS_FIELDS = new Set(['pageOptions', 'options', 'settings', 'hideFromMenu', 'showInMenu', 'parent', 'publishedAt', 'redirects'])\n\nconst GROUPS = [\n {name: 'content', title: 'Content', default: true},\n {name: 'sections', title: 'Sections'},\n {name: 'seo', title: 'SEO'},\n {name: 'settings', title: 'Settings'},\n] as const\n\ntype Field = {name?: string; group?: unknown; hidden?: unknown}\ntype TypeLike = {type?: string; groups?: unknown; fields?: Field[]}\n\n/** Onglet d'un champ d'après son nom. */\nexport function formTabOf(name: string, pageBuilderField = DEFAULT_PAGE_BUILDER_FIELD): (typeof GROUPS)[number]['name'] {\n if (name === pageBuilderField) return 'sections'\n if (SEO_FIELDS.has(name)) return 'seo'\n if (SETTINGS_FIELDS.has(name)) return 'settings'\n return 'content'\n}\n\nexport function withNcfFormTabs<T>(types: readonly T[], options: {pageBuilderField?: string} = {}): T[] {\n return types.map((input) => {\n const type = input as unknown as TypeLike\n if (type.type !== 'document' || type.groups || !Array.isArray(type.fields)) return input\n // Champ toujours caché (hidden: true) : pas d'onglet (il n'en ferait naître un vide).\n const fields = type.fields.map((field) =>\n field.group || !field.name || field.hidden === true ? field : {...field, group: formTabOf(field.name, options.pageBuilderField)},\n )\n const used = new Set(fields.map((f) => f.group).flat())\n const groups = GROUPS.filter((g) => used.has(g.name)).map((g) => ({...g}))\n if (groups.length < 2) return input\n if (!groups.some((g) => 'default' in g && g.default)) (groups[0] as {default?: boolean}).default = true\n return {...type, groups, fields} as unknown as T\n })\n}\n","import type {ComponentType} from 'react'\nimport type {SanityClient} from 'sanity'\nimport type {StructureBuilder, ListItemBuilder} from 'sanity/structure'\nimport {redirectKey, redirectMapOf, followRedirects} from '../lib/finalUrl'\nimport {toPath} from '../lib/paths'\nimport {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from '../lib/siteRoutes'\n\n/**\n * RÈGLES DES REDIRECTIONS (embarquées par le kit, mêmes dans tous les projets) :\n *\n * 1. Trois familles, rangées chacune dans son sous-dossier du Studio (« Redirects ») :\n * - manuelles : saisies par l'équipe ;\n * - changements de slug : créées à la publication d'un nouveau slug\n * (identifiant `redirect-auto-…`) ;\n * - langues : adresse « slug d'origine » d'une version traduite vers son slug\n * traduit (identifiant `redirect-translation-…`, syncTranslationRedirects).\n * La famille vient de l'identifiant : rien à migrer, rien à saisir.\n *\n * 2. Une redirection EN CONFLIT ne peut pas être publiée (validation, erreur) :\n * - même adresse de départ qu'une autre redirection ;\n * - départ = adresse d'une page en ligne (elle deviendrait inaccessible) ;\n * - destination = départ d'une autre redirection (chaîne : viser l'adresse finale) ;\n * - boucle (la destination ramène au départ) ;\n * - destination identique au départ.\n */\n\nexport type RedirectKind = 'manual' | 'slug' | 'translation'\n\nexport const TRANSLATION_REDIRECT_PREFIX = 'redirect-translation-'\nexport const SLUG_REDIRECT_PREFIX = 'redirect-auto-'\n\n/** Famille d'une redirection, d'après son identifiant (brouillon compris). */\nexport function redirectKindOf(id: string | null | undefined): RedirectKind {\n const clean = (id ?? '').replace(/^drafts\\./, '')\n if (clean.startsWith(TRANSLATION_REDIRECT_PREFIX)) return 'translation'\n if (clean.startsWith(SLUG_REDIRECT_PREFIX)) return 'slug'\n return 'manual'\n}\n\nconst idIn = (prefix: string) => `(_id in path(\"${prefix}*\") || _id in path(\"drafts.${prefix}*\"))`\n\n/** Filtre GROQ de chaque famille (à combiner avec `_type == $type`). */\nexport const REDIRECT_KIND_FILTERS: Record<RedirectKind, string> = {\n translation: idIn(TRANSLATION_REDIRECT_PREFIX),\n slug: idIn(SLUG_REDIRECT_PREFIX),\n manual: `!${idIn(TRANSLATION_REDIRECT_PREFIX)} && !${idIn(SLUG_REDIRECT_PREFIX)}`,\n}\n\nexport interface RedirectsStructureOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Titre de l'entrée. Défaut : « Redirects ». */\n title?: string\n /** Icône de l'entrée (celle du projet). */\n icon?: ComponentType\n /** Libellés des sous-dossiers (langue du Studio du projet). Défaut : anglais. */\n labels?: Partial<Record<RedirectKind | 'all', string>>\n}\n\nconst DEFAULT_LABELS: Record<RedirectKind | 'all', string> = {\n manual: 'Manual',\n slug: 'Slug changes (automatic)',\n translation: 'Languages (automatic)',\n all: 'All redirects',\n}\n\n/**\n * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création\n * possible), changements de slug et langues (automatiques), puis toutes.\n * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])\n */\nexport function redirectsStructure(S: StructureBuilder, options: RedirectsStructureOptions = {}): ListItemBuilder {\n const type = options.redirectType ?? 'redirect'\n const title = options.title ?? 'Redirects'\n const labels = {...DEFAULT_LABELS, ...options.labels}\n const list = (kind: RedirectKind, label: string) =>\n S.listItem()\n .id(`redirects-${kind}`)\n .title(label)\n .schemaType(type)\n .child(\n S.documentList()\n .id(`redirects-${kind}-list`)\n .title(label)\n .schemaType(type)\n .apiVersion('2024-10-01')\n .filter(`_type == $type && ${REDIRECT_KIND_FILTERS[kind]}`)\n .params({type})\n .defaultOrdering([{field: 'from', direction: 'asc'}])\n // Création seulement dans les manuelles : les autres sont automatiques.\n .initialValueTemplates(kind === 'manual' ? [S.initialValueTemplateItem(type)] : []),\n )\n const item = S.listItem()\n .id('redirects')\n .title(title)\n .child(\n S.list()\n .id('redirects')\n .title(title)\n .items([\n list('manual', labels.manual),\n list('slug', labels.slug),\n list('translation', labels.translation),\n S.divider(),\n S.listItem().id('redirects-all').title(labels.all).schemaType(type).child(S.documentTypeList(type).title(labels.all)),\n ]),\n )\n return options.icon ? item.icon(options.icon) : item\n}\n\nexport interface RedirectConflictOptions {\n /** Type des redirections. Défaut : `redirect`. */\n redirectType?: string\n /** Registre des pages du site (site-routes.json) : adresses des pages en ligne. */\n siteRoutes?: SiteRoutesRegistry | null\n /** Langues : langue principale (sans préfixe) et champ de langue. */\n i18n?: {defaultLocale: string; field?: string} | null\n /** Champ slug des pages. Défaut : `slug`. */\n slugField?: string\n}\n\ntype Ctx = {document?: {_id?: string; from?: unknown; to?: unknown} | null; getClient: (o: {apiVersion: string}) => SanityClient}\ntype Row = {_id: string; from?: string | null; to?: string | null}\n\nconst clean = (v: unknown) => (typeof v === 'string' ? v.trim() : '')\n\nasync function otherRedirects(ctx: Ctx, type: string): Promise<Row[]> {\n const id = (ctx.document?._id ?? '').replace(/^drafts\\./, '')\n // Publiées et brouillons des AUTRES redirections (le brouillon d'une publiée la remplace).\n const rows = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'raw'})\n .fetch<Row[]>(`*[_type == $type && !(_id in [$id, $draft])]{_id, from, to}`, {type, id, draft: `drafts.${id}`})\n const byBase = new Map<string, Row>()\n for (const r of rows) {\n const base = r._id.replace(/^drafts\\./, '')\n if (!byBase.has(base) || r._id.startsWith('drafts.')) byBase.set(base, r)\n }\n return [...byBase.values()]\n}\n\nconst label = (r: Row) => `${clean(r.from)} → ${clean(r.to)}`\n\n/**\n * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :\n * la publication est bloquée, avec la raison et la redirection en cause).\n * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})\n * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})\n * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})\n */\nexport function redirectConflicts(options: RedirectConflictOptions = {}) {\n const type = options.redirectType ?? 'redirect'\n const field = options.i18n?.field ?? 'language'\n const slugField = options.slugField ?? 'slug'\n const pageTypes = options.siteRoutes ? pageTypesFromSiteRoutes(options.siteRoutes).filter((t) => !t.path) : []\n const i18n = options.i18n ? {field, defaultLocale: options.i18n.defaultLocale, locales: [], defaultsSourceLocale: options.i18n.defaultLocale} : null\n\n // Page en ligne à cette adresse (publiée, dossier et slug de sa langue) ?\n async function pageAt(ctx: Ctx, path: string): Promise<string | null> {\n if (!pageTypes.length) return null\n const key = redirectKey(path)\n const docs = await ctx\n .getClient({apiVersion: '2024-10-01'})\n .withConfig({perspective: 'published'})\n .fetch<{_type: string; title?: string; slug?: string; lang?: string}[]>(\n `*[_type in $types && defined(${slugField}.current)]{_type, title, \"slug\": ${slugField}.current, \"lang\": ${field}}`,\n {types: pageTypes.map((t) => t.type)},\n )\n for (const d of docs) {\n const t = pageTypes.find((p) => p.type === d._type)\n const p = t && toPath({slug: d.slug, pathPrefix: t.pathPrefix, localizedPrefixes: t.localizedPrefixes, locale: d.lang}, i18n)\n if (p && redirectKey(p) === key) return d.title || p\n }\n return null\n }\n\n return {\n async from(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const from = clean(value)\n if (!from.startsWith('/')) return true\n const others = await otherRedirects(ctx, type)\n const same = others.find((r) => r.from && redirectKey(r.from) === redirectKey(from))\n if (same) return `Conflict: another redirect already starts from this address (${label(same)}). Edit that one instead.`\n const page = await pageAt(ctx, from)\n if (page) return `Conflict: \"${from}\" is the address of a live page (\"${page}\"). Redirecting it would make that page unreachable.`\n return true\n },\n async to(value: unknown, context: unknown): Promise<true | string> {\n const ctx = context as Ctx\n const to = clean(value)\n const from = clean(ctx.document?.from)\n if (!to.startsWith('/')) return true\n if (from && redirectKey(from) === redirectKey(to)) return 'Conflict: the new address is the same as the old one.'\n const others = await otherRedirects(ctx, type)\n const chained = others.find((r) => r.from && redirectKey(r.from) === redirectKey(to))\n if (chained) {\n const final = followRedirects(to, redirectMapOf(others))\n if (from && redirectKey(final) === redirectKey(from)) return `Conflict: loop. \"${to}\" already redirects back to \"${from}\" (${label(chained)}).`\n return `Conflict: \"${to}\" is itself redirected (${label(chained)}). Point directly to the final address: ${final}`\n }\n return true\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAO;CAAkB;CAAU;CAAW;CAAa;CAAmB;CAAW;CAAa;AAAc,CAAC,GAC3I,kCAAkB,IAAI,IAAI;CAAC;CAAe;CAAW;CAAY;CAAgB;CAAc;CAAU;CAAe;AAAW,CAAC,GAEpI,SAAS;CACb;EAAC,MAAM;EAAW,OAAO;EAAW,SAAS;CAAI;CACjD;EAAC,MAAM;EAAY,OAAO;CAAU;CACpC;EAAC,MAAM;EAAO,OAAO;CAAK;CAC1B;EAAC,MAAM;EAAY,OAAO;CAAU;AACtC;;AAMA,SAAgB,UAAU,MAAc,mBAAmB,4BAA6D;CAItH,OAHI,SAAS,mBAAyB,aAClC,WAAW,IAAI,IAAI,IAAU,QAC7B,gBAAgB,IAAI,IAAI,IAAU,aAC/B;AACT;AAEA,SAAgB,gBAAmB,OAAqB,UAAuC,CAAC,GAAQ;CACtG,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAM,OAAO;EACb,IAAI,KAAK,SAAS,cAAc,KAAK,UAAU,CAAC,MAAM,QAAQ,KAAK,MAAM,GAAG,OAAO;EAEnF,IAAM,SAAS,KAAK,OAAO,KAAK,UAC9B,MAAM,SAAS,CAAC,MAAM,QAAQ,MAAM,WAAW,KAAO,QAAQ;GAAC,GAAG;GAAO,OAAO,UAAU,MAAM,MAAM,QAAQ,gBAAgB;EAAC,CACjI,GACM,OAAO,IAAI,IAAI,OAAO,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,KAA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OAAO;GAElC,IAAM,QAAO,MADQ,eAAe,KAAK,IAAI,EAAA,CACzB,MAAM,MAAM,EAAE,QAAQ,YAAY,EAAE,IAAI,MAAM,YAAY,IAAI,CAAC;GACnF,IAAI,MAAM,OAAO,gEAAgE,MAAM,IAAI,EAAE;GAC7F,IAAM,OAAO,MAAM,OAAO,KAAK,IAAI;GAEnC,OADA,CAAI,QAAa,cAAc,KAAK,oCAAoC,KAAK;EAE/E;EACA,MAAM,GAAG,OAAgB,SAA0C;GACjE,IAAM,MAAM,SACN,KAAK,MAAM,KAAK,GAChB,OAAO,MAAM,IAAI,UAAU,IAAI;GACrC,IAAI,CAAC,GAAG,WAAW,GAAG,GAAG,OAAO;GAChC,IAAI,QAAQ,YAAY,IAAI,MAAM,YAAY,EAAE,GAAG,OAAO;GAC1D,IAAM,SAAS,MAAM,eAAe,KAAK,IAAI,GACvC,UAAU,OAAO,MAAM,MAAM,EAAE,QAAQ,YAAY,EAAE,IAAI,MAAM,YAAY,EAAE,CAAC;GACpF,IAAI,SAAS;IACX,IAAM,QAAQ,gBAAgB,IAAI,cAAc,MAAM,CAAC;IAEvD,OADI,QAAQ,YAAY,KAAK,MAAM,YAAY,IAAI,IAAU,oBAAoB,GAAG,+BAA+B,KAAK,KAAK,MAAM,OAAO,EAAE,MACrI,cAAc,GAAG,0BAA0B,MAAM,OAAO,EAAE,0CAA0C;GAC7G;GACA,OAAO;EACT;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocode-factory/sanity-kit",
3
- "version": "2.43.0",
3
+ "version": "2.44.1",
4
4
  "description": "Outils Studio de NoCode Factory : Pages (liste + board), Composants, Historique",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -61,21 +61,22 @@
61
61
  "peerDependencies": {
62
62
  "next": ">=15",
63
63
  "react": "^19.2",
64
- "sanity": "^6.0.0",
65
- "react-dom": "^19.2"
64
+ "react-dom": "^19.2",
65
+ "sanity": "^6.0.0"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@sanity/pkg-utils": "13.0.1",
69
69
  "@types/node": "^26.6.3",
70
70
  "@types/react": "^19.2.14",
71
+ "@types/react-dom": "^19.2.3",
71
72
  "next": "^16.3.8",
72
73
  "react": "^19.2.4",
73
74
  "react-dom": "^19.2.4",
74
75
  "sanity": "6.15.0",
75
76
  "styled-components": "^6.1.18",
76
77
  "typescript": "^5.9.3",
77
- "vitest": "^4.1.11",
78
- "@types/react-dom": "^19.2.3"
78
+ "urlpattern-polyfill": "10.1.0",
79
+ "vitest": "^4.1.11"
79
80
  },
80
81
  "publishConfig": {
81
82
  "registry": "https://registry.npmjs.org",
@@ -19,8 +19,8 @@ const quote = (value: string) => JSON.stringify(value)
19
19
  *
20
20
  * Une route par adresse et par langue (langue principale sans préfixe, les autres
21
21
  * sous /<langue>) : accueil, pages codées du registre (`pageSlug`), collections
22
- * (`<préfixe>/:slug`), design system (valeurs par défaut des composants). Ordre :
23
- * langues préfixées d'abord, puis du plus précis au plus général (`/:slug` en
22
+ * (`<préfixe>/:slug+`, slug à plusieurs niveaux compris), design system (valeurs par défaut des composants). Ordre :
23
+ * langues préfixées d'abord, puis du plus précis au plus général (`/:slug+` en
24
24
  * dernier), pour que `/en` ne soit pas lu comme la page de slug « en ».
25
25
  *
26
26
  * ```ts
@@ -63,14 +63,16 @@ export function ncfMainDocuments(
63
63
  // Pages à chemin fixe (l'accueil).
64
64
  for (const t of config.pageTypes) if (t.path) out.push({route: at(t.path), filter: `_type == ${quote(t.type)}${lang}`})
65
65
 
66
- // Collections : préfixe le plus long d'abord, la racine (`/:slug`) en dernier.
66
+ // Collections : préfixe le plus long d'abord, la racine (`/:slug+`) en dernier.
67
67
  // Dossier traduit par langue (localizedPrefixes) s'il existe.
68
68
  const prefixOf = (t: (typeof slugTypes)[number]) => (locale && t.localizedPrefixes?.[locale] !== undefined ? t.localizedPrefixes[locale] : t.pathPrefix) ?? ''
69
69
  const collections = [...slugTypes].sort((a, b) => prefixOf(b).length - prefixOf(a).length)
70
70
  for (const t of collections) {
71
71
  const p = prefixOf(t)
72
72
  const base = p && p !== '/' ? p : ''
73
- out.push({route: at(`${base}/:slug`), filter: `_type == ${quote(t.type)} && ${t.slugField}.current == $slug${lang}`})
73
+ // `:slug+` : un slug peut avoir plusieurs niveaux (« telecom/projets ») ; la valeur
74
+ // transmise à $slug est alors le slug complet (URLPattern de Presentation).
75
+ out.push({route: at(`${base}/:slug+`), filter: `_type == ${quote(t.type)} && ${t.slugField}.current == $slug${lang}`})
74
76
  }
75
77
  }
76
78
  return out
@@ -22,3 +22,15 @@ export {withNcfFormTabs, formTabOf} from './formTabs'
22
22
  export {withSameLanguageReferences} from './sameLanguageReferences'
23
23
  export {fixCrossLanguageReferences, type CrossLanguageReport} from '../lib/fixCrossLanguageReferences'
24
24
  export {syncTranslationRedirects, translationRedirectId, type TranslationRedirectOptions, type TranslationRedirect} from '../lib/translationRedirects'
25
+
26
+ export {
27
+ redirectsStructure,
28
+ redirectConflicts,
29
+ redirectKindOf,
30
+ REDIRECT_KIND_FILTERS,
31
+ TRANSLATION_REDIRECT_PREFIX,
32
+ SLUG_REDIRECT_PREFIX,
33
+ type RedirectKind,
34
+ type RedirectsStructureOptions,
35
+ type RedirectConflictOptions,
36
+ } from './redirects'
@@ -0,0 +1,205 @@
1
+ import type {ComponentType} from 'react'
2
+ import type {SanityClient} from 'sanity'
3
+ import type {StructureBuilder, ListItemBuilder} from 'sanity/structure'
4
+ import {redirectKey, redirectMapOf, followRedirects} from '../lib/finalUrl'
5
+ import {toPath} from '../lib/paths'
6
+ import {pageTypesFromSiteRoutes, type SiteRoutesRegistry} from '../lib/siteRoutes'
7
+
8
+ /**
9
+ * RÈGLES DES REDIRECTIONS (embarquées par le kit, mêmes dans tous les projets) :
10
+ *
11
+ * 1. Trois familles, rangées chacune dans son sous-dossier du Studio (« Redirects ») :
12
+ * - manuelles : saisies par l'équipe ;
13
+ * - changements de slug : créées à la publication d'un nouveau slug
14
+ * (identifiant `redirect-auto-…`) ;
15
+ * - langues : adresse « slug d'origine » d'une version traduite vers son slug
16
+ * traduit (identifiant `redirect-translation-…`, syncTranslationRedirects).
17
+ * La famille vient de l'identifiant : rien à migrer, rien à saisir.
18
+ *
19
+ * 2. Une redirection EN CONFLIT ne peut pas être publiée (validation, erreur) :
20
+ * - même adresse de départ qu'une autre redirection ;
21
+ * - départ = adresse d'une page en ligne (elle deviendrait inaccessible) ;
22
+ * - destination = départ d'une autre redirection (chaîne : viser l'adresse finale) ;
23
+ * - boucle (la destination ramène au départ) ;
24
+ * - destination identique au départ.
25
+ */
26
+
27
+ export type RedirectKind = 'manual' | 'slug' | 'translation'
28
+
29
+ export const TRANSLATION_REDIRECT_PREFIX = 'redirect-translation-'
30
+ export const SLUG_REDIRECT_PREFIX = 'redirect-auto-'
31
+
32
+ /** Famille d'une redirection, d'après son identifiant (brouillon compris). */
33
+ export function redirectKindOf(id: string | null | undefined): RedirectKind {
34
+ const clean = (id ?? '').replace(/^drafts\./, '')
35
+ if (clean.startsWith(TRANSLATION_REDIRECT_PREFIX)) return 'translation'
36
+ if (clean.startsWith(SLUG_REDIRECT_PREFIX)) return 'slug'
37
+ return 'manual'
38
+ }
39
+
40
+ const idIn = (prefix: string) => `(_id in path("${prefix}*") || _id in path("drafts.${prefix}*"))`
41
+
42
+ /** Filtre GROQ de chaque famille (à combiner avec `_type == $type`). */
43
+ export const REDIRECT_KIND_FILTERS: Record<RedirectKind, string> = {
44
+ translation: idIn(TRANSLATION_REDIRECT_PREFIX),
45
+ slug: idIn(SLUG_REDIRECT_PREFIX),
46
+ manual: `!${idIn(TRANSLATION_REDIRECT_PREFIX)} && !${idIn(SLUG_REDIRECT_PREFIX)}`,
47
+ }
48
+
49
+ export interface RedirectsStructureOptions {
50
+ /** Type des redirections. Défaut : `redirect`. */
51
+ redirectType?: string
52
+ /** Titre de l'entrée. Défaut : « Redirects ». */
53
+ title?: string
54
+ /** Icône de l'entrée (celle du projet). */
55
+ icon?: ComponentType
56
+ /** Libellés des sous-dossiers (langue du Studio du projet). Défaut : anglais. */
57
+ labels?: Partial<Record<RedirectKind | 'all', string>>
58
+ }
59
+
60
+ const DEFAULT_LABELS: Record<RedirectKind | 'all', string> = {
61
+ manual: 'Manual',
62
+ slug: 'Slug changes (automatic)',
63
+ translation: 'Languages (automatic)',
64
+ all: 'All redirects',
65
+ }
66
+
67
+ /**
68
+ * Entrée « Redirects » du Studio, rangée en sous-dossiers : manuelles (création
69
+ * possible), changements de slug et langues (automatiques), puis toutes.
70
+ * S.list().items([..., redirectsStructure(S, {icon: MyIcon})])
71
+ */
72
+ export function redirectsStructure(S: StructureBuilder, options: RedirectsStructureOptions = {}): ListItemBuilder {
73
+ const type = options.redirectType ?? 'redirect'
74
+ const title = options.title ?? 'Redirects'
75
+ const labels = {...DEFAULT_LABELS, ...options.labels}
76
+ const list = (kind: RedirectKind, label: string) =>
77
+ S.listItem()
78
+ .id(`redirects-${kind}`)
79
+ .title(label)
80
+ .schemaType(type)
81
+ .child(
82
+ S.documentList()
83
+ .id(`redirects-${kind}-list`)
84
+ .title(label)
85
+ .schemaType(type)
86
+ .apiVersion('2024-10-01')
87
+ .filter(`_type == $type && ${REDIRECT_KIND_FILTERS[kind]}`)
88
+ .params({type})
89
+ .defaultOrdering([{field: 'from', direction: 'asc'}])
90
+ // Création seulement dans les manuelles : les autres sont automatiques.
91
+ .initialValueTemplates(kind === 'manual' ? [S.initialValueTemplateItem(type)] : []),
92
+ )
93
+ const item = S.listItem()
94
+ .id('redirects')
95
+ .title(title)
96
+ .child(
97
+ S.list()
98
+ .id('redirects')
99
+ .title(title)
100
+ .items([
101
+ list('manual', labels.manual),
102
+ list('slug', labels.slug),
103
+ list('translation', labels.translation),
104
+ S.divider(),
105
+ S.listItem().id('redirects-all').title(labels.all).schemaType(type).child(S.documentTypeList(type).title(labels.all)),
106
+ ]),
107
+ )
108
+ return options.icon ? item.icon(options.icon) : item
109
+ }
110
+
111
+ export interface RedirectConflictOptions {
112
+ /** Type des redirections. Défaut : `redirect`. */
113
+ redirectType?: string
114
+ /** Registre des pages du site (site-routes.json) : adresses des pages en ligne. */
115
+ siteRoutes?: SiteRoutesRegistry | null
116
+ /** Langues : langue principale (sans préfixe) et champ de langue. */
117
+ i18n?: {defaultLocale: string; field?: string} | null
118
+ /** Champ slug des pages. Défaut : `slug`. */
119
+ slugField?: string
120
+ }
121
+
122
+ type Ctx = {document?: {_id?: string; from?: unknown; to?: unknown} | null; getClient: (o: {apiVersion: string}) => SanityClient}
123
+ type Row = {_id: string; from?: string | null; to?: string | null}
124
+
125
+ const clean = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
126
+
127
+ async function otherRedirects(ctx: Ctx, type: string): Promise<Row[]> {
128
+ const id = (ctx.document?._id ?? '').replace(/^drafts\./, '')
129
+ // Publiées et brouillons des AUTRES redirections (le brouillon d'une publiée la remplace).
130
+ const rows = await ctx
131
+ .getClient({apiVersion: '2024-10-01'})
132
+ .withConfig({perspective: 'raw'})
133
+ .fetch<Row[]>(`*[_type == $type && !(_id in [$id, $draft])]{_id, from, to}`, {type, id, draft: `drafts.${id}`})
134
+ const byBase = new Map<string, Row>()
135
+ for (const r of rows) {
136
+ const base = r._id.replace(/^drafts\./, '')
137
+ if (!byBase.has(base) || r._id.startsWith('drafts.')) byBase.set(base, r)
138
+ }
139
+ return [...byBase.values()]
140
+ }
141
+
142
+ const label = (r: Row) => `${clean(r.from)} → ${clean(r.to)}`
143
+
144
+ /**
145
+ * Validations anti-conflit des champs `from` et `to` d'une redirection (erreurs :
146
+ * la publication est bloquée, avec la raison et la redirection en cause).
147
+ * const conflicts = redirectConflicts({siteRoutes: routes, i18n: {defaultLocale}})
148
+ * defineField({name: 'from', validation: (r) => r.required().custom(conflicts.from)})
149
+ * defineField({name: 'to', validation: (r) => r.required().custom(conflicts.to)})
150
+ */
151
+ export function redirectConflicts(options: RedirectConflictOptions = {}) {
152
+ const type = options.redirectType ?? 'redirect'
153
+ const field = options.i18n?.field ?? 'language'
154
+ const slugField = options.slugField ?? 'slug'
155
+ const pageTypes = options.siteRoutes ? pageTypesFromSiteRoutes(options.siteRoutes).filter((t) => !t.path) : []
156
+ const i18n = options.i18n ? {field, defaultLocale: options.i18n.defaultLocale, locales: [], defaultsSourceLocale: options.i18n.defaultLocale} : null
157
+
158
+ // Page en ligne à cette adresse (publiée, dossier et slug de sa langue) ?
159
+ async function pageAt(ctx: Ctx, path: string): Promise<string | null> {
160
+ if (!pageTypes.length) return null
161
+ const key = redirectKey(path)
162
+ const docs = await ctx
163
+ .getClient({apiVersion: '2024-10-01'})
164
+ .withConfig({perspective: 'published'})
165
+ .fetch<{_type: string; title?: string; slug?: string; lang?: string}[]>(
166
+ `*[_type in $types && defined(${slugField}.current)]{_type, title, "slug": ${slugField}.current, "lang": ${field}}`,
167
+ {types: pageTypes.map((t) => t.type)},
168
+ )
169
+ for (const d of docs) {
170
+ const t = pageTypes.find((p) => p.type === d._type)
171
+ const p = t && toPath({slug: d.slug, pathPrefix: t.pathPrefix, localizedPrefixes: t.localizedPrefixes, locale: d.lang}, i18n)
172
+ if (p && redirectKey(p) === key) return d.title || p
173
+ }
174
+ return null
175
+ }
176
+
177
+ return {
178
+ async from(value: unknown, context: unknown): Promise<true | string> {
179
+ const ctx = context as Ctx
180
+ const from = clean(value)
181
+ if (!from.startsWith('/')) return true
182
+ const others = await otherRedirects(ctx, type)
183
+ const same = others.find((r) => r.from && redirectKey(r.from) === redirectKey(from))
184
+ if (same) return `Conflict: another redirect already starts from this address (${label(same)}). Edit that one instead.`
185
+ const page = await pageAt(ctx, from)
186
+ if (page) return `Conflict: "${from}" is the address of a live page ("${page}"). Redirecting it would make that page unreachable.`
187
+ return true
188
+ },
189
+ async to(value: unknown, context: unknown): Promise<true | string> {
190
+ const ctx = context as Ctx
191
+ const to = clean(value)
192
+ const from = clean(ctx.document?.from)
193
+ if (!to.startsWith('/')) return true
194
+ if (from && redirectKey(from) === redirectKey(to)) return 'Conflict: the new address is the same as the old one.'
195
+ const others = await otherRedirects(ctx, type)
196
+ const chained = others.find((r) => r.from && redirectKey(r.from) === redirectKey(to))
197
+ if (chained) {
198
+ const final = followRedirects(to, redirectMapOf(others))
199
+ if (from && redirectKey(final) === redirectKey(from)) return `Conflict: loop. "${to}" already redirects back to "${from}" (${label(chained)}).`
200
+ return `Conflict: "${to}" is itself redirected (${label(chained)}). Point directly to the final address: ${final}`
201
+ }
202
+ return true
203
+ },
204
+ }
205
+ }
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * quelle version. Recopiée de `package.json` par `npm version` (scripts/sync-version.mjs) ; un test
4
4
  * le vérifie.
5
5
  */
6
- export const KIT_VERSION = '2.43.0'
6
+ export const KIT_VERSION = '2.44.1'