@quazardous/qdadm 2.14.0 → 2.15.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 +1 -0
- package/package.json +6 -4
- package/src/chain/index.ts +5 -0
- package/src/composables/useEntityItemShowPage.ts +8 -0
- package/src/composables/useListPage.ts +23 -0
- package/src/composables/useListPage.types.ts +3 -0
- package/src/composables/useLiveEntity.ts +115 -0
- package/src/deferred/index.ts +5 -0
- package/src/entity/EntityManager.cache.ts +20 -0
- package/src/entity/EntityManager.interface.ts +3 -0
- package/src/entity/EntityManager.ts +29 -1
- package/src/entity/EntityManager.types.ts +32 -0
- package/src/gen/vite-plugin.ts +4 -0
- package/src/index.ts +10 -0
- package/src/kernel/Kernel.registries.ts +31 -5
- package/src/kernel/Kernel.ts +3 -0
- package/src/kernel/Kernel.types.ts +31 -0
- package/src/kernel/LiveEntityRouter.ts +189 -0
- package/src/kernel/SSEBridge.ts +3 -0
- package/src/query/index.ts +7 -0
- package/src/types/index.ts +2 -0
- package/src/utils/pluralize.ts +472 -0
- package/src/vite/qdadmPlugin.ts +5 -19
- package/src/vite-env.d.ts +0 -16
- package/src/generated/managers/testManager.js +0 -45
- package/src/types/pluralize.d.ts +0 -19
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LiveEntityRouter — turns "something changed elsewhere" into cache
|
|
3
|
+
* invalidation for the right EntityManager (#1888 lot C, reported in #1887).
|
|
4
|
+
*
|
|
5
|
+
* The transport is deliberately not part of this class. Its entry point is
|
|
6
|
+
* `notify()`, a plain fact: *this entity changed, possibly this record*. SSE is
|
|
7
|
+
* wired on top by `attachSignalTransport()`, and a WebSocket or a
|
|
8
|
+
* `BroadcastChannel` between two tabs of the same admin would attach the same
|
|
9
|
+
* way — see docs/adr/0009-live-entities.md.
|
|
10
|
+
*
|
|
11
|
+
* Two boundaries the ADR fixes and this class enforces:
|
|
12
|
+
*
|
|
13
|
+
* - **The event carries a fact, never an instruction.** Nothing in the payload
|
|
14
|
+
* may tell the front what to do; the payload says what changed and the front
|
|
15
|
+
* decides what that implies.
|
|
16
|
+
* - **The security scope is the front's.** An event never causes a request the
|
|
17
|
+
* current user could not have issued: an entity they cannot read is dropped
|
|
18
|
+
* rather than refetched, otherwise every pushed event sprays 401/403.
|
|
19
|
+
*
|
|
20
|
+
* @experimental Shape may change in a minor release — see docs/API_STABILITY.md.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { SignalBus } from './SignalBus'
|
|
24
|
+
|
|
25
|
+
/** The actions a live event can report. */
|
|
26
|
+
export type LiveEntityAction = 'created' | 'updated' | 'deleted'
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Which entities the app declares as having an external writer.
|
|
30
|
+
* `true` / `'*'` accepts every registered entity.
|
|
31
|
+
*/
|
|
32
|
+
export type LiveEntitiesDeclaration = string[] | true | '*'
|
|
33
|
+
|
|
34
|
+
/** Minimal orchestrator surface this router needs. */
|
|
35
|
+
export interface LiveOrchestratorLike {
|
|
36
|
+
has(name: string): boolean
|
|
37
|
+
get(name: string): { canRead?: () => boolean } | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface LiveEntityRouterOptions {
|
|
41
|
+
signals: SignalBus
|
|
42
|
+
/** Entities declared as externally written. */
|
|
43
|
+
entities: LiveEntitiesDeclaration
|
|
44
|
+
/** Used to resolve the manager for the permission check. */
|
|
45
|
+
orchestrator?: LiveOrchestratorLike | null
|
|
46
|
+
/** Signal prefix the transport publishes under (default: 'sse'). */
|
|
47
|
+
signalPrefix?: string
|
|
48
|
+
debug?: boolean
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Payload shape a transport frame is expected to carry. */
|
|
52
|
+
interface LiveFramePayload {
|
|
53
|
+
entity?: string
|
|
54
|
+
id?: string | number
|
|
55
|
+
action?: LiveEntityAction
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const ACTION_BY_EVENT: Record<string, LiveEntityAction> = {
|
|
59
|
+
'entity:created': 'created',
|
|
60
|
+
'entity:updated': 'updated',
|
|
61
|
+
'entity:deleted': 'deleted',
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class LiveEntityRouter {
|
|
65
|
+
private _signals: SignalBus
|
|
66
|
+
private _entities: LiveEntitiesDeclaration
|
|
67
|
+
private _orchestrator: LiveOrchestratorLike | null
|
|
68
|
+
private _signalPrefix: string
|
|
69
|
+
private _debug: boolean
|
|
70
|
+
private _cleanups: Array<() => void> = []
|
|
71
|
+
/** Entities seen on the wire but never declared — warned about once each. */
|
|
72
|
+
private _warned = new Set<string>()
|
|
73
|
+
|
|
74
|
+
constructor(options: LiveEntityRouterOptions) {
|
|
75
|
+
const {
|
|
76
|
+
signals,
|
|
77
|
+
entities,
|
|
78
|
+
orchestrator = null,
|
|
79
|
+
signalPrefix = 'sse',
|
|
80
|
+
debug = false,
|
|
81
|
+
} = options
|
|
82
|
+
|
|
83
|
+
if (!signals) throw new Error('[LiveEntityRouter] signals (SignalBus) is required')
|
|
84
|
+
|
|
85
|
+
this._signals = signals
|
|
86
|
+
this._entities = entities
|
|
87
|
+
this._orchestrator = orchestrator
|
|
88
|
+
this._signalPrefix = signalPrefix
|
|
89
|
+
this._debug = debug
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Is this entity declared as externally written? */
|
|
93
|
+
isDeclared(entity: string): boolean {
|
|
94
|
+
if (this._entities === true || this._entities === '*') return true
|
|
95
|
+
return Array.isArray(this._entities) && this._entities.includes(entity)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Report an external change. Transport-agnostic entry point.
|
|
100
|
+
*
|
|
101
|
+
* @returns true when the change was routed, false when it was dropped
|
|
102
|
+
* (undeclared entity, unknown manager, or one the user cannot read).
|
|
103
|
+
*/
|
|
104
|
+
notify(entity: string, action: LiveEntityAction = 'updated', id?: string | number): boolean {
|
|
105
|
+
if (!entity) return false
|
|
106
|
+
|
|
107
|
+
if (!this.isDeclared(entity)) {
|
|
108
|
+
// Not an error: a stream carries more than entity mutations. But a
|
|
109
|
+
// silently dropped frame is the hardest kind of bug to find, so say it
|
|
110
|
+
// once per entity in dev.
|
|
111
|
+
if (!this._warned.has(entity)) {
|
|
112
|
+
this._warned.add(entity)
|
|
113
|
+
this._log(
|
|
114
|
+
`Ignoring a live event for "${entity}": not declared in sse.entities. ` +
|
|
115
|
+
`Add it there if this backend writes to it out of session.`
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
return false
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// has() first: Orchestrator.get() THROWS for an unknown name (it is built
|
|
122
|
+
// to catch developer typos loudly). Letting that escape would blow up
|
|
123
|
+
// inside the signal bus on every incoming frame — a declared entity whose
|
|
124
|
+
// module is lazily loaded, or a typo in sse.entities, must degrade to a
|
|
125
|
+
// dropped event, not to an exception storm.
|
|
126
|
+
let manager: { canRead?: () => boolean } | undefined
|
|
127
|
+
if (this._orchestrator) {
|
|
128
|
+
if (!this._orchestrator.has(entity)) {
|
|
129
|
+
this._log(`Ignoring a live event for "${entity}": no manager registered under that name.`)
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
manager = this._orchestrator.get(entity)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// The security scope is the front's: never refetch what this user could not
|
|
136
|
+
// have asked for in the first place.
|
|
137
|
+
if (manager?.canRead && !manager.canRead()) {
|
|
138
|
+
this._log(`Ignoring a live event for "${entity}": current user cannot read it.`)
|
|
139
|
+
return false
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
this._signals.emit('entity:data-invalidate', {
|
|
143
|
+
entity,
|
|
144
|
+
action,
|
|
145
|
+
id,
|
|
146
|
+
source: 'remote',
|
|
147
|
+
})
|
|
148
|
+
this._signals.emitEntity?.(entity, action, { id, source: 'remote' })
|
|
149
|
+
|
|
150
|
+
this._log(`Routed ${action} on "${entity}"${id !== undefined ? ` (id ${id})` : ''}`)
|
|
151
|
+
return true
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Subscribe to the transport's frames on the signal bus.
|
|
156
|
+
*
|
|
157
|
+
* Recognises `{prefix}:entity:{created,updated,deleted}` carrying
|
|
158
|
+
* `{ entity, id? }` — the contract validated downstream in #1887.
|
|
159
|
+
*/
|
|
160
|
+
attachSignalTransport(): void {
|
|
161
|
+
for (const [event, action] of Object.entries(ACTION_BY_EVENT)) {
|
|
162
|
+
const signal = `${this._signalPrefix}:${event}`
|
|
163
|
+
this._cleanups.push(
|
|
164
|
+
this._signals.on(signal, (received: { name: string; data: unknown }) => {
|
|
165
|
+
const frame = (received?.data ?? {}) as { data?: LiveFramePayload }
|
|
166
|
+
// Transports wrap the decoded body in `data` (see SSEBridge); accept
|
|
167
|
+
// a bare payload too so a non-SSE caller isn't forced to fake it.
|
|
168
|
+
const payload = (frame.data ?? frame) as LiveFramePayload
|
|
169
|
+
if (!payload?.entity) return
|
|
170
|
+
this.notify(payload.entity, payload.action ?? action, payload.id)
|
|
171
|
+
})
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Drop every subscription. */
|
|
177
|
+
destroy(): void {
|
|
178
|
+
this._cleanups.forEach((off) => off())
|
|
179
|
+
this._cleanups = []
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private _log(...args: unknown[]): void {
|
|
183
|
+
if (this._debug) console.debug('[LiveEntityRouter]', ...args)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function createLiveEntityRouter(options: LiveEntityRouterOptions): LiveEntityRouter {
|
|
188
|
+
return new LiveEntityRouter(options)
|
|
189
|
+
}
|
package/src/kernel/SSEBridge.ts
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
* shared with qdcms. The auth-aware connect/disconnect behaviour is now
|
|
6
6
|
* configurable via `connectOnSignal` / `disconnectOnSignal` options; defaults
|
|
7
7
|
* remain `'auth:login'` / `'auth:logout'` for backwards compatibility.
|
|
8
|
+
*
|
|
9
|
+
* @experimental Signal mapping and reconnection options may change in a minor
|
|
10
|
+
* release — see docs/API_STABILITY.md.
|
|
8
11
|
*/
|
|
9
12
|
|
|
10
13
|
export { SSEBridge, createSSEBridge, SSE_SIGNALS } from '@quazardous/qdcore'
|
package/src/query/index.ts
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
* Query Module - MongoDB-like filtering for arrays
|
|
3
3
|
*
|
|
4
4
|
* Provides client-side filtering with the same query syntax used for API calls.
|
|
5
|
+
*
|
|
6
|
+
* @experimental Applies to the EXECUTOR CLASSES below, used directly. The query
|
|
7
|
+
* object syntax they interpret (`{ field: { $in: [...] } }`) is stable — it is
|
|
8
|
+
* what list filters and EntityManager.query() speak. See
|
|
9
|
+
* docs/API_STABILITY.md.
|
|
10
|
+
*
|
|
11
|
+
* @module query
|
|
5
12
|
*/
|
|
6
13
|
|
|
7
14
|
export { QueryExecutor, getNestedValue } from './QueryExecutor'
|
package/src/types/index.ts
CHANGED
|
@@ -164,6 +164,8 @@ export interface EntityManagerOptions<T extends EntityRecord = EntityRecord> {
|
|
|
164
164
|
readOnly?: boolean
|
|
165
165
|
warmup?: boolean
|
|
166
166
|
authSensitive?: boolean
|
|
167
|
+
/** What this entity does when it changed elsewhere (#1888). */
|
|
168
|
+
live?: { refresh?: 'mounted' | false; coalesceMs?: number }
|
|
167
169
|
system?: boolean
|
|
168
170
|
scopeWhitelist?: string[] | null
|
|
169
171
|
isOwn?: ((record: T, user: unknown) => boolean) | null
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vendored ESM port of `pluralize@8.0.0` (#1454).
|
|
3
|
+
*
|
|
4
|
+
* qdadm ships raw TS sources; `pluralize` was our only CJS dependency and
|
|
5
|
+
* forced the whole `optimizeDeps.include` machinery in qdadmVitePlugin —
|
|
6
|
+
* which still broke for file:-linked consumers (npm install-links=false)
|
|
7
|
+
* where the dep is never installed at the consumer root. Vendoring removes
|
|
8
|
+
* the dependency class entirely. Rules/irregulars tables are verbatim.
|
|
9
|
+
*
|
|
10
|
+
* Original: https://github.com/plurals/pluralize
|
|
11
|
+
*
|
|
12
|
+
* The MIT License (MIT)
|
|
13
|
+
*
|
|
14
|
+
* Copyright (c) 2013 Blake Embrey (hello@blakeembrey.com)
|
|
15
|
+
*
|
|
16
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
17
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
18
|
+
* in the Software without restriction, including without limitation the rights
|
|
19
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
20
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
21
|
+
* furnished to do so, subject to the following conditions:
|
|
22
|
+
*
|
|
23
|
+
* The above copyright notice and this permission notice shall be included in
|
|
24
|
+
* all copies or substantial portions of the Software.
|
|
25
|
+
*
|
|
26
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
27
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
28
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
29
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
30
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
31
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
32
|
+
* THE SOFTWARE.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
type Rule = [RegExp, string]
|
|
36
|
+
|
|
37
|
+
// Rule storage - pluralize and singularize need to be run sequentially,
|
|
38
|
+
// while other rules can be optimized using an object for instant lookups.
|
|
39
|
+
const pluralRules: Rule[] = []
|
|
40
|
+
const singularRules: Rule[] = []
|
|
41
|
+
const uncountables: Record<string, boolean> = {}
|
|
42
|
+
const irregularPlurals: Record<string, string> = {}
|
|
43
|
+
const irregularSingles: Record<string, string> = {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Sanitize a pluralization rule to a usable regular expression.
|
|
47
|
+
*/
|
|
48
|
+
function sanitizeRule(rule: RegExp | string): RegExp {
|
|
49
|
+
if (typeof rule === 'string') {
|
|
50
|
+
return new RegExp('^' + rule + '$', 'i')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return rule
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Pass in a word token to produce a function that can replicate the case on
|
|
58
|
+
* another word.
|
|
59
|
+
*/
|
|
60
|
+
function restoreCase(word: string, token: string): string {
|
|
61
|
+
// Tokens are an exact match.
|
|
62
|
+
if (word === token) return token
|
|
63
|
+
|
|
64
|
+
// Lower cased words. E.g. "hello".
|
|
65
|
+
if (word === word.toLowerCase()) return token.toLowerCase()
|
|
66
|
+
|
|
67
|
+
// Upper cased words. E.g. "WHISKY".
|
|
68
|
+
if (word === word.toUpperCase()) return token.toUpperCase()
|
|
69
|
+
|
|
70
|
+
// Title cased words. E.g. "Title".
|
|
71
|
+
if (word.charAt(0) === word.charAt(0).toUpperCase()) {
|
|
72
|
+
return token.charAt(0).toUpperCase() + token.substring(1).toLowerCase()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Lower cased words. E.g. "test".
|
|
76
|
+
return token.toLowerCase()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Interpolate a regexp string.
|
|
81
|
+
*/
|
|
82
|
+
function interpolate(str: string, args: IArguments): string {
|
|
83
|
+
return str.replace(/\$(\d{1,2})/g, function (_match, index) {
|
|
84
|
+
return args[index] || ''
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Replace a word using a rule.
|
|
90
|
+
*/
|
|
91
|
+
function replace(word: string, rule: Rule): string {
|
|
92
|
+
return word.replace(rule[0], function (match, index) {
|
|
93
|
+
// eslint-disable-next-line prefer-rest-params
|
|
94
|
+
const result = interpolate(rule[1], arguments)
|
|
95
|
+
|
|
96
|
+
if (match === '') {
|
|
97
|
+
return restoreCase(word.charAt(index - 1), result)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return restoreCase(match, result)
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Sanitize a word by passing in the word and sanitization rules.
|
|
106
|
+
*/
|
|
107
|
+
function sanitizeWord(token: string, word: string, rules: Rule[]): string {
|
|
108
|
+
// Empty string or doesn't need fixing.
|
|
109
|
+
if (!token.length || Object.prototype.hasOwnProperty.call(uncountables, token)) {
|
|
110
|
+
return word
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let len = rules.length
|
|
114
|
+
|
|
115
|
+
// Iterate over the sanitization rules and use the first one to match.
|
|
116
|
+
while (len--) {
|
|
117
|
+
const rule = rules[len]!
|
|
118
|
+
|
|
119
|
+
if (rule[0].test(word)) return replace(word, rule)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return word
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Replace a word with the updated word.
|
|
127
|
+
*/
|
|
128
|
+
function replaceWord(
|
|
129
|
+
replaceMap: Record<string, string>,
|
|
130
|
+
keepMap: Record<string, string>,
|
|
131
|
+
rules: Rule[]
|
|
132
|
+
): (word: string) => string {
|
|
133
|
+
return function (word: string): string {
|
|
134
|
+
// Get the correct token and case restoration functions.
|
|
135
|
+
const token = word.toLowerCase()
|
|
136
|
+
|
|
137
|
+
// Check against the keep object map.
|
|
138
|
+
if (Object.prototype.hasOwnProperty.call(keepMap, token)) {
|
|
139
|
+
return restoreCase(word, token)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Check against the replacement map for a direct word replacement.
|
|
143
|
+
if (Object.prototype.hasOwnProperty.call(replaceMap, token)) {
|
|
144
|
+
return restoreCase(word, replaceMap[token]!)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Run all the rules against the word.
|
|
148
|
+
return sanitizeWord(token, word, rules)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Check if a word is part of the map.
|
|
154
|
+
*/
|
|
155
|
+
function checkWord(
|
|
156
|
+
replaceMap: Record<string, string>,
|
|
157
|
+
keepMap: Record<string, string>,
|
|
158
|
+
rules: Rule[]
|
|
159
|
+
): (word: string) => boolean {
|
|
160
|
+
return function (word: string): boolean {
|
|
161
|
+
const token = word.toLowerCase()
|
|
162
|
+
|
|
163
|
+
if (Object.prototype.hasOwnProperty.call(keepMap, token)) return true
|
|
164
|
+
if (Object.prototype.hasOwnProperty.call(replaceMap, token)) return false
|
|
165
|
+
|
|
166
|
+
return sanitizeWord(token, token, rules) === token
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Pluralize a word.
|
|
172
|
+
*/
|
|
173
|
+
const plural = replaceWord(irregularSingles, irregularPlurals, pluralRules)
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Check if a word is plural.
|
|
177
|
+
*/
|
|
178
|
+
const isPlural = checkWord(irregularSingles, irregularPlurals, pluralRules)
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Singularize a word.
|
|
182
|
+
*/
|
|
183
|
+
const singular = replaceWord(irregularPlurals, irregularSingles, singularRules)
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Check if a word is singular.
|
|
187
|
+
*/
|
|
188
|
+
const isSingular = checkWord(irregularPlurals, irregularSingles, singularRules)
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Pluralize or singularize a word based on the passed in count.
|
|
192
|
+
*/
|
|
193
|
+
function pluralize(word: string, count?: number, inclusive?: boolean): string {
|
|
194
|
+
const pluralized = count === 1 ? singular(word) : plural(word)
|
|
195
|
+
|
|
196
|
+
return (inclusive ? count + ' ' : '') + pluralized
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function addPluralRule(rule: RegExp | string, replacement: string): void {
|
|
200
|
+
pluralRules.push([sanitizeRule(rule), replacement])
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function addSingularRule(rule: RegExp | string, replacement: string): void {
|
|
204
|
+
singularRules.push([sanitizeRule(rule), replacement])
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function addUncountableRule(word: RegExp | string): void {
|
|
208
|
+
if (typeof word === 'string') {
|
|
209
|
+
uncountables[word.toLowerCase()] = true
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Set singular and plural references for the word.
|
|
214
|
+
addPluralRule(word, '$0')
|
|
215
|
+
addSingularRule(word, '$0')
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function addIrregularRule(single: string, plural: string): void {
|
|
219
|
+
plural = plural.toLowerCase()
|
|
220
|
+
single = single.toLowerCase()
|
|
221
|
+
|
|
222
|
+
irregularSingles[single] = plural
|
|
223
|
+
irregularPlurals[plural] = single
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Irregular rules.
|
|
228
|
+
*/
|
|
229
|
+
;(
|
|
230
|
+
[
|
|
231
|
+
// Pronouns.
|
|
232
|
+
['I', 'we'],
|
|
233
|
+
['me', 'us'],
|
|
234
|
+
['he', 'they'],
|
|
235
|
+
['she', 'they'],
|
|
236
|
+
['them', 'them'],
|
|
237
|
+
['myself', 'ourselves'],
|
|
238
|
+
['yourself', 'yourselves'],
|
|
239
|
+
['itself', 'themselves'],
|
|
240
|
+
['herself', 'themselves'],
|
|
241
|
+
['himself', 'themselves'],
|
|
242
|
+
['themself', 'themselves'],
|
|
243
|
+
['is', 'are'],
|
|
244
|
+
['was', 'were'],
|
|
245
|
+
['has', 'have'],
|
|
246
|
+
['this', 'these'],
|
|
247
|
+
['that', 'those'],
|
|
248
|
+
// Words ending in with a consonant and `o`.
|
|
249
|
+
['echo', 'echoes'],
|
|
250
|
+
['dingo', 'dingoes'],
|
|
251
|
+
['volcano', 'volcanoes'],
|
|
252
|
+
['tornado', 'tornadoes'],
|
|
253
|
+
['torpedo', 'torpedoes'],
|
|
254
|
+
// Ends with `us`.
|
|
255
|
+
['genus', 'genera'],
|
|
256
|
+
['viscus', 'viscera'],
|
|
257
|
+
// Ends with `ma`.
|
|
258
|
+
['stigma', 'stigmata'],
|
|
259
|
+
['stoma', 'stomata'],
|
|
260
|
+
['dogma', 'dogmata'],
|
|
261
|
+
['lemma', 'lemmata'],
|
|
262
|
+
['schema', 'schemata'],
|
|
263
|
+
['anathema', 'anathemata'],
|
|
264
|
+
// Other irregular rules.
|
|
265
|
+
['ox', 'oxen'],
|
|
266
|
+
['axe', 'axes'],
|
|
267
|
+
['die', 'dice'],
|
|
268
|
+
['yes', 'yeses'],
|
|
269
|
+
['foot', 'feet'],
|
|
270
|
+
['eave', 'eaves'],
|
|
271
|
+
['goose', 'geese'],
|
|
272
|
+
['tooth', 'teeth'],
|
|
273
|
+
['quiz', 'quizzes'],
|
|
274
|
+
['human', 'humans'],
|
|
275
|
+
['proof', 'proofs'],
|
|
276
|
+
['carve', 'carves'],
|
|
277
|
+
['valve', 'valves'],
|
|
278
|
+
['looey', 'looies'],
|
|
279
|
+
['thief', 'thieves'],
|
|
280
|
+
['groove', 'grooves'],
|
|
281
|
+
['pickaxe', 'pickaxes'],
|
|
282
|
+
['passerby', 'passersby'],
|
|
283
|
+
] as Array<[string, string]>
|
|
284
|
+
).forEach((rule) => addIrregularRule(rule[0], rule[1]))
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Pluralization rules.
|
|
288
|
+
*/
|
|
289
|
+
;(
|
|
290
|
+
[
|
|
291
|
+
[/s?$/i, 's'],
|
|
292
|
+
[/[^\u0000-\u007F]$/i, '$0'],
|
|
293
|
+
[/([^aeiou]ese)$/i, '$1'],
|
|
294
|
+
[/(ax|test)is$/i, '$1es'],
|
|
295
|
+
[/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],
|
|
296
|
+
[/(e[mn]u)s?$/i, '$1s'],
|
|
297
|
+
[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],
|
|
298
|
+
[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],
|
|
299
|
+
[/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],
|
|
300
|
+
[/(seraph|cherub)(?:im)?$/i, '$1im'],
|
|
301
|
+
[/(her|at|gr)o$/i, '$1oes'],
|
|
302
|
+
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],
|
|
303
|
+
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],
|
|
304
|
+
[/sis$/i, 'ses'],
|
|
305
|
+
[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],
|
|
306
|
+
[/([^aeiouy]|qu)y$/i, '$1ies'],
|
|
307
|
+
[/([^ch][ieo][ln])ey$/i, '$1ies'],
|
|
308
|
+
[/(x|ch|ss|sh|zz)$/i, '$1es'],
|
|
309
|
+
[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],
|
|
310
|
+
[/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],
|
|
311
|
+
[/(pe)(?:rson|ople)$/i, '$1ople'],
|
|
312
|
+
[/(child)(?:ren)?$/i, '$1ren'],
|
|
313
|
+
[/eaux$/i, '$0'],
|
|
314
|
+
[/m[ae]n$/i, 'men'],
|
|
315
|
+
['thou', 'you'],
|
|
316
|
+
] as Array<[RegExp | string, string]>
|
|
317
|
+
).forEach((rule) => addPluralRule(rule[0], rule[1]))
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Singularization rules.
|
|
321
|
+
*/
|
|
322
|
+
;(
|
|
323
|
+
[
|
|
324
|
+
[/s$/i, ''],
|
|
325
|
+
[/(ss)$/i, '$1'],
|
|
326
|
+
[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'],
|
|
327
|
+
[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],
|
|
328
|
+
[/ies$/i, 'y'],
|
|
329
|
+
[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],
|
|
330
|
+
[/\b(mon|smil)ies$/i, '$1ey'],
|
|
331
|
+
[/\b((?:tit)?m|l)ice$/i, '$1ouse'],
|
|
332
|
+
[/(seraph|cherub)im$/i, '$1'],
|
|
333
|
+
[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'],
|
|
334
|
+
[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'],
|
|
335
|
+
[/(movie|twelve|abuse|e[mn]u)s$/i, '$1'],
|
|
336
|
+
[/(test)(?:is|es)$/i, '$1is'],
|
|
337
|
+
[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],
|
|
338
|
+
[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],
|
|
339
|
+
[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],
|
|
340
|
+
[/(alumn|alg|vertebr)ae$/i, '$1a'],
|
|
341
|
+
[/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],
|
|
342
|
+
[/(matr|append)ices$/i, '$1ix'],
|
|
343
|
+
[/(pe)(rson|ople)$/i, '$1rson'],
|
|
344
|
+
[/(child)ren$/i, '$1'],
|
|
345
|
+
[/(eau)x?$/i, '$1'],
|
|
346
|
+
[/men$/i, 'man'],
|
|
347
|
+
] as Array<[RegExp | string, string]>
|
|
348
|
+
).forEach((rule) => addSingularRule(rule[0], rule[1]))
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Uncountable rules.
|
|
352
|
+
*/
|
|
353
|
+
;(
|
|
354
|
+
[
|
|
355
|
+
// Singular words with no plurals.
|
|
356
|
+
'adulthood',
|
|
357
|
+
'advice',
|
|
358
|
+
'agenda',
|
|
359
|
+
'aid',
|
|
360
|
+
'aircraft',
|
|
361
|
+
'alcohol',
|
|
362
|
+
'ammo',
|
|
363
|
+
'analytics',
|
|
364
|
+
'anime',
|
|
365
|
+
'athletics',
|
|
366
|
+
'audio',
|
|
367
|
+
'bison',
|
|
368
|
+
'blood',
|
|
369
|
+
'bream',
|
|
370
|
+
'buffalo',
|
|
371
|
+
'butter',
|
|
372
|
+
'carp',
|
|
373
|
+
'cash',
|
|
374
|
+
'chassis',
|
|
375
|
+
'chess',
|
|
376
|
+
'clothing',
|
|
377
|
+
'cod',
|
|
378
|
+
'commerce',
|
|
379
|
+
'cooperation',
|
|
380
|
+
'corps',
|
|
381
|
+
'debris',
|
|
382
|
+
'diabetes',
|
|
383
|
+
'digestion',
|
|
384
|
+
'elk',
|
|
385
|
+
'energy',
|
|
386
|
+
'equipment',
|
|
387
|
+
'excretion',
|
|
388
|
+
'expertise',
|
|
389
|
+
'firmware',
|
|
390
|
+
'flounder',
|
|
391
|
+
'fun',
|
|
392
|
+
'gallows',
|
|
393
|
+
'garbage',
|
|
394
|
+
'graffiti',
|
|
395
|
+
'hardware',
|
|
396
|
+
'headquarters',
|
|
397
|
+
'health',
|
|
398
|
+
'herpes',
|
|
399
|
+
'highjinks',
|
|
400
|
+
'homework',
|
|
401
|
+
'housework',
|
|
402
|
+
'information',
|
|
403
|
+
'jeans',
|
|
404
|
+
'justice',
|
|
405
|
+
'kudos',
|
|
406
|
+
'labour',
|
|
407
|
+
'literature',
|
|
408
|
+
'machinery',
|
|
409
|
+
'mackerel',
|
|
410
|
+
'mail',
|
|
411
|
+
'media',
|
|
412
|
+
'mews',
|
|
413
|
+
'moose',
|
|
414
|
+
'music',
|
|
415
|
+
'mud',
|
|
416
|
+
'manga',
|
|
417
|
+
'news',
|
|
418
|
+
'only',
|
|
419
|
+
'personnel',
|
|
420
|
+
'pike',
|
|
421
|
+
'plankton',
|
|
422
|
+
'pliers',
|
|
423
|
+
'police',
|
|
424
|
+
'pollution',
|
|
425
|
+
'premises',
|
|
426
|
+
'rain',
|
|
427
|
+
'research',
|
|
428
|
+
'rice',
|
|
429
|
+
'salmon',
|
|
430
|
+
'scissors',
|
|
431
|
+
'series',
|
|
432
|
+
'sewage',
|
|
433
|
+
'shambles',
|
|
434
|
+
'shrimp',
|
|
435
|
+
'software',
|
|
436
|
+
'species',
|
|
437
|
+
'staff',
|
|
438
|
+
'swine',
|
|
439
|
+
'tennis',
|
|
440
|
+
'traffic',
|
|
441
|
+
'transportation',
|
|
442
|
+
'trout',
|
|
443
|
+
'tuna',
|
|
444
|
+
'wealth',
|
|
445
|
+
'welfare',
|
|
446
|
+
'whiting',
|
|
447
|
+
'wildebeest',
|
|
448
|
+
'wildlife',
|
|
449
|
+
'you',
|
|
450
|
+
/pok[eé]mon$/i,
|
|
451
|
+
// Regexes.
|
|
452
|
+
/[^aeiou]ese$/i, // "chinese", "japanese"
|
|
453
|
+
/deer$/i, // "deer", "reindeer"
|
|
454
|
+
/fish$/i, // "fish", "blowfish", "angelfish"
|
|
455
|
+
/measles$/i,
|
|
456
|
+
/o[iu]s$/i, // "carnivorous"
|
|
457
|
+
/pox$/i, // "chickpox", "smallpox"
|
|
458
|
+
/sheep$/i,
|
|
459
|
+
] as Array<RegExp | string>
|
|
460
|
+
).forEach(addUncountableRule)
|
|
461
|
+
|
|
462
|
+
pluralize.plural = plural
|
|
463
|
+
pluralize.isPlural = isPlural
|
|
464
|
+
pluralize.singular = singular
|
|
465
|
+
pluralize.isSingular = isSingular
|
|
466
|
+
pluralize.addPluralRule = addPluralRule
|
|
467
|
+
pluralize.addSingularRule = addSingularRule
|
|
468
|
+
pluralize.addUncountableRule = addUncountableRule
|
|
469
|
+
pluralize.addIrregularRule = addIrregularRule
|
|
470
|
+
|
|
471
|
+
export { plural, isPlural, singular, isSingular, addPluralRule, addSingularRule, addUncountableRule, addIrregularRule }
|
|
472
|
+
export default pluralize
|