inflekt 0.7.1 → 0.8.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/esm/index.js CHANGED
@@ -5,8 +5,8 @@
5
5
  * It uses the 'inflection' package with custom overrides for Latin plural suffixes
6
6
  * that PostGraphile handles differently than standard English pluralization.
7
7
  */
8
- export * from './pluralize';
9
8
  export * from './case';
10
- export * from './naming';
11
9
  export * from './matching';
10
+ export * from './naming';
11
+ export * from './pluralize';
12
12
  export * from './transform-keys';
package/esm/pluralize.js CHANGED
@@ -2,63 +2,35 @@
2
2
  * Pluralization utilities with PostGraphile-compatible Latin suffix handling
3
3
  *
4
4
  * Uses the 'inflection' package with custom overrides for Latin plural suffixes
5
- * that PostGraphile handles differently than standard English pluralization.
5
+ * that PostGraphile handles differently than standard English pluralization,
6
+ * plus a dictionary-proven exception table for the words where no suffix rule
7
+ * is right (see exceptions.ts).
6
8
  */
7
9
  import * as inflection from 'inflection';
10
+ import { SINGULAR_EXCEPTIONS } from './exceptions';
11
+ import { enforceDoubleSPlural, normalizeMalformedDoubleS, pluralizeFStem, restoreWordCase, singularizeByRules, } from './rules';
12
+ const LAST_SEGMENT_REGEX = /([A-Z]|_[a-z0-9])[a-z0-9]*_*$/;
8
13
  /**
9
- * Latin plural suffixes that inflection handles differently than PostGraphile.
10
- *
11
- * The inflection library correctly singularizes Latin words (schemata -> schematum),
12
- * but PostGraphile uses English-style naming (schemata -> schema).
13
- *
14
- * Format: [pluralSuffix, singularSuffix]
15
- */
16
- const LATIN_SUFFIX_OVERRIDES = [
17
- ['schemata', 'schema'],
18
- ['criteria', 'criterion'],
19
- ['phenomena', 'phenomenon'],
20
- ['media', 'medium'],
21
- ['memoranda', 'memorandum'],
22
- ['strata', 'stratum'],
23
- ['curricula', 'curriculum'],
24
- ['data', 'datum'],
25
- ];
26
- /**
27
- * Compound words ending in "base" that the inflection library incorrectly
28
- * singularizes via its (b)a branch in the ses$ rule (e.g. codebases -> codebasis).
29
- * We intercept these before delegating to inflection.singularize().
14
+ * Locate the final word segment of a compound name ("user_cookies" -> "cookies",
15
+ * "UserCookies" -> "Cookies") so the exception table applies to compounds too.
30
16
  */
31
- const COMPOUND_BASE_REGEX = /(database|codebase|firebase|knowledgebase)s$/i;
32
- const TRAILING_TRIPLE_S_REGEX = /[sS]{3,}$/;
33
- const TRAILING_TRIPLE_S_BEFORE_ES_REGEX = /[sS]{3,}(?=e[sS]$)/;
34
- function normalizeTrailingSRun(suffix) {
35
- return suffix === suffix.toUpperCase() ? 'SS' : 'ss';
36
- }
37
- function normalizeTripleSBeforeEs(word) {
38
- return word.replace(TRAILING_TRIPLE_S_BEFORE_ES_REGEX, normalizeTrailingSRun);
39
- }
40
- function normalizeTrailingTripleS(word) {
41
- const match = word.match(TRAILING_TRIPLE_S_REGEX);
42
- if (!match) {
43
- return word;
17
+ function splitLastSegment(str) {
18
+ const matches = str.match(LAST_SEGMENT_REGEX);
19
+ if (!matches) {
20
+ return null;
44
21
  }
45
- const suffix = match[0];
46
- const prefix = word.slice(0, -suffix.length);
47
- const normalizedSuffix = normalizeTrailingSRun(suffix);
48
- return `${prefix}${normalizedSuffix}`;
49
- }
50
- function normalizeMalformedDoubleS(word) {
51
- return normalizeTrailingTripleS(normalizeTripleSBeforeEs(word));
52
- }
53
- function enforceDoubleSPlural(singularWord, pluralWord) {
54
- if (!singularWord.toLowerCase().endsWith('ss')) {
55
- return pluralWord;
22
+ const index = (matches.index ?? 0) + matches[1].length - 1;
23
+ if (index <= 0) {
24
+ return null;
56
25
  }
57
- // Defensive normalization for malformed outputs like "hazardClasss".
58
- if (pluralWord === `${singularWord}s`) {
59
- return `${singularWord}es`;
26
+ return { prefix: str.slice(0, index), word: str.slice(index) };
27
+ }
28
+ function lookupException(word) {
29
+ const key = word.toLowerCase();
30
+ if (!Object.prototype.hasOwnProperty.call(SINGULAR_EXCEPTIONS, key)) {
31
+ return null;
60
32
  }
61
- return pluralWord;
33
+ return restoreWordCase(word, SINGULAR_EXCEPTIONS[key]);
62
34
  }
63
35
  /**
64
36
  * Convert a word to its singular form with PostGraphile-compatible Latin handling
@@ -66,38 +38,36 @@ function enforceDoubleSPlural(singularWord, pluralWord) {
66
38
  */
67
39
  export function singularize(word) {
68
40
  const normalizedWord = normalizeMalformedDoubleS(word);
69
- const lowerWord = normalizedWord.toLowerCase();
70
- for (const [pluralSuffix, singularSuffix] of LATIN_SUFFIX_OVERRIDES) {
71
- if (lowerWord.endsWith(pluralSuffix)) {
72
- const suffixStart = normalizedWord.length - pluralSuffix.length;
73
- const prefix = normalizedWord.slice(0, suffixStart);
74
- const originalSuffix = normalizedWord.slice(suffixStart);
75
- const isAllCaps = originalSuffix === originalSuffix.toUpperCase();
76
- const isUpperSuffix = originalSuffix[0] === originalSuffix[0].toUpperCase();
77
- let newSuffix;
78
- if (isAllCaps) {
79
- newSuffix = singularSuffix.toUpperCase();
80
- }
81
- else if (isUpperSuffix) {
82
- newSuffix = singularSuffix.charAt(0).toUpperCase() + singularSuffix.slice(1);
83
- }
84
- else {
85
- newSuffix = singularSuffix;
86
- }
87
- return prefix + newSuffix;
88
- }
41
+ const exception = lookupException(normalizedWord);
42
+ if (exception) {
43
+ return exception;
89
44
  }
90
- // Compound *base words: the inflection library's (b)a branch in the ses$
91
- // rule incorrectly produces "codebasis" instead of "codebase".
92
- const baseMatch = normalizedWord.match(COMPOUND_BASE_REGEX);
93
- if (baseMatch) {
94
- return normalizedWord.slice(0, -1);
45
+ const segment = splitLastSegment(normalizedWord);
46
+ if (segment) {
47
+ const segmentException = lookupException(segment.word);
48
+ if (segmentException) {
49
+ return segment.prefix + segmentException;
50
+ }
95
51
  }
96
- return normalizeMalformedDoubleS(inflection.singularize(normalizedWord));
52
+ return singularizeByRules(normalizedWord);
97
53
  }
54
+ const F_OR_FE_REGEX = /(?:f|fe)$/i;
98
55
  function pluralizeCanonical(word) {
99
56
  const normalizedWord = normalizeMalformedDoubleS(word);
57
+ // -f/-fe words: only the f-stem nouns take -ves; the rest take a plain "s".
58
+ const fStem = pluralizeFStem(normalizedWord);
59
+ if (fStem) {
60
+ return fStem;
61
+ }
62
+ if (F_OR_FE_REGEX.test(normalizedWord)) {
63
+ return `${normalizedWord}s`;
64
+ }
100
65
  const pluralWord = normalizeMalformedDoubleS(inflection.pluralize(normalizedWord));
66
+ // -is nouns the inflection library leaves untouched (iris, chassis) rather
67
+ // than treating as Greek/Latin (analysis -> analyses).
68
+ if (pluralWord === normalizedWord && /is$/i.test(normalizedWord)) {
69
+ return `${normalizedWord}es`;
70
+ }
101
71
  return enforceDoubleSPlural(singularize(normalizedWord), pluralWord);
102
72
  }
103
73
  /**
@@ -116,7 +86,7 @@ export function pluralize(word) {
116
86
  * @returns The transformed string with only the final segment changed
117
87
  */
118
88
  function changeLastWord(fn, str) {
119
- const matches = str.match(/([A-Z]|_[a-z0-9])[a-z0-9]*_*$/);
89
+ const matches = str.match(LAST_SEGMENT_REGEX);
120
90
  const index = matches ? (matches.index ?? 0) + matches[1].length - 1 : 0;
121
91
  const suffixMatches = str.match(/_*$/);
122
92
  const suffixIndex = suffixMatches && suffixMatches.index !== undefined
package/esm/rules.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Rule-based singularization: the suffix rules alone, with no exception table.
3
+ *
4
+ * Kept separate from pluralize.ts so that scripts/generate-exceptions.ts can
5
+ * diff the rules against a dictionary without the exception table masking the
6
+ * very defects it is meant to record. Not part of the public API.
7
+ */
8
+ import * as inflection from 'inflection';
9
+ /**
10
+ * Latin plural suffixes that inflection handles differently than PostGraphile.
11
+ *
12
+ * The inflection library correctly singularizes Latin words (schemata -> schematum),
13
+ * but PostGraphile uses English-style naming (schemata -> schema).
14
+ *
15
+ * Format: [pluralSuffix, singularSuffix]
16
+ */
17
+ const LATIN_SUFFIX_OVERRIDES = [
18
+ ['schemata', 'schema'],
19
+ ['criteria', 'criterion'],
20
+ ['phenomena', 'phenomenon'],
21
+ ['media', 'medium'],
22
+ ['memoranda', 'memorandum'],
23
+ ['strata', 'stratum'],
24
+ ['curricula', 'curriculum'],
25
+ ['data', 'datum'],
26
+ ];
27
+ /**
28
+ * Compound words ending in "base" that the inflection library incorrectly
29
+ * singularizes via its (b)a branch in the ses$ rule (e.g. codebases -> codebasis).
30
+ * We intercept these before delegating to inflection.singularize().
31
+ */
32
+ const COMPOUND_BASE_REGEX = /(database|codebase|firebase|knowledgebase)s$/i;
33
+ /**
34
+ * Generic suffix rules applied before delegating to the inflection library,
35
+ * replacing inflection rules that are wrong for most English words.
36
+ *
37
+ * The biggest offender is `-ves`: inflection rewrites it to `-fe`/`-f` (knives
38
+ * -> knife, wolves -> wolf), but the overwhelming majority of `-ves` words
39
+ * simply drop the trailing "s" (derives -> derive, solves -> solve, olives ->
40
+ * olive). The genuine f-stem nouns are carried by SINGULAR_EXCEPTIONS, so the
41
+ * generic case here is "drop the s".
42
+ *
43
+ * Format: [pluralPattern, singularReplacement]
44
+ */
45
+ /**
46
+ * The complete set of English nouns whose plural rewrites -f/-fe to -ves.
47
+ *
48
+ * Both directions are wrong in the inflection library, which applies the -ves
49
+ * pattern by suffix shape: it invents "caves" for cafe, "saves" for safe and
50
+ * "barves" for barf, while spelling the real cases "leafs", "thiefs" and
51
+ * "loafs". Matched as a suffix so compounds work (bookshelf -> bookshelves,
52
+ * jackknife -> jackknives).
53
+ *
54
+ * Format: [singular, plural]
55
+ */
56
+ export const F_STEM_PLURALS = [
57
+ ['calf', 'calves'],
58
+ ['dwarf', 'dwarves'],
59
+ ['elf', 'elves'],
60
+ ['half', 'halves'],
61
+ ['hoof', 'hooves'],
62
+ ['knife', 'knives'],
63
+ ['leaf', 'leaves'],
64
+ ['life', 'lives'],
65
+ ['loaf', 'loaves'],
66
+ ['scarf', 'scarves'],
67
+ ['self', 'selves'],
68
+ ['sheaf', 'sheaves'],
69
+ ['shelf', 'shelves'],
70
+ ['thief', 'thieves'],
71
+ ['wharf', 'wharves'],
72
+ ['wife', 'wives'],
73
+ ['wolf', 'wolves'],
74
+ ];
75
+ /**
76
+ * Adjectives, never plurals: anxious, various, porous. No noun stem ends in
77
+ * "ou", so nothing here is ever a dropped-s away from a singular.
78
+ *
79
+ * There is no equivalent rule for the rest of "-is"/"-us", because none exists:
80
+ * "apis" and "iris" are both a vowel plus "s" (api + s, iri + s), so no suffix
81
+ * tells the plural from the singular. Whether a word is one or the other is a
82
+ * dictionary fact, and the dictionary-proven singulars live in
83
+ * SINGULAR_EXCEPTIONS as self-mappings (status -> status, analysis -> analysis).
84
+ * Words the dictionary does not know fall through to the generic "drop the s",
85
+ * which is what coined identifiers want: apis -> api, cpus -> cpu, uris -> uri.
86
+ */
87
+ const ADJECTIVE_OUS_REGEX = /ous$/i;
88
+ /**
89
+ * The only -ice plurals. The inflection library's rule is written `([m|l])ice`,
90
+ * whose character class also matches "|", and it fires on any word ending in
91
+ * "ice": police -> polouse, chalice -> chalouse, service -> servouse.
92
+ */
93
+ const MOUSE_PLURALS = {
94
+ dormice: 'dormouse',
95
+ fieldmice: 'fieldmouse',
96
+ lice: 'louse',
97
+ mice: 'mouse',
98
+ titmice: 'titmouse',
99
+ woodlice: 'woodlouse',
100
+ };
101
+ const ICE_REGEX = /ice$/i;
102
+ /** @see the GENERIC_SINGULAR_RULES documentation above. */
103
+ const GENERIC_SINGULAR_RULES = [
104
+ [/zzes$/i, 'zz'], // buzzes -> buzz
105
+ [/tzes$/i, 'tz'], // waltzes -> waltz
106
+ [/yses$/i, 'ysis'], // analyses -> analysis, dialyses -> dialysis
107
+ [/([^aeiou])uses$/i, '$1us'], // cactuses -> cactus, focuses -> focus
108
+ [/ves$/i, 've'], // derives -> derive, solves -> solve, olives -> olive
109
+ ];
110
+ const TRAILING_TRIPLE_S_REGEX = /[sS]{3,}$/;
111
+ const TRAILING_TRIPLE_S_BEFORE_ES_REGEX = /[sS]{3,}(?=e[sS]$)/;
112
+ function normalizeTrailingSRun(suffix) {
113
+ return suffix === suffix.toUpperCase() ? 'SS' : 'ss';
114
+ }
115
+ function normalizeTripleSBeforeEs(word) {
116
+ return word.replace(TRAILING_TRIPLE_S_BEFORE_ES_REGEX, normalizeTrailingSRun);
117
+ }
118
+ function normalizeTrailingTripleS(word) {
119
+ const match = word.match(TRAILING_TRIPLE_S_REGEX);
120
+ if (!match) {
121
+ return word;
122
+ }
123
+ const suffix = match[0];
124
+ const prefix = word.slice(0, -suffix.length);
125
+ const normalizedSuffix = normalizeTrailingSRun(suffix);
126
+ return `${prefix}${normalizedSuffix}`;
127
+ }
128
+ export function normalizeMalformedDoubleS(word) {
129
+ return normalizeTrailingTripleS(normalizeTripleSBeforeEs(word));
130
+ }
131
+ export function enforceDoubleSPlural(singularWord, pluralWord) {
132
+ if (!singularWord.toLowerCase().endsWith('ss')) {
133
+ return pluralWord;
134
+ }
135
+ // Defensive normalization for malformed outputs like "hazardClasss".
136
+ if (pluralWord === `${singularWord}s`) {
137
+ return `${singularWord}es`;
138
+ }
139
+ return pluralWord;
140
+ }
141
+ /**
142
+ * Pluralize the f-stem nouns (and their compounds), or null when `word` is not
143
+ * one — in which case an -f/-fe word takes a plain "s" (cafes, roofs, barfs).
144
+ */
145
+ export function pluralizeFStem(word) {
146
+ const lowerWord = word.toLowerCase();
147
+ for (const [singular, plural] of F_STEM_PLURALS) {
148
+ if (!lowerWord.endsWith(singular)) {
149
+ continue;
150
+ }
151
+ const stem = word.slice(0, word.length - singular.length);
152
+ const matched = word.slice(word.length - singular.length);
153
+ return stem + matchCase(matched, plural);
154
+ }
155
+ return null;
156
+ }
157
+ /**
158
+ * Restore the capitalization of `source` onto `replacement`.
159
+ */
160
+ export function restoreWordCase(source, replacement) {
161
+ if (source === source.toUpperCase()) {
162
+ return replacement.toUpperCase();
163
+ }
164
+ if (source[0] === source[0].toUpperCase()) {
165
+ return replacement.charAt(0).toUpperCase() + replacement.slice(1);
166
+ }
167
+ return replacement;
168
+ }
169
+ function matchCase(source, replacement) {
170
+ if (source && source === source.toUpperCase()) {
171
+ return replacement.toUpperCase();
172
+ }
173
+ return replacement;
174
+ }
175
+ function applyGenericSingularRules(word) {
176
+ for (const [pattern, replacement] of GENERIC_SINGULAR_RULES) {
177
+ if (!pattern.test(word)) {
178
+ continue;
179
+ }
180
+ return word.replace(pattern, (matched, ...groups) => {
181
+ const expanded = replacement.replace(/\$(\d)/g, (_, index) => String(groups[Number(index) - 1] ?? ''));
182
+ return matchCase(matched, expanded);
183
+ });
184
+ }
185
+ return null;
186
+ }
187
+ /**
188
+ * Singularize using suffix rules only — the fallback for words absent from the
189
+ * exception table (including coined identifiers that no dictionary knows).
190
+ */
191
+ export function singularizeByRules(word) {
192
+ const normalizedWord = normalizeMalformedDoubleS(word);
193
+ const lowerWord = normalizedWord.toLowerCase();
194
+ if (ADJECTIVE_OUS_REGEX.test(normalizedWord)) {
195
+ return normalizedWord;
196
+ }
197
+ if (ICE_REGEX.test(normalizedWord)) {
198
+ const mouse = Object.prototype.hasOwnProperty.call(MOUSE_PLURALS, lowerWord)
199
+ ? MOUSE_PLURALS[lowerWord]
200
+ : null;
201
+ return mouse ? restoreWordCase(normalizedWord, mouse) : normalizedWord;
202
+ }
203
+ for (const [pluralSuffix, singularSuffix] of LATIN_SUFFIX_OVERRIDES) {
204
+ if (lowerWord.endsWith(pluralSuffix)) {
205
+ const suffixStart = normalizedWord.length - pluralSuffix.length;
206
+ const prefix = normalizedWord.slice(0, suffixStart);
207
+ const originalSuffix = normalizedWord.slice(suffixStart);
208
+ const isAllCaps = originalSuffix === originalSuffix.toUpperCase();
209
+ const isUpperSuffix = originalSuffix[0] === originalSuffix[0].toUpperCase();
210
+ let newSuffix;
211
+ if (isAllCaps) {
212
+ newSuffix = singularSuffix.toUpperCase();
213
+ }
214
+ else if (isUpperSuffix) {
215
+ newSuffix =
216
+ singularSuffix.charAt(0).toUpperCase() + singularSuffix.slice(1);
217
+ }
218
+ else {
219
+ newSuffix = singularSuffix;
220
+ }
221
+ return prefix + newSuffix;
222
+ }
223
+ }
224
+ // Compound *base words: the inflection library's (b)a branch in the ses$
225
+ // rule incorrectly produces "codebasis" instead of "codebase".
226
+ if (COMPOUND_BASE_REGEX.test(normalizedWord)) {
227
+ return normalizedWord.slice(0, -1);
228
+ }
229
+ const generic = applyGenericSingularRules(normalizedWord);
230
+ if (generic) {
231
+ return generic;
232
+ }
233
+ return normalizeMalformedDoubleS(inflection.singularize(normalizedWord));
234
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Plural -> singular pairs that no generic suffix rule gets right.
3
+ *
4
+ * English singularization is not rule-decidable: `-ies` is `-y` for "bodies"
5
+ * but `-ie` for "cookies"; `-ches` drops "es" for "matches" but only "s" for
6
+ * "aches"; `-oes` drops "es" for "potatoes" but only "s" for "shoes". The
7
+ * generic rules in pluralize.ts handle the majority case for each suffix and
8
+ * this table carries the words where the majority case is wrong.
9
+ *
10
+ * GENERATED — do not hand-edit. Regenerate with:
11
+ *
12
+ * sudo apt-get install -y wamerican
13
+ * npx ts-node scripts/generate-exceptions.ts
14
+ *
15
+ * Every entry is dictionary-proven: the singular is a real word whose
16
+ * pluralization returns the key (see scripts/generate-exceptions.ts).
17
+ */
18
+ export declare const SINGULAR_EXCEPTIONS: Record<string, string>;