|
1 | 1 | import { MessageFormatElement, parse, ParserOptions } from '@formatjs/icu-messageformat-parser'
|
2 |
| -import { LoaderDefinition } from 'webpack' |
3 | 2 | import { validate } from 'schema-utils'
|
| 3 | +import { LoaderDefinition } from 'webpack' |
4 | 4 |
|
5 | 5 | import { prehandle } from './prehandler'
|
6 |
| -import { getPseudoLocale } from './pseudo-locale' |
| 6 | +import { getPseudoLocale, Handler } from './pseudo-locale' |
7 | 7 | import { Options, ResourceQuery, schemaOptions, schemaResourceQuery } from './types'
|
8 | 8 |
|
9 | 9 | const loader: LoaderDefinition<Options> = function (source) {
|
10 | 10 | this.cacheable()
|
11 | 11 | const options = this.getOptions(schemaOptions)
|
12 |
| - const pseudoLocale = options.pseudoLocale ?? getResourceQuery(this).pseudoLocale |
13 | 12 | const compiled = compile(prehandle(options.format ?? 'default', JSON.parse(source)), {
|
14 | 13 | ignoreTag: options.ignoreTag,
|
15 | 14 | requiresOtherClause: options.requiresOtherClause,
|
16 | 15 | shouldParseSkeletons: options.shouldParseSkeletons,
|
17 |
| - posthandler: typeof pseudoLocale === 'string' ? getPseudoLocale(pseudoLocale) : undefined, |
| 16 | + handlers: [ |
| 17 | + // 1. Pseudo-locales |
| 18 | + getPseudoLocale(options.pseudoLocale ?? getResourceQuery(this).pseudoLocale), |
| 19 | + ], |
18 | 20 | })
|
19 | 21 | return JSON.stringify(Object.fromEntries(compiled))
|
20 | 22 | }
|
21 | 23 |
|
22 | 24 | export default loader
|
23 | 25 |
|
24 | 26 | interface CompileOptions extends ParserOptions {
|
25 |
| - posthandler?(elements: MessageFormatElement[]): MessageFormatElement[] |
| 27 | + readonly handlers: readonly (Handler | undefined)[] |
26 | 28 | }
|
27 | 29 |
|
28 |
| -function compile(messages: [string, string][], options: CompileOptions) { |
29 |
| - type ParsedEntry = readonly [string, MessageFormatElement[]] |
30 |
| - return messages.map(([key, message]): ParsedEntry => { |
31 |
| - const parsed = parse(message, options) |
32 |
| - return [key, options.posthandler?.(parsed) ?? parsed] |
| 30 | +function compile(messages: [string, string][], { handlers, ...options }: CompileOptions) { |
| 31 | + return messages.map(([key, message]): [string, MessageFormatElement[]] => { |
| 32 | + const elements = handlers.reduceRight<Iterable<MessageFormatElement>>( |
| 33 | + (elements, handler) => handler?.(elements) ?? elements, |
| 34 | + parse(message, options) |
| 35 | + ) |
| 36 | + return [key, Array.from(elements)] |
33 | 37 | })
|
34 | 38 | }
|
35 | 39 |
|
|
0 commit comments