|
1 | 1 | import resolve from "./resolver";
|
2 |
| -import parse from "./parser"; |
| 2 | +import FluentResource from "./resource"; |
3 | 3 |
|
4 | 4 | /**
|
5 | 5 | * Message contexts are single-language stores of translations. They are
|
@@ -115,22 +115,45 @@ export class MessageContext {
|
115 | 115 | * @returns {Array<Error>}
|
116 | 116 | */
|
117 | 117 | addMessages(source) {
|
118 |
| - const [entries, errors] = parse(source); |
119 |
| - for (const id in entries) { |
| 118 | + const res = FluentResource.fromString(source); |
| 119 | + return this.addResource(res); |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Add a translation resource to the context. |
| 124 | + * |
| 125 | + * The translation resource must be a proper FluentResource |
| 126 | + * parsed by `MessageContext.parseResource`. |
| 127 | + * |
| 128 | + * let res = MessageContext.parseResource("foo = Foo"); |
| 129 | + * ctx.addResource(res); |
| 130 | + * ctx.getMessage('foo'); |
| 131 | + * |
| 132 | + * // Returns a raw representation of the 'foo' message. |
| 133 | + * |
| 134 | + * Parsed entities should be formatted with the `format` method in case they |
| 135 | + * contain logic (references, select expressions etc.). |
| 136 | + * |
| 137 | + * @param {FluentResource} res - FluentResource object. |
| 138 | + * @returns {Array<Error>} |
| 139 | + */ |
| 140 | + addResource(res) { |
| 141 | + const errors = res.errors.slice(); |
| 142 | + for (const [id, value] of res) { |
120 | 143 | if (id.startsWith("-")) {
|
121 | 144 | // Identifiers starting with a dash (-) define terms. Terms are private
|
122 | 145 | // and cannot be retrieved from MessageContext.
|
123 | 146 | if (this._terms.has(id)) {
|
124 | 147 | errors.push(`Attempt to override an existing term: "${id}"`);
|
125 | 148 | continue;
|
126 | 149 | }
|
127 |
| - this._terms.set(id, entries[id]); |
| 150 | + this._terms.set(id, value); |
128 | 151 | } else {
|
129 | 152 | if (this._messages.has(id)) {
|
130 | 153 | errors.push(`Attempt to override an existing message: "${id}"`);
|
131 | 154 | continue;
|
132 | 155 | }
|
133 |
| - this._messages.set(id, entries[id]); |
| 156 | + this._messages.set(id, value); |
134 | 157 | }
|
135 | 158 | }
|
136 | 159 |
|
|
0 commit comments