@localness/contract 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,10 @@ const { entries } = readLocaleFile(source)
33
33
  const next = writeLocaleFile(source, { 'home.title': 'Welcome', 'old.key': null }, 'nested-json')
34
34
  ```
35
35
 
36
+ Arrays are read by index: `{"steps":[{"title":"A"}],"tips":["x"]}` gives the keys `steps.0.title` and `tips.0`. Such a key can only be updated in place. `unwritableKeys` refuses a new key under an array (`steps.1.title` while `steps` has one element, `tips.x`), and a `null` for a key inside an array is ignored, so no write ever adds or removes an element and shifts the keys after it. `inArray(path)` tells such a key apart: `inArray(readLocaleFile(source).paths.get(key)!)`.
37
+
38
+ `paths` and `blocked` hold `LocaleKeyPath` (`(string | number)[]`, a number per array index), and `arrays` lists the path of every array. Before 0.6.0 they were `string[]` and arrays were only `blocked`.
39
+
36
40
  ## Versioning
37
41
 
38
42
  Independent of the Localness server version.
package/dist/index.d.mts CHANGED
@@ -71,6 +71,7 @@ export declare const deliveryKeyConventionSchema: z.ZodObject<{
71
71
  style: z.ZodEnum<{
72
72
  snake_case: "snake_case";
73
73
  camelCase: "camelCase";
74
+ none: "none";
74
75
  }>;
75
76
  maxDepth: z.ZodNumber;
76
77
  guidance: z.ZodNullable<z.ZodString>;
@@ -105,6 +106,7 @@ export declare const deliveryMetaSchema: z.ZodObject<{
105
106
  style: z.ZodEnum<{
106
107
  snake_case: "snake_case";
107
108
  camelCase: "camelCase";
109
+ none: "none";
108
110
  }>;
109
111
  maxDepth: z.ZodNumber;
110
112
  guidance: z.ZodNullable<z.ZodString>;
@@ -440,6 +442,7 @@ export declare const keyViolationSchema: z.ZodEnum<{
440
442
  prefix: "prefix";
441
443
  charset: "charset";
442
444
  segment: "segment";
445
+ separator: "separator";
443
446
  case: "case";
444
447
  depth: "depth";
445
448
  }>;
@@ -460,6 +463,7 @@ export declare const keyNameSuggestionSchema: z.ZodObject<{
460
463
  prefix: "prefix";
461
464
  charset: "charset";
462
465
  segment: "segment";
466
+ separator: "separator";
463
467
  case: "case";
464
468
  depth: "depth";
465
469
  }>>;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as KEY_STYLE_VALUES } from "./key-convention-C4ZHbNKy.mjs";
1
+ import { i as KEY_VIOLATION_VALUES, t as KEY_STYLE_VALUES } from "./key-convention-C-urfySC.mjs";
2
2
  import { z } from "zod/v4";
3
3
  // ../../shared/contract/release.ts
4
4
  /** A row id, which the API sends as a number but the UI also carries as text. */
@@ -303,13 +303,7 @@ const keyDraftConflictSchema = z.object({
303
303
  locales: z.array(z.string()),
304
304
  key: deliveryKeyStateSchema
305
305
  });
306
- const keyViolationSchema = z.enum([
307
- "prefix",
308
- "charset",
309
- "segment",
310
- "case",
311
- "depth"
312
- ]);
306
+ const keyViolationSchema = z.enum(KEY_VIOLATION_VALUES);
313
307
  /**
314
308
  * `POST /api/v1/keys/suggest-name` — the web app's AI key naming, under the
315
309
  * project's key convention. `key` is empty when the text has nothing nameable.
@@ -0,0 +1,108 @@
1
+ // ../../shared/contract/key-convention.ts
2
+ /**
3
+ * The per-project rules an i18n key has to follow. Pure, so a client that
4
+ * names keys itself checks them exactly the way the server does.
5
+ */
6
+ const KEY_STYLE_VALUES = [
7
+ "snake_case",
8
+ "camelCase",
9
+ "none"
10
+ ];
11
+ const KEY_VIOLATION_VALUES = [
12
+ "prefix",
13
+ "charset",
14
+ "segment",
15
+ "separator",
16
+ "case",
17
+ "depth"
18
+ ];
19
+ /**
20
+ * Errors make a key unusable as a name; warnings are the project's style, which
21
+ * legacy keys may never have followed, so nothing refuses a key over them.
22
+ */
23
+ const KEY_VIOLATION_LEVEL = {
24
+ prefix: "error",
25
+ charset: "error",
26
+ segment: "error",
27
+ separator: "warning",
28
+ case: "warning",
29
+ depth: "warning"
30
+ };
31
+ const KEY_VIOLATION_TEXT = {
32
+ prefix: "Missing the project key prefix",
33
+ charset: "Uses characters other than letters, digits, \".\", \"_\" and \"-\"",
34
+ segment: "Has an empty segment",
35
+ separator: "Uses a separator other than the configured one",
36
+ case: "Does not match the configured casing",
37
+ depth: "Has more levels than the convention suggests"
38
+ };
39
+ function keyViolationErrors(violations) {
40
+ return violations.filter((one) => KEY_VIOLATION_LEVEL[one] === "error");
41
+ }
42
+ function keyViolationWarnings(violations) {
43
+ return violations.filter((one) => KEY_VIOLATION_LEVEL[one] === "warning");
44
+ }
45
+ /** Characters any key may use to join its parts, whatever the configured separator. */
46
+ const KEY_BOUNDARY = [
47
+ ".",
48
+ "_",
49
+ "-"
50
+ ];
51
+ const WORD_PATTERN = {
52
+ snake_case: /^[a-z0-9]+$/,
53
+ camelCase: /^[a-z][A-Za-z0-9]*$/
54
+ };
55
+ function boundaryChars(separator) {
56
+ return /* @__PURE__ */ new Set([...KEY_BOUNDARY, ...separator]);
57
+ }
58
+ /**
59
+ * The characters that start a new level. In a snake_case project whose
60
+ * separator is not `_`, the underscore joins words inside one level.
61
+ */
62
+ function levelChars(convention) {
63
+ const chars = boundaryChars(convention.separator);
64
+ if (convention.style === "snake_case" && !convention.separator.includes("_")) chars.delete("_");
65
+ return chars;
66
+ }
67
+ function splitOn(text, chars) {
68
+ const parts = [""];
69
+ for (const char of text) if (chars.has(char)) parts.push("");
70
+ else parts[parts.length - 1] += char;
71
+ return parts;
72
+ }
73
+ /** How many levels a key path has under the convention. */
74
+ function keyDepth(path, convention) {
75
+ return path ? splitOn(path, levelChars(convention)).length : 0;
76
+ }
77
+ /**
78
+ * Pure: every way `key` breaks the convention, in the order worth fixing. Use
79
+ * `KEY_VIOLATION_LEVEL` to tell what must block from what is only advice.
80
+ *
81
+ * An empty key is **legal** (a symbol-only source text has no name), so it is
82
+ * not a violation here — callers treat it as "cannot name", not as an error.
83
+ *
84
+ * The prefix itself is exempt: it is copied verbatim from the project settings,
85
+ * so the configured rules govern the path that follows it. Any boundary
86
+ * character may follow it, so legacy keys that joined it differently still count.
87
+ */
88
+ function checkI18nKey(key, convention) {
89
+ if (!key) return [];
90
+ const { prefix, separator, style, maxDepth } = convention;
91
+ if (!separator) return [];
92
+ const boundary = boundaryChars(separator);
93
+ const violations = [];
94
+ const prefixed = Boolean(prefix) && key.startsWith(prefix) && boundary.has(key.charAt(prefix.length));
95
+ if (prefix && !prefixed) violations.push("prefix");
96
+ const path = prefixed ? key.slice(prefix.length + 1) : key;
97
+ const allowed = (char) => /[0-9a-zA-Z]/.test(char) || boundary.has(char);
98
+ if ([...path].some((char) => !allowed(char))) violations.push("charset");
99
+ if (splitOn(path, boundary).some((word) => word === "")) violations.push("segment");
100
+ const levels = levelChars(convention);
101
+ if ([...path].some((char) => levels.has(char) && !separator.includes(char))) violations.push("separator");
102
+ if (style !== "none") {
103
+ if (splitOn(path, boundary).some((word) => word && !WORD_PATTERN[style].test(word))) violations.push("case");
104
+ }
105
+ if (keyDepth(path, convention) > maxDepth) violations.push("depth");
106
+ return violations;
107
+ }
108
+ export { checkI18nKey as a, keyViolationWarnings as c, KEY_VIOLATION_VALUES as i, KEY_VIOLATION_LEVEL as n, keyDepth as o, KEY_VIOLATION_TEXT as r, keyViolationErrors as s, KEY_STYLE_VALUES as t };
@@ -31,31 +31,45 @@ export declare function localeFilesScopeError(dir: string, pattern: string): str
31
31
  export declare function localeFileName(locale: string, localeMap: Record<string, string> | null): string;
32
32
  /** `/`-separated path of a locale's file. `dir` must pass `localeFilesScopeError`. */
33
33
  export declare function localeFilePath(dir: string, pattern: string, locale: string, localeMap: Record<string, string> | null): string;
34
+ /** JSON path of a value: property names, and a number for each array index. */
35
+ export type LocaleKeyPath = (string | number)[];
34
36
  /**
35
37
  * Keys are read the same way Translations import reads them — nested objects
36
38
  * joined with `.` — and every key remembers the property path it came from, so
37
39
  * a write lands on that exact property even in a file that mixes flat and
38
40
  * nested keys.
41
+ *
42
+ * Arrays are read by index: `{"list":[{"title":"A"}]}` is the key
43
+ * `list.0.title`. A key inside an array (see `inArray`) can only be updated:
44
+ * no write adds or removes an array element, since that would shift the keys
45
+ * of the elements after it.
39
46
  */
40
47
  export type LocaleFileContent = {
41
48
  entries: Record<string, string>;
42
- paths: Map<string, string[]>;
43
- /** Paths holding something other than an object or text (arrays, null). */
44
- blocked: string[][];
49
+ paths: Map<string, LocaleKeyPath>;
50
+ /** Paths holding something other than an object, array or text (null). */
51
+ blocked: LocaleKeyPath[];
52
+ /** Path of every array, empty ones included. */
53
+ arrays: LocaleKeyPath[];
45
54
  };
55
+ /** True when the path runs through an array, so its key may be updated but never added or removed. */
56
+ export declare function inArray(path: readonly (string | number)[]): boolean;
46
57
  export declare function readLocaleFile(source: string): LocaleFileContent;
47
58
  /**
48
59
  * Keys a write cannot place. A key already in the file is always writable, in
49
60
  * place. A new nested key is not when its path runs into an existing value
50
61
  * (`a` is text, so `a.b` has nowhere to go), would replace an object, has an
51
62
  * empty segment, or collides that way with another new key — then neither of
52
- * the two is written, since there is no right one to pick.
63
+ * the two is written, since there is no right one to pick. In either format a
64
+ * new key under an array (`list.4` when `list` has four elements, `list.x`) is
65
+ * not writable: arrays only take updates to the elements they already have.
53
66
  */
54
67
  export declare function unwritableKeys(file: LocaleFileContent, keys: string[], format: LocaleFileFormat): Set<string>;
55
68
  /**
56
69
  * Sets each entry in place and leaves everything else byte-for-byte: key
57
70
  * order, indentation, comments and line endings. A new key goes to the end of
58
- * its parent object. A `null` value removes the key. `source` null creates the
59
- * file. Callers must drop `unwritableKeys` first.
71
+ * its parent object. A `null` value removes the key, except a key inside an
72
+ * array, which is left as it is. `source` null creates the file. Callers must
73
+ * drop `unwritableKeys` first.
60
74
  */
61
75
  export declare function writeLocaleFile(source: string | null, entries: Record<string, string | null>, format: LocaleFileFormat): string;
@@ -1256,6 +1256,10 @@ function localeFileName(locale, localeMap) {
1256
1256
  function localeFilePath(dir, pattern, locale, localeMap) {
1257
1257
  return `${dir}/${pattern.replace(LOCALE_PLACEHOLDER, localeFileName(locale, localeMap))}`;
1258
1258
  }
1259
+ /** True when the path runs through an array, so its key may be updated but never added or removed. */
1260
+ function inArray(path) {
1261
+ return path.some((segment) => typeof segment === "number");
1262
+ }
1259
1263
  function readLocaleFile(source) {
1260
1264
  const errors = [];
1261
1265
  const root = parseTree(source, errors, { allowTrailingComma: true });
@@ -1265,45 +1269,48 @@ function readLocaleFile(source) {
1265
1269
  const entries = emptyEntries();
1266
1270
  const paths = /* @__PURE__ */ new Map();
1267
1271
  const blocked = [];
1268
- const walk = (node, path) => {
1269
- for (const property of node.children ?? []) {
1270
- const [nameNode, valueNode] = property.children ?? [];
1271
- if (!nameNode || !valueNode) continue;
1272
- const segments = [...path, String(nameNode.value)];
1273
- switch (valueNode.type) {
1274
- case "object":
1275
- walk(valueNode, segments);
1276
- break;
1277
- case "string":
1278
- case "number":
1279
- case "boolean": {
1280
- const key = segments.join(".");
1281
- paths.set(key, segments);
1282
- const text = normalizeLocaleText(valueNode.value);
1283
- if (text !== null) entries[key] = text;
1284
- break;
1285
- }
1286
- case "array":
1287
- case "null":
1288
- case "property":
1289
- blocked.push(segments);
1290
- break;
1291
- default: {
1292
- const unreachable = valueNode.type;
1293
- throw new Error(`Unknown JSON node type: ${unreachable}`);
1272
+ const arrays = [];
1273
+ const visit = (node, segments) => {
1274
+ switch (node.type) {
1275
+ case "object":
1276
+ for (const property of node.children ?? []) {
1277
+ const [nameNode, valueNode] = property.children ?? [];
1278
+ if (nameNode && valueNode) visit(valueNode, [...segments, String(nameNode.value)]);
1294
1279
  }
1280
+ break;
1281
+ case "array":
1282
+ arrays.push(segments);
1283
+ node.children?.forEach((element, index) => visit(element, [...segments, index]));
1284
+ break;
1285
+ case "string":
1286
+ case "number":
1287
+ case "boolean": {
1288
+ const key = segments.join(".");
1289
+ paths.set(key, segments);
1290
+ const text = normalizeLocaleText(node.value);
1291
+ if (text !== null) entries[key] = text;
1292
+ break;
1293
+ }
1294
+ case "null":
1295
+ case "property":
1296
+ blocked.push(segments);
1297
+ break;
1298
+ default: {
1299
+ const unreachable = node.type;
1300
+ throw new Error(`Unknown JSON node type: ${unreachable}`);
1295
1301
  }
1296
1302
  }
1297
1303
  };
1298
- walk(root, []);
1304
+ visit(root, []);
1299
1305
  return {
1300
1306
  entries,
1301
1307
  paths,
1302
- blocked
1308
+ blocked,
1309
+ arrays
1303
1310
  };
1304
1311
  }
1305
1312
  function isPrefix(a, b) {
1306
- return a.length <= b.length && a.every((segment, i) => segment === b[i]);
1313
+ return a.length <= b.length && a.every((segment, i) => String(segment) === String(b[i]));
1307
1314
  }
1308
1315
  function newKeyPath(key, format) {
1309
1316
  switch (format) {
@@ -1317,11 +1324,18 @@ function newKeyPath(key, format) {
1317
1324
  * place. A new nested key is not when its path runs into an existing value
1318
1325
  * (`a` is text, so `a.b` has nowhere to go), would replace an object, has an
1319
1326
  * empty segment, or collides that way with another new key — then neither of
1320
- * the two is written, since there is no right one to pick.
1327
+ * the two is written, since there is no right one to pick. In either format a
1328
+ * new key under an array (`list.4` when `list` has four elements, `list.x`) is
1329
+ * not writable: arrays only take updates to the elements they already have.
1321
1330
  */
1322
1331
  function unwritableKeys(file, keys, format) {
1323
1332
  const out = /* @__PURE__ */ new Set();
1324
- const occupied = [...file.paths.values(), ...file.blocked];
1333
+ const occupied = [
1334
+ ...file.paths.values(),
1335
+ ...file.blocked,
1336
+ ...file.arrays
1337
+ ];
1338
+ const arrayKeys = file.arrays.map((path) => path.join("."));
1325
1339
  const fresh = keys.filter((key) => !file.paths.has(key)).map((key) => ({
1326
1340
  key,
1327
1341
  path: newKeyPath(key, format)
@@ -1331,7 +1345,7 @@ function unwritableKeys(file, keys, format) {
1331
1345
  out.add(item.key);
1332
1346
  continue;
1333
1347
  }
1334
- const hitsFile = occupied.some((path) => isPrefix(path, item.path) || isPrefix(item.path, path));
1348
+ const hitsFile = arrayKeys.some((prefix) => item.key === prefix || item.key.startsWith(`${prefix}.`)) || occupied.some((path) => isPrefix(path, item.path) || isPrefix(item.path, path));
1335
1349
  const hitsFresh = fresh.some((other) => other.key !== item.key && (isPrefix(other.path, item.path) || isPrefix(item.path, other.path)));
1336
1350
  if (hitsFile || hitsFresh) out.add(item.key);
1337
1351
  }
@@ -1355,8 +1369,9 @@ function detectIndent(source) {
1355
1369
  /**
1356
1370
  * Sets each entry in place and leaves everything else byte-for-byte: key
1357
1371
  * order, indentation, comments and line endings. A new key goes to the end of
1358
- * its parent object. A `null` value removes the key. `source` null creates the
1359
- * file. Callers must drop `unwritableKeys` first.
1372
+ * its parent object. A `null` value removes the key, except a key inside an
1373
+ * array, which is left as it is. `source` null creates the file. Callers must
1374
+ * drop `unwritableKeys` first.
1360
1375
  */
1361
1376
  function writeLocaleFile(source, entries, format) {
1362
1377
  let text = source ?? "{}\n";
@@ -1375,7 +1390,7 @@ function writeLocaleFile(source, entries, format) {
1375
1390
  set(known ?? newKeyPath(key, format), value);
1376
1391
  continue;
1377
1392
  }
1378
- if (!known) continue;
1393
+ if (!known || inArray(known)) continue;
1379
1394
  set(known, void 0);
1380
1395
  for (let depth = known.length - 1; depth > 0; depth--) {
1381
1396
  const parent = known.slice(0, depth);
@@ -1386,4 +1401,4 @@ function writeLocaleFile(source, entries, format) {
1386
1401
  }
1387
1402
  return text.endsWith("\n") ? text : `${text}${eol}`;
1388
1403
  }
1389
- export { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_KEY_SEPARATOR, LOCALE_PLACEHOLDER, LocaleFileFormat, emptyEntries, localeFileName, localeFilePath, localeFilesScopeError, normalizeLocaleText, readLocaleFile, unwritableKeys, writeLocaleFile };
1404
+ export { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_KEY_SEPARATOR, LOCALE_PLACEHOLDER, LocaleFileFormat, emptyEntries, inArray, localeFileName, localeFilePath, localeFilesScopeError, normalizeLocaleText, readLocaleFile, unwritableKeys, writeLocaleFile };
package/dist/rules.d.mts CHANGED
@@ -2,28 +2,41 @@
2
2
  * The per-project rules an i18n key has to follow. Pure, so a client that
3
3
  * names keys itself checks them exactly the way the server does.
4
4
  */
5
- export declare const KEY_STYLE_VALUES: readonly ["snake_case", "camelCase"];
5
+ export declare const KEY_STYLE_VALUES: readonly ["snake_case", "camelCase", "none"];
6
6
  export type KeyStyle = (typeof KEY_STYLE_VALUES)[number];
7
7
  export type KeyConvention = {
8
8
  /** Without the trailing separator; `''` means no prefix. */
9
9
  prefix: string;
10
- /** Joins the segments. Must be non-empty — the settings schema enforces it. */
10
+ /** The suggested joint between levels. Must be non-empty — the settings schema enforces it. */
11
11
  separator: string;
12
+ /** `none` leaves casing to the project, for keys named before the convention existed. */
12
13
  style: KeyStyle;
13
- /** How many segments may follow the prefix. */
14
+ /** The suggested number of levels after the prefix. */
14
15
  maxDepth: number;
15
16
  };
17
+ export declare const KEY_VIOLATION_VALUES: readonly ["prefix", "charset", "segment", "separator", "case", "depth"];
16
18
  /** Why a key does not follow the convention. Sent to the client as a code. */
17
- export type KeyViolation = 'prefix' | 'charset' | 'segment' | 'case' | 'depth';
19
+ export type KeyViolation = (typeof KEY_VIOLATION_VALUES)[number];
20
+ /**
21
+ * Errors make a key unusable as a name; warnings are the project's style, which
22
+ * legacy keys may never have followed, so nothing refuses a key over them.
23
+ */
24
+ export declare const KEY_VIOLATION_LEVEL: Record<KeyViolation, 'error' | 'warning'>;
18
25
  export declare const KEY_VIOLATION_TEXT: Record<KeyViolation, string>;
26
+ export declare function keyViolationErrors(violations: KeyViolation[]): KeyViolation[];
27
+ export declare function keyViolationWarnings(violations: KeyViolation[]): KeyViolation[];
28
+ /** How many levels a key path has under the convention. */
29
+ export declare function keyDepth(path: string, convention: KeyConvention): number;
19
30
  /**
20
- * Pure: every way `key` breaks the convention, in the order worth fixing.
31
+ * Pure: every way `key` breaks the convention, in the order worth fixing. Use
32
+ * `KEY_VIOLATION_LEVEL` to tell what must block from what is only advice.
21
33
  *
22
34
  * An empty key is **legal** (a symbol-only source text has no name), so it is
23
35
  * not a violation here — callers treat it as "cannot name", not as an error.
24
36
  *
25
37
  * The prefix itself is exempt: it is copied verbatim from the project settings,
26
- * so the configured rules govern the path that follows it.
38
+ * so the configured rules govern the path that follows it. Any boundary
39
+ * character may follow it, so legacy keys that joined it differently still count.
27
40
  */
28
41
  export declare function checkI18nKey(key: string, convention: KeyConvention): KeyViolation[];
29
42
  /**
package/dist/rules.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as KEY_VIOLATION_TEXT, r as checkI18nKey, t as KEY_STYLE_VALUES } from "./key-convention-C4ZHbNKy.mjs";
1
+ import { a as checkI18nKey, c as keyViolationWarnings, i as KEY_VIOLATION_VALUES, n as KEY_VIOLATION_LEVEL, o as keyDepth, r as KEY_VIOLATION_TEXT, s as keyViolationErrors, t as KEY_STYLE_VALUES } from "./key-convention-C-urfySC.mjs";
2
2
  // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
@@ -695,4 +695,4 @@ function entryMatchesReleaseFilter(releaseIds, filter) {
695
695
  if (filter === "unassigned") return ids.length === 0;
696
696
  return ids.some((releaseId) => String(releaseId) === String(filter));
697
697
  }
698
- export { KEY_STYLE_VALUES, KEY_VIOLATION_TEXT, LEGACY_DRAFT_KEY_PREFIX, NAMESPACE_BOUNDARY, UNNAMED_KEY_PREFIX, checkI18nKey, entryMatchesReleaseFilter, formatI18nKeyDisplay, fpTranslation, isUnnamedKey, namespaceOf, stripProjectPrefix };
698
+ export { KEY_STYLE_VALUES, KEY_VIOLATION_LEVEL, KEY_VIOLATION_TEXT, KEY_VIOLATION_VALUES, LEGACY_DRAFT_KEY_PREFIX, NAMESPACE_BOUNDARY, UNNAMED_KEY_PREFIX, checkI18nKey, entryMatchesReleaseFilter, formatI18nKeyDisplay, fpTranslation, isUnnamedKey, keyDepth, keyViolationErrors, keyViolationWarnings, namespaceOf, stripProjectPrefix };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@localness/contract",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Response contracts of the Localness public /api/v1: zod schemas and the types inferred from them.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
@@ -1,49 +0,0 @@
1
- // ../../shared/contract/key-convention.ts
2
- /**
3
- * The per-project rules an i18n key has to follow. Pure, so a client that
4
- * names keys itself checks them exactly the way the server does.
5
- */
6
- const KEY_STYLE_VALUES = ["snake_case", "camelCase"];
7
- const KEY_VIOLATION_TEXT = {
8
- prefix: "Missing the project key prefix",
9
- charset: "Uses characters the key convention does not allow",
10
- segment: "Has an empty segment",
11
- case: "Does not match the configured casing",
12
- depth: "Has more segments than the convention allows"
13
- };
14
- const SEGMENT_PATTERN = {
15
- snake_case: /^[a-z0-9]+$/,
16
- camelCase: /^[a-z][A-Za-z0-9]*$/
17
- };
18
- /** The key an empty prefix produces nothing in front of. */
19
- function requiredStart(convention) {
20
- return convention.prefix ? convention.prefix + convention.separator : "";
21
- }
22
- /**
23
- * Pure: every way `key` breaks the convention, in the order worth fixing.
24
- *
25
- * An empty key is **legal** (a symbol-only source text has no name), so it is
26
- * not a violation here — callers treat it as "cannot name", not as an error.
27
- *
28
- * The prefix itself is exempt: it is copied verbatim from the project settings,
29
- * so the configured rules govern the path that follows it.
30
- */
31
- function checkI18nKey(key, convention) {
32
- if (!key) return [];
33
- const { separator, style, maxDepth } = convention;
34
- if (!separator) return [];
35
- const violations = [];
36
- const start = requiredStart(convention);
37
- const prefixed = Boolean(start) && key.startsWith(start);
38
- if (start && !prefixed) violations.push("prefix");
39
- const path = prefixed ? key.slice(start.length) : key;
40
- const separatorChars = new Set(separator.split(""));
41
- const allowed = (char) => /[0-9a-zA-Z]/.test(char) || separatorChars.has(char);
42
- if ([...path].some((char) => !allowed(char))) violations.push("charset");
43
- const segments = path.split(separator);
44
- if (segments.some((segment) => segment === "")) violations.push("segment");
45
- if (segments.length > maxDepth) violations.push("depth");
46
- if (segments.some((one) => one && !SEGMENT_PATTERN[style].test(one))) violations.push("case");
47
- return violations;
48
- }
49
- export { KEY_VIOLATION_TEXT as n, checkI18nKey as r, KEY_STYLE_VALUES as t };