UNPKG

17 kBTypeScriptView Raw
1/**
2 * Declares a copy of the `AbsoluteFsPath` branded type in `@angular/compiler-cli` to avoid an
3 * import into `@angular/compiler-cli`. The compiler-cli's declaration files are not necessarily
4 * compatible with web environments that use `@angular/localize`, and would inadvertently include
5 * `typescript` declaration files in any compilation unit that uses `@angular/localize` (which
6 * increases parsing time and memory usage during builds) using a default import that only
7 * type-checks when `allowSyntheticDefaultImports` is enabled.
8 *
9 * @see https://github.com/angular/angular/issues/45179
10 */
11declare type AbsoluteFsPathLocalizeCopy = string & {
12 _brand: 'AbsoluteFsPath';
13};
14
15/**
16 * Remove all translations for `$localize`, if doing runtime translation.
17 *
18 * All translations that had been loading into memory using `loadTranslations()` will be removed.
19 *
20 * @see `loadTranslations()` for loading translations at runtime.
21 * @see `$localize` for tagging messages as needing to be translated.
22 *
23 * @publicApi
24 */
25export declare function clearTranslations(): void;
26
27/**
28 * Load translations for use by `$localize`, if doing runtime translation.
29 *
30 * If the `$localize` tagged strings are not going to be replaced at compiled time, it is possible
31 * to load a set of translations that will be applied to the `$localize` tagged strings at runtime,
32 * in the browser.
33 *
34 * Loading a new translation will overwrite a previous translation if it has the same `MessageId`.
35 *
36 * Note that `$localize` messages are only processed once, when the tagged string is first
37 * encountered, and does not provide dynamic language changing without refreshing the browser.
38 * Loading new translations later in the application life-cycle will not change the translated text
39 * of messages that have already been translated.
40 *
41 * The message IDs and translations are in the same format as that rendered to "simple JSON"
42 * translation files when extracting messages. In particular, placeholders in messages are rendered
43 * using the `{$PLACEHOLDER_NAME}` syntax. For example the message from the following template:
44 *
45 * ```html
46 * <div i18n>pre<span>inner-pre<b>bold</b>inner-post</span>post</div>
47 * ```
48 *
49 * would have the following form in the `translations` map:
50 *
51 * ```ts
52 * {
53 * "2932901491976224757":
54 * "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post"
55 * }
56 * ```
57 *
58 * @param translations A map from message ID to translated message.
59 *
60 * These messages are processed and added to a lookup based on their `MessageId`.
61 *
62 * @see `clearTranslations()` for removing translations loaded using this function.
63 * @see `$localize` for tagging messages as needing to be translated.
64 * @publicApi
65 */
66export declare function loadTranslations(translations: Record<MessageId, TargetMessage>): void;
67
68/**
69 * A string that uniquely identifies a message, to be used for matching translations.
70 */
71export declare type MessageId = string;
72
73/**
74 * Additional information that can be associated with a message.
75 */
76declare interface MessageMetadata {
77 /**
78 * A human readable rendering of the message
79 */
80 text: string;
81 /**
82 * Legacy message ids, if provided.
83 *
84 * In legacy message formats the message id can only be computed directly from the original
85 * template source.
86 *
87 * Since this information is not available in `$localize` calls, the legacy message ids may be
88 * attached by the compiler to the `$localize` metablock so it can be used if needed at the point
89 * of translation if the translations are encoded using the legacy message id.
90 */
91 legacyIds?: string[];
92 /**
93 * The id of the `message` if a custom one was specified explicitly.
94 *
95 * This id overrides any computed or legacy ids.
96 */
97 customId?: string;
98 /**
99 * The meaning of the `message`, used to distinguish identical `messageString`s.
100 */
101 meaning?: string;
102 /**
103 * The description of the `message`, used to aid translation.
104 */
105 description?: string;
106 /**
107 * The location of the message in the source.
108 */
109 location?: ɵSourceLocation;
110}
111
112/**
113 * A string containing a translation target message.
114 *
115 * I.E. the message that indicates what will be translated to.
116 *
117 * Uses `{$placeholder-name}` to indicate a placeholder.
118 */
119export declare type TargetMessage = string;
120
121/**
122 * Tag a template literal string for localization.
123 *
124 * For example:
125 *
126 * ```ts
127 * $localize `some string to localize`
128 * ```
129 *
130 * **Providing meaning, description and id**
131 *
132 * You can optionally specify one or more of `meaning`, `description` and `id` for a localized
133 * string by pre-pending it with a colon delimited block of the form:
134 *
135 * ```ts
136 * $localize`:meaning|description@@id:source message text`;
137 *
138 * $localize`:meaning|:source message text`;
139 * $localize`:description:source message text`;
140 * $localize`:@@id:source message text`;
141 * ```
142 *
143 * This format is the same as that used for `i18n` markers in Angular templates. See the
144 * [Angular i18n guide](guide/i18n-common-prepare#mark-text-in-component-template).
145 *
146 * **Naming placeholders**
147 *
148 * If the template literal string contains expressions, then the expressions will be automatically
149 * associated with placeholder names for you.
150 *
151 * For example:
152 *
153 * ```ts
154 * $localize `Hi ${name}! There are ${items.length} items.`;
155 * ```
156 *
157 * will generate a message-source of `Hi {$PH}! There are {$PH_1} items`.
158 *
159 * The recommended practice is to name the placeholder associated with each expression though.
160 *
161 * Do this by providing the placeholder name wrapped in `:` characters directly after the
162 * expression. These placeholder names are stripped out of the rendered localized string.
163 *
164 * For example, to name the `items.length` expression placeholder `itemCount` you write:
165 *
166 * ```ts
167 * $localize `There are ${items.length}:itemCount: items`;
168 * ```
169 *
170 * **Escaping colon markers**
171 *
172 * If you need to use a `:` character directly at the start of a tagged string that has no
173 * metadata block, or directly after a substitution expression that has no name you must escape
174 * the `:` by preceding it with a backslash:
175 *
176 * For example:
177 *
178 * ```ts
179 * // message has a metadata block so no need to escape colon
180 * $localize `:some description::this message starts with a colon (:)`;
181 * // no metadata block so the colon must be escaped
182 * $localize `\:this message starts with a colon (:)`;
183 * ```
184 *
185 * ```ts
186 * // named substitution so no need to escape colon
187 * $localize `${label}:label:: ${}`
188 * // anonymous substitution so colon must be escaped
189 * $localize `${label}\: ${}`
190 * ```
191 *
192 * **Processing localized strings:**
193 *
194 * There are three scenarios:
195 *
196 * * **compile-time inlining**: the `$localize` tag is transformed at compile time by a
197 * transpiler, removing the tag and replacing the template literal string with a translated
198 * literal string from a collection of translations provided to the transpilation tool.
199 *
200 * * **run-time evaluation**: the `$localize` tag is a run-time function that replaces and
201 * reorders the parts (static strings and expressions) of the template literal string with strings
202 * from a collection of translations loaded at run-time.
203 *
204 * * **pass-through evaluation**: the `$localize` tag is a run-time function that simply evaluates
205 * the original template literal string without applying any translations to the parts. This
206 * version is used during development or where there is no need to translate the localized
207 * template literals.
208 *
209 * @param messageParts a collection of the static parts of the template string.
210 * @param expressions a collection of the values of each placeholder in the template string.
211 * @returns the translated string, with the `messageParts` and `expressions` interleaved together.
212 *
213 * @globalApi
214 * @publicApi
215 */
216export declare const ɵ$localize: ɵLocalizeFn;
217
218export declare const ɵ_global: any;
219
220export declare function ɵcomputeMsgId(msg: string, meaning?: string): string;
221
222/**
223 * Find the end of a "marked block" indicated by the first non-escaped colon.
224 *
225 * @param cooked The cooked string (where escaped chars have been processed)
226 * @param raw The raw string (where escape sequences are still in place)
227 *
228 * @returns the index of the end of block marker
229 * @throws an error if the block is unterminated
230 */
231export declare function ɵfindEndOfBlock(cooked: string, raw: string): number;
232
233export declare function ɵisMissingTranslationError(e: any): e is ɵMissingTranslationError;
234
235
236/** @nodoc */
237export declare interface ɵLocalizeFn {
238 (messageParts: TemplateStringsArray, ...expressions: readonly any[]): string;
239 /**
240 * A function that converts an input "message with expressions" into a translated "message with
241 * expressions".
242 *
243 * The conversion may be done in place, modifying the array passed to the function, so
244 * don't assume that this has no side-effects.
245 *
246 * The expressions must be passed in since it might be they need to be reordered for
247 * different translations.
248 */
249 translate?: ɵTranslateFn;
250 /**
251 * The current locale of the translated messages.
252 *
253 * The compile-time translation inliner is able to replace the following code:
254 *
255 * ```
256 * typeof $localize !== "undefined" && $localize.locale
257 * ```
258 *
259 * with a string literal of the current locale. E.g.
260 *
261 * ```
262 * "fr"
263 * ```
264 */
265 locale?: string;
266}
267
268/**
269 * Create a `ParsedTranslation` from a set of `messageParts` and `placeholderNames`.
270 *
271 * @param messageParts The message parts to appear in the ParsedTranslation.
272 * @param placeholderNames The names of the placeholders to intersperse between the `messageParts`.
273 */
274export declare function ɵmakeParsedTranslation(messageParts: string[], placeholderNames?: string[]): ɵParsedTranslation;
275
276/**
277 * Create the specialized array that is passed to tagged-string tag functions.
278 *
279 * @param cooked The message parts with their escape codes processed.
280 * @param raw The message parts with their escaped codes as-is.
281 */
282export declare function ɵmakeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray;
283
284export declare class ɵMissingTranslationError extends Error {
285 readonly parsedMessage: ɵParsedMessage;
286 private readonly type;
287 constructor(parsedMessage: ɵParsedMessage);
288}
289
290/**
291 * Information parsed from a `$localize` tagged string that is used to translate it.
292 *
293 * For example:
294 *
295 * ```
296 * const name = 'Jo Bloggs';
297 * $localize`Hello ${name}:title@@ID:!`;
298 * ```
299 *
300 * May be parsed into:
301 *
302 * ```
303 * {
304 * id: '6998194507597730591',
305 * substitutions: { title: 'Jo Bloggs' },
306 * messageString: 'Hello {$title}!',
307 * placeholderNames: ['title'],
308 * associatedMessageIds: { title: 'ID' },
309 * }
310 * ```
311 */
312export declare interface ɵParsedMessage extends MessageMetadata {
313 /**
314 * The key used to look up the appropriate translation target.
315 */
316 id: MessageId;
317 /**
318 * A mapping of placeholder names to substitution values.
319 */
320 substitutions: Record<string, any>;
321 /**
322 * An optional mapping of placeholder names to associated MessageIds.
323 * This can be used to match ICU placeholders to the message that contains the ICU.
324 */
325 associatedMessageIds?: Record<string, MessageId>;
326 /**
327 * An optional mapping of placeholder names to source locations
328 */
329 substitutionLocations?: Record<string, ɵSourceLocation | undefined>;
330 /**
331 * The static parts of the message.
332 */
333 messageParts: string[];
334 /**
335 * An optional mapping of message parts to source locations
336 */
337 messagePartLocations?: (ɵSourceLocation | undefined)[];
338 /**
339 * The names of the placeholders that will be replaced with substitutions.
340 */
341 placeholderNames: string[];
342}
343
344/**
345 * A translation message that has been processed to extract the message parts and placeholders.
346 */
347export declare interface ɵParsedTranslation extends MessageMetadata {
348 messageParts: TemplateStringsArray;
349 placeholderNames: string[];
350}
351
352/**
353 * The internal structure used by the runtime localization to translate messages.
354 */
355export declare type ɵParsedTranslations = Record<MessageId, ɵParsedTranslation>;
356
357/**
358 * Parse a `$localize` tagged string into a structure that can be used for translation or
359 * extraction.
360 *
361 * See `ParsedMessage` for an example.
362 */
363export declare function ɵparseMessage(messageParts: TemplateStringsArray, expressions?: readonly any[], location?: ɵSourceLocation, messagePartLocations?: (ɵSourceLocation | undefined)[], expressionLocations?: (ɵSourceLocation | undefined)[]): ɵParsedMessage;
364
365/**
366 * Parse the given message part (`cooked` + `raw`) to extract the message metadata from the text.
367 *
368 * If the message part has a metadata block this function will extract the `meaning`,
369 * `description`, `customId` and `legacyId` (if provided) from the block. These metadata properties
370 * are serialized in the string delimited by `|`, `@@` and `␟` respectively.
371 *
372 * (Note that `␟` is the `LEGACY_ID_INDICATOR` - see `constants.ts`.)
373 *
374 * For example:
375 *
376 * ```ts
377 * `:meaning|description@@custom-id:`
378 * `:meaning|@@custom-id:`
379 * `:meaning|description:`
380 * `:description@@custom-id:`
381 * `:meaning|:`
382 * `:description:`
383 * `:@@custom-id:`
384 * `:meaning|description@@custom-id␟legacy-id-1␟legacy-id-2:`
385 * ```
386 *
387 * @param cooked The cooked version of the message part to parse.
388 * @param raw The raw version of the message part to parse.
389 * @returns A object containing any metadata that was parsed from the message part.
390 */
391export declare function ɵparseMetadata(cooked: string, raw: string): MessageMetadata;
392
393/**
394 * Parse the `messageParts` and `placeholderNames` out of a target `message`.
395 *
396 * Used by `loadTranslations()` to convert target message strings into a structure that is more
397 * appropriate for doing translation.
398 *
399 * @param message the message to be parsed.
400 */
401export declare function ɵparseTranslation(messageString: TargetMessage): ɵParsedTranslation;
402
403/**
404 * The location of the message in the source file.
405 *
406 * The `line` and `column` values for the `start` and `end` properties are zero-based.
407 */
408export declare interface ɵSourceLocation {
409 start: {
410 line: number;
411 column: number;
412 };
413 end: {
414 line: number;
415 column: number;
416 };
417 file: AbsoluteFsPathLocalizeCopy;
418 text?: string;
419}
420
421/**
422 * A string containing a translation source message.
423 *
424 * I.E. the message that indicates what will be translated from.
425 *
426 * Uses `{$placeholder-name}` to indicate a placeholder.
427 */
428export declare type ɵSourceMessage = string;
429
430/**
431 * Split a message part (`cooked` + `raw`) into an optional delimited "block" off the front and the
432 * rest of the text of the message part.
433 *
434 * Blocks appear at the start of message parts. They are delimited by a colon `:` character at the
435 * start and end of the block.
436 *
437 * If the block is in the first message part then it will be metadata about the whole message:
438 * meaning, description, id. Otherwise it will be metadata about the immediately preceding
439 * substitution: placeholder name.
440 *
441 * Since blocks are optional, it is possible that the content of a message block actually starts
442 * with a block marker. In this case the marker must be escaped `\:`.
443 *
444 * @param cooked The cooked version of the message part to parse.
445 * @param raw The raw version of the message part to parse.
446 * @returns An object containing the `text` of the message part and the text of the `block`, if it
447 * exists.
448 * @throws an error if the `block` is unterminated
449 */
450export declare function ɵsplitBlock(cooked: string, raw: string): {
451 text: string;
452 block?: string;
453};
454
455/**
456 * Translate the text of the `$localize` tagged-string (i.e. `messageParts` and
457 * `substitutions`) using the given `translations`.
458 *
459 * The tagged-string is parsed to extract its `messageId` which is used to find an appropriate
460 * `ParsedTranslation`. If this doesn't match and there are legacy ids then try matching a
461 * translation using those.
462 *
463 * If one is found then it is used to translate the message into a new set of `messageParts` and
464 * `substitutions`.
465 * The translation may reorder (or remove) substitutions as appropriate.
466 *
467 * If there is no translation with a matching message id then an error is thrown.
468 * If a translation contains a placeholder that is not found in the message being translated then an
469 * error is thrown.
470 */
471export declare function ɵtranslate(translations: Record<string, ɵParsedTranslation>, messageParts: TemplateStringsArray, substitutions: readonly any[]): [TemplateStringsArray, readonly any[]];
472
473/** @nodoc */
474export declare interface ɵTranslateFn {
475 (messageParts: TemplateStringsArray, expressions: readonly any[]): [TemplateStringsArray, readonly any[]];
476}
477
478export { }