_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/localize/tools/src/translate/index.ts_0_5055 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getFileSystem, relativeFrom} from '@angular/compiler-cli/private/localize';
import {DiagnosticHandlingStrategy, Diagnostics} from '../diagnostics';
import {AssetTranslationHandler} from './asset_files/asset_translation_handler';
import {OutputPathFn} from './output_path';
import {SourceFileTranslationHandler} from './source_files/source_file_translation_handler';
import {TranslationLoader} from './translation_files/translation_loader';
import {ArbTranslationParser} from './translation_files/translation_parsers/arb_translation_parser';
import {SimpleJsonTranslationParser} from './translation_files/translation_parsers/simple_json_translation_parser';
import {Xliff1TranslationParser} from './translation_files/translation_parsers/xliff1_translation_parser';
import {Xliff2TranslationParser} from './translation_files/translation_parsers/xliff2_translation_parser';
import {XtbTranslationParser} from './translation_files/translation_parsers/xtb_translation_parser';
import {Translator} from './translator';
export interface TranslateFilesOptions {
/**
* The root path of the files to translate, either absolute or relative to the current working
* directory. E.g. `dist/en`
*/
sourceRootPath: string;
/**
* The files to translate, relative to the `root` path.
*/
sourceFilePaths: string[];
/**
* An array of paths to the translation files to load, either absolute or relative to the current
* working directory.
*
* For each locale to be translated, there should be an element in `translationFilePaths`.
* Each element is either an absolute path to the translation file, or an array of absolute paths
* to translation files, for that locale.
*
* If the element contains more than one translation file, then the translations are merged.
*
* If allowed by the `duplicateTranslation` property, when more than one translation has the same
* message id, the message from the earlier translation file in the array is used.
*
* For example, if the files are `[app.xlf, lib-1.xlf, lib-2.xlif]` then a message that appears in
* `app.xlf` will override the same message in `lib-1.xlf` or `lib-2.xlf`.
*/
translationFilePaths: (string | string[])[];
/**
* A collection of the target locales for the translation files.
*
* If there is a locale provided in `translationFileLocales` then this is used rather than a
* locale extracted from the file itself.
* If there is neither a provided locale nor a locale parsed from the file, then an error is
* thrown.
* If there are both a provided locale and a locale parsed from the file, and they are not the
* same, then a warning is reported.
*/
translationFileLocales: (string | undefined)[];
/**
* A function that computes the output path of where the translated files will be
* written. The marker `{{LOCALE}}` will be replaced with the target locale. E.g.
* `dist/{{LOCALE}}`.
*/
outputPathFn: OutputPathFn;
/**
* An object that will receive any diagnostics messages due to the processing.
*/
diagnostics: Diagnostics;
/**
* How to handle missing translations.
*/
missingTranslation: DiagnosticHandlingStrategy;
/**
* How to handle duplicate translations.
*/
duplicateTranslation: DiagnosticHandlingStrategy;
/**
* The locale of the source files.
* If this is provided then a copy of the application will be created with no translation but just
* the `$localize` calls stripped out.
*/
sourceLocale?: string;
}
export function translateFiles({
sourceRootPath,
sourceFilePaths,
translationFilePaths,
translationFileLocales,
outputPathFn,
diagnostics,
missingTranslation,
duplicateTranslation,
sourceLocale,
}: TranslateFilesOptions) {
const fs = getFileSystem();
const translationLoader = new TranslationLoader(
fs,
[
new Xliff2TranslationParser(),
new Xliff1TranslationParser(),
new XtbTranslationParser(),
new SimpleJsonTranslationParser(),
new ArbTranslationParser(),
],
duplicateTranslation,
diagnostics,
);
const resourceProcessor = new Translator(
fs,
[new SourceFileTranslationHandler(fs, {missingTranslation}), new AssetTranslationHandler(fs)],
diagnostics,
);
// Convert all the `translationFilePaths` elements to arrays.
const translationFilePathsArrays = translationFilePaths.map((filePaths) =>
Array.isArray(filePaths) ? filePaths.map((p) => fs.resolve(p)) : [fs.resolve(filePaths)],
);
const translations = translationLoader.loadBundles(
translationFilePathsArrays,
translationFileLocales,
);
sourceRootPath = fs.resolve(sourceRootPath);
resourceProcessor.translateFiles(
sourceFilePaths.map(relativeFrom),
fs.resolve(sourceRootPath),
outputPathFn,
translations,
sourceLocale,
);
}
| {
"end_byte": 5055,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/index.ts"
} |
angular/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts_0_1896 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
absoluteFrom,
AbsoluteFsPath,
FileSystem,
PathSegment,
} from '@angular/compiler-cli/private/localize';
import {Diagnostics} from '../../diagnostics';
import {OutputPathFn} from '../output_path';
import {TranslationBundle, TranslationHandler} from '../translator';
/**
* Translate an asset file by simply copying it to the appropriate translation output paths.
*/
export class AssetTranslationHandler implements TranslationHandler {
constructor(private fs: FileSystem) {}
canTranslate(_relativeFilePath: PathSegment | AbsoluteFsPath, _contents: Uint8Array): boolean {
return true;
}
translate(
diagnostics: Diagnostics,
_sourceRoot: AbsoluteFsPath,
relativeFilePath: PathSegment | AbsoluteFsPath,
contents: Uint8Array,
outputPathFn: OutputPathFn,
translations: TranslationBundle[],
sourceLocale?: string,
): void {
for (const translation of translations) {
this.writeAssetFile(
diagnostics,
outputPathFn,
translation.locale,
relativeFilePath,
contents,
);
}
if (sourceLocale !== undefined) {
this.writeAssetFile(diagnostics, outputPathFn, sourceLocale, relativeFilePath, contents);
}
}
private writeAssetFile(
diagnostics: Diagnostics,
outputPathFn: OutputPathFn,
locale: string,
relativeFilePath: PathSegment | AbsoluteFsPath,
contents: Uint8Array,
): void {
try {
const outputPath = absoluteFrom(outputPathFn(locale, relativeFilePath));
this.fs.ensureDir(this.fs.dirname(outputPath));
this.fs.writeFile(outputPath, contents);
} catch (e) {
diagnostics.error((e as Error).message);
}
}
}
| {
"end_byte": 1896,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/asset_files/asset_translation_handler.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_loader.ts_0_6104 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AbsoluteFsPath, ReadonlyFileSystem} from '@angular/compiler-cli/private/localize';
import {DiagnosticHandlingStrategy, Diagnostics} from '../../diagnostics';
import {TranslationBundle} from '../translator';
import {ParseAnalysis, TranslationParser} from './translation_parsers/translation_parser';
/**
* Use this class to load a collection of translation files from disk.
*/
export class TranslationLoader {
constructor(
private fs: ReadonlyFileSystem,
private translationParsers: TranslationParser<any>[],
private duplicateTranslation: DiagnosticHandlingStrategy,
/** @deprecated */ private diagnostics?: Diagnostics,
) {}
/**
* Load and parse the translation files into a collection of `TranslationBundles`.
*
* @param translationFilePaths An array, per locale, of absolute paths to translation files.
*
* For each locale to be translated, there is an element in `translationFilePaths`. Each element
* is an array of absolute paths to translation files for that locale.
* If the array contains more than one translation file, then the translations are merged.
* If allowed by the `duplicateTranslation` property, when more than one translation has the same
* message id, the message from the earlier translation file in the array is used.
* For example, if the files are `[app.xlf, lib-1.xlf, lib-2.xlif]` then a message that appears in
* `app.xlf` will override the same message in `lib-1.xlf` or `lib-2.xlf`.
*
* @param translationFileLocales An array of locales for each of the translation files.
*
* If there is a locale provided in `translationFileLocales` then this is used rather than a
* locale extracted from the file itself.
* If there is neither a provided locale nor a locale parsed from the file, then an error is
* thrown.
* If there are both a provided locale and a locale parsed from the file, and they are not the
* same, then a warning is reported.
*/
loadBundles(
translationFilePaths: AbsoluteFsPath[][],
translationFileLocales: (string | undefined)[],
): TranslationBundle[] {
return translationFilePaths.map((filePaths, index) => {
const providedLocale = translationFileLocales[index];
return this.mergeBundles(filePaths, providedLocale);
});
}
/**
* Load all the translations from the file at the given `filePath`.
*/
private loadBundle(
filePath: AbsoluteFsPath,
providedLocale: string | undefined,
): TranslationBundle {
const fileContents = this.fs.readFile(filePath);
const unusedParsers = new Map<TranslationParser<any>, ParseAnalysis<any>>();
for (const translationParser of this.translationParsers) {
const result = translationParser.analyze(filePath, fileContents);
if (!result.canParse) {
unusedParsers.set(translationParser, result);
continue;
}
const {
locale: parsedLocale,
translations,
diagnostics,
} = translationParser.parse(filePath, fileContents, result.hint);
if (diagnostics.hasErrors) {
throw new Error(
diagnostics.formatDiagnostics(`The translation file "${filePath}" could not be parsed.`),
);
}
const locale = providedLocale || parsedLocale;
if (locale === undefined) {
throw new Error(
`The translation file "${filePath}" does not contain a target locale and no explicit locale was provided for this file.`,
);
}
if (
parsedLocale !== undefined &&
providedLocale !== undefined &&
parsedLocale !== providedLocale
) {
diagnostics.warn(
`The provided locale "${providedLocale}" does not match the target locale "${parsedLocale}" found in the translation file "${filePath}".`,
);
}
// If we were passed a diagnostics object then copy the messages over to it.
if (this.diagnostics) {
this.diagnostics.merge(diagnostics);
}
return {locale, translations, diagnostics};
}
const diagnosticsMessages: string[] = [];
for (const [parser, result] of unusedParsers.entries()) {
diagnosticsMessages.push(
result.diagnostics.formatDiagnostics(
`\n${parser.constructor.name} cannot parse translation file.`,
),
);
}
throw new Error(
`There is no "TranslationParser" that can parse this translation file: ${filePath}.` +
diagnosticsMessages.join('\n'),
);
}
/**
* There is more than one `filePath` for this locale, so load each as a bundle and then merge
* them all together.
*/
private mergeBundles(
filePaths: AbsoluteFsPath[],
providedLocale: string | undefined,
): TranslationBundle {
const bundles = filePaths.map((filePath) => this.loadBundle(filePath, providedLocale));
const bundle = bundles[0];
for (let i = 1; i < bundles.length; i++) {
const nextBundle = bundles[i];
if (nextBundle.locale !== bundle.locale) {
if (this.diagnostics) {
const previousFiles = filePaths
.slice(0, i)
.map((f) => `"${f}"`)
.join(', ');
this.diagnostics.warn(
`When merging multiple translation files, the target locale "${nextBundle.locale}" found in "${filePaths[i]}" does not match the target locale "${bundle.locale}" found in earlier files [${previousFiles}].`,
);
}
}
Object.keys(nextBundle.translations).forEach((messageId) => {
if (bundle.translations[messageId] !== undefined) {
this.diagnostics?.add(
this.duplicateTranslation,
`Duplicate translations for message "${messageId}" when merging "${filePaths[i]}".`,
);
} else {
bundle.translations[messageId] = nextBundle.translations[messageId];
}
});
}
return bundle;
}
}
| {
"end_byte": 6104,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_loader.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/base_visitor.ts_0_1127 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Attribute,
Block,
BlockParameter,
Comment,
Element,
Expansion,
ExpansionCase,
LetDeclaration,
Text,
Visitor,
} from '@angular/compiler';
/**
* A simple base class for the `Visitor` interface, which is a noop for every method.
*
* Sub-classes only need to override the methods that they care about.
*/
export class BaseVisitor implements Visitor {
visitElement(_element: Element, _context: any): any {}
visitAttribute(_attribute: Attribute, _context: any): any {}
visitText(_text: Text, _context: any): any {}
visitComment(_comment: Comment, _context: any): any {}
visitExpansion(_expansion: Expansion, _context: any): any {}
visitExpansionCase(_expansionCase: ExpansionCase, _context: any): any {}
visitBlock(_block: Block, _context: any) {}
visitBlockParameter(_parameter: BlockParameter, _context: any) {}
visitLetDeclaration(_decl: LetDeclaration, _context: any) {}
}
| {
"end_byte": 1127,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/base_visitor.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/message_serialization/message_serializer.ts_0_3635 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Element, Expansion, ExpansionCase, Node, Text, visitAll} from '@angular/compiler';
import {BaseVisitor} from '../base_visitor';
import {TranslationParseError} from '../translation_parsers/translation_parse_error';
import {getAttribute, getAttrOrThrow} from '../translation_parsers/translation_utils';
import {MessageRenderer} from './message_renderer';
export interface MessageSerializerConfig {
inlineElements: string[];
placeholder?: {elementName: string; nameAttribute: string; bodyAttribute?: string};
placeholderContainer?: {elementName: string; startAttribute: string; endAttribute: string};
}
/**
* This visitor will walk over a set of XML nodes, which represent an i18n message, and serialize
* them into a message object of type `T`.
* The type of the serialized message is controlled by the
*/
export class MessageSerializer<T> extends BaseVisitor {
constructor(
private renderer: MessageRenderer<T>,
private config: MessageSerializerConfig,
) {
super();
}
serialize(nodes: Node[]): T {
this.renderer.startRender();
visitAll(this, nodes);
this.renderer.endRender();
return this.renderer.message;
}
override visitElement(element: Element): void {
if (this.config.placeholder && element.name === this.config.placeholder.elementName) {
const name = getAttrOrThrow(element, this.config.placeholder.nameAttribute);
const body =
this.config.placeholder.bodyAttribute &&
getAttribute(element, this.config.placeholder.bodyAttribute);
this.visitPlaceholder(name, body);
} else if (
this.config.placeholderContainer &&
element.name === this.config.placeholderContainer.elementName
) {
const start = getAttrOrThrow(element, this.config.placeholderContainer.startAttribute);
const end = getAttrOrThrow(element, this.config.placeholderContainer.endAttribute);
this.visitPlaceholderContainer(start, element.children, end);
} else if (this.config.inlineElements.indexOf(element.name) !== -1) {
visitAll(this, element.children);
} else {
throw new TranslationParseError(element.sourceSpan, `Invalid element found in message.`);
}
}
override visitText(text: Text): void {
this.renderer.text(text.value);
}
override visitExpansion(expansion: Expansion): void {
this.renderer.startIcu();
this.renderer.text(`${expansion.switchValue}, ${expansion.type},`);
visitAll(this, expansion.cases);
this.renderer.endIcu();
}
override visitExpansionCase(expansionCase: ExpansionCase): void {
this.renderer.text(` ${expansionCase.value} {`);
this.renderer.startContainer();
visitAll(this, expansionCase.expression);
this.renderer.closeContainer();
this.renderer.text(`}`);
}
visitContainedNodes(nodes: Node[]): void {
this.renderer.startContainer();
visitAll(this, nodes);
this.renderer.closeContainer();
}
visitPlaceholder(name: string, body: string | undefined): void {
this.renderer.placeholder(name, body);
}
visitPlaceholderContainer(startName: string, children: Node[], closeName: string): void {
this.renderer.startPlaceholder(startName);
this.visitContainedNodes(children);
this.renderer.closePlaceholder(closeName);
}
private isPlaceholderContainer(node: Node): boolean {
return node instanceof Element && node.name === this.config.placeholderContainer!.elementName;
}
}
| {
"end_byte": 3635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/message_serialization/message_serializer.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/message_serialization/target_message_renderer.ts_0_1927 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵmakeParsedTranslation, ɵParsedTranslation} from '@angular/localize';
import {MessageRenderer} from './message_renderer';
/**
* A message renderer that outputs `ɵParsedTranslation` objects.
*/
export class TargetMessageRenderer implements MessageRenderer<ɵParsedTranslation> {
private current: MessageInfo = {messageParts: [], placeholderNames: [], text: ''};
private icuDepth = 0;
get message(): ɵParsedTranslation {
const {messageParts, placeholderNames} = this.current;
return ɵmakeParsedTranslation(messageParts, placeholderNames);
}
startRender(): void {}
endRender(): void {
this.storeMessagePart();
}
text(text: string): void {
this.current.text += text;
}
placeholder(name: string, body: string | undefined): void {
this.renderPlaceholder(name);
}
startPlaceholder(name: string): void {
this.renderPlaceholder(name);
}
closePlaceholder(name: string): void {
this.renderPlaceholder(name);
}
startContainer(): void {}
closeContainer(): void {}
startIcu(): void {
this.icuDepth++;
this.text('{');
}
endIcu(): void {
this.icuDepth--;
this.text('}');
}
private normalizePlaceholderName(name: string) {
return name.replace(/-/g, '_');
}
private renderPlaceholder(name: string) {
name = this.normalizePlaceholderName(name);
if (this.icuDepth > 0) {
this.text(`{${name}}`);
} else {
this.storeMessagePart();
this.current.placeholderNames.push(name);
}
}
private storeMessagePart() {
this.current.messageParts.push(this.current.text);
this.current.text = '';
}
}
interface MessageInfo {
messageParts: string[];
placeholderNames: string[];
text: string;
}
| {
"end_byte": 1927,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/message_serialization/target_message_renderer.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/message_serialization/message_renderer.ts_0_561 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface MessageRenderer<T> {
message: T;
startRender(): void;
endRender(): void;
text(text: string): void;
placeholder(name: string, body: string | undefined): void;
startPlaceholder(name: string): void;
closePlaceholder(name: string): void;
startContainer(): void;
closeContainer(): void;
startIcu(): void;
endIcu(): void;
}
| {
"end_byte": 561,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/message_serialization/message_renderer.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/xliff2_translation_parser.ts_0_5598 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Element, Node, ParseErrorLevel, visitAll} from '@angular/compiler';
import {Diagnostics} from '../../../diagnostics';
import {BaseVisitor} from '../base_visitor';
import {serializeTranslationMessage} from './serialize_translation_message';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
import {
addErrorsToBundle,
addParseDiagnostic,
addParseError,
canParseXml,
getAttribute,
isNamedElement,
XmlTranslationParserHint,
} from './translation_utils';
/**
* A translation parser that can load translations from XLIFF 2 files.
*
* https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
*
* @see Xliff2TranslationSerializer
* @publicApi used by CLI
*/
export class Xliff2TranslationParser implements TranslationParser<XmlTranslationParserHint> {
analyze(filePath: string, contents: string): ParseAnalysis<XmlTranslationParserHint> {
return canParseXml(filePath, contents, 'xliff', {version: '2.0'});
}
parse(
filePath: string,
contents: string,
hint: XmlTranslationParserHint,
): ParsedTranslationBundle {
return this.extractBundle(hint);
}
private extractBundle({element, errors}: XmlTranslationParserHint): ParsedTranslationBundle {
const diagnostics = new Diagnostics();
errors.forEach((e) => addParseError(diagnostics, e));
const locale = getAttribute(element, 'trgLang');
const files = element.children.filter(isFileElement);
if (files.length === 0) {
addParseDiagnostic(
diagnostics,
element.sourceSpan,
'No <file> elements found in <xliff>',
ParseErrorLevel.WARNING,
);
} else if (files.length > 1) {
addParseDiagnostic(
diagnostics,
files[1].sourceSpan,
'More than one <file> element found in <xliff>',
ParseErrorLevel.WARNING,
);
}
const bundle = {locale, translations: {}, diagnostics};
const translationVisitor = new Xliff2TranslationVisitor();
for (const file of files) {
visitAll(translationVisitor, file.children, {bundle});
}
return bundle;
}
}
interface TranslationVisitorContext {
unit?: string;
bundle: ParsedTranslationBundle;
}
class Xliff2TranslationVisitor extends BaseVisitor {
override visitElement(element: Element, {bundle, unit}: TranslationVisitorContext): any {
if (element.name === 'unit') {
this.visitUnitElement(element, bundle);
} else if (element.name === 'segment') {
this.visitSegmentElement(element, bundle, unit);
} else {
visitAll(this, element.children, {bundle, unit});
}
}
private visitUnitElement(element: Element, bundle: ParsedTranslationBundle): void {
// Error if no `id` attribute
const externalId = getAttribute(element, 'id');
if (externalId === undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Missing required "id" attribute on <trans-unit> element.`,
ParseErrorLevel.ERROR,
);
return;
}
// Error if there is already a translation with the same id
if (bundle.translations[externalId] !== undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Duplicated translations for message "${externalId}"`,
ParseErrorLevel.ERROR,
);
return;
}
visitAll(this, element.children, {bundle, unit: externalId});
}
private visitSegmentElement(
element: Element,
bundle: ParsedTranslationBundle,
unit: string | undefined,
): void {
// A `<segment>` element must be below a `<unit>` element
if (unit === undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
'Invalid <segment> element: should be a child of a <unit> element.',
ParseErrorLevel.ERROR,
);
return;
}
let targetMessage = element.children.find(isNamedElement('target'));
if (targetMessage === undefined) {
// Warn if there is no `<target>` child element
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
'Missing <target> element',
ParseErrorLevel.WARNING,
);
// Fallback to the `<source>` element if available.
targetMessage = element.children.find(isNamedElement('source'));
if (targetMessage === undefined) {
// Error if there is neither `<target>` nor `<source>`.
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
'Missing required element: one of <target> or <source> is required',
ParseErrorLevel.ERROR,
);
return;
}
}
const {translation, parseErrors, serializeErrors} = serializeTranslationMessage(targetMessage, {
inlineElements: ['cp', 'sc', 'ec', 'mrk', 'sm', 'em'],
placeholder: {elementName: 'ph', nameAttribute: 'equiv', bodyAttribute: 'disp'},
placeholderContainer: {
elementName: 'pc',
startAttribute: 'equivStart',
endAttribute: 'equivEnd',
},
});
if (translation !== null) {
bundle.translations[unit] = translation;
}
addErrorsToBundle(bundle, parseErrors);
addErrorsToBundle(bundle, serializeErrors);
}
}
function isFileElement(node: Node): node is Element {
return node instanceof Element && node.name === 'file';
}
| {
"end_byte": 5598,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/xliff2_translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_parser.ts_0_2976 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageId, ɵParsedTranslation} from '@angular/localize';
import {Diagnostics} from '../../../diagnostics';
/**
* Indicates that a parser can parse a given file, with a hint that can be used to speed up actual
* parsing.
*/
export interface CanParseAnalysis<Hint> {
canParse: true;
diagnostics: Diagnostics;
hint: Hint;
}
/**
* Indicates that a parser cannot parse a given file with diagnostics as why this is.
* */
export interface CannotParseAnalysis {
canParse: false;
diagnostics: Diagnostics;
}
/**
* Information about whether a `TranslationParser` can parse a given file.
*/
export type ParseAnalysis<Hint> = CanParseAnalysis<Hint> | CannotParseAnalysis;
/**
* An object that holds translations that have been parsed from a translation file.
*/
export interface ParsedTranslationBundle {
locale: string | undefined;
translations: Record<MessageId, ɵParsedTranslation>;
diagnostics: Diagnostics;
}
/**
* Implement this interface to provide a class that can parse the contents of a translation file.
*
* The `analyze()` method can return a hint that can be used by the `parse()` method to speed
* up parsing. This allows the parser to do significant work to determine if the file can be parsed
* without duplicating the work when it comes to actually parsing the file.
*
* Example usage:
*
* ```
* const parser: TranslationParser = getParser();
* const analysis = parser.analyze(filePath, content);
* if (analysis.canParse) {
* return parser.parse(filePath, content, analysis.hint);
* }
* ```
*/
export interface TranslationParser<Hint = true> {
/**
* Analyze the file to see if this parser can parse the given file.
*
* @param filePath The absolute path to the translation file.
* @param contents The contents of the translation file.
* @returns Information indicating whether the file can be parsed by this parser.
*/
analyze(filePath: string, contents: string): ParseAnalysis<Hint>;
/**
* Parses the given file, extracting the target locale and translations.
*
* Note that this method should not throw an error. Check the `bundle.diagnostics` property for
* potential parsing errors and warnings.
*
* @param filePath The absolute path to the translation file.
* @param contents The contents of the translation file.
* @param hint A value that can be used by the parser to speed up parsing of the file. This will
* have been provided as the return result from calling `analyze()`.
* @returns The translation bundle parsed from the file.
* @throws No errors. If there was a problem with parsing the bundle will contain errors
* in the `diagnostics` property.
*/
parse(filePath: string, contents: string, hint: Hint): ParsedTranslationBundle;
}
| {
"end_byte": 2976,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/simple_json_translation_parser.ts_0_2902 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageId, ɵParsedTranslation, ɵparseTranslation} from '@angular/localize';
import {extname} from 'path';
import {Diagnostics} from '../../../diagnostics';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
interface SimpleJsonFile {
locale: string;
translations: {[messageId: string]: string};
}
/**
* A translation parser that can parse JSON that has the form:
*
* ```
* {
* "locale": "...",
* "translations": {
* "message-id": "Target message string",
* ...
* }
* }
* ```
*
* @see SimpleJsonTranslationSerializer
* @publicApi used by CLI
*/
export class SimpleJsonTranslationParser implements TranslationParser<SimpleJsonFile> {
analyze(filePath: string, contents: string): ParseAnalysis<SimpleJsonFile> {
const diagnostics = new Diagnostics();
// For this to be parsable, the extension must be `.json` and the contents must include "locale"
// and "translations" keys.
if (
extname(filePath) !== '.json' ||
!(contents.includes('"locale"') && contents.includes('"translations"'))
) {
diagnostics.warn('File does not have .json extension.');
return {canParse: false, diagnostics};
}
try {
const json = JSON.parse(contents) as SimpleJsonFile;
if (json.locale === undefined) {
diagnostics.warn('Required "locale" property missing.');
return {canParse: false, diagnostics};
}
if (typeof json.locale !== 'string') {
diagnostics.warn('The "locale" property is not a string.');
return {canParse: false, diagnostics};
}
if (json.translations === undefined) {
diagnostics.warn('Required "translations" property missing.');
return {canParse: false, diagnostics};
}
if (typeof json.translations !== 'object') {
diagnostics.warn('The "translations" is not an object.');
return {canParse: false, diagnostics};
}
return {canParse: true, diagnostics, hint: json};
} catch (e) {
diagnostics.warn('File is not valid JSON.');
return {canParse: false, diagnostics};
}
}
parse(_filePath: string, contents: string, json?: SimpleJsonFile): ParsedTranslationBundle {
const {locale: parsedLocale, translations} = json || (JSON.parse(contents) as SimpleJsonFile);
const parsedTranslations: Record<MessageId, ɵParsedTranslation> = {};
for (const messageId in translations) {
const targetMessage = translations[messageId];
parsedTranslations[messageId] = ɵparseTranslation(targetMessage);
}
return {locale: parsedLocale, translations: parsedTranslations, diagnostics: new Diagnostics()};
}
}
| {
"end_byte": 2902,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/simple_json_translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_utils.ts_0_6016 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Element,
LexerRange,
Node,
ParseError,
ParseErrorLevel,
ParseSourceSpan,
ParseTreeResult,
XmlParser,
} from '@angular/compiler';
import {Diagnostics} from '../../../diagnostics';
import {TranslationParseError} from './translation_parse_error';
import {ParseAnalysis, ParsedTranslationBundle} from './translation_parser';
export function getAttrOrThrow(element: Element, attrName: string): string {
const attrValue = getAttribute(element, attrName);
if (attrValue === undefined) {
throw new TranslationParseError(
element.sourceSpan,
`Missing required "${attrName}" attribute:`,
);
}
return attrValue;
}
export function getAttribute(element: Element, attrName: string): string | undefined {
const attr = element.attrs.find((a) => a.name === attrName);
return attr !== undefined ? attr.value : undefined;
}
/**
* Parse the "contents" of an XML element.
*
* This would be equivalent to parsing the `innerHTML` string of an HTML document.
*
* @param element The element whose inner range we want to parse.
* @returns a collection of XML `Node` objects and any errors that were parsed from the element's
* contents.
*/
export function parseInnerRange(element: Element): ParseTreeResult {
const xmlParser = new XmlParser();
const xml = xmlParser.parse(
element.sourceSpan.start.file.content,
element.sourceSpan.start.file.url,
{tokenizeExpansionForms: true, range: getInnerRange(element)},
);
return xml;
}
/**
* Compute a `LexerRange` that contains all the children of the given `element`.
* @param element The element whose inner range we want to compute.
*/
function getInnerRange(element: Element): LexerRange {
const start = element.startSourceSpan.end;
const end = element.endSourceSpan!.start;
return {
startPos: start.offset,
startLine: start.line,
startCol: start.col,
endPos: end.offset,
};
}
/**
* This "hint" object is used to pass information from `analyze()` to `parse()` for
* `TranslationParser`s that expect XML contents.
*
* This saves the `parse()` method from having to re-parse the XML.
*/
export interface XmlTranslationParserHint {
element: Element;
errors: ParseError[];
}
/**
* Can this XML be parsed for translations, given the expected `rootNodeName` and expected root node
* `attributes` that should appear in the file.
*
* @param filePath The path to the file being checked.
* @param contents The contents of the file being checked.
* @param rootNodeName The expected name of an XML root node that should exist.
* @param attributes The attributes (and their values) that should appear on the root node.
* @returns The `XmlTranslationParserHint` object for use by `TranslationParser.parse()` if the XML
* document has the expected format.
*/
export function canParseXml(
filePath: string,
contents: string,
rootNodeName: string,
attributes: Record<string, string>,
): ParseAnalysis<XmlTranslationParserHint> {
const diagnostics = new Diagnostics();
const xmlParser = new XmlParser();
const xml = xmlParser.parse(contents, filePath);
if (
xml.rootNodes.length === 0 ||
xml.errors.some((error) => error.level === ParseErrorLevel.ERROR)
) {
xml.errors.forEach((e) => addParseError(diagnostics, e));
return {canParse: false, diagnostics};
}
const rootElements = xml.rootNodes.filter(isNamedElement(rootNodeName));
const rootElement = rootElements[0];
if (rootElement === undefined) {
diagnostics.warn(`The XML file does not contain a <${rootNodeName}> root node.`);
return {canParse: false, diagnostics};
}
for (const attrKey of Object.keys(attributes)) {
const attr = rootElement.attrs.find((attr) => attr.name === attrKey);
if (attr === undefined || attr.value !== attributes[attrKey]) {
addParseDiagnostic(
diagnostics,
rootElement.sourceSpan,
`The <${rootNodeName}> node does not have the required attribute: ${attrKey}="${attributes[attrKey]}".`,
ParseErrorLevel.WARNING,
);
return {canParse: false, diagnostics};
}
}
if (rootElements.length > 1) {
xml.errors.push(
new ParseError(
xml.rootNodes[1].sourceSpan,
'Unexpected root node. XLIFF 1.2 files should only have a single <xliff> root node.',
ParseErrorLevel.WARNING,
),
);
}
return {canParse: true, diagnostics, hint: {element: rootElement, errors: xml.errors}};
}
/**
* Create a predicate, which can be used by things like `Array.filter()`, that will match a named
* XML Element from a collection of XML Nodes.
*
* @param name The expected name of the element to match.
*/
export function isNamedElement(name: string): (node: Node) => node is Element {
function predicate(node: Node): node is Element {
return node instanceof Element && node.name === name;
}
return predicate;
}
/**
* Add an XML parser related message to the given `diagnostics` object.
*/
export function addParseDiagnostic(
diagnostics: Diagnostics,
sourceSpan: ParseSourceSpan,
message: string,
level: ParseErrorLevel,
): void {
addParseError(diagnostics, new ParseError(sourceSpan, message, level));
}
/**
* Copy the formatted error message from the given `parseError` object into the given `diagnostics`
* object.
*/
export function addParseError(diagnostics: Diagnostics, parseError: ParseError): void {
if (parseError.level === ParseErrorLevel.ERROR) {
diagnostics.error(parseError.toString());
} else {
diagnostics.warn(parseError.toString());
}
}
/**
* Add the provided `errors` to the `bundle` diagnostics.
*/
export function addErrorsToBundle(bundle: ParsedTranslationBundle, errors: ParseError[]): void {
for (const error of errors) {
addParseError(bundle.diagnostics, error);
}
}
| {
"end_byte": 6016,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_utils.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts_0_1259 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Element, ParseError} from '@angular/compiler';
import {ɵParsedTranslation} from '@angular/localize';
import {
MessageSerializer,
MessageSerializerConfig,
} from '../message_serialization/message_serializer';
import {TargetMessageRenderer} from '../message_serialization/target_message_renderer';
import {parseInnerRange} from './translation_utils';
/**
* Serialize the given `element` into a parsed translation using the given `serializer`.
*/
export function serializeTranslationMessage(
element: Element,
config: MessageSerializerConfig,
): {
translation: ɵParsedTranslation | null;
parseErrors: ParseError[];
serializeErrors: ParseError[];
} {
const {rootNodes, errors: parseErrors} = parseInnerRange(element);
try {
const serializer = new MessageSerializer(new TargetMessageRenderer(), config);
const translation = serializer.serialize(rootNodes);
return {translation, parseErrors, serializeErrors: []};
} catch (e) {
return {translation: null, parseErrors, serializeErrors: [e as ParseError]};
}
}
| {
"end_byte": 1259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/serialize_translation_message.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_parse_error.ts_0_929 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ParseErrorLevel, ParseSourceSpan} from '@angular/compiler';
/**
* This error is thrown when there is a problem parsing a translation file.
*/
export class TranslationParseError extends Error {
constructor(
public span: ParseSourceSpan,
public msg: string,
public level: ParseErrorLevel = ParseErrorLevel.ERROR,
) {
super(contextualMessage(span, msg, level));
}
}
function contextualMessage(span: ParseSourceSpan, msg: string, level: ParseErrorLevel): string {
const ctx = span.start.getContext(100, 2);
msg += `\nAt ${span.start}${span.details ? `, ${span.details}` : ''}:\n`;
if (ctx) {
msg += `...${ctx.before}[${ParseErrorLevel[level]} ->]${ctx.after}...\n`;
}
return msg;
}
| {
"end_byte": 929,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/translation_parse_error.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/arb_translation_parser.ts_0_2859 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageId, ɵparseTranslation, ɵSourceMessage} from '@angular/localize';
import {Diagnostics} from '../../../diagnostics';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
export interface ArbJsonObject extends Record<MessageId, ɵSourceMessage | ArbMetadata> {
'@@locale': string;
}
export interface ArbMetadata {
type?: 'text' | 'image' | 'css';
description?: string;
['x-locations']?: ArbLocation[];
}
export interface ArbLocation {
start: {line: number; column: number};
end: {line: number; column: number};
file: string;
}
/**
* A translation parser that can parse JSON formatted as an Application Resource Bundle (ARB).
*
* See https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification
*
* ```
* {
* "@@locale": "en-US",
* "message-id": "Target message string",
* "@message-id": {
* "type": "text",
* "description": "Some description text",
* "x-locations": [
* {
* "start": {"line": 23, "column": 145},
* "end": {"line": 24, "column": 53},
* "file": "some/file.ts"
* },
* ...
* ]
* },
* ...
* }
* ```
*/
export class ArbTranslationParser implements TranslationParser<ArbJsonObject> {
analyze(_filePath: string, contents: string): ParseAnalysis<ArbJsonObject> {
const diagnostics = new Diagnostics();
if (!contents.includes('"@@locale"')) {
return {canParse: false, diagnostics};
}
try {
// We can parse this file if it is valid JSON and contains the `"@@locale"` property.
return {canParse: true, diagnostics, hint: this.tryParseArbFormat(contents)};
} catch {
diagnostics.warn('File is not valid JSON.');
return {canParse: false, diagnostics};
}
}
parse(
_filePath: string,
contents: string,
arb: ArbJsonObject = this.tryParseArbFormat(contents),
): ParsedTranslationBundle {
const bundle: ParsedTranslationBundle = {
locale: arb['@@locale'],
translations: {},
diagnostics: new Diagnostics(),
};
for (const messageId of Object.keys(arb)) {
if (messageId.startsWith('@')) {
// Skip metadata keys
continue;
}
const targetMessage = arb[messageId] as string;
bundle.translations[messageId] = ɵparseTranslation(targetMessage);
}
return bundle;
}
private tryParseArbFormat(contents: string): ArbJsonObject {
const json = JSON.parse(contents) as ArbJsonObject;
if (typeof json['@@locale'] !== 'string') {
throw new Error('Missing @@locale property.');
}
return json;
}
}
| {
"end_byte": 2859,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/arb_translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/xliff1_translation_parser.ts_0_5417 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Element, ParseErrorLevel, visitAll} from '@angular/compiler';
import {Diagnostics} from '../../../diagnostics';
import {BaseVisitor} from '../base_visitor';
import {serializeTranslationMessage} from './serialize_translation_message';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
import {
addErrorsToBundle,
addParseDiagnostic,
addParseError,
canParseXml,
getAttribute,
isNamedElement,
XmlTranslationParserHint,
} from './translation_utils';
/**
* A translation parser that can load XLIFF 1.2 files.
*
* https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
* https://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
*
* @see Xliff1TranslationSerializer
* @publicApi used by CLI
*/
export class Xliff1TranslationParser implements TranslationParser<XmlTranslationParserHint> {
analyze(filePath: string, contents: string): ParseAnalysis<XmlTranslationParserHint> {
return canParseXml(filePath, contents, 'xliff', {version: '1.2'});
}
parse(
filePath: string,
contents: string,
hint: XmlTranslationParserHint,
): ParsedTranslationBundle {
return this.extractBundle(hint);
}
private extractBundle({element, errors}: XmlTranslationParserHint): ParsedTranslationBundle {
const diagnostics = new Diagnostics();
errors.forEach((e) => addParseError(diagnostics, e));
if (element.children.length === 0) {
addParseDiagnostic(
diagnostics,
element.sourceSpan,
'Missing expected <file> element',
ParseErrorLevel.WARNING,
);
return {locale: undefined, translations: {}, diagnostics};
}
const files = element.children.filter(isNamedElement('file'));
if (files.length === 0) {
addParseDiagnostic(
diagnostics,
element.sourceSpan,
'No <file> elements found in <xliff>',
ParseErrorLevel.WARNING,
);
} else if (files.length > 1) {
addParseDiagnostic(
diagnostics,
files[1].sourceSpan,
'More than one <file> element found in <xliff>',
ParseErrorLevel.WARNING,
);
}
const bundle: ParsedTranslationBundle = {locale: undefined, translations: {}, diagnostics};
const translationVisitor = new XliffTranslationVisitor();
const localesFound = new Set<string>();
for (const file of files) {
const locale = getAttribute(file, 'target-language');
if (locale !== undefined) {
localesFound.add(locale);
bundle.locale = locale;
}
visitAll(translationVisitor, file.children, bundle);
}
if (localesFound.size > 1) {
addParseDiagnostic(
diagnostics,
element.sourceSpan,
`More than one locale found in translation file: ${JSON.stringify(
Array.from(localesFound),
)}. Using "${bundle.locale}"`,
ParseErrorLevel.WARNING,
);
}
return bundle;
}
}
class XliffTranslationVisitor extends BaseVisitor {
override visitElement(element: Element, bundle: ParsedTranslationBundle): void {
if (element.name === 'trans-unit') {
this.visitTransUnitElement(element, bundle);
} else {
visitAll(this, element.children, bundle);
}
}
private visitTransUnitElement(element: Element, bundle: ParsedTranslationBundle): void {
// Error if no `id` attribute
const id = getAttribute(element, 'id');
if (id === undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Missing required "id" attribute on <trans-unit> element.`,
ParseErrorLevel.ERROR,
);
return;
}
// Error if there is already a translation with the same id
if (bundle.translations[id] !== undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Duplicated translations for message "${id}"`,
ParseErrorLevel.ERROR,
);
return;
}
let targetMessage = element.children.find(isNamedElement('target'));
if (targetMessage === undefined) {
// Warn if there is no `<target>` child element
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
'Missing <target> element',
ParseErrorLevel.WARNING,
);
// Fallback to the `<source>` element if available.
targetMessage = element.children.find(isNamedElement('source'));
if (targetMessage === undefined) {
// Error if there is neither `<target>` nor `<source>`.
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
'Missing required element: one of <target> or <source> is required',
ParseErrorLevel.ERROR,
);
return;
}
}
const {translation, parseErrors, serializeErrors} = serializeTranslationMessage(targetMessage, {
inlineElements: ['g', 'bx', 'ex', 'bpt', 'ept', 'ph', 'it', 'mrk'],
placeholder: {elementName: 'x', nameAttribute: 'id'},
});
if (translation !== null) {
bundle.translations[id] = translation;
}
addErrorsToBundle(bundle, parseErrors);
addErrorsToBundle(bundle, serializeErrors);
}
}
| {
"end_byte": 5417,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/xliff1_translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/translation_files/translation_parsers/xtb_translation_parser.ts_0_4213 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Element, ParseError, ParseErrorLevel, visitAll} from '@angular/compiler';
import {extname} from 'path';
import {Diagnostics} from '../../../diagnostics';
import {BaseVisitor} from '../base_visitor';
import {serializeTranslationMessage} from './serialize_translation_message';
import {ParseAnalysis, ParsedTranslationBundle, TranslationParser} from './translation_parser';
import {
addErrorsToBundle,
addParseDiagnostic,
addParseError,
canParseXml,
getAttribute,
XmlTranslationParserHint,
} from './translation_utils';
/**
* A translation parser that can load XTB files.
*
* http://cldr.unicode.org/development/development-process/design-proposals/xmb
*
* @see XmbTranslationSerializer
* @publicApi used by CLI
*/
export class XtbTranslationParser implements TranslationParser<XmlTranslationParserHint> {
analyze(filePath: string, contents: string): ParseAnalysis<XmlTranslationParserHint> {
const extension = extname(filePath);
if (extension !== '.xtb' && extension !== '.xmb') {
const diagnostics = new Diagnostics();
diagnostics.warn('Must have xtb or xmb extension.');
return {canParse: false, diagnostics};
}
return canParseXml(filePath, contents, 'translationbundle', {});
}
parse(
filePath: string,
contents: string,
hint: XmlTranslationParserHint,
): ParsedTranslationBundle {
return this.extractBundle(hint);
}
private extractBundle({element, errors}: XmlTranslationParserHint): ParsedTranslationBundle {
const langAttr = element.attrs.find((attr) => attr.name === 'lang');
const bundle: ParsedTranslationBundle = {
locale: langAttr && langAttr.value,
translations: {},
diagnostics: new Diagnostics(),
};
errors.forEach((e) => addParseError(bundle.diagnostics, e));
const bundleVisitor = new XtbVisitor();
visitAll(bundleVisitor, element.children, bundle);
return bundle;
}
}
class XtbVisitor extends BaseVisitor {
override visitElement(element: Element, bundle: ParsedTranslationBundle): any {
switch (element.name) {
case 'translation':
// Error if no `id` attribute
const id = getAttribute(element, 'id');
if (id === undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Missing required "id" attribute on <translation> element.`,
ParseErrorLevel.ERROR,
);
return;
}
// Error if there is already a translation with the same id
if (bundle.translations[id] !== undefined) {
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Duplicated translations for message "${id}"`,
ParseErrorLevel.ERROR,
);
return;
}
const {translation, parseErrors, serializeErrors} = serializeTranslationMessage(element, {
inlineElements: [],
placeholder: {elementName: 'ph', nameAttribute: 'name'},
});
if (parseErrors.length) {
// We only want to warn (not error) if there were problems parsing the translation for
// XTB formatted files. See https://github.com/angular/angular/issues/14046.
bundle.diagnostics.warn(computeParseWarning(id, parseErrors));
} else if (translation !== null) {
// Only store the translation if there were no parse errors
bundle.translations[id] = translation;
}
addErrorsToBundle(bundle, serializeErrors);
break;
default:
addParseDiagnostic(
bundle.diagnostics,
element.sourceSpan,
`Unexpected <${element.name}> tag.`,
ParseErrorLevel.ERROR,
);
}
}
}
function computeParseWarning(id: string, errors: ParseError[]): string {
const msg = errors.map((e) => e.toString()).join('\n');
return (
`Could not parse message with id "${id}" - perhaps it has an unrecognised ICU format?\n` + msg
);
}
| {
"end_byte": 4213,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/translation_files/translation_parsers/xtb_translation_parser.ts"
} |
angular/packages/localize/tools/src/translate/source_files/es2015_translate_plugin.ts_0_2213 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getFileSystem, PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedTranslation} from '@angular/localize';
import {NodePath, PluginObj, types as t} from '@babel/core';
import {Diagnostics} from '../../diagnostics';
import {
buildCodeFrameError,
buildLocalizeReplacement,
isBabelParseError,
isLocalize,
translate,
TranslatePluginOptions,
unwrapMessagePartsFromTemplateLiteral,
} from '../../source_file_utils';
/**
* Create a Babel plugin that can be used to do compile-time translation of `$localize` tagged
* messages.
*
* @publicApi used by CLI
*/
export function makeEs2015TranslatePlugin(
diagnostics: Diagnostics,
translations: Record<string, ɵParsedTranslation>,
{missingTranslation = 'error', localizeName = '$localize'}: TranslatePluginOptions = {},
fs: PathManipulation = getFileSystem(),
): PluginObj {
return {
visitor: {
TaggedTemplateExpression(path: NodePath<t.TaggedTemplateExpression>, state) {
try {
const tag = path.get('tag');
if (isLocalize(tag, localizeName)) {
const [messageParts] = unwrapMessagePartsFromTemplateLiteral(
path.get('quasi').get('quasis'),
fs,
);
const translated = translate(
diagnostics,
translations,
messageParts,
path.node.quasi.expressions,
missingTranslation,
);
path.replaceWith(buildLocalizeReplacement(translated[0], translated[1]));
}
} catch (e) {
if (isBabelParseError(e)) {
// If we get a BabelParseError here then something went wrong with Babel itself
// since there must be something wrong with the structure of the AST generated
// by Babel parsing a TaggedTemplateExpression.
throw buildCodeFrameError(fs, path, state.file, e);
} else {
throw e;
}
}
},
},
};
}
| {
"end_byte": 2213,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/source_files/es2015_translate_plugin.ts"
} |
angular/packages/localize/tools/src/translate/source_files/es5_translate_plugin.ts_0_2029 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getFileSystem, PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedTranslation} from '@angular/localize';
import {NodePath, PluginObj, types as t} from '@babel/core';
import {Diagnostics} from '../../diagnostics';
import {
buildCodeFrameError,
buildLocalizeReplacement,
isBabelParseError,
isLocalize,
translate,
TranslatePluginOptions,
unwrapMessagePartsFromLocalizeCall,
unwrapSubstitutionsFromLocalizeCall,
} from '../../source_file_utils';
/**
* Create a Babel plugin that can be used to do compile-time translation of `$localize` tagged
* messages.
*
* @publicApi used by CLI
*/
export function makeEs5TranslatePlugin(
diagnostics: Diagnostics,
translations: Record<string, ɵParsedTranslation>,
{missingTranslation = 'error', localizeName = '$localize'}: TranslatePluginOptions = {},
fs: PathManipulation = getFileSystem(),
): PluginObj {
return {
visitor: {
CallExpression(callPath: NodePath<t.CallExpression>, state) {
try {
const calleePath = callPath.get('callee');
if (isLocalize(calleePath, localizeName)) {
const [messageParts] = unwrapMessagePartsFromLocalizeCall(callPath, fs);
const [expressions] = unwrapSubstitutionsFromLocalizeCall(callPath, fs);
const translated = translate(
diagnostics,
translations,
messageParts,
expressions,
missingTranslation,
);
callPath.replaceWith(buildLocalizeReplacement(translated[0], translated[1]));
}
} catch (e) {
if (isBabelParseError(e)) {
diagnostics.error(buildCodeFrameError(fs, callPath, state.file, e));
} else {
throw e;
}
}
},
},
};
}
| {
"end_byte": 2029,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/source_files/es5_translate_plugin.ts"
} |
angular/packages/localize/tools/src/translate/source_files/locale_plugin.ts_0_3705 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NodePath, PluginObj, types as t} from '@babel/core';
import {isLocalize, TranslatePluginOptions} from '../../source_file_utils';
/**
* This Babel plugin will replace the following code forms with a string literal containing the
* given `locale`.
*
* * `$localize.locale` -> `"locale"`
* * `typeof $localize !== "undefined" && $localize.locale` -> `"locale"`
* * `xxx && typeof $localize !== "undefined" && $localize.locale` -> `"xxx && locale"`
* * `$localize.locale || default` -> `"locale" || default`
*
* @param locale The name of the locale to inline into the code.
* @param options Additional options including the name of the `$localize` function.
* @publicApi used by CLI
*/
export function makeLocalePlugin(
locale: string,
{localizeName = '$localize'}: TranslatePluginOptions = {},
): PluginObj {
return {
visitor: {
MemberExpression(expression: NodePath<t.MemberExpression>) {
const obj = expression.get('object');
if (!isLocalize(obj, localizeName)) {
return;
}
const property = expression.get('property') as NodePath;
if (!property.isIdentifier({name: 'locale'})) {
return;
}
if (
expression.parentPath.isAssignmentExpression() &&
expression.parentPath.get('left') === expression
) {
return;
}
// Check for the `$localize.locale` being guarded by a check on the existence of
// `$localize`.
const parent = expression.parentPath;
if (parent.isLogicalExpression({operator: '&&'}) && parent.get('right') === expression) {
const left = parent.get('left');
if (isLocalizeGuard(left, localizeName)) {
// Replace `typeof $localize !== "undefined" && $localize.locale` with
// `$localize.locale`
parent.replaceWith(expression);
} else if (
left.isLogicalExpression({operator: '&&'}) &&
isLocalizeGuard(left.get('right'), localizeName)
) {
// The `$localize` is part of a preceding logical AND.
// Replace XXX && typeof $localize !== "undefined" && $localize.locale` with `XXX &&
// $localize.locale`
left.replaceWith(left.get('left'));
}
}
// Replace the `$localize.locale` with the string literal
expression.replaceWith(t.stringLiteral(locale));
},
},
};
}
/**
* Returns true if the expression one of:
* * `typeof $localize !== "undefined"`
* * `"undefined" !== typeof $localize`
* * `typeof $localize != "undefined"`
* * `"undefined" != typeof $localize`
*
* @param expression the expression to check
* @param localizeName the name of the `$localize` symbol
*/
function isLocalizeGuard(expression: NodePath, localizeName: string): boolean {
if (
!expression.isBinaryExpression() ||
!(expression.node.operator === '!==' || expression.node.operator === '!=')
) {
return false;
}
const left = expression.get('left');
const right = expression.get('right');
return (
(left.isUnaryExpression({operator: 'typeof'}) &&
isLocalize(left.get('argument'), localizeName) &&
right.isStringLiteral({value: 'undefined'})) ||
(right.isUnaryExpression({operator: 'typeof'}) &&
isLocalize(right.get('argument'), localizeName) &&
left.isStringLiteral({value: 'undefined'}))
);
}
| {
"end_byte": 3705,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/source_files/locale_plugin.ts"
} |
angular/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts_0_5028 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
absoluteFrom,
AbsoluteFsPath,
FileSystem,
PathSegment,
} from '@angular/compiler-cli/private/localize';
import babel, {types as t} from '@babel/core';
import {Diagnostics} from '../../diagnostics';
import {TranslatePluginOptions} from '../../source_file_utils';
import {OutputPathFn} from '../output_path';
import {TranslationBundle, TranslationHandler} from '../translator';
import {makeEs2015TranslatePlugin} from './es2015_translate_plugin';
import {makeEs5TranslatePlugin} from './es5_translate_plugin';
import {makeLocalePlugin} from './locale_plugin';
/**
* Translate a file by inlining all messages tagged by `$localize` with the appropriate translated
* message.
*/
export class SourceFileTranslationHandler implements TranslationHandler {
private sourceLocaleOptions: TranslatePluginOptions;
constructor(
private fs: FileSystem,
private translationOptions: TranslatePluginOptions = {},
) {
this.sourceLocaleOptions = {
...this.translationOptions,
missingTranslation: 'ignore',
};
}
canTranslate(relativeFilePath: PathSegment | AbsoluteFsPath, _contents: Uint8Array): boolean {
return this.fs.extname(relativeFilePath) === '.js';
}
translate(
diagnostics: Diagnostics,
sourceRoot: AbsoluteFsPath,
relativeFilePath: PathSegment,
contents: Uint8Array,
outputPathFn: OutputPathFn,
translations: TranslationBundle[],
sourceLocale?: string,
): void {
const sourceCode = Buffer.from(contents).toString('utf8');
// A short-circuit check to avoid parsing the file into an AST if it does not contain any
// `$localize` identifiers.
if (!sourceCode.includes('$localize')) {
for (const translation of translations) {
this.writeSourceFile(
diagnostics,
outputPathFn,
translation.locale,
relativeFilePath,
contents,
);
}
if (sourceLocale !== undefined) {
this.writeSourceFile(diagnostics, outputPathFn, sourceLocale, relativeFilePath, contents);
}
} else {
const ast = babel.parseSync(sourceCode, {sourceRoot, filename: relativeFilePath});
if (!ast) {
diagnostics.error(
`Unable to parse source file: ${this.fs.join(sourceRoot, relativeFilePath)}`,
);
return;
}
// Output a translated copy of the file for each locale.
for (const translationBundle of translations) {
this.translateFile(
diagnostics,
ast,
translationBundle,
sourceRoot,
relativeFilePath,
outputPathFn,
this.translationOptions,
);
}
if (sourceLocale !== undefined) {
// Also output a copy of the file for the source locale.
// There will be no translations - by definition - so we "ignore" `missingTranslations`.
this.translateFile(
diagnostics,
ast,
{locale: sourceLocale, translations: {}},
sourceRoot,
relativeFilePath,
outputPathFn,
this.sourceLocaleOptions,
);
}
}
}
private translateFile(
diagnostics: Diagnostics,
ast: t.File | t.Program,
translationBundle: TranslationBundle,
sourceRoot: AbsoluteFsPath,
filename: PathSegment,
outputPathFn: OutputPathFn,
options: TranslatePluginOptions,
) {
const translated = babel.transformFromAstSync(ast, undefined, {
compact: true,
generatorOpts: {minified: true},
plugins: [
makeLocalePlugin(translationBundle.locale),
makeEs2015TranslatePlugin(diagnostics, translationBundle.translations, options, this.fs),
makeEs5TranslatePlugin(diagnostics, translationBundle.translations, options, this.fs),
],
cwd: sourceRoot,
filename,
});
if (translated && translated.code) {
this.writeSourceFile(
diagnostics,
outputPathFn,
translationBundle.locale,
filename,
translated.code,
);
const outputPath = absoluteFrom(outputPathFn(translationBundle.locale, filename));
this.fs.ensureDir(this.fs.dirname(outputPath));
this.fs.writeFile(outputPath, translated.code);
} else {
diagnostics.error(`Unable to translate source file: ${this.fs.join(sourceRoot, filename)}`);
return;
}
}
private writeSourceFile(
diagnostics: Diagnostics,
outputPathFn: OutputPathFn,
locale: string,
relativeFilePath: PathSegment,
contents: string | Uint8Array,
): void {
try {
const outputPath = absoluteFrom(outputPathFn(locale, relativeFilePath));
this.fs.ensureDir(this.fs.dirname(outputPath));
this.fs.writeFile(outputPath, contents);
} catch (e) {
diagnostics.error((e as Error).message);
}
}
}
| {
"end_byte": 5028,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/translate/source_files/source_file_translation_handler.ts"
} |
angular/packages/localize/tools/src/migrate/migrate.ts_0_918 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/** Mapping between legacy message IDs and their canonical counterparts. */
export type MigrationMapping = {
[legacyId: string]: string;
};
/** Migrates the legacy message IDs within a single file. */
export function migrateFile(sourceCode: string, mapping: MigrationMapping) {
const legacyIds = Object.keys(mapping);
for (const legacyId of legacyIds) {
const canonicalId = mapping[legacyId];
const pattern = new RegExp(escapeRegExp(legacyId), 'g');
sourceCode = sourceCode.replace(pattern, canonicalId);
}
return sourceCode;
}
/** Escapes special regex characters in a string. */
function escapeRegExp(str: string): string {
return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
| {
"end_byte": 918,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/migrate/migrate.ts"
} |
angular/packages/localize/tools/src/migrate/cli.ts_0_1526 | #!/usr/bin/env node
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ConsoleLogger,
LogLevel,
NodeJSFileSystem,
setFileSystem,
} from '@angular/compiler-cli/private/localize';
import glob from 'fast-glob';
import yargs from 'yargs';
import {migrateFiles} from './index';
const args = process.argv.slice(2);
const options = yargs(args)
.option('r', {
alias: 'root',
default: '.',
describe:
'The root path for other paths provided in these options.\n' +
'This should either be absolute or relative to the current working directory.',
type: 'string',
})
.option('f', {
alias: 'files',
required: true,
describe:
'A glob pattern indicating what files to migrate. This should be relative to the root path',
type: 'string',
})
.option('m', {
alias: 'mapFile',
required: true,
describe:
'Path to the migration mapping file generated by `localize-extract`. This should be relative to the root path.',
type: 'string',
})
.strict()
.help()
.parseSync();
const fs = new NodeJSFileSystem();
setFileSystem(fs);
const rootPath = options.r;
const translationFilePaths = glob.sync(options.f, {cwd: rootPath, onlyFiles: true});
const logger = new ConsoleLogger(LogLevel.warn);
migrateFiles({rootPath, translationFilePaths, mappingFilePath: options.m, logger});
process.exit(0);
| {
"end_byte": 1526,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/migrate/cli.ts"
} |
angular/packages/localize/tools/src/migrate/index.ts_0_1744 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getFileSystem, Logger} from '@angular/compiler-cli/private/localize';
import {migrateFile, MigrationMapping} from './migrate';
export interface MigrateFilesOptions {
/**
* The base path for other paths provided in these options.
* This should either be absolute or relative to the current working directory.
*/
rootPath: string;
/** Paths to the files that should be migrated. Should be relative to the `rootPath`. */
translationFilePaths: string[];
/** Path to the file containing the message ID mappings. Should be relative to the `rootPath`. */
mappingFilePath: string;
/** Logger to use for diagnostic messages. */
logger: Logger;
}
/** Migrates the legacy message IDs based on the passed in configuration. */
export function migrateFiles({
rootPath,
translationFilePaths,
mappingFilePath,
logger,
}: MigrateFilesOptions) {
const fs = getFileSystem();
const absoluteMappingPath = fs.resolve(rootPath, mappingFilePath);
const mapping = JSON.parse(fs.readFile(absoluteMappingPath)) as MigrationMapping;
if (Object.keys(mapping).length === 0) {
logger.warn(
`Mapping file at ${absoluteMappingPath} is empty. Either there are no messages ` +
`that need to be migrated, or the extraction step failed to find them.`,
);
} else {
translationFilePaths.forEach((path) => {
const absolutePath = fs.resolve(rootPath, path);
const sourceCode = fs.readFile(absolutePath);
fs.writeFile(absolutePath, migrateFile(sourceCode, mapping));
});
}
}
| {
"end_byte": 1744,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/migrate/index.ts"
} |
angular/packages/localize/tools/src/extract/cli.ts_0_3841 | #!/usr/bin/env node
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ConsoleLogger,
LogLevel,
NodeJSFileSystem,
setFileSystem,
} from '@angular/compiler-cli/private/localize';
import glob from 'fast-glob';
import yargs from 'yargs';
import {DiagnosticHandlingStrategy} from '../diagnostics';
import {parseFormatOptions} from './translation_files/format_options';
import {extractTranslations} from './index';
process.title = 'Angular Localization Message Extractor (localize-extract)';
const args = process.argv.slice(2);
const options = yargs(args)
.option('l', {
alias: 'locale',
describe: 'The locale of the source being processed',
default: 'en',
type: 'string',
})
.option('r', {
alias: 'root',
default: '.',
describe:
'The root path for other paths provided in these options.\n' +
'This should either be absolute or relative to the current working directory.',
type: 'string',
})
.option('s', {
alias: 'source',
required: true,
describe:
'A glob pattern indicating what files to search for translations, e.g. `./dist/**/*.js`.\n' +
'This should be relative to the root path.',
type: 'string',
})
.option('f', {
alias: 'format',
required: true,
choices: [
'xmb',
'xlf',
'xlif',
'xliff',
'xlf2',
'xlif2',
'xliff2',
'json',
'legacy-migrate',
'arb',
],
describe: 'The format of the translation file.',
type: 'string',
})
.option('formatOptions', {
describe:
'Additional options to pass to the translation file serializer, in the form of JSON formatted key-value string pairs:\n' +
'For example: `--formatOptions {"xml:space":"preserve"}.\n' +
'The meaning of the options is specific to the format being serialized.',
type: 'string',
})
.option('o', {
alias: 'outputPath',
required: true,
describe:
'A path to where the translation file will be written. This should be relative to the root path.',
type: 'string',
})
.option('loglevel', {
describe: 'The lowest severity logging message that should be output.',
choices: ['debug', 'info', 'warn', 'error'],
type: 'string',
})
.option('useSourceMaps', {
type: 'boolean',
default: true,
describe:
'Whether to generate source information in the output files by following source-map mappings found in the source files',
})
.option('useLegacyIds', {
type: 'boolean',
default: true,
describe:
'Whether to use the legacy id format for messages that were extracted from Angular templates.',
})
.option('d', {
alias: 'duplicateMessageHandling',
describe: 'How to handle messages with the same id but different text.',
choices: ['error', 'warning', 'ignore'],
default: 'warning',
type: 'string',
})
.strict()
.help()
.parseSync();
const fileSystem = new NodeJSFileSystem();
setFileSystem(fileSystem);
const rootPath = options.r;
const sourceFilePaths = glob.sync(options.s, {cwd: rootPath});
const logLevel = options.loglevel as keyof typeof LogLevel | undefined;
const logger = new ConsoleLogger(logLevel ? LogLevel[logLevel] : LogLevel.warn);
const duplicateMessageHandling = options.d as DiagnosticHandlingStrategy;
const formatOptions = parseFormatOptions(options.formatOptions);
const format = options.f;
extractTranslations({
rootPath,
sourceFilePaths,
sourceLocale: options.l,
format,
outputPath: options.o,
logger,
useSourceMaps: options.useSourceMaps,
useLegacyIds: format === 'legacy-migrate' || options.useLegacyIds,
duplicateMessageHandling,
formatOptions,
fileSystem,
});
| {
"end_byte": 3841,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/cli.ts"
} |
angular/packages/localize/tools/src/extract/extraction.ts_0_5154 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AbsoluteFsPath,
Logger,
ReadonlyFileSystem,
SourceFile,
SourceFileLoader,
} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
import {transformSync} from '@babel/core';
import {makeEs2015ExtractPlugin} from './source_files/es2015_extract_plugin';
import {makeEs5ExtractPlugin} from './source_files/es5_extract_plugin';
export interface ExtractionOptions {
basePath: AbsoluteFsPath;
useSourceMaps?: boolean;
localizeName?: string;
}
/**
* Extracts parsed messages from file contents, by parsing the contents as JavaScript
* and looking for occurrences of `$localize` in the source code.
*
* @publicApi used by CLI
*/
export class MessageExtractor {
private basePath: AbsoluteFsPath;
private useSourceMaps: boolean;
private localizeName: string;
private loader: SourceFileLoader;
constructor(
private fs: ReadonlyFileSystem,
private logger: Logger,
{basePath, useSourceMaps = true, localizeName = '$localize'}: ExtractionOptions,
) {
this.basePath = basePath;
this.useSourceMaps = useSourceMaps;
this.localizeName = localizeName;
this.loader = new SourceFileLoader(this.fs, this.logger, {webpack: basePath});
}
extractMessages(filename: string): ɵParsedMessage[] {
const messages: ɵParsedMessage[] = [];
const sourceCode = this.fs.readFile(this.fs.resolve(this.basePath, filename));
if (sourceCode.includes(this.localizeName)) {
// Only bother to parse the file if it contains a reference to `$localize`.
transformSync(sourceCode, {
sourceRoot: this.basePath,
filename,
plugins: [
makeEs2015ExtractPlugin(this.fs, messages, this.localizeName),
makeEs5ExtractPlugin(this.fs, messages, this.localizeName),
],
code: false,
ast: false,
});
if (this.useSourceMaps && messages.length > 0) {
this.updateSourceLocations(filename, sourceCode, messages);
}
}
return messages;
}
/**
* Update the location of each message to point to the source-mapped original source location, if
* available.
*/
private updateSourceLocations(
filename: string,
contents: string,
messages: ɵParsedMessage[],
): void {
const sourceFile = this.loader.loadSourceFile(
this.fs.resolve(this.basePath, filename),
contents,
);
if (sourceFile === null) {
return;
}
for (const message of messages) {
if (message.location !== undefined) {
message.location = this.getOriginalLocation(sourceFile, message.location);
if (message.messagePartLocations) {
message.messagePartLocations = message.messagePartLocations.map(
(location) => location && this.getOriginalLocation(sourceFile, location),
);
}
if (message.substitutionLocations) {
const placeholderNames = Object.keys(message.substitutionLocations);
for (const placeholderName of placeholderNames) {
const location = message.substitutionLocations[placeholderName];
message.substitutionLocations[placeholderName] =
location && this.getOriginalLocation(sourceFile, location);
}
}
}
}
}
/**
* Find the original location using source-maps if available.
*
* @param sourceFile The generated `sourceFile` that contains the `location`.
* @param location The location within the generated `sourceFile` that needs mapping.
*
* @returns A new location that refers to the original source location mapped from the given
* `location` in the generated `sourceFile`.
*/
private getOriginalLocation(sourceFile: SourceFile, location: ɵSourceLocation): ɵSourceLocation {
const originalStart = sourceFile.getOriginalLocation(
location.start.line,
location.start.column,
);
if (originalStart === null) {
return location;
}
const originalEnd = sourceFile.getOriginalLocation(location.end.line, location.end.column);
const start = {line: originalStart.line, column: originalStart.column};
// We check whether the files are the same, since the returned location can only have a single
// `file` and it would not make sense to store the end position from a different source file.
const end =
originalEnd !== null && originalEnd.file === originalStart.file
? {line: originalEnd.line, column: originalEnd.column}
: start;
const originalSourceFile = sourceFile.sources.find(
(sf) => sf?.sourcePath === originalStart.file,
)!;
const startPos = originalSourceFile.startOfLinePositions[start.line] + start.column;
const endPos = originalSourceFile.startOfLinePositions[end.line] + end.column;
const text = originalSourceFile.contents.substring(startPos, endPos).trim();
return {file: originalStart.file, start, end, text};
}
}
| {
"end_byte": 5154,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/extraction.ts"
} |
angular/packages/localize/tools/src/extract/index.ts_0_4988 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AbsoluteFsPath,
FileSystem,
Logger,
PathManipulation,
} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage} from '@angular/localize';
import {DiagnosticHandlingStrategy, Diagnostics} from '../diagnostics';
import {checkDuplicateMessages} from './duplicates';
import {MessageExtractor} from './extraction';
import {ArbTranslationSerializer} from './translation_files/arb_translation_serializer';
import {FormatOptions} from './translation_files/format_options';
import {SimpleJsonTranslationSerializer} from './translation_files/json_translation_serializer';
import {LegacyMessageIdMigrationSerializer} from './translation_files/legacy_message_id_migration_serializer';
import {TranslationSerializer} from './translation_files/translation_serializer';
import {Xliff1TranslationSerializer} from './translation_files/xliff1_translation_serializer';
import {Xliff2TranslationSerializer} from './translation_files/xliff2_translation_serializer';
import {XmbTranslationSerializer} from './translation_files/xmb_translation_serializer';
export interface ExtractTranslationsOptions {
/**
* The locale of the source being processed.
*/
sourceLocale: string;
/**
* The base path for other paths provided in these options.
* This should either be absolute or relative to the current working directory.
*/
rootPath: string;
/**
* An array of paths to files to search for translations. These should be relative to the
* rootPath.
*/
sourceFilePaths: string[];
/**
* The format of the translation file.
*/
format: string;
/**
* A path to where the translation file will be written. This should be relative to the rootPath.
*/
outputPath: string;
/**
* The logger to use for diagnostic messages.
*/
logger: Logger;
/**
* Whether to generate source information in the output files by following source-map mappings
* found in the source file.
*/
useSourceMaps: boolean;
/**
* Whether to use the legacy id format for messages that were extracted from Angular templates
*/
useLegacyIds: boolean;
/**
* How to handle messages with the same id but not the same text.
*/
duplicateMessageHandling: DiagnosticHandlingStrategy;
/**
* A collection of formatting options to pass to the translation file serializer.
*/
formatOptions?: FormatOptions;
/**
* The file-system abstraction to use.
*/
fileSystem: FileSystem;
}
export function extractTranslations({
rootPath,
sourceFilePaths,
sourceLocale,
format,
outputPath: output,
logger,
useSourceMaps,
useLegacyIds,
duplicateMessageHandling,
formatOptions = {},
fileSystem: fs,
}: ExtractTranslationsOptions) {
const basePath = fs.resolve(rootPath);
const extractor = new MessageExtractor(fs, logger, {basePath, useSourceMaps});
const messages: ɵParsedMessage[] = [];
for (const file of sourceFilePaths) {
messages.push(...extractor.extractMessages(file));
}
const diagnostics = checkDuplicateMessages(fs, messages, duplicateMessageHandling, basePath);
if (diagnostics.hasErrors) {
throw new Error(diagnostics.formatDiagnostics('Failed to extract messages'));
}
const outputPath = fs.resolve(rootPath, output);
const serializer = getSerializer(
format,
sourceLocale,
fs.dirname(outputPath),
useLegacyIds,
formatOptions,
fs,
diagnostics,
);
const translationFile = serializer.serialize(messages);
fs.ensureDir(fs.dirname(outputPath));
fs.writeFile(outputPath, translationFile);
if (diagnostics.messages.length) {
logger.warn(diagnostics.formatDiagnostics('Messages extracted with warnings'));
}
}
function getSerializer(
format: string,
sourceLocale: string,
rootPath: AbsoluteFsPath,
useLegacyIds: boolean,
formatOptions: FormatOptions = {},
fs: PathManipulation,
diagnostics: Diagnostics,
): TranslationSerializer {
switch (format) {
case 'xlf':
case 'xlif':
case 'xliff':
return new Xliff1TranslationSerializer(
sourceLocale,
rootPath,
useLegacyIds,
formatOptions,
fs,
);
case 'xlf2':
case 'xlif2':
case 'xliff2':
return new Xliff2TranslationSerializer(
sourceLocale,
rootPath,
useLegacyIds,
formatOptions,
fs,
);
case 'xmb':
return new XmbTranslationSerializer(rootPath, useLegacyIds, fs);
case 'json':
return new SimpleJsonTranslationSerializer(sourceLocale);
case 'arb':
return new ArbTranslationSerializer(sourceLocale, rootPath, fs);
case 'legacy-migrate':
return new LegacyMessageIdMigrationSerializer(diagnostics);
}
throw new Error(`No translation serializer can handle the provided format: ${format}`);
}
| {
"end_byte": 4988,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/index.ts"
} |
angular/packages/localize/tools/src/extract/duplicates.ts_0_2227 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AbsoluteFsPath, PathManipulation} from '@angular/compiler-cli/private/localize';
import {MessageId, ɵParsedMessage} from '@angular/localize';
import {DiagnosticHandlingStrategy, Diagnostics} from '../diagnostics';
import {serializeLocationPosition} from '../source_file_utils';
/**
* Check each of the given `messages` to find those that have the same id but different message
* text. Add diagnostics messages for each of these duplicate messages to the given `diagnostics`
* object (as necessary).
*/
export function checkDuplicateMessages(
fs: PathManipulation,
messages: ɵParsedMessage[],
duplicateMessageHandling: DiagnosticHandlingStrategy,
basePath: AbsoluteFsPath,
): Diagnostics {
const diagnostics = new Diagnostics();
if (duplicateMessageHandling === 'ignore') return diagnostics;
const messageMap = new Map<MessageId, ɵParsedMessage[]>();
for (const message of messages) {
if (messageMap.has(message.id)) {
messageMap.get(message.id)!.push(message);
} else {
messageMap.set(message.id, [message]);
}
}
for (const duplicates of messageMap.values()) {
if (duplicates.length <= 1) continue;
if (duplicates.every((message) => message.text === duplicates[0].text)) continue;
const diagnosticMessage =
`Duplicate messages with id "${duplicates[0].id}":\n` +
duplicates.map((message) => serializeMessage(fs, basePath, message)).join('\n');
diagnostics.add(duplicateMessageHandling, diagnosticMessage);
}
return diagnostics;
}
/**
* Serialize the given `message` object into a string.
*/
function serializeMessage(
fs: PathManipulation,
basePath: AbsoluteFsPath,
message: ɵParsedMessage,
): string {
if (message.location === undefined) {
return ` - "${message.text}"`;
} else {
const locationFile = fs.relative(basePath, message.location.file);
const locationPosition = serializeLocationPosition(message.location);
return ` - "${message.text}" : ${locationFile}:${locationPosition}`;
}
}
| {
"end_byte": 2227,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/duplicates.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/json_translation_serializer.ts_0_1187 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageId, ɵParsedMessage, ɵSourceMessage} from '@angular/localize';
import {TranslationSerializer} from './translation_serializer';
import {consolidateMessages} from './utils';
interface SimpleJsonTranslationFile {
locale: string;
translations: Record<MessageId, ɵSourceMessage>;
}
/**
* This is a semi-public bespoke serialization format that is used for testing and sometimes as a
* format for storing translations that will be inlined at runtime.
*
* @see SimpleJsonTranslationParser
*/
export class SimpleJsonTranslationSerializer implements TranslationSerializer {
constructor(private sourceLocale: string) {}
serialize(messages: ɵParsedMessage[]): string {
const fileObj: SimpleJsonTranslationFile = {locale: this.sourceLocale, translations: {}};
for (const [message] of consolidateMessages(messages, (message) => message.id)) {
fileObj.translations[message.id] = message.text;
}
return JSON.stringify(fileObj, null, 2);
}
}
| {
"end_byte": 1187,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/json_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/icu_parsing.ts_0_6582 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Split the given `text` into an array of "static strings" and ICU "placeholder names".
*
* This is required because ICU expressions in `$localize` tagged messages may contain "dynamic"
* piece (e.g. interpolations or element markers). These markers need to be translated to
* placeholders in extracted translation files. So we must parse ICUs to identify them and separate
* them out so that the translation serializers can render them appropriately.
*
* An example of an ICU with interpolations:
*
* ```
* {VAR_PLURAL, plural, one {{INTERPOLATION}} other {{INTERPOLATION_1} post}}
* ```
*
* In this ICU, `INTERPOLATION` and `INTERPOLATION_1` are actually placeholders that will be
* replaced with dynamic content at runtime.
*
* Such placeholders are identifiable as text wrapped in curly braces, within an ICU case
* expression.
*
* To complicate matters, it is possible for ICUs to be nested indefinitely within each other. In
* such cases, the nested ICU expression appears enclosed in a set of curly braces in the same way
* as a placeholder. The nested ICU expressions can be differentiated from placeholders as they
* contain a comma `,`, which separates the ICU value from the ICU type.
*
* Furthermore, nested ICUs can have placeholders of their own, which need to be extracted.
*
* An example of a nested ICU containing its own placeholders:
*
* ```
* {VAR_SELECT_1, select,
* invoice {Invoice for {INTERPOLATION}}
* payment {{VAR_SELECT, select,
* processor {Payment gateway}
* other {{INTERPOLATION_1}}
* }}
* ```
*
* @param text Text to be broken.
* @returns an array of strings, where
* - even values are static strings (e.g. 0, 2, 4, etc)
* - odd values are placeholder names (e.g. 1, 3, 5, etc)
*/
export function extractIcuPlaceholders(text: string): string[] {
const state = new StateStack();
const pieces = new IcuPieces();
const braces = /[{}]/g;
let lastPos = 0;
let match: RegExpMatchArray | null;
while ((match = braces.exec(text))) {
if (match[0] == '{') {
state.enterBlock();
} else {
// We must have hit a `}`
state.leaveBlock();
}
if (state.getCurrent() === 'placeholder') {
const name = tryParsePlaceholder(text, braces.lastIndex);
if (name) {
// We found a placeholder so store it in the pieces;
// store the current static text (minus the opening curly brace);
// skip the closing brace and leave the placeholder block.
pieces.addText(text.substring(lastPos, braces.lastIndex - 1));
pieces.addPlaceholder(name);
braces.lastIndex += name.length + 1;
state.leaveBlock();
} else {
// This is not a placeholder, so it must be a nested ICU;
// store the current static text (including the opening curly brace).
pieces.addText(text.substring(lastPos, braces.lastIndex));
state.nestedIcu();
}
} else {
pieces.addText(text.substring(lastPos, braces.lastIndex));
}
lastPos = braces.lastIndex;
}
// Capture the last piece of text after the ICUs (if any).
pieces.addText(text.substring(lastPos));
return pieces.toArray();
}
/**
* A helper class to store the pieces ("static text" or "placeholder name") in an ICU.
*/
class IcuPieces {
private pieces: string[] = [''];
/**
* Add the given `text` to the current "static text" piece.
*
* Sequential calls to `addText()` will append to the current text piece.
*/
addText(text: string): void {
this.pieces[this.pieces.length - 1] += text;
}
/**
* Add the given placeholder `name` to the stored pieces.
*/
addPlaceholder(name: string): void {
this.pieces.push(name);
this.pieces.push('');
}
/**
* Return the stored pieces as an array of strings.
*
* Even values are static strings (e.g. 0, 2, 4, etc)
* Odd values are placeholder names (e.g. 1, 3, 5, etc)
*/
toArray(): string[] {
return this.pieces;
}
}
/**
* A helper class to track the current state of parsing the strings for ICU placeholders.
*
* State changes happen when we enter or leave a curly brace block.
* Since ICUs can be nested the state is stored as a stack.
*/
class StateStack {
private stack: ParserState[] = [];
/**
* Update the state upon entering a block.
*
* The new state is computed from the current state and added to the stack.
*/
enterBlock(): void {
const current = this.getCurrent();
switch (current) {
case 'icu':
this.stack.push('case');
break;
case 'case':
this.stack.push('placeholder');
break;
case 'placeholder':
this.stack.push('case');
break;
default:
this.stack.push('icu');
break;
}
}
/**
* Update the state upon leaving a block.
*
* The previous state is popped off the stack.
*/
leaveBlock(): ParserState {
return this.stack.pop();
}
/**
* Update the state upon arriving at a nested ICU.
*
* In this case, the current state of "placeholder" is incorrect, so this is popped off and the
* correct "icu" state is stored.
*/
nestedIcu(): void {
const current = this.stack.pop();
assert(current === 'placeholder', 'A nested ICU must replace a placeholder but got ' + current);
this.stack.push('icu');
}
/**
* Get the current (most recent) state from the stack.
*/
getCurrent() {
return this.stack[this.stack.length - 1];
}
}
type ParserState = 'icu' | 'case' | 'placeholder' | undefined;
/**
* Attempt to parse a simple placeholder name from a curly braced block.
*
* If the block contains a comma `,` then it cannot be a placeholder - and is probably a nest ICU
* instead.
*
* @param text the whole string that is being parsed.
* @param start the index of the character in the `text` string where this placeholder may start.
* @returns the placeholder name or `null` if it is not a placeholder.
*/
function tryParsePlaceholder(text: string, start: number): string | null {
for (let i = start; i < text.length; i++) {
if (text[i] === ',') {
break;
}
if (text[i] === '}') {
return text.substring(start, i);
}
}
return null;
}
function assert(test: boolean, message: string): void {
if (!test) {
throw new Error('Assertion failure: ' + message);
}
}
| {
"end_byte": 6582,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/icu_parsing.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/xliff2_translation_serializer.ts_0_8430 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AbsoluteFsPath,
getFileSystem,
PathManipulation,
} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
import {FormatOptions, validateOptions} from './format_options';
import {extractIcuPlaceholders} from './icu_parsing';
import {TranslationSerializer} from './translation_serializer';
import {consolidateMessages, hasLocation} from './utils';
import {XmlFile} from './xml_file';
/** This is the maximum number of characters that can appear in a legacy XLIFF 2.0 message id. */
const MAX_LEGACY_XLIFF_2_MESSAGE_LENGTH = 20;
/**
* A translation serializer that can write translations in XLIFF 2 format.
*
* https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
*
* @see Xliff2TranslationParser
* @publicApi used by CLI
*/
export class Xliff2TranslationSerializer implements TranslationSerializer {
private currentPlaceholderId = 0;
constructor(
private sourceLocale: string,
private basePath: AbsoluteFsPath,
private useLegacyIds: boolean,
private formatOptions: FormatOptions = {},
private fs: PathManipulation = getFileSystem(),
) {
validateOptions('Xliff1TranslationSerializer', [['xml:space', ['preserve']]], formatOptions);
}
serialize(messages: ɵParsedMessage[]): string {
const messageGroups = consolidateMessages(messages, (message) => this.getMessageId(message));
const xml = new XmlFile();
xml.startTag('xliff', {
'version': '2.0',
'xmlns': 'urn:oasis:names:tc:xliff:document:2.0',
'srcLang': this.sourceLocale,
});
// NOTE: the `original` property is set to the legacy `ng.template` value for backward
// compatibility.
// We could compute the file from the `message.location` property, but there could
// be multiple values for this in the collection of `messages`. In that case we would probably
// need to change the serializer to output a new `<file>` element for each collection of
// messages that come from a particular original file, and the translation file parsers may
// not
xml.startTag('file', {'id': 'ngi18n', 'original': 'ng.template', ...this.formatOptions});
for (const duplicateMessages of messageGroups) {
const message = duplicateMessages[0];
const id = this.getMessageId(message);
xml.startTag('unit', {id});
const messagesWithLocations = duplicateMessages.filter(hasLocation);
if (message.meaning || message.description || messagesWithLocations.length) {
xml.startTag('notes');
// Write all the locations
for (const {
location: {file, start, end},
} of messagesWithLocations) {
const endLineString =
end !== undefined && end.line !== start.line ? `,${end.line + 1}` : '';
this.serializeNote(
xml,
'location',
`${this.fs.relative(this.basePath, file)}:${start.line + 1}${endLineString}`,
);
}
if (message.description) {
this.serializeNote(xml, 'description', message.description);
}
if (message.meaning) {
this.serializeNote(xml, 'meaning', message.meaning);
}
xml.endTag('notes');
}
xml.startTag('segment');
xml.startTag('source', {}, {preserveWhitespace: true});
this.serializeMessage(xml, message);
xml.endTag('source', {preserveWhitespace: false});
xml.endTag('segment');
xml.endTag('unit');
}
xml.endTag('file');
xml.endTag('xliff');
return xml.toString();
}
private serializeMessage(xml: XmlFile, message: ɵParsedMessage): void {
this.currentPlaceholderId = 0;
const length = message.messageParts.length - 1;
for (let i = 0; i < length; i++) {
this.serializeTextPart(xml, message.messageParts[i]);
const name = message.placeholderNames[i];
const associatedMessageId =
message.associatedMessageIds && message.associatedMessageIds[name];
this.serializePlaceholder(xml, name, message.substitutionLocations, associatedMessageId);
}
this.serializeTextPart(xml, message.messageParts[length]);
}
private serializeTextPart(xml: XmlFile, text: string): void {
const pieces = extractIcuPlaceholders(text);
const length = pieces.length - 1;
for (let i = 0; i < length; i += 2) {
xml.text(pieces[i]);
this.serializePlaceholder(xml, pieces[i + 1], undefined, undefined);
}
xml.text(pieces[length]);
}
private serializePlaceholder(
xml: XmlFile,
placeholderName: string,
substitutionLocations: Record<string, ɵSourceLocation | undefined> | undefined,
associatedMessageId: string | undefined,
): void {
const text = substitutionLocations?.[placeholderName]?.text;
if (placeholderName.startsWith('START_')) {
// Replace the `START` with `CLOSE` and strip off any `_1` ids from the end.
const closingPlaceholderName = placeholderName
.replace(/^START/, 'CLOSE')
.replace(/_\d+$/, '');
const closingText = substitutionLocations?.[closingPlaceholderName]?.text;
const attrs: Record<string, string> = {
id: `${this.currentPlaceholderId++}`,
equivStart: placeholderName,
equivEnd: closingPlaceholderName,
};
const type = getTypeForPlaceholder(placeholderName);
if (type !== null) {
attrs['type'] = type;
}
if (text !== undefined) {
attrs['dispStart'] = text;
}
if (closingText !== undefined) {
attrs['dispEnd'] = closingText;
}
xml.startTag('pc', attrs);
} else if (placeholderName.startsWith('CLOSE_')) {
xml.endTag('pc');
} else {
const attrs: Record<string, string> = {
id: `${this.currentPlaceholderId++}`,
equiv: placeholderName,
};
const type = getTypeForPlaceholder(placeholderName);
if (type !== null) {
attrs['type'] = type;
}
if (text !== undefined) {
attrs['disp'] = text;
}
if (associatedMessageId !== undefined) {
attrs['subFlows'] = associatedMessageId;
}
xml.startTag('ph', attrs, {selfClosing: true});
}
}
private serializeNote(xml: XmlFile, name: string, value: string) {
xml.startTag('note', {category: name}, {preserveWhitespace: true});
xml.text(value);
xml.endTag('note', {preserveWhitespace: false});
}
/**
* Get the id for the given `message`.
*
* If there was a custom id provided, use that.
*
* If we have requested legacy message ids, then try to return the appropriate id
* from the list of legacy ids that were extracted.
*
* Otherwise return the canonical message id.
*
* An Xliff 2.0 legacy message id is a 64 bit number encoded as a decimal string, which will have
* at most 20 digits, since 2^65-1 = 36,893,488,147,419,103,231. This digest is based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
private getMessageId(message: ɵParsedMessage): string {
return (
message.customId ||
(this.useLegacyIds &&
message.legacyIds !== undefined &&
message.legacyIds.find(
(id) => id.length <= MAX_LEGACY_XLIFF_2_MESSAGE_LENGTH && !/[^0-9]/.test(id),
)) ||
message.id
);
}
}
/**
* Compute the value of the `type` attribute from the `placeholder` name.
*
* If the tag is not known but starts with `TAG_`, `START_TAG_` or `CLOSE_TAG_` then the type is
* `other`. Certain formatting tags (e.g. bold, italic, etc) have type `fmt`. Line-breaks, images
* and links are special cases.
*/
function getTypeForPlaceholder(placeholder: string): string | null {
const tag = placeholder.replace(/^(START_|CLOSE_)/, '').replace(/_\d+$/, '');
switch (tag) {
case 'BOLD_TEXT':
case 'EMPHASISED_TEXT':
case 'ITALIC_TEXT':
case 'LINE_BREAK':
case 'STRIKETHROUGH_TEXT':
case 'UNDERLINED_TEXT':
return 'fmt';
case 'TAG_IMG':
return 'image';
case 'LINK':
return 'link';
default:
return /^(START_|CLOSE_)/.test(placeholder) ? 'other' : null;
}
}
| {
"end_byte": 8430,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/xliff2_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/xmb_translation_serializer.ts_0_5015 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AbsoluteFsPath,
getFileSystem,
PathManipulation,
} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
import {extractIcuPlaceholders} from './icu_parsing';
import {TranslationSerializer} from './translation_serializer';
import {consolidateMessages} from './utils';
import {XmlFile} from './xml_file';
/**
* Defines the `handler` value on the serialized XMB, indicating that Angular
* generated the bundle. This is useful for analytics in Translation Console.
*
* NOTE: Keep in sync with packages/compiler/src/i18n/serializers/xmb.ts.
*/
const XMB_HANDLER = 'angular';
/**
* A translation serializer that can write files in XMB format.
*
* http://cldr.unicode.org/development/development-process/design-proposals/xmb
*
* @see XmbTranslationParser
* @publicApi used by CLI
*/
export class XmbTranslationSerializer implements TranslationSerializer {
constructor(
private basePath: AbsoluteFsPath,
private useLegacyIds: boolean,
private fs: PathManipulation = getFileSystem(),
) {}
serialize(messages: ɵParsedMessage[]): string {
const messageGroups = consolidateMessages(messages, (message) => this.getMessageId(message));
const xml = new XmlFile();
xml.rawText(
`<!DOCTYPE messagebundle [\n` +
`<!ELEMENT messagebundle (msg)*>\n` +
`<!ATTLIST messagebundle class CDATA #IMPLIED>\n` +
`\n` +
`<!ELEMENT msg (#PCDATA|ph|source)*>\n` +
`<!ATTLIST msg id CDATA #IMPLIED>\n` +
`<!ATTLIST msg seq CDATA #IMPLIED>\n` +
`<!ATTLIST msg name CDATA #IMPLIED>\n` +
`<!ATTLIST msg desc CDATA #IMPLIED>\n` +
`<!ATTLIST msg meaning CDATA #IMPLIED>\n` +
`<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n` +
`<!ATTLIST msg xml:space (default|preserve) "default">\n` +
`<!ATTLIST msg is_hidden CDATA #IMPLIED>\n` +
`\n` +
`<!ELEMENT source (#PCDATA)>\n` +
`\n` +
`<!ELEMENT ph (#PCDATA|ex)*>\n` +
`<!ATTLIST ph name CDATA #REQUIRED>\n` +
`\n` +
`<!ELEMENT ex (#PCDATA)>\n` +
`]>\n`,
);
xml.startTag('messagebundle', {
'handler': XMB_HANDLER,
});
for (const duplicateMessages of messageGroups) {
const message = duplicateMessages[0];
const id = this.getMessageId(message);
xml.startTag(
'msg',
{id, desc: message.description, meaning: message.meaning},
{preserveWhitespace: true},
);
if (message.location) {
this.serializeLocation(xml, message.location);
}
this.serializeMessage(xml, message);
xml.endTag('msg', {preserveWhitespace: false});
}
xml.endTag('messagebundle');
return xml.toString();
}
private serializeLocation(xml: XmlFile, location: ɵSourceLocation): void {
xml.startTag('source');
const endLineString =
location.end !== undefined && location.end.line !== location.start.line
? `,${location.end.line + 1}`
: '';
xml.text(
`${this.fs.relative(this.basePath, location.file)}:${location.start.line}${endLineString}`,
);
xml.endTag('source');
}
private serializeMessage(xml: XmlFile, message: ɵParsedMessage): void {
const length = message.messageParts.length - 1;
for (let i = 0; i < length; i++) {
this.serializeTextPart(xml, message.messageParts[i]);
xml.startTag('ph', {name: message.placeholderNames[i]}, {selfClosing: true});
}
this.serializeTextPart(xml, message.messageParts[length]);
}
private serializeTextPart(xml: XmlFile, text: string): void {
const pieces = extractIcuPlaceholders(text);
const length = pieces.length - 1;
for (let i = 0; i < length; i += 2) {
xml.text(pieces[i]);
xml.startTag('ph', {name: pieces[i + 1]}, {selfClosing: true});
}
xml.text(pieces[length]);
}
/**
* Get the id for the given `message`.
*
* If there was a custom id provided, use that.
*
* If we have requested legacy message ids, then try to return the appropriate id
* from the list of legacy ids that were extracted.
*
* Otherwise return the canonical message id.
*
* An XMB legacy message id is a 64 bit number encoded as a decimal string, which will have
* at most 20 digits, since 2^65-1 = 36,893,488,147,419,103,231. This digest is based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
private getMessageId(message: ɵParsedMessage): string {
return (
message.customId ||
(this.useLegacyIds &&
message.legacyIds !== undefined &&
message.legacyIds.find((id) => id.length <= 20 && !/[^0-9]/.test(id))) ||
message.id
);
}
}
| {
"end_byte": 5015,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/xmb_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/utils.ts_0_2669 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MessageId, ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
/**
* Consolidate messages into groups that have the same id.
*
* Messages with the same id are grouped together so that we can quickly deduplicate messages when
* rendering into translation files.
*
* To ensure that messages are rendered in a deterministic order:
* - the messages within a group are sorted by location (file path, then start position)
* - the groups are sorted by the location of the first message in the group
*
* @param messages the messages to consolidate.
* @param getMessageId a function that will compute the message id of a message.
* @returns an array of message groups, where each group is an array of messages that have the same
* id.
*/
export function consolidateMessages(
messages: ɵParsedMessage[],
getMessageId: (message: ɵParsedMessage) => string,
): ɵParsedMessage[][] {
const messageGroups = new Map<MessageId, ɵParsedMessage[]>();
for (const message of messages) {
const id = getMessageId(message);
if (!messageGroups.has(id)) {
messageGroups.set(id, [message]);
} else {
messageGroups.get(id)!.push(message);
}
}
// Here we sort the messages within a group into location order.
// Note that `Array.sort()` will mutate the array in-place.
for (const messages of messageGroups.values()) {
messages.sort(compareLocations);
}
// Now we sort the groups by location of the first message in the group.
return Array.from(messageGroups.values()).sort((a1, a2) => compareLocations(a1[0], a2[0]));
}
/**
* Does the given message have a location property?
*/
export function hasLocation(
message: ɵParsedMessage,
): message is ɵParsedMessage & {location: ɵSourceLocation} {
return message.location !== undefined;
}
export function compareLocations(
{location: location1}: ɵParsedMessage,
{location: location2}: ɵParsedMessage,
): number {
if (location1 === location2) {
return 0;
}
if (location1 === undefined) {
return -1;
}
if (location2 === undefined) {
return 1;
}
if (location1.file !== location2.file) {
return location1.file < location2.file ? -1 : 1;
}
if (location1.start.line !== location2.start.line) {
return location1.start.line < location2.start.line ? -1 : 1;
}
if (location1.start.column !== location2.start.column) {
return location1.start.column < location2.start.column ? -1 : 1;
}
return 0;
}
| {
"end_byte": 2669,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/utils.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/format_options.ts_0_1742 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export type FormatOptions = Record<string, string>;
export type ValidOption = [key: string, values: string[]];
export type ValidOptions = ValidOption[];
/**
* Check that the given `options` are allowed based on the given `validOptions`.
* @param name The name of the serializer that is receiving the options.
* @param validOptions An array of valid options and their allowed values.
* @param options The options to be validated.
*/
export function validateOptions(name: string, validOptions: ValidOptions, options: FormatOptions) {
const validOptionsMap = new Map<ValidOption[0], ValidOption[1]>(validOptions);
for (const option in options) {
if (!validOptionsMap.has(option)) {
throw new Error(
`Invalid format option for ${name}: "${option}".\n` +
`Allowed options are ${JSON.stringify(Array.from(validOptionsMap.keys()))}.`,
);
}
const validOptionValues = validOptionsMap.get(option)!;
const optionValue = options[option];
if (!validOptionValues.includes(optionValue)) {
throw new Error(
`Invalid format option value for ${name}: "${option}".\n` +
`Allowed option values are ${JSON.stringify(
validOptionValues,
)} but received "${optionValue}".`,
);
}
}
}
/**
* Parse the given `optionString` into a collection of `FormatOptions`.
* @param optionString The string to parse.
*/
export function parseFormatOptions(optionString: string = '{}'): FormatOptions {
return JSON.parse(optionString) as FormatOptions;
}
| {
"end_byte": 1742,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/format_options.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/xliff1_translation_serializer.ts_0_7526 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AbsoluteFsPath,
getFileSystem,
PathManipulation,
} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
import {FormatOptions, validateOptions} from './format_options';
import {extractIcuPlaceholders} from './icu_parsing';
import {TranslationSerializer} from './translation_serializer';
import {consolidateMessages, hasLocation} from './utils';
import {XmlFile} from './xml_file';
/** This is the number of characters that a legacy Xliff 1.2 message id has. */
const LEGACY_XLIFF_MESSAGE_LENGTH = 40;
/**
* A translation serializer that can write XLIFF 1.2 formatted files.
*
* https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
* https://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
*
* @see Xliff1TranslationParser
* @publicApi used by CLI
*/
export class Xliff1TranslationSerializer implements TranslationSerializer {
constructor(
private sourceLocale: string,
private basePath: AbsoluteFsPath,
private useLegacyIds: boolean,
private formatOptions: FormatOptions = {},
private fs: PathManipulation = getFileSystem(),
) {
validateOptions('Xliff1TranslationSerializer', [['xml:space', ['preserve']]], formatOptions);
}
serialize(messages: ɵParsedMessage[]): string {
const messageGroups = consolidateMessages(messages, (message) => this.getMessageId(message));
const xml = new XmlFile();
xml.startTag('xliff', {'version': '1.2', 'xmlns': 'urn:oasis:names:tc:xliff:document:1.2'});
// NOTE: the `original` property is set to the legacy `ng2.template` value for backward
// compatibility.
// We could compute the file from the `message.location` property, but there could
// be multiple values for this in the collection of `messages`. In that case we would probably
// need to change the serializer to output a new `<file>` element for each collection of
// messages that come from a particular original file, and the translation file parsers may not
// be able to cope with this.
xml.startTag('file', {
'source-language': this.sourceLocale,
'datatype': 'plaintext',
'original': 'ng2.template',
...this.formatOptions,
});
xml.startTag('body');
for (const duplicateMessages of messageGroups) {
const message = duplicateMessages[0];
const id = this.getMessageId(message);
xml.startTag('trans-unit', {id, datatype: 'html'});
xml.startTag('source', {}, {preserveWhitespace: true});
this.serializeMessage(xml, message);
xml.endTag('source', {preserveWhitespace: false});
// Write all the locations
for (const {location} of duplicateMessages.filter(hasLocation)) {
this.serializeLocation(xml, location);
}
if (message.description) {
this.serializeNote(xml, 'description', message.description);
}
if (message.meaning) {
this.serializeNote(xml, 'meaning', message.meaning);
}
xml.endTag('trans-unit');
}
xml.endTag('body');
xml.endTag('file');
xml.endTag('xliff');
return xml.toString();
}
private serializeMessage(xml: XmlFile, message: ɵParsedMessage): void {
const length = message.messageParts.length - 1;
for (let i = 0; i < length; i++) {
this.serializeTextPart(xml, message.messageParts[i]);
const name = message.placeholderNames[i];
const location = message.substitutionLocations?.[name];
const associatedMessageId =
message.associatedMessageIds && message.associatedMessageIds[name];
this.serializePlaceholder(xml, name, location?.text, associatedMessageId);
}
this.serializeTextPart(xml, message.messageParts[length]);
}
private serializeTextPart(xml: XmlFile, text: string): void {
const pieces = extractIcuPlaceholders(text);
const length = pieces.length - 1;
for (let i = 0; i < length; i += 2) {
xml.text(pieces[i]);
this.serializePlaceholder(xml, pieces[i + 1], undefined, undefined);
}
xml.text(pieces[length]);
}
private serializePlaceholder(
xml: XmlFile,
id: string,
text: string | undefined,
associatedId: string | undefined,
): void {
const attrs: Record<string, string> = {id};
const ctype = getCtypeForPlaceholder(id);
if (ctype !== null) {
attrs['ctype'] = ctype;
}
if (text !== undefined) {
attrs['equiv-text'] = text;
}
if (associatedId !== undefined) {
attrs['xid'] = associatedId;
}
xml.startTag('x', attrs, {selfClosing: true});
}
private serializeNote(xml: XmlFile, name: string, value: string): void {
xml.startTag('note', {priority: '1', from: name}, {preserveWhitespace: true});
xml.text(value);
xml.endTag('note', {preserveWhitespace: false});
}
private serializeLocation(xml: XmlFile, location: ɵSourceLocation): void {
xml.startTag('context-group', {purpose: 'location'});
this.renderContext(xml, 'sourcefile', this.fs.relative(this.basePath, location.file));
const endLineString =
location.end !== undefined && location.end.line !== location.start.line
? `,${location.end.line + 1}`
: '';
this.renderContext(xml, 'linenumber', `${location.start.line + 1}${endLineString}`);
xml.endTag('context-group');
}
private renderContext(xml: XmlFile, type: string, value: string): void {
xml.startTag('context', {'context-type': type}, {preserveWhitespace: true});
xml.text(value);
xml.endTag('context', {preserveWhitespace: false});
}
/**
* Get the id for the given `message`.
*
* If there was a custom id provided, use that.
*
* If we have requested legacy message ids, then try to return the appropriate id
* from the list of legacy ids that were extracted.
*
* Otherwise return the canonical message id.
*
* An Xliff 1.2 legacy message id is a hex encoded SHA-1 string, which is 40 characters long. See
* https://csrc.nist.gov/csrc/media/publications/fips/180/4/final/documents/fips180-4-draft-aug2014.pdf
*/
private getMessageId(message: ɵParsedMessage): string {
return (
message.customId ||
(this.useLegacyIds &&
message.legacyIds !== undefined &&
message.legacyIds.find((id) => id.length === LEGACY_XLIFF_MESSAGE_LENGTH)) ||
message.id
);
}
}
/**
* Compute the value of the `ctype` attribute from the `placeholder` name.
*
* The placeholder can take the following forms:
*
* - `START_BOLD_TEXT`/`END_BOLD_TEXT`
* - `TAG_<ELEMENT_NAME>`
* - `START_TAG_<ELEMENT_NAME>`
* - `CLOSE_TAG_<ELEMENT_NAME>`
*
* In these cases the element name of the tag is extracted from the placeholder name and returned as
* `x-<element_name>`.
*
* Line breaks and images are special cases.
*/
function getCtypeForPlaceholder(placeholder: string): string | null {
const tag = placeholder.replace(/^(START_|CLOSE_)/, '');
switch (tag) {
case 'LINE_BREAK':
return 'lb';
case 'TAG_IMG':
return 'image';
default:
const element = tag.startsWith('TAG_')
? tag.replace(/^TAG_(.+)/, (_, tagName: string) => tagName.toLowerCase())
: TAG_MAP[tag];
if (element === undefined) {
return null;
}
return `x-${element}`;
}
}
cons | {
"end_byte": 7526,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/xliff1_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/xliff1_translation_serializer.ts_7528_8278 | TAG_MAP: Record<string, string> = {
'LINK': 'a',
'BOLD_TEXT': 'b',
'EMPHASISED_TEXT': 'em',
'HEADING_LEVEL1': 'h1',
'HEADING_LEVEL2': 'h2',
'HEADING_LEVEL3': 'h3',
'HEADING_LEVEL4': 'h4',
'HEADING_LEVEL5': 'h5',
'HEADING_LEVEL6': 'h6',
'HORIZONTAL_RULE': 'hr',
'ITALIC_TEXT': 'i',
'LIST_ITEM': 'li',
'MEDIA_LINK': 'link',
'ORDERED_LIST': 'ol',
'PARAGRAPH': 'p',
'QUOTATION': 'q',
'STRIKETHROUGH_TEXT': 's',
'SMALL_TEXT': 'small',
'SUBSTRIPT': 'sub',
'SUPERSCRIPT': 'sup',
'TABLE_BODY': 'tbody',
'TABLE_CELL': 'td',
'TABLE_FOOTER': 'tfoot',
'TABLE_HEADER_CELL': 'th',
'TABLE_HEADER': 'thead',
'TABLE_ROW': 'tr',
'MONOSPACED_TEXT': 'tt',
'UNDERLINED_TEXT': 'u',
'UNORDERED_LIST': 'ul',
};
| {
"end_byte": 8278,
"start_byte": 7528,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/xliff1_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/arb_translation_serializer.ts_0_3370 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AbsoluteFsPath, PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize';
import {TranslationSerializer} from './translation_serializer';
import {consolidateMessages, hasLocation} from './utils';
/**
* A translation serializer that can render JSON formatted as an Application Resource Bundle (ARB).
*
* See https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification
*
* ```
* {
* "@@locale": "en-US",
* "message-id": "Target message string",
* "@message-id": {
* "type": "text",
* "description": "Some description text",
* "x-locations": [
* {
* "start": {"line": 23, "column": 145},
* "end": {"line": 24, "column": 53},
* "file": "some/file.ts"
* },
* ...
* ]
* },
* ...
* }
* ```
*/
export class ArbTranslationSerializer implements TranslationSerializer {
constructor(
private sourceLocale: string,
private basePath: AbsoluteFsPath,
private fs: PathManipulation,
) {}
serialize(messages: ɵParsedMessage[]): string {
const messageGroups = consolidateMessages(messages, (message) => getMessageId(message));
let output = `{\n "@@locale": ${JSON.stringify(this.sourceLocale)}`;
for (const duplicateMessages of messageGroups) {
const message = duplicateMessages[0];
const id = getMessageId(message);
output += this.serializeMessage(id, message);
output += this.serializeMeta(
id,
message.description,
message.meaning,
duplicateMessages.filter(hasLocation).map((m) => m.location),
);
}
output += '\n}';
return output;
}
private serializeMessage(id: string, message: ɵParsedMessage): string {
return `,\n ${JSON.stringify(id)}: ${JSON.stringify(message.text)}`;
}
private serializeMeta(
id: string,
description: string | undefined,
meaning: string | undefined,
locations: ɵSourceLocation[],
): string {
const meta: string[] = [];
if (description) {
meta.push(`\n "description": ${JSON.stringify(description)}`);
}
if (meaning) {
meta.push(`\n "x-meaning": ${JSON.stringify(meaning)}`);
}
if (locations.length > 0) {
let locationStr = `\n "x-locations": [`;
for (let i = 0; i < locations.length; i++) {
locationStr += (i > 0 ? ',\n' : '\n') + this.serializeLocation(locations[i]);
}
locationStr += '\n ]';
meta.push(locationStr);
}
return meta.length > 0 ? `,\n ${JSON.stringify('@' + id)}: {${meta.join(',')}\n }` : '';
}
private serializeLocation({file, start, end}: ɵSourceLocation): string {
return [
` {`,
` "file": ${JSON.stringify(this.fs.relative(this.basePath, file))},`,
` "start": { "line": "${start.line}", "column": "${start.column}" },`,
` "end": { "line": "${end.line}", "column": "${end.column}" }`,
` }`,
].join('\n');
}
}
function getMessageId(message: ɵParsedMessage): string {
return message.customId || message.id;
}
| {
"end_byte": 3370,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/arb_translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/translation_serializer.ts_0_661 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵParsedMessage} from '@angular/localize';
/**
* Implement this interface to provide a class that can render messages into a translation file.
*/
export interface TranslationSerializer {
/**
* Serialize the contents of a translation file containing the given `messages`.
*
* @param messages The messages to render to the file.
* @returns The contents of the serialized file.
*/
serialize(messages: ɵParsedMessage[]): string;
}
| {
"end_byte": 661,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/translation_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/legacy_message_id_migration_serializer.ts_0_1780 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵParsedMessage as ParsedMessage} from '@angular/localize';
import {Diagnostics} from '../../diagnostics';
import {TranslationSerializer} from './translation_serializer';
/**
* A translation serializer that generates the mapping file for the legacy message ID migration.
* The file is used by the `localize-migrate` script to migrate existing translation files from
* the legacy message IDs to the canonical ones.
*/
export class LegacyMessageIdMigrationSerializer implements TranslationSerializer {
constructor(private _diagnostics: Diagnostics) {}
serialize(messages: ParsedMessage[]): string {
let hasMessages = false;
const mapping = messages.reduce(
(output, message) => {
if (shouldMigrate(message)) {
for (const legacyId of message.legacyIds!) {
if (output.hasOwnProperty(legacyId)) {
this._diagnostics.warn(`Detected duplicate legacy ID ${legacyId}.`);
}
output[legacyId] = message.id;
hasMessages = true;
}
}
return output;
},
{} as Record<string, string>,
);
if (!hasMessages) {
this._diagnostics.warn(
'Could not find any legacy message IDs in source files while generating ' +
'the legacy message migration file.',
);
}
return JSON.stringify(mapping, null, 2);
}
}
/** Returns true if a message needs to be migrated. */
function shouldMigrate(message: ParsedMessage): boolean {
return !message.customId && !!message.legacyIds && message.legacyIds.length > 0;
}
| {
"end_byte": 1780,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/legacy_message_id_migration_serializer.ts"
} |
angular/packages/localize/tools/src/extract/translation_files/xml_file.ts_0_2497 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
interface Options {
selfClosing?: boolean;
preserveWhitespace?: boolean;
}
export class XmlFile {
private output = '<?xml version="1.0" encoding="UTF-8" ?>\n';
private indent = '';
private elements: string[] = [];
private preservingWhitespace = false;
toString() {
return this.output;
}
startTag(
name: string,
attributes: Record<string, string | undefined> = {},
{selfClosing = false, preserveWhitespace}: Options = {},
): this {
if (!this.preservingWhitespace) {
this.output += this.indent;
}
this.output += `<${name}`;
for (const [attrName, attrValue] of Object.entries(attributes)) {
if (attrValue) {
this.output += ` ${attrName}="${escapeXml(attrValue)}"`;
}
}
if (selfClosing) {
this.output += '/>';
} else {
this.output += '>';
this.elements.push(name);
this.incIndent();
}
if (preserveWhitespace !== undefined) {
this.preservingWhitespace = preserveWhitespace;
}
if (!this.preservingWhitespace) {
this.output += `\n`;
}
return this;
}
endTag(name: string, {preserveWhitespace}: Options = {}): this {
const expectedTag = this.elements.pop();
if (expectedTag !== name) {
throw new Error(`Unexpected closing tag: "${name}", expected: "${expectedTag}"`);
}
this.decIndent();
if (!this.preservingWhitespace) {
this.output += this.indent;
}
this.output += `</${name}>`;
if (preserveWhitespace !== undefined) {
this.preservingWhitespace = preserveWhitespace;
}
if (!this.preservingWhitespace) {
this.output += `\n`;
}
return this;
}
text(str: string): this {
this.output += escapeXml(str);
return this;
}
rawText(str: string): this {
this.output += str;
return this;
}
private incIndent() {
this.indent = this.indent + ' ';
}
private decIndent() {
this.indent = this.indent.slice(0, -2);
}
}
const _ESCAPED_CHARS: [RegExp, string][] = [
[/&/g, '&'],
[/"/g, '"'],
[/'/g, '''],
[/</g, '<'],
[/>/g, '>'],
];
function escapeXml(text: string): string {
return _ESCAPED_CHARS.reduce(
(text: string, entry: [RegExp, string]) => text.replace(entry[0], entry[1]),
text,
);
}
| {
"end_byte": 2497,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/translation_files/xml_file.ts"
} |
angular/packages/localize/tools/src/extract/source_files/es2015_extract_plugin.ts_0_1615 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵparseMessage} from '@angular/localize';
import {NodePath, PluginObj, types as t} from '@babel/core';
import {
getLocation,
isGlobalIdentifier,
isNamedIdentifier,
unwrapExpressionsFromTemplateLiteral,
unwrapMessagePartsFromTemplateLiteral,
} from '../../source_file_utils';
export function makeEs2015ExtractPlugin(
fs: PathManipulation,
messages: ɵParsedMessage[],
localizeName = '$localize',
): PluginObj {
return {
visitor: {
TaggedTemplateExpression(path: NodePath<t.TaggedTemplateExpression>) {
const tag = path.get('tag');
if (isNamedIdentifier(tag, localizeName) && isGlobalIdentifier(tag)) {
const quasiPath = path.get('quasi');
const [messageParts, messagePartLocations] = unwrapMessagePartsFromTemplateLiteral(
quasiPath.get('quasis'),
fs,
);
const [expressions, expressionLocations] = unwrapExpressionsFromTemplateLiteral(
quasiPath,
fs,
);
const location = getLocation(fs, quasiPath);
const message = ɵparseMessage(
messageParts,
expressions,
location,
messagePartLocations,
expressionLocations,
);
messages.push(message);
}
},
},
};
}
| {
"end_byte": 1615,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/source_files/es2015_extract_plugin.ts"
} |
angular/packages/localize/tools/src/extract/source_files/es5_extract_plugin.ts_0_2194 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵparseMessage} from '@angular/localize';
import {NodePath, PluginObj, types as t} from '@babel/core';
import {
buildCodeFrameError,
getLocation,
isBabelParseError,
isGlobalIdentifier,
isNamedIdentifier,
unwrapMessagePartsFromLocalizeCall,
unwrapSubstitutionsFromLocalizeCall,
} from '../../source_file_utils';
export function makeEs5ExtractPlugin(
fs: PathManipulation,
messages: ɵParsedMessage[],
localizeName = '$localize',
): PluginObj {
return {
visitor: {
CallExpression(callPath: NodePath<t.CallExpression>, state) {
try {
const calleePath = callPath.get('callee');
if (isNamedIdentifier(calleePath, localizeName) && isGlobalIdentifier(calleePath)) {
const [messageParts, messagePartLocations] = unwrapMessagePartsFromLocalizeCall(
callPath,
fs,
);
const [expressions, expressionLocations] = unwrapSubstitutionsFromLocalizeCall(
callPath,
fs,
);
const [messagePartsArg, expressionsArg] = callPath.get('arguments');
const location = getLocation(fs, messagePartsArg, expressionsArg);
const message = ɵparseMessage(
messageParts,
expressions,
location,
messagePartLocations,
expressionLocations,
);
messages.push(message);
}
} catch (e) {
if (isBabelParseError(e)) {
// If we get a BabelParseError here then something went wrong with Babel itself
// since there must be something wrong with the structure of the AST generated
// by Babel parsing a TaggedTemplateExpression.
throw buildCodeFrameError(fs, callPath, state.file, e);
} else {
throw e;
}
}
},
},
};
}
| {
"end_byte": 2194,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/tools/src/extract/source_files/es5_extract_plugin.ts"
} |
angular/packages/localize/test/translate_spec.ts_0_3527 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Ensure that `$localize` is loaded to the global scope.
import '@angular/localize/init';
import {clearTranslations, loadTranslations} from '../localize';
import {computeMsgId, MessageId, TargetMessage} from '../src/utils';
describe('$localize tag with translations', () => {
describe('identities', () => {
beforeEach(() => {
loadTranslations(
computeIds({
'abc': 'abc',
'abc{$PH}': 'abc{$PH}',
'abc{$PH}def': 'abc{$PH}def',
'abc{$PH}def{$PH_1}': 'abc{$PH}def{$PH_1}',
'Hello, {$PH}!': 'Hello, {$PH}!',
}),
);
});
afterEach(() => {
clearTranslations();
});
it('should render template literals as-is', () => {
expect($localize`abc`).toEqual('abc');
expect($localize`abc${1 + 2 + 3}`).toEqual('abc6');
expect($localize`abc${1 + 2 + 3}def`).toEqual('abc6def');
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6}`).toEqual('abc6def15');
const getName = () => 'World';
expect($localize`Hello, ${getName()}!`).toEqual('Hello, World!');
});
});
describe('to upper-case messageParts', () => {
beforeEach(() => {
loadTranslations(
computeIds({
'abc': 'ABC',
'abc{$PH}': 'ABC{$PH}',
'abc{$PH}def': 'ABC{$PH}DEF',
'abc{$PH}def{$PH_1}': 'ABC{$PH}DEF{$PH_1}',
'Hello, {$PH}!': 'HELLO, {$PH}!',
}),
);
});
afterEach(() => {
clearTranslations();
});
it('should render template literals with messages upper-cased', () => {
expect($localize`abc`).toEqual('ABC');
expect($localize`abc${1 + 2 + 3}`).toEqual('ABC6');
expect($localize`abc${1 + 2 + 3}def`).toEqual('ABC6DEF');
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6}`).toEqual('ABC6DEF15');
const getName = () => 'World';
expect($localize`Hello, ${getName()}!`).toEqual('HELLO, World!');
});
});
describe('to reverse expressions', () => {
beforeEach(() => {
loadTranslations(
computeIds({
'abc{$PH}def{$PH_1} - Hello, {$PH_2}!': 'abc{$PH_2}def{$PH_1} - Hello, {$PH}!',
}),
);
});
afterEach(() => {
clearTranslations();
});
it('should render template literals with expressions reversed', () => {
const getName = () => 'World';
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`).toEqual(
'abcWorlddef15 - Hello, 6!',
);
});
});
describe('to remove expressions', () => {
beforeEach(() => {
loadTranslations(
computeIds({
'abc{$PH}def{$PH_1} - Hello, {$PH_2}!': 'abc{$PH} - Hello, {$PH_2}!',
}),
);
});
afterEach(() => {
clearTranslations();
});
it('should render template literals with expressions removed', () => {
const getName = () => 'World';
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`).toEqual(
'abc6 - Hello, World!',
);
});
});
});
function computeIds(
translations: Record<MessageId, TargetMessage>,
): Record<MessageId, TargetMessage> {
const processed: Record<MessageId, TargetMessage> = {};
Object.keys(translations).forEach(
(key) => (processed[computeMsgId(key, '')] = translations[key]),
);
return processed;
}
| {
"end_byte": 3527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/test/translate_spec.ts"
} |
angular/packages/localize/test/BUILD.bazel_0_698 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/localize/index.mjs",
deps = ["//packages/localize"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*_spec.ts"],
),
deps = [
"//packages:types",
"//packages/localize",
"//packages/localize/init",
"//packages/localize/src/utils",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 698,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/test/BUILD.bazel"
} |
angular/packages/localize/schematics/BUILD.bazel_0_435 | load("//tools:defaults.bzl", "pkg_npm")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "package_assets",
srcs = [
"collection.json",
"package.json",
],
visibility = ["//packages/localize:__subpackages__"],
)
pkg_npm(
name = "npm_package",
srcs = [":package_assets"],
validate = False,
deps = [
"//packages/localize/schematics/ng-add:assets",
],
)
| {
"end_byte": 435,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/BUILD.bazel"
} |
angular/packages/localize/schematics/ng-add/README.md_0_479 | # @angular/localize schematic for `ng add`
This schematic will be executed when an Angular CLI user runs `ng add @angular/localize`.
It will search their `angular.json` file, and add `types: ["@angular/localize"]` in the TypeScript
configuration files of the project.
If the user specifies that they want to use `$localize` at runtime then the dependency will be
added to the `dependencies` section of `package.json` rather than in the `devDependencies` which
is the default.
| {
"end_byte": 479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/ng-add/README.md"
} |
angular/packages/localize/schematics/ng-add/BUILD.bazel_0_1234 | load("//tools:defaults.bzl", "esbuild", "jasmine_node_test", "ts_config", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_config(
name = "tsconfig",
src = "tsconfig-build.json",
deps = ["//packages:tsconfig-build.json"],
)
ts_library(
name = "ng-add",
srcs = [
"index.ts",
"schema.d.ts",
],
tsconfig = ":tsconfig",
deps = [
"@npm//@angular-devkit/schematics",
"@npm//@schematics/angular",
],
)
esbuild(
name = "ng_add_bundle",
entry_point = ":index.ts",
external = [
"@angular-devkit/*",
"@schematics/*",
],
format = "cjs",
platform = "node",
deps = [":ng-add"],
)
filegroup(
name = "assets",
srcs = [
"schema.json",
":ng_add_bundle",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = [
"index_spec.ts",
],
data = [
"//packages/localize/schematics:package_assets",
],
deps = [
"@npm//@angular-devkit/schematics",
"@npm//@bazel/runfiles",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
deps = [
":assets",
":ng-add",
":test_lib",
],
)
| {
"end_byte": 1234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/ng-add/BUILD.bazel"
} |
angular/packages/localize/schematics/ng-add/schema.d.ts_0_514 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface Schema {
/**
* The name of the project.
*/
project?: string;
/**
* Will this project use $localize at runtime?
*
* If true then the dependency is included in the `dependencies` section of package.json, rather
* than `devDependencies`.
*/
useAtRuntime?: boolean;
}
| {
"end_byte": 514,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/ng-add/schema.d.ts"
} |
angular/packages/localize/schematics/ng-add/index.ts_0_5315 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*
* @fileoverview Schematics for `ng add @angular/localize` schematic.
*/
import {chain, noop, Rule, SchematicsException, Tree} from '@angular-devkit/schematics';
import {
AngularBuilder,
addDependency,
readWorkspace,
updateWorkspace,
} from '@schematics/angular/utility';
import {removePackageJsonDependency} from '@schematics/angular/utility/dependencies';
import {JSONFile, JSONPath} from '@schematics/angular/utility/json-file';
import {Schema} from './schema';
const localizeType = `@angular/localize`;
const localizePolyfill = '@angular/localize/init';
const localizeTripleSlashType = `/// <reference types="@angular/localize" />`;
function addPolyfillToConfig(projectName: string): Rule {
return updateWorkspace((workspace) => {
const project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Invalid project name '${projectName}'.`);
}
const isLocalizePolyfill = (path: string) => path.startsWith('@angular/localize');
for (const target of project.targets.values()) {
switch (target.builder) {
case AngularBuilder.Karma:
case AngularBuilder.Server:
case AngularBuilder.Browser:
case AngularBuilder.BrowserEsbuild:
case AngularBuilder.Application:
case AngularBuilder.BuildApplication:
target.options ??= {};
const value = target.options['polyfills'];
if (typeof value === 'string') {
if (!isLocalizePolyfill(value)) {
target.options['polyfills'] = [value, localizePolyfill];
}
} else if (Array.isArray(value)) {
if (!(value as string[]).some(isLocalizePolyfill)) {
value.push(localizePolyfill);
}
} else {
target.options['polyfills'] = [localizePolyfill];
}
break;
}
}
});
}
function addTypeScriptConfigTypes(projectName: string): Rule {
return async (host: Tree) => {
const workspace = await readWorkspace(host);
const project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Invalid project name '${projectName}'.`);
}
// We add the root workspace tsconfig for better IDE support.
const tsConfigFiles = new Set<string>();
for (const target of project.targets.values()) {
switch (target.builder) {
case AngularBuilder.Karma:
case AngularBuilder.Server:
case AngularBuilder.BrowserEsbuild:
case AngularBuilder.Browser:
case AngularBuilder.Application:
case AngularBuilder.BuildApplication:
const value = target.options?.['tsConfig'];
if (typeof value === 'string') {
tsConfigFiles.add(value);
}
break;
}
if (
target.builder === AngularBuilder.Browser ||
target.builder === AngularBuilder.BrowserEsbuild
) {
const value = target.options?.['main'];
if (typeof value === 'string') {
addTripleSlashType(host, value);
}
} else if (target.builder === AngularBuilder.Application) {
const value = target.options?.['browser'];
if (typeof value === 'string') {
addTripleSlashType(host, value);
}
}
}
const typesJsonPath: JSONPath = ['compilerOptions', 'types'];
for (const path of tsConfigFiles) {
if (!host.exists(path)) {
continue;
}
const json = new JSONFile(host, path);
const types = json.get(typesJsonPath) ?? [];
if (!Array.isArray(types)) {
throw new SchematicsException(
`TypeScript configuration file '${path}' has an invalid 'types' property. It must be an array.`,
);
}
const hasLocalizeType = types.some(
(t) => t === localizeType || t === '@angular/localize/init',
);
if (hasLocalizeType) {
// Skip has already localize type.
continue;
}
json.modify(typesJsonPath, [...types, localizeType]);
}
};
}
function addTripleSlashType(host: Tree, path: string): void {
const content = host.readText(path);
if (!content.includes(localizeTripleSlashType)) {
host.overwrite(path, localizeTripleSlashType + '\n\n' + content);
}
}
function moveToDependencies(host: Tree): Rule | void {
if (!host.exists('package.json')) {
return;
}
// Remove the previous dependency and add in a new one under the desired type.
removePackageJsonDependency(host, '@angular/localize');
return addDependency('@angular/localize', `~0.0.0-PLACEHOLDER`);
}
export default function (options: Schema): Rule {
const projectName = options.project;
if (!projectName) {
throw new SchematicsException('Option "project" is required.');
}
return chain([
addTypeScriptConfigTypes(projectName),
addPolyfillToConfig(projectName),
// If `$localize` will be used at runtime then must install `@angular/localize`
// into `dependencies`, rather than the default of `devDependencies`.
options.useAtRuntime ? moveToDependencies : noop(),
]);
}
| {
"end_byte": 5315,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/ng-add/index.ts"
} |
angular/packages/localize/schematics/ng-add/index_spec.ts_0_7927 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EmptyTree, Tree} from '@angular-devkit/schematics';
import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import ts from 'typescript';
interface TsConfig {
compilerOptions?: ts.CompilerOptions;
}
describe('ng-add schematic', () => {
const localizeTripleSlashType = `/// <reference types="@angular/localize" />`;
const defaultOptions = {project: 'demo'};
const schematicRunner = new SchematicTestRunner(
'@angular/localize',
runfiles.resolvePackageRelative('../collection.json'),
);
let host: Tree;
beforeEach(() => {
host = new EmptyTree();
host.create(
'package.json',
JSON.stringify({
'devDependencies': {
// The default (according to `ng-add` in its package.json) is for `@angular/localize` to be
// saved to `devDependencies`.
'@angular/localize': '~0.0.0-PLACEHOLDER',
},
}),
);
host.create(
'main.ts',
`
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
`,
);
host.create(
'angular.json',
JSON.stringify({
version: 1,
projects: {
'demo': {
root: '',
architect: {
application: {
builder: '@angular-devkit/build-angular:application',
options: {
browser: './main.ts',
tsConfig: './tsconfig.application.json',
polyfills: ['zone.js'],
},
},
build: {
builder: '@angular-devkit/build-angular:browser',
options: {
main: './main.ts',
tsConfig: './tsconfig.app.json',
},
},
test: {
builder: '@angular-devkit/build-angular:karma',
options: {
tsConfig: './tsconfig.spec.json',
polyfills: 'zone.js',
},
},
server: {
builder: '@angular-devkit/build-angular:server',
options: {
tsConfig: './tsconfig.server.json',
},
},
unknown: {
builder: '@custom-builder/build-angular:unknown',
options: {
tsConfig: './tsconfig.unknown.json',
},
},
},
},
},
}),
);
});
it(`should add '@angular/localize' type reference in 'main.ts'`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
expect(host.readText('main.ts')).toContain(localizeTripleSlashType);
});
it(`should not add '@angular/localize' type reference in 'main.ts' if already present`, async () => {
const mainContentInput = `
${localizeTripleSlashType}
import { enableProdMode } from '@angular/core';
`;
host.overwrite('main.ts', mainContentInput);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
expect(host.readText('main.ts')).toBe(mainContentInput);
});
it(`should not add '@angular/localize' in 'types' tsconfigs referenced in non official builders`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.unknown.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.unknown.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).not.toContain('@angular/localize');
expect(types).toHaveSize(1);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in browser builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.app.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.app.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in application builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.application.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.application.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize/init' in 'polyfills' in application builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.application.options.polyfills;
expect(polyfills).toEqual(['zone.js', '@angular/localize/init']);
});
it(`should add '@angular/localize/init' in 'polyfills' in karma builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.test.options.polyfills;
expect(polyfills).toEqual(['zone.js', '@angular/localize/init']);
});
it(`should add '@angular/localize/init' in 'polyfills' in browser builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.build.options.polyfills;
expect(polyfills).toEqual(['@angular/localize/init']);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in karma builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.spec.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.spec.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in server builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {},
});
host.create('tsconfig.server.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.server.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(1);
});
it('should add package to `dependencies` if `useAtRuntime` is `true`', async () => {
host = await schematicRunner.runSchematic(
'ng-add',
{...defaultOptions, useAtRuntime: true},
host,
);
const {devDependencies, dependencies} = host.readJson('/package.json') as {
devDependencies: {[key: string]: string};
dependencies: {[key: string]: string};
};
expect(dependencies?.['@angular/localize']).toBe('~0.0.0-PLACEHOLDER');
expect(devDependencies?.['@angular/localize']).toBeUndefined();
});
});
| {
"end_byte": 7927,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/schematics/ng-add/index_spec.ts"
} |
angular/packages/localize/src/translate.ts_0_3768 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {LocalizeFn} from './localize';
import {
MessageId,
ParsedTranslation,
parseTranslation,
TargetMessage,
translate as _translate,
} from './utils';
/**
* We augment the `$localize` object to also store the translations.
*
* Note that because the TRANSLATIONS are attached to a global object, they will be shared between
* all applications that are running in a single page of the browser.
*/
declare const $localize: LocalizeFn & {TRANSLATIONS: Record<MessageId, ParsedTranslation>};
/**
* Load translations for use by `$localize`, if doing runtime translation.
*
* If the `$localize` tagged strings are not going to be replaced at compiled time, it is possible
* to load a set of translations that will be applied to the `$localize` tagged strings at runtime,
* in the browser.
*
* Loading a new translation will overwrite a previous translation if it has the same `MessageId`.
*
* Note that `$localize` messages are only processed once, when the tagged string is first
* encountered, and does not provide dynamic language changing without refreshing the browser.
* Loading new translations later in the application life-cycle will not change the translated text
* of messages that have already been translated.
*
* The message IDs and translations are in the same format as that rendered to "simple JSON"
* translation files when extracting messages. In particular, placeholders in messages are rendered
* using the `{$PLACEHOLDER_NAME}` syntax. For example the message from the following template:
*
* ```html
* <div i18n>pre<span>inner-pre<b>bold</b>inner-post</span>post</div>
* ```
*
* would have the following form in the `translations` map:
*
* ```ts
* {
* "2932901491976224757":
* "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post"
* }
* ```
*
* @param translations A map from message ID to translated message.
*
* These messages are processed and added to a lookup based on their `MessageId`.
*
* @see {@link clearTranslations} for removing translations loaded using this function.
* @see {@link $localize} for tagging messages as needing to be translated.
* @publicApi
*/
export function loadTranslations(translations: Record<MessageId, TargetMessage>) {
// Ensure the translate function exists
if (!$localize.translate) {
$localize.translate = translate;
}
if (!$localize.TRANSLATIONS) {
$localize.TRANSLATIONS = {};
}
Object.keys(translations).forEach((key) => {
$localize.TRANSLATIONS[key] = parseTranslation(translations[key]);
});
}
/**
* Remove all translations for `$localize`, if doing runtime translation.
*
* All translations that had been loading into memory using `loadTranslations()` will be removed.
*
* @see {@link loadTranslations} for loading translations at runtime.
* @see {@link $localize} for tagging messages as needing to be translated.
*
* @publicApi
*/
export function clearTranslations() {
$localize.translate = undefined;
$localize.TRANSLATIONS = {};
}
/**
* Translate the text of the given message, using the loaded translations.
*
* This function may reorder (or remove) substitutions as indicated in the matching translation.
*/
export function translate(
messageParts: TemplateStringsArray,
substitutions: readonly any[],
): [TemplateStringsArray, readonly any[]] {
try {
return _translate($localize.TRANSLATIONS, messageParts, substitutions);
} catch (e) {
console.warn((e as Error).message);
return [messageParts, substitutions];
}
}
| {
"end_byte": 3768,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/translate.ts"
} |
angular/packages/localize/src/utils/BUILD.bazel_0_386 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "utils",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/compiler",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]),
)
| {
"end_byte": 386,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/BUILD.bazel"
} |
angular/packages/localize/src/utils/index.ts_0_304 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/constants';
export * from './src/messages';
export * from './src/translations';
| {
"end_byte": 304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/index.ts"
} |
angular/packages/localize/src/utils/test/translations_spec.ts_0_4444 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
computeMsgId,
makeParsedTranslation,
makeTemplateObject,
ParsedTranslation,
parseTranslation,
TargetMessage,
translate,
} from '..';
describe('utils', () => {
describe('makeTemplateObject', () => {
it('should return an array containing the cooked items', () => {
const template = makeTemplateObject(
['cooked-a', 'cooked-b', 'cooked-c'],
['raw-a', 'raw-b', 'raw-c'],
);
expect(template).toEqual(['cooked-a', 'cooked-b', 'cooked-c']);
});
it('should return an array that has a raw property containing the raw items', () => {
const template = makeTemplateObject(
['cooked-a', 'cooked-b', 'cooked-c'],
['raw-a', 'raw-b', 'raw-c'],
);
expect(template.raw).toEqual(['raw-a', 'raw-b', 'raw-c']);
});
});
describe('makeParsedTranslation()', () => {
it('should compute a template object from the parts', () => {
expect(makeParsedTranslation(['a', 'b', 'c'], ['ph1', 'ph2']).messageParts).toEqual(
makeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']),
);
});
it('should include the placeholder names', () => {
expect(makeParsedTranslation(['a', 'b', 'c'], ['ph1', 'ph2']).placeholderNames).toEqual([
'ph1',
'ph2',
]);
});
it('should compute the message string from the parts and placeholder names', () => {
expect(makeParsedTranslation(['a', 'b', 'c'], ['ph1', 'ph2']).text).toEqual(
'a{$ph1}b{$ph2}c',
);
});
});
describe('parseTranslation', () => {
it('should extract the messageParts as a TemplateStringsArray', () => {
const translation = parseTranslation('a{$one}b{$two}c');
expect(translation.messageParts).toEqual(['a', 'b', 'c']);
expect(translation.messageParts.raw).toEqual(['a', 'b', 'c']);
});
it('should extract the messageParts with leading expression as a TemplateStringsArray', () => {
const translation = parseTranslation('{$one}a{$two}b');
expect(translation.messageParts).toEqual(['', 'a', 'b']);
expect(translation.messageParts.raw).toEqual(['', 'a', 'b']);
});
it('should extract the messageParts with trailing expression as a TemplateStringsArray', () => {
const translation = parseTranslation('a{$one}b{$two}');
expect(translation.messageParts).toEqual(['a', 'b', '']);
expect(translation.messageParts.raw).toEqual(['a', 'b', '']);
});
it('should extract the messageParts with escaped characters as a TemplateStringsArray', () => {
const translation = parseTranslation('a{$one}\nb\n{$two}c');
expect(translation.messageParts).toEqual(['a', '\nb\n', 'c']);
// `messageParts.raw` are not actually escaped as they are not generally used by `$localize`.
// See the "escaped placeholders" test below...
expect(translation.messageParts.raw).toEqual(['a', '\nb\n', 'c']);
});
it('should extract the messageParts with escaped placeholders as a TemplateStringsArray', () => {
const translation = parseTranslation('a{$one}:marker:b{$two}c');
expect(translation.messageParts).toEqual(['a', ':marker:b', 'c']);
// A `messagePart` that starts with a placeholder marker does get escaped in
// `messageParts.raw` as this is used by `$localize`.
expect(translation.messageParts.raw).toEqual(['a', '\\:marker:b', 'c']);
});
it('should extract the placeholder names, in order', () => {
const translation = parseTranslation('a{$one}b{$two}c');
expect(translation.placeholderNames).toEqual(['one', 'two']);
});
it('should handle a translation with no substitutions', () => {
const translation = parseTranslation('abc');
expect(translation.messageParts).toEqual(['abc']);
expect(translation.messageParts.raw).toEqual(['abc']);
expect(translation.placeholderNames).toEqual([]);
});
it('should handle a translation with only substitutions', () => {
const translation = parseTranslation('{$one}{$two}');
expect(translation.messageParts).toEqual(['', '', '']);
expect(translation.messageParts.raw).toEqual(['', '', '']);
expect(translation.placeholderNames).toEqual(['one', 'two']);
});
}); | {
"end_byte": 4444,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/test/translations_spec.ts"
} |
angular/packages/localize/src/utils/test/translations_spec.ts_4448_9420 | describe('translate', () => {
it('should throw an error if there is no matching translation', () => {
expect(() => doTranslate({}, parts`abc`)).toThrowError(
'No translation found for "2674653928643152084" ("abc").',
);
expect(() => doTranslate({}, parts`:@@customId:abc`)).toThrowError(
'No translation found for "customId" ("abc").',
);
expect(() =>
doTranslate({}, parts`:␟d42e3c2d3aa340581d42f53c46eb49ecb3d3beb4␟3896949568605777881:abc`),
).toThrowError(
'No translation found for "2674653928643152084" ["d42e3c2d3aa340581d42f53c46eb49ecb3d3beb4", "3896949568605777881"] ("abc").',
);
expect(() => doTranslate({}, parts`:meaning|:abc`)).toThrowError(
'No translation found for "1071947593002928768" ("abc" - "meaning").',
);
});
it('should throw an error if the translation contains placeholders that are not in the message', () => {
expect(() =>
doTranslate({'abc{$INTERPOLATION}def': 'a{$PH}bc'}, parts`abc${1 + 2}:INTERPOLATION:def`),
).toThrowError(
`There is a placeholder name mismatch with the translation provided for the message "8986527425650846693" ("abc{$INTERPOLATION}def").\n` +
`The translation contains a placeholder with name PH, which does not exist in the message.`,
);
});
it('(with identity translations) should render template literals as-is', () => {
const translations = {
'abc': 'abc',
'abc{$PH}': 'abc{$PH}',
'abc{$PH}def': 'abc{$PH}def',
'abc{$PH}def{$PH_1}': 'abc{$PH}def{$PH_1}',
'Hello, {$PH}!': 'Hello, {$PH}!',
};
expect(doTranslate(translations, parts`abc`)).toEqual(parts`abc`);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}`)).toEqual(parts`abc${1 + 2 + 3}`);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}def`)).toEqual(
parts`abc${1 + 2 + 3}def`,
);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}def${4 + 5 + 6}`)).toEqual(
parts`abc${1 + 2 + 3}def${4 + 5 + 6}`,
);
const getName = () => 'World';
expect(doTranslate(translations, parts`Hello, ${getName()}!`)).toEqual(
parts`Hello, ${'World'}!`,
);
});
it('(with upper-casing translations) should render template literals with messages upper-cased', () => {
const translations = {
'abc': 'ABC',
'abc{$PH}': 'ABC{$PH}',
'abc{$PH}def': 'ABC{$PH}DEF',
'abc{$PH}def{$PH_1}': 'ABC{$PH}DEF{$PH_1}',
'Hello, {$PH}!': 'HELLO, {$PH}!',
};
expect(doTranslate(translations, parts`abc`)).toEqual(parts`ABC`);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}`)).toEqual(parts`ABC${1 + 2 + 3}`);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}def`)).toEqual(
parts`ABC${1 + 2 + 3}DEF`,
);
expect(doTranslate(translations, parts`abc${1 + 2 + 3}def${4 + 5 + 6}`)).toEqual(
parts`ABC${1 + 2 + 3}DEF${4 + 5 + 6}`,
);
const getName = () => 'World';
expect(doTranslate(translations, parts`Hello, ${getName()}!`)).toEqual(
parts`HELLO, ${'World'}!`,
);
});
it('(with translations to reverse expressions) should render template literals with expressions reversed', () => {
const translations = {
'abc{$PH}def{$PH_1} - Hello, {$PH_2}!': 'abc{$PH_2}def{$PH_1} - Hello, {$PH}!',
};
const getName = () => 'World';
expect(
doTranslate(translations, parts`abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`),
).toEqual(parts`abc${'World'}def${4 + 5 + 6} - Hello, ${1 + 2 + 3}!`);
});
it('(with translations to remove expressions) should render template literals with expressions removed', () => {
const translations = {
'abc{$PH}def{$PH_1} - Hello, {$PH_2}!': 'abc{$PH} - Hello, {$PH_2}!',
};
const getName = () => 'World';
expect(
doTranslate(translations, parts`abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`),
).toEqual(parts`abc${1 + 2 + 3} - Hello, ${'World'}!`);
});
function parts(
messageParts: TemplateStringsArray,
...substitutions: any[]
): [TemplateStringsArray, any[]] {
return [messageParts, substitutions];
}
function parseTranslations(
translations: Record<string, TargetMessage>,
): Record<string, ParsedTranslation> {
const parsedTranslations: Record<string, ParsedTranslation> = {};
Object.keys(translations).forEach((key) => {
parsedTranslations[computeMsgId(key, '')] = parseTranslation(translations[key]);
});
return parsedTranslations;
}
function doTranslate(
translations: Record<string, TargetMessage>,
message: [TemplateStringsArray, any[]],
): [TemplateStringsArray, readonly any[]] {
return translate(parseTranslations(translations), message[0], message[1]);
}
});
});
| {
"end_byte": 9420,
"start_byte": 4448,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/test/translations_spec.ts"
} |
angular/packages/localize/src/utils/test/BUILD.bazel_0_397 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*_spec.ts"],
),
deps = [
"//packages:types",
"//packages/localize/src/utils",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/test/BUILD.bazel"
} |
angular/packages/localize/src/utils/test/messages_spec.ts_0_6871 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {findEndOfBlock, makeTemplateObject, parseMessage, parseMetadata, splitBlock} from '..';
describe('messages utils', () => {
describe('parseMessage', () => {
it('should use the custom id parsed from the metadata for the message id, if available', () => {
const message = parseMessage(
makeTemplateObject(
[':@@custom-message-id:a', ':one:b', ':two:c'],
[':@@custom-message-id:a', ':one:b', ':two:c'],
),
[1, 2],
);
expect(message.customId).toEqual('custom-message-id');
expect(message.id).toEqual(message.customId!);
});
it('should compute the translation key if no metadata', () => {
const message = parseMessage(
makeTemplateObject(['a', ':one:b', ':two:c'], ['a', ':one:b', ':two:c']),
[1, 2],
);
expect(message.id).toEqual('8865273085679272414');
});
it('should compute the translation key if no custom id in the metadata', () => {
const message = parseMessage(
makeTemplateObject(
[':description:a', ':one:b', ':two:c'],
[':description:a', ':one:b', ':two:c'],
),
[1, 2],
);
expect(message.id).toEqual('8865273085679272414');
});
it('should compute a different id if the meaning changes', () => {
const message1 = parseMessage(makeTemplateObject(['abc'], ['abc']), []);
const message2 = parseMessage(makeTemplateObject([':meaning1|:abc'], [':meaning1|:abc']), []);
const message3 = parseMessage(makeTemplateObject([':meaning2|:abc'], [':meaning2|:abc']), []);
expect(message1.id).not.toEqual(message2.id);
expect(message2.id).not.toEqual(message3.id);
expect(message3.id).not.toEqual(message1.id);
});
it('should capture legacy ids if available', () => {
const message1 = parseMessage(
makeTemplateObject(
[':␟legacy-1␟legacy-2␟legacy-3:a', ':one:b', ':two:c'],
[':␟legacy-1␟legacy-2␟legacy-3:a', ':one:b', ':two:c'],
),
[1, 2],
);
expect(message1.id).toEqual('8865273085679272414');
expect(message1.legacyIds).toEqual(['legacy-1', 'legacy-2', 'legacy-3']);
const message2 = parseMessage(
makeTemplateObject(
[':@@custom-message-id␟legacy-message-id:a', ':one:b', ':two:c'],
[':@@custom-message-id␟legacy-message-id:a', ':one:b', ':two:c'],
),
[1, 2],
);
expect(message2.id).toEqual('custom-message-id');
expect(message2.legacyIds).toEqual(['legacy-message-id']);
const message3 = parseMessage(
makeTemplateObject(
[':@@custom-message-id:a', ':one:b', ':two:c'],
[':@@custom-message-id:a', ':one:b', ':two:c'],
),
[1, 2],
);
expect(message3.id).toEqual('custom-message-id');
expect(message3.legacyIds).toEqual([]);
});
it('should infer placeholder names if not given', () => {
const parts1 = ['a', 'b', 'c'];
const message1 = parseMessage(makeTemplateObject(parts1, parts1), [1, 2]);
expect(message1.id).toEqual('8107531564991075946');
const parts2 = ['a', ':custom1:b', ':custom2:c'];
const message2 = parseMessage(makeTemplateObject(parts2, parts2), [1, 2]);
expect(message2.id).toEqual('1822117095464505589');
// Note that the placeholder names are part of the message so affect the message id.
expect(message1.id).not.toEqual(message2.id);
expect(message1.text).not.toEqual(message2.text);
});
it('should ignore placeholder blocks whose markers have been escaped', () => {
const message = parseMessage(
makeTemplateObject(['a', ':one:b', ':two:c'], ['a', '\\:one:b', '\\:two:c']),
[1, 2],
);
expect(message.id).toEqual('2623373088949454037');
});
it('should extract the meaning, description and placeholder names', () => {
const message1 = parseMessage(makeTemplateObject(['abc'], ['abc']), []);
expect(message1.messageParts).toEqual(['abc']);
expect(message1.meaning).toEqual('');
expect(message1.description).toEqual('');
expect(message1.placeholderNames).toEqual([]);
const message2 = parseMessage(
makeTemplateObject([':meaning|description:abc'], [':meaning|description:abc']),
[],
);
expect(message2.messageParts).toEqual(['abc']);
expect(message2.meaning).toEqual('meaning');
expect(message2.description).toEqual('description');
expect(message2.placeholderNames).toEqual([]);
const message3 = parseMessage(
makeTemplateObject(['a', ':custom:b', 'c'], ['a', ':custom:b', 'c']),
[0, 1],
);
expect(message3.messageParts).toEqual(['a', 'b', 'c']);
expect(message3.meaning).toEqual('');
expect(message3.description).toEqual('');
expect(message3.placeholderNames).toEqual(['custom', 'PH_1']);
});
it('should build a map of named placeholders to expressions', () => {
const message = parseMessage(
makeTemplateObject(['a', ':one:b', ':two:c'], ['a', ':one:b', ':two:c']),
[1, 2],
);
expect(message.substitutions).toEqual({one: 1, two: 2});
});
it('should build a map of implied placeholders to expressions', () => {
const message = parseMessage(makeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']), [1, 2]);
expect(message.substitutions).toEqual({PH: 1, PH_1: 2});
});
});
describe('splitBlock()', () => {
it('should return just the text if there is no block', () => {
expect(splitBlock('abc def', 'abc def')).toEqual({text: 'abc def'});
});
it('should return just the text and block if there is one', () => {
expect(splitBlock(':block info:abc def', ':block info:abc def')).toEqual({
text: 'abc def',
block: 'block info',
});
});
it('should handle an empty block if there is one', () => {
expect(splitBlock('::abc def', '::abc def')).toEqual({text: 'abc def', block: ''});
});
it('should error on an unterminated block', () => {
expect(() => splitBlock(':abc def', ':abc def')).toThrowError(
'Unterminated $localize metadata block in ":abc def".',
);
});
it('should handle escaped block markers', () => {
expect(splitBlock(':part of the message:abc def', '\\:part of the message:abc def')).toEqual({
text: ':part of the message:abc def',
});
expect(
splitBlock(':block with escaped : in it:abc def', ':block with escaped \\: in it:abc def'),
).toEqual({text: 'abc def', block: 'block with escaped : in it'});
});
});
describe('fi | {
"end_byte": 6871,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/test/messages_spec.ts"
} |
angular/packages/localize/src/utils/test/messages_spec.ts_6875_11715 | dOfBlock()', () => {
it('should throw error if there is no end of block marker', () => {
expect(() => findEndOfBlock(':some text', ':some text')).toThrowError(
'Unterminated $localize metadata block in ":some text".',
);
expect(() => findEndOfBlock(':escaped colon:', ':escaped colon\\:')).toThrowError(
'Unterminated $localize metadata block in ":escaped colon\\:".',
);
});
it('should return index of the end of block marker', () => {
expect(findEndOfBlock(':block:', ':block:')).toEqual(6);
expect(findEndOfBlock(':block::', ':block::')).toEqual(6);
expect(findEndOfBlock(':block:some text', ':block:some text')).toEqual(6);
expect(findEndOfBlock(':block:some text:more text', ':block:some text:more text')).toEqual(6);
expect(findEndOfBlock('::::', ':\\:\\::')).toEqual(3);
expect(findEndOfBlock(':block::', ':block\\::')).toEqual(7);
expect(findEndOfBlock(':block:more:some text', ':block\\:more:some text')).toEqual(11);
expect(
findEndOfBlock(':block:more:and-more:some text', ':block\\:more\\:and-more:some text'),
).toEqual(20);
});
});
describe('parseMetadata()', () => {
it('should return just the text if there is no block', () => {
expect(parseMetadata('abc def', 'abc def')).toEqual({text: 'abc def'});
});
it('should extract the metadata if provided', () => {
expect(parseMetadata(':description:abc def', ':description:abc def')).toEqual({
text: 'abc def',
description: 'description',
meaning: undefined,
customId: undefined,
legacyIds: [],
});
expect(parseMetadata(':meaning|:abc def', ':meaning|:abc def')).toEqual({
text: 'abc def',
description: undefined,
meaning: 'meaning',
customId: undefined,
legacyIds: [],
});
expect(parseMetadata(':@@message-id:abc def', ':@@message-id:abc def')).toEqual({
text: 'abc def',
description: undefined,
meaning: undefined,
customId: 'message-id',
legacyIds: [],
});
expect(parseMetadata(':meaning|description:abc def', ':meaning|description:abc def')).toEqual(
{
text: 'abc def',
description: 'description',
meaning: 'meaning',
customId: undefined,
legacyIds: [],
},
);
expect(
parseMetadata(':description@@message-id:abc def', ':description@@message-id:abc def'),
).toEqual({
text: 'abc def',
description: 'description',
meaning: undefined,
customId: 'message-id',
legacyIds: [],
});
expect(
parseMetadata(':meaning|@@message-id:abc def', ':meaning|@@message-id:abc def'),
).toEqual({
text: 'abc def',
description: undefined,
meaning: 'meaning',
customId: 'message-id',
legacyIds: [],
});
expect(
parseMetadata(
':description@@message-id␟legacy-1␟legacy-2␟legacy-3:abc def',
':description@@message-id␟legacy-1␟legacy-2␟legacy-3:abc def',
),
).toEqual({
text: 'abc def',
description: 'description',
meaning: undefined,
customId: 'message-id',
legacyIds: ['legacy-1', 'legacy-2', 'legacy-3'],
});
expect(
parseMetadata(
':meaning|@@message-id␟legacy-message-id:abc def',
':meaning|@@message-id␟legacy-message-id:abc def',
),
).toEqual({
text: 'abc def',
description: undefined,
meaning: 'meaning',
customId: 'message-id',
legacyIds: ['legacy-message-id'],
});
expect(
parseMetadata(':meaning|␟legacy-message-id:abc def', ':meaning|␟legacy-message-id:abc def'),
).toEqual({
text: 'abc def',
description: undefined,
meaning: 'meaning',
customId: undefined,
legacyIds: ['legacy-message-id'],
});
expect(parseMetadata(':␟legacy-message-id:abc def', ':␟legacy-message-id:abc def')).toEqual({
text: 'abc def',
description: undefined,
meaning: undefined,
customId: undefined,
legacyIds: ['legacy-message-id'],
});
});
it('should handle an empty block if there is one', () => {
expect(parseMetadata('::abc def', '::abc def')).toEqual({
text: 'abc def',
meaning: undefined,
description: undefined,
customId: undefined,
legacyIds: [],
});
});
it('should handle escaped block markers', () => {
expect(
parseMetadata(':part of the message:abc def', '\\:part of the message:abc def'),
).toEqual({text: ':part of the message:abc def'});
});
});
});
| {
"end_byte": 11715,
"start_byte": 6875,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/test/messages_spec.ts"
} |
angular/packages/localize/src/utils/src/messages.ts_0_7853 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This module specifier is intentionally a relative path to allow bundling the code directly
// into the package.
// @ng_package: ignore-cross-repo-import
import {computeMsgId} from '../../../../compiler/src/i18n/digest';
import {BLOCK_MARKER, ID_SEPARATOR, LEGACY_ID_INDICATOR, MEANING_SEPARATOR} from './constants';
/**
* Re-export this helper function so that users of `@angular/localize` don't need to actively import
* from `@angular/compiler`.
*/
export {computeMsgId};
/**
* A string containing a translation source message.
*
* I.E. the message that indicates what will be translated from.
*
* Uses `{$placeholder-name}` to indicate a placeholder.
*/
export type SourceMessage = string;
/**
* A string containing a translation target message.
*
* I.E. the message that indicates what will be translated to.
*
* Uses `{$placeholder-name}` to indicate a placeholder.
*
* @publicApi
*/
export type TargetMessage = string;
/**
* A string that uniquely identifies a message, to be used for matching translations.
*
* @publicApi
*/
export type MessageId = string;
/**
* Declares a copy of the `AbsoluteFsPath` branded type in `@angular/compiler-cli` to avoid an
* import into `@angular/compiler-cli`. The compiler-cli's declaration files are not necessarily
* compatible with web environments that use `@angular/localize`, and would inadvertently include
* `typescript` declaration files in any compilation unit that uses `@angular/localize` (which
* increases parsing time and memory usage during builds) using a default import that only
* type-checks when `allowSyntheticDefaultImports` is enabled.
*
* @see https://github.com/angular/angular/issues/45179
*/
type AbsoluteFsPathLocalizeCopy = string & {_brand: 'AbsoluteFsPath'};
/**
* The location of the message in the source file.
*
* The `line` and `column` values for the `start` and `end` properties are zero-based.
*/
export interface SourceLocation {
start: {line: number; column: number};
end: {line: number; column: number};
file: AbsoluteFsPathLocalizeCopy;
text?: string;
}
/**
* Additional information that can be associated with a message.
*/
export interface MessageMetadata {
/**
* A human readable rendering of the message
*/
text: string;
/**
* Legacy message ids, if provided.
*
* In legacy message formats the message id can only be computed directly from the original
* template source.
*
* Since this information is not available in `$localize` calls, the legacy message ids may be
* attached by the compiler to the `$localize` metablock so it can be used if needed at the point
* of translation if the translations are encoded using the legacy message id.
*/
legacyIds?: string[];
/**
* The id of the `message` if a custom one was specified explicitly.
*
* This id overrides any computed or legacy ids.
*/
customId?: string;
/**
* The meaning of the `message`, used to distinguish identical `messageString`s.
*/
meaning?: string;
/**
* The description of the `message`, used to aid translation.
*/
description?: string;
/**
* The location of the message in the source.
*/
location?: SourceLocation;
}
/**
* Information parsed from a `$localize` tagged string that is used to translate it.
*
* For example:
*
* ```
* const name = 'Jo Bloggs';
* $localize`Hello ${name}:title@@ID:!`;
* ```
*
* May be parsed into:
*
* ```
* {
* id: '6998194507597730591',
* substitutions: { title: 'Jo Bloggs' },
* messageString: 'Hello {$title}!',
* placeholderNames: ['title'],
* associatedMessageIds: { title: 'ID' },
* }
* ```
*/
export interface ParsedMessage extends MessageMetadata {
/**
* The key used to look up the appropriate translation target.
*/
id: MessageId;
/**
* A mapping of placeholder names to substitution values.
*/
substitutions: Record<string, any>;
/**
* An optional mapping of placeholder names to associated MessageIds.
* This can be used to match ICU placeholders to the message that contains the ICU.
*/
associatedMessageIds?: Record<string, MessageId>;
/**
* An optional mapping of placeholder names to source locations
*/
substitutionLocations?: Record<string, SourceLocation | undefined>;
/**
* The static parts of the message.
*/
messageParts: string[];
/**
* An optional mapping of message parts to source locations
*/
messagePartLocations?: (SourceLocation | undefined)[];
/**
* The names of the placeholders that will be replaced with substitutions.
*/
placeholderNames: string[];
}
/**
* Parse a `$localize` tagged string into a structure that can be used for translation or
* extraction.
*
* See `ParsedMessage` for an example.
*/
export function parseMessage(
messageParts: TemplateStringsArray,
expressions?: readonly any[],
location?: SourceLocation,
messagePartLocations?: (SourceLocation | undefined)[],
expressionLocations: (SourceLocation | undefined)[] = [],
): ParsedMessage {
const substitutions: {[placeholderName: string]: any} = {};
const substitutionLocations: {[placeholderName: string]: SourceLocation | undefined} = {};
const associatedMessageIds: {[placeholderName: string]: MessageId} = {};
const metadata = parseMetadata(messageParts[0], messageParts.raw[0]);
const cleanedMessageParts: string[] = [metadata.text];
const placeholderNames: string[] = [];
let messageString = metadata.text;
for (let i = 1; i < messageParts.length; i++) {
const {
messagePart,
placeholderName = computePlaceholderName(i),
associatedMessageId,
} = parsePlaceholder(messageParts[i], messageParts.raw[i]);
messageString += `{$${placeholderName}}${messagePart}`;
if (expressions !== undefined) {
substitutions[placeholderName] = expressions[i - 1];
substitutionLocations[placeholderName] = expressionLocations[i - 1];
}
placeholderNames.push(placeholderName);
if (associatedMessageId !== undefined) {
associatedMessageIds[placeholderName] = associatedMessageId;
}
cleanedMessageParts.push(messagePart);
}
const messageId = metadata.customId || computeMsgId(messageString, metadata.meaning || '');
const legacyIds = metadata.legacyIds ? metadata.legacyIds.filter((id) => id !== messageId) : [];
return {
id: messageId,
legacyIds,
substitutions,
substitutionLocations,
text: messageString,
customId: metadata.customId,
meaning: metadata.meaning || '',
description: metadata.description || '',
messageParts: cleanedMessageParts,
messagePartLocations,
placeholderNames,
associatedMessageIds,
location,
};
}
/**
* Parse the given message part (`cooked` + `raw`) to extract the message metadata from the text.
*
* If the message part has a metadata block this function will extract the `meaning`,
* `description`, `customId` and `legacyId` (if provided) from the block. These metadata properties
* are serialized in the string delimited by `|`, `@@` and `␟` respectively.
*
* (Note that `␟` is the `LEGACY_ID_INDICATOR` - see `constants.ts`.)
*
* For example:
*
* ```ts
* `:meaning|description@@custom-id:`
* `:meaning|@@custom-id:`
* `:meaning|description:`
* `:description@@custom-id:`
* `:meaning|:`
* `:description:`
* `:@@custom-id:`
* `:meaning|description@@custom-id␟legacy-id-1␟legacy-id-2:`
* ```
*
* @param cooked The cooked version of the message part to parse.
* @param raw The raw version of the message part to parse.
* @returns A object containing any metadata that was parsed from the message part.
*/
export | {
"end_byte": 7853,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/src/messages.ts"
} |
angular/packages/localize/src/utils/src/messages.ts_7854_11864 | unction parseMetadata(cooked: string, raw: string): MessageMetadata {
const {text: messageString, block} = splitBlock(cooked, raw);
if (block === undefined) {
return {text: messageString};
} else {
const [meaningDescAndId, ...legacyIds] = block.split(LEGACY_ID_INDICATOR);
const [meaningAndDesc, customId] = meaningDescAndId.split(ID_SEPARATOR, 2);
let [meaning, description]: (string | undefined)[] = meaningAndDesc.split(MEANING_SEPARATOR, 2);
if (description === undefined) {
description = meaning;
meaning = undefined;
}
if (description === '') {
description = undefined;
}
return {text: messageString, meaning, description, customId, legacyIds};
}
}
/**
* Parse the given message part (`cooked` + `raw`) to extract any placeholder metadata from the
* text.
*
* If the message part has a metadata block this function will extract the `placeholderName` and
* `associatedMessageId` (if provided) from the block.
*
* These metadata properties are serialized in the string delimited by `@@`.
*
* For example:
*
* ```ts
* `:placeholder-name@@associated-id:`
* ```
*
* @param cooked The cooked version of the message part to parse.
* @param raw The raw version of the message part to parse.
* @returns A object containing the metadata (`placeholderName` and `associatedMessageId`) of the
* preceding placeholder, along with the static text that follows.
*/
export function parsePlaceholder(
cooked: string,
raw: string,
): {messagePart: string; placeholderName?: string; associatedMessageId?: string} {
const {text: messagePart, block} = splitBlock(cooked, raw);
if (block === undefined) {
return {messagePart};
} else {
const [placeholderName, associatedMessageId] = block.split(ID_SEPARATOR);
return {messagePart, placeholderName, associatedMessageId};
}
}
/**
* Split a message part (`cooked` + `raw`) into an optional delimited "block" off the front and the
* rest of the text of the message part.
*
* Blocks appear at the start of message parts. They are delimited by a colon `:` character at the
* start and end of the block.
*
* If the block is in the first message part then it will be metadata about the whole message:
* meaning, description, id. Otherwise it will be metadata about the immediately preceding
* substitution: placeholder name.
*
* Since blocks are optional, it is possible that the content of a message block actually starts
* with a block marker. In this case the marker must be escaped `\:`.
*
* @param cooked The cooked version of the message part to parse.
* @param raw The raw version of the message part to parse.
* @returns An object containing the `text` of the message part and the text of the `block`, if it
* exists.
* @throws an error if the `block` is unterminated
*/
export function splitBlock(cooked: string, raw: string): {text: string; block?: string} {
if (raw.charAt(0) !== BLOCK_MARKER) {
return {text: cooked};
} else {
const endOfBlock = findEndOfBlock(cooked, raw);
return {
block: cooked.substring(1, endOfBlock),
text: cooked.substring(endOfBlock + 1),
};
}
}
function computePlaceholderName(index: number) {
return index === 1 ? 'PH' : `PH_${index - 1}`;
}
/**
* Find the end of a "marked block" indicated by the first non-escaped colon.
*
* @param cooked The cooked string (where escaped chars have been processed)
* @param raw The raw string (where escape sequences are still in place)
*
* @returns the index of the end of block marker
* @throws an error if the block is unterminated
*/
export function findEndOfBlock(cooked: string, raw: string): number {
for (let cookedIndex = 1, rawIndex = 1; cookedIndex < cooked.length; cookedIndex++, rawIndex++) {
if (raw[rawIndex] === '\\') {
rawIndex++;
} else if (cooked[cookedIndex] === BLOCK_MARKER) {
return cookedIndex;
}
}
throw new Error(`Unterminated $localize metadata block in "${raw}".`);
}
| {
"end_byte": 11864,
"start_byte": 7854,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/src/messages.ts"
} |
angular/packages/localize/src/utils/src/constants.ts_0_1853 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* The character used to mark the start and end of a "block" in a `$localize` tagged string.
* A block can indicate metadata about the message or specify a name of a placeholder for a
* substitution expressions.
*
* For example:
*
* ```ts
* $localize`Hello, ${title}:title:!`;
* $localize`:meaning|description@@id:source message text`;
* ```
*/
export const BLOCK_MARKER = ':';
/**
* The marker used to separate a message's "meaning" from its "description" in a metadata block.
*
* For example:
*
* ```ts
* $localize `:correct|Indicates that the user got the answer correct: Right!`;
* $localize `:movement|Button label for moving to the right: Right!`;
* ```
*/
export const MEANING_SEPARATOR = '|';
/**
* The marker used to separate a message's custom "id" from its "description" in a metadata block.
*
* For example:
*
* ```ts
* $localize `:A welcome message on the home page@@myApp-homepage-welcome: Welcome!`;
* ```
*/
export const ID_SEPARATOR = '@@';
/**
* The marker used to separate legacy message ids from the rest of a metadata block.
*
* For example:
*
* ```ts
* $localize `:@@custom-id␟2df64767cd895a8fabe3e18b94b5b6b6f9e2e3f0: Welcome!`;
* ```
*
* Note that this character is the "symbol for the unit separator" (␟) not the "unit separator
* character" itself, since that has no visual representation. See https://graphemica.com/%E2%90%9F.
*
* Here is some background for the original "unit separator character":
* https://stackoverflow.com/questions/8695118/whats-the-file-group-record-unit-separator-control-characters-and-its-usage
*/
export const LEGACY_ID_INDICATOR = '\u241F';
| {
"end_byte": 1853,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/src/constants.ts"
} |
angular/packages/localize/src/utils/src/translations.ts_0_5495 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BLOCK_MARKER} from './constants';
import {MessageId, MessageMetadata, ParsedMessage, parseMessage, TargetMessage} from './messages';
/**
* A translation message that has been processed to extract the message parts and placeholders.
*/
export interface ParsedTranslation extends MessageMetadata {
messageParts: TemplateStringsArray;
placeholderNames: string[];
}
/**
* The internal structure used by the runtime localization to translate messages.
*/
export type ParsedTranslations = Record<MessageId, ParsedTranslation>;
export class MissingTranslationError extends Error {
private readonly type = 'MissingTranslationError';
constructor(readonly parsedMessage: ParsedMessage) {
super(`No translation found for ${describeMessage(parsedMessage)}.`);
}
}
export function isMissingTranslationError(e: any): e is MissingTranslationError {
return e.type === 'MissingTranslationError';
}
/**
* Translate the text of the `$localize` tagged-string (i.e. `messageParts` and
* `substitutions`) using the given `translations`.
*
* The tagged-string is parsed to extract its `messageId` which is used to find an appropriate
* `ParsedTranslation`. If this doesn't match and there are legacy ids then try matching a
* translation using those.
*
* If one is found then it is used to translate the message into a new set of `messageParts` and
* `substitutions`.
* The translation may reorder (or remove) substitutions as appropriate.
*
* If there is no translation with a matching message id then an error is thrown.
* If a translation contains a placeholder that is not found in the message being translated then an
* error is thrown.
*/
export function translate(
translations: Record<string, ParsedTranslation>,
messageParts: TemplateStringsArray,
substitutions: readonly any[],
): [TemplateStringsArray, readonly any[]] {
const message = parseMessage(messageParts, substitutions);
// Look up the translation using the messageId, and then the legacyId if available.
let translation = translations[message.id];
// If the messageId did not match a translation, try matching the legacy ids instead
if (message.legacyIds !== undefined) {
for (let i = 0; i < message.legacyIds.length && translation === undefined; i++) {
translation = translations[message.legacyIds[i]];
}
}
if (translation === undefined) {
throw new MissingTranslationError(message);
}
return [
translation.messageParts,
translation.placeholderNames.map((placeholder) => {
if (message.substitutions.hasOwnProperty(placeholder)) {
return message.substitutions[placeholder];
} else {
throw new Error(
`There is a placeholder name mismatch with the translation provided for the message ${describeMessage(
message,
)}.\n` +
`The translation contains a placeholder with name ${placeholder}, which does not exist in the message.`,
);
}
}),
];
}
/**
* Parse the `messageParts` and `placeholderNames` out of a target `message`.
*
* Used by `loadTranslations()` to convert target message strings into a structure that is more
* appropriate for doing translation.
*
* @param message the message to be parsed.
*/
export function parseTranslation(messageString: TargetMessage): ParsedTranslation {
const parts = messageString.split(/{\$([^}]*)}/);
const messageParts = [parts[0]];
const placeholderNames: string[] = [];
for (let i = 1; i < parts.length - 1; i += 2) {
placeholderNames.push(parts[i]);
messageParts.push(`${parts[i + 1]}`);
}
const rawMessageParts = messageParts.map((part) =>
part.charAt(0) === BLOCK_MARKER ? '\\' + part : part,
);
return {
text: messageString,
messageParts: makeTemplateObject(messageParts, rawMessageParts),
placeholderNames,
};
}
/**
* Create a `ParsedTranslation` from a set of `messageParts` and `placeholderNames`.
*
* @param messageParts The message parts to appear in the ParsedTranslation.
* @param placeholderNames The names of the placeholders to intersperse between the `messageParts`.
*/
export function makeParsedTranslation(
messageParts: string[],
placeholderNames: string[] = [],
): ParsedTranslation {
let messageString = messageParts[0];
for (let i = 0; i < placeholderNames.length; i++) {
messageString += `{$${placeholderNames[i]}}${messageParts[i + 1]}`;
}
return {
text: messageString,
messageParts: makeTemplateObject(messageParts, messageParts),
placeholderNames,
};
}
/**
* Create the specialized array that is passed to tagged-string tag functions.
*
* @param cooked The message parts with their escape codes processed.
* @param raw The message parts with their escaped codes as-is.
*/
export function makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray {
Object.defineProperty(cooked, 'raw', {value: raw});
return cooked as any;
}
function describeMessage(message: ParsedMessage): string {
const meaningString = message.meaning && ` - "${message.meaning}"`;
const legacy =
message.legacyIds && message.legacyIds.length > 0
? ` [${message.legacyIds.map((l) => `"${l}"`).join(', ')}]`
: '';
return `"${message.id}"${legacy} ("${message.text}"${meaningString})`;
}
| {
"end_byte": 5495,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/utils/src/translations.ts"
} |
angular/packages/localize/src/localize/BUILD.bazel_0_608 | load("//tools:defaults.bzl", "generate_api_docs", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "localize",
srcs = glob(
[
"**/*.ts",
],
),
deps = [
"//packages/localize/src/utils",
"@npm//@types/node",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]),
)
generate_api_docs(
name = "localize_init_docs",
srcs = [
":files_for_docgen",
],
entry_point = ":doc_index.ts",
module_name = "@angular/localize/init",
)
| {
"end_byte": 608,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/BUILD.bazel"
} |
angular/packages/localize/src/localize/index.ts_0_270 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {$localize, LocalizeFn, TranslateFn} from './src/localize';
| {
"end_byte": 270,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/index.ts"
} |
angular/packages/localize/src/localize/doc_index.ts_0_245 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {$localize} from './src/localize';
| {
"end_byte": 245,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/doc_index.ts"
} |
angular/packages/localize/src/localize/test/localize_spec.ts_0_4533 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {$localize, TranslateFn} from '../src/localize';
describe('$localize tag', () => {
describe('with no `translate()` defined (the default)', () => {
it('should render template literals as-is', () => {
expect($localize.translate).toBeUndefined();
expect($localize`abc`).toEqual('abc');
expect($localize`abc${1 + 2 + 3}`).toEqual('abc6');
expect($localize`abc${1 + 2 + 3}def`).toEqual('abc6def');
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6}`).toEqual('abc6def15');
const getName = () => 'World';
expect($localize`Hello, ${getName()}!`).toEqual('Hello, World!');
});
it('should strip metadata block from message parts', () => {
expect($localize.translate).toBeUndefined();
expect($localize`:meaning|description@@custom-id:abcdef`).toEqual('abcdef');
});
it('should ignore escaped metadata block marker', () => {
expect($localize.translate).toBeUndefined();
expect($localize`\:abc:def`).toEqual(':abc:def');
});
it('should strip metadata block containing escaped block markers', () => {
expect($localize.translate).toBeUndefined();
expect($localize`:abc\:def:content`).toEqual('content');
});
it('should strip placeholder names from message parts', () => {
expect($localize.translate).toBeUndefined();
expect($localize`abc${1 + 2 + 3}:ph1:def${4 + 5 + 6}:ph2:`).toEqual('abc6def15');
});
it('should ignore escaped placeholder name marker', () => {
expect($localize.translate).toBeUndefined();
expect($localize`abc${1 + 2 + 3}\:ph1:def${4 + 5 + 6}\:ph2:`).toEqual('abc6:ph1:def15:ph2:');
});
});
describe('with `translate()` defined as an identity', () => {
beforeEach(() => {
$localize.translate = identityTranslate;
});
afterEach(() => {
$localize.translate = undefined;
});
it('should render template literals as-is', () => {
expect($localize`abc`).toEqual('abc');
expect($localize`abc${1 + 2 + 3}`).toEqual('abc6');
expect($localize`abc${1 + 2 + 3}def`).toEqual('abc6def');
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6}`).toEqual('abc6def15');
const getName = () => 'World';
expect($localize`Hello, ${getName()}!`).toEqual('Hello, World!');
});
});
describe('with `translate()` defined to upper-case messageParts', () => {
beforeEach(() => {
$localize.translate = upperCaseTranslate;
});
afterEach(() => {
$localize.translate = undefined;
});
it('should render template literals with messages upper-cased', () => {
expect($localize`abc`).toEqual('ABC');
expect($localize`abc${1 + 2 + 3}`).toEqual('ABC6');
expect($localize`abc${1 + 2 + 3}def`).toEqual('ABC6DEF');
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6}`).toEqual('ABC6DEF15');
const getName = () => 'World';
expect($localize`Hello, ${getName()}!`).toEqual('HELLO, World!');
});
});
describe('with `translate()` defined to reverse expressions', () => {
beforeEach(() => {
$localize.translate = reverseTranslate;
});
afterEach(() => {
$localize.translate = undefined;
});
it('should render template literals with expressions reversed', () => {
const getName = () => 'World';
expect($localize`abc${1 + 2 + 3}def${4 + 5 + 6} - Hello, ${getName()}!`).toEqual(
'abcWorlddef15 - Hello, 6!',
);
});
});
});
function makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray {
Object.defineProperty(cooked, 'raw', {value: raw});
return cooked as any;
}
const identityTranslate: TranslateFn = function (
messageParts: TemplateStringsArray,
expressions: readonly any[],
) {
return [messageParts, expressions];
};
const upperCaseTranslate: TranslateFn = function (
messageParts: TemplateStringsArray,
expressions: readonly any[],
) {
return [
makeTemplateObject(
Array.from(messageParts).map((part: string) => part.toUpperCase()),
messageParts.raw.map((part: string) => part.toUpperCase()),
),
expressions,
];
};
const reverseTranslate: TranslateFn = function (
messageParts: TemplateStringsArray,
expressions: readonly any[],
) {
expressions = Array.from(expressions).reverse();
return [messageParts, expressions];
};
| {
"end_byte": 4533,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/test/localize_spec.ts"
} |
angular/packages/localize/src/localize/test/BUILD.bazel_0_397 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["*_spec.ts"],
),
deps = [
"//packages:types",
"//packages/localize/src/localize",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/test/BUILD.bazel"
} |
angular/packages/localize/src/localize/src/localize.ts_0_6324 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {findEndOfBlock} from '../../utils';
/** @nodoc */
export interface LocalizeFn {
(messageParts: TemplateStringsArray, ...expressions: readonly any[]): string;
/**
* A function that converts an input "message with expressions" into a translated "message with
* expressions".
*
* The conversion may be done in place, modifying the array passed to the function, so
* don't assume that this has no side-effects.
*
* The expressions must be passed in since it might be they need to be reordered for
* different translations.
*/
translate?: TranslateFn;
/**
* The current locale of the translated messages.
*
* The compile-time translation inliner is able to replace the following code:
*
* ```
* typeof $localize !== "undefined" && $localize.locale
* ```
*
* with a string literal of the current locale. E.g.
*
* ```
* "fr"
* ```
*/
locale?: string;
}
/** @nodoc */
export interface TranslateFn {
(
messageParts: TemplateStringsArray,
expressions: readonly any[],
): [TemplateStringsArray, readonly any[]];
}
/**
* Tag a template literal string for localization.
*
* For example:
*
* ```ts
* $localize `some string to localize`
* ```
*
* **Providing meaning, description and id**
*
* You can optionally specify one or more of `meaning`, `description` and `id` for a localized
* string by pre-pending it with a colon delimited block of the form:
*
* ```ts
* $localize`:meaning|description@@id:source message text`;
*
* $localize`:meaning|:source message text`;
* $localize`:description:source message text`;
* $localize`:@@id:source message text`;
* ```
*
* This format is the same as that used for `i18n` markers in Angular templates. See the
* [Angular i18n guide](guide/i18n/prepare#mark-text-in-component-template).
*
* **Naming placeholders**
*
* If the template literal string contains expressions, then the expressions will be automatically
* associated with placeholder names for you.
*
* For example:
*
* ```ts
* $localize `Hi ${name}! There are ${items.length} items.`;
* ```
*
* will generate a message-source of `Hi {$PH}! There are {$PH_1} items`.
*
* The recommended practice is to name the placeholder associated with each expression though.
*
* Do this by providing the placeholder name wrapped in `:` characters directly after the
* expression. These placeholder names are stripped out of the rendered localized string.
*
* For example, to name the `items.length` expression placeholder `itemCount` you write:
*
* ```ts
* $localize `There are ${items.length}:itemCount: items`;
* ```
*
* **Escaping colon markers**
*
* If you need to use a `:` character directly at the start of a tagged string that has no
* metadata block, or directly after a substitution expression that has no name you must escape
* the `:` by preceding it with a backslash:
*
* For example:
*
* ```ts
* // message has a metadata block so no need to escape colon
* $localize `:some description::this message starts with a colon (:)`;
* // no metadata block so the colon must be escaped
* $localize `\:this message starts with a colon (:)`;
* ```
*
* ```ts
* // named substitution so no need to escape colon
* $localize `${label}:label:: ${}`
* // anonymous substitution so colon must be escaped
* $localize `${label}\: ${}`
* ```
*
* **Processing localized strings:**
*
* There are three scenarios:
*
* * **compile-time inlining**: the `$localize` tag is transformed at compile time by a
* transpiler, removing the tag and replacing the template literal string with a translated
* literal string from a collection of translations provided to the transpilation tool.
*
* * **run-time evaluation**: the `$localize` tag is a run-time function that replaces and
* reorders the parts (static strings and expressions) of the template literal string with strings
* from a collection of translations loaded at run-time.
*
* * **pass-through evaluation**: the `$localize` tag is a run-time function that simply evaluates
* the original template literal string without applying any translations to the parts. This
* version is used during development or where there is no need to translate the localized
* template literals.
*
* @param messageParts a collection of the static parts of the template string.
* @param expressions a collection of the values of each placeholder in the template string.
* @returns the translated string, with the `messageParts` and `expressions` interleaved together.
*
* @publicApi
*/
export const $localize: LocalizeFn = function (
messageParts: TemplateStringsArray,
...expressions: readonly any[]
) {
if ($localize.translate) {
// Don't use array expansion here to avoid the compiler adding `__read()` helper unnecessarily.
const translation = $localize.translate(messageParts, expressions);
messageParts = translation[0];
expressions = translation[1];
}
let message = stripBlock(messageParts[0], messageParts.raw[0]);
for (let i = 1; i < messageParts.length; i++) {
message += expressions[i - 1] + stripBlock(messageParts[i], messageParts.raw[i]);
}
return message;
};
const BLOCK_MARKER = ':';
/**
* Strip a delimited "block" from the start of the `messagePart`, if it is found.
*
* If a marker character (:) actually appears in the content at the start of a tagged string or
* after a substitution expression, where a block has not been provided the character must be
* escaped with a backslash, `\:`. This function checks for this by looking at the `raw`
* messagePart, which should still contain the backslash.
*
* @param messagePart The cooked message part to process.
* @param rawMessagePart The raw message part to check.
* @returns the message part with the placeholder name stripped, if found.
* @throws an error if the block is unterminated
*/
function stripBlock(messagePart: string, rawMessagePart: string) {
return rawMessagePart.charAt(0) === BLOCK_MARKER
? messagePart.substring(findEndOfBlock(messagePart, rawMessagePart) + 1)
: messagePart;
}
| {
"end_byte": 6324,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/src/localize/src/localize.ts"
} |
angular/packages/common/PACKAGE.md_0_344 | Implements fundamental Angular framework functionality, including directives and pipes, location services used in routing, HTTP services, localization support, and so on.
The `CommonModule` exports are re-exported by `BrowserModule`, which is included automatically in the root `AppModule` when you create a new app with the CLI `new` command. | {
"end_byte": 344,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/PACKAGE.md"
} |
angular/packages/common/BUILD.bazel_0_3166 | load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/common/locales:index.bzl", "generate_base_currencies_file")
load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package")
package(default_visibility = ["//visibility:public"])
# This generates the `src/i18n/currencies.ts` file through the `generate-locales` tool. Since
# the base currencies file is checked-in for Google3, we add a `generated_file_test` to ensure
# the checked-in file is up-to-date. To disambiguate from the test, we use a more precise target
# name here.
generate_base_currencies_file(
name = "base_currencies_file_generated",
output_file = "base_currencies_generated.ts",
)
generated_file_test(
name = "base_currencies_file",
src = "src/i18n/currencies.ts",
generated = ":base_currencies_file_generated",
)
ng_module(
name = "common",
package_name = "@angular/common",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/core",
"@npm//rxjs",
],
)
ng_package(
name = "npm_package",
srcs = [
"package.json",
],
nested_packages = ["//packages/common/locales:package"],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//adev:__pkg__",
"//adev/shared-docs:__subpackages__",
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
"//packages/bazel/test/ng_package:__pkg__",
"//packages/compiler-cli/integrationtest:__pkg__",
"//packages/compiler-cli/test:__pkg__",
"//packages/compiler-cli/test/diagnostics:__pkg__",
"//packages/compiler-cli/test/transformers:__pkg__",
"//packages/compiler/test:__pkg__",
"//packages/language-service/test:__pkg__",
],
deps = [
"//packages/common",
"//packages/common/http",
"//packages/common/http/testing",
"//packages/common/testing",
"//packages/common/upgrade",
],
)
api_golden_test_npm_package(
name = "common_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/common",
npm_package = "angular/packages/common/npm_package",
)
api_golden_test(
name = "common_errors",
data = [
"//goldens:public-api",
"//packages/common",
],
entry_point = "angular/packages/common/src/errors.d.ts",
golden = "angular/goldens/public-api/common/errors.api.md",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "common_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/platform-browser:files_for_docgen",
"//packages/platform-browser-dynamic:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/common",
)
| {
"end_byte": 3166,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/BUILD.bazel"
} |
angular/packages/common/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/index.ts"
} |
angular/packages/common/public_api.ts_0_397 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/common';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/public_api.ts"
} |
angular/packages/common/upgrade/PACKAGE.md_0_197 | Provides tools for upgrading from the `$location` service provided in AngularJS
to Angular's [unified location service](https://angular.io/guide/upgrade#using-the-unified-angular-location-service). | {
"end_byte": 197,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/PACKAGE.md"
} |
angular/packages/common/upgrade/BUILD.bazel_0_783 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "upgrade",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/common",
"//packages/core",
"//packages/upgrade",
"//packages/upgrade/static",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "common_upgrade_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/common/upgrade",
)
| {
"end_byte": 783,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/BUILD.bazel"
} |
angular/packages/common/upgrade/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/index.ts"
} |
angular/packages/common/upgrade/public_api.ts_0_396 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/index';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 396,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/public_api.ts"
} |
angular/packages/common/upgrade/test/upgrade.spec.ts_0_5314 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, PathLocationStrategy} from '@angular/common';
import {inject, TestBed} from '@angular/core/testing';
import {UpgradeModule} from '@angular/upgrade/static';
import {$locationShim} from '../src/location_shim';
import {LocationUpgradeTestModule} from './upgrade_location_test_module';
export class MockUpgradeModule {
$injector = {
get(key: string) {
if (key === '$rootScope') {
return new $rootScopeMock();
} else {
throw new Error(`Unsupported mock service requested: ${key}`);
}
},
};
}
export function injectorFactory() {
const rootScopeMock = new $rootScopeMock();
const rootElementMock = {on: () => undefined};
return function $injectorGet(provider: string) {
if (provider === '$rootScope') {
return rootScopeMock;
} else if (provider === '$rootElement') {
return rootElementMock;
} else {
throw new Error(`Unsupported injectable mock: ${provider}`);
}
};
}
export class $rootScopeMock {
private watchers: any[] = [];
private events: {[k: string]: any[]} = {};
runWatchers() {
this.watchers.forEach((fn) => fn());
}
$watch(fn: any) {
this.watchers.push(fn);
}
$broadcast(evt: string, ...args: any[]) {
if (this.events[evt]) {
this.events[evt].forEach((fn) => {
fn.apply(fn, args);
});
}
return {
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
};
}
$on(evt: string, fn: any) {
this.events[evt] ||= [];
this.events[evt].push(fn);
}
$evalAsync(fn: any) {
fn();
}
}
describe('LocationProvider', () => {
let upgradeModule: UpgradeModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [LocationUpgradeTestModule.config()],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
});
it('should instantiate LocationProvider', inject([$locationShim], ($location: $locationShim) => {
expect($location).toBeDefined();
expect($location instanceof $locationShim).toBe(true);
}));
});
describe('LocationHtml5Url', function () {
let $location: $locationShim;
let upgradeModule: UpgradeModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
LocationUpgradeTestModule.config({
useHash: false,
appBaseHref: '/pre',
startUrl: 'http://server',
}),
],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
});
beforeEach(inject([$locationShim], (loc: $locationShim) => {
$location = loc;
}));
it('should set the URL', () => {
$location.url('');
expect($location.absUrl()).toBe('http://server/pre/');
$location.url('/test');
expect($location.absUrl()).toBe('http://server/pre/test');
$location.url('test');
expect($location.absUrl()).toBe('http://server/pre/test');
$location.url('/somewhere?something=1#hash_here');
expect($location.absUrl()).toBe('http://server/pre/somewhere?something=1#hash_here');
});
it('should rewrite regular URL', () => {
expect(parseLinkAndReturn($location, 'http://other')).toEqual(undefined);
expect(parseLinkAndReturn($location, 'http://server/pre')).toEqual('http://server/pre/');
expect(parseLinkAndReturn($location, 'http://server/pre/')).toEqual('http://server/pre/');
expect(parseLinkAndReturn($location, 'http://server/pre/otherPath')).toEqual(
'http://server/pre/otherPath',
);
// Note: relies on the previous state!
expect(parseLinkAndReturn($location, 'someIgnoredAbsoluteHref', '#test')).toEqual(
'http://server/pre/otherPath#test',
);
});
it('should rewrite index URL', () => {
// Reset hostname url and hostname
$location.$$parseLinkUrl('http://server/pre/index.html');
expect($location.absUrl()).toEqual('http://server/pre/');
expect(parseLinkAndReturn($location, 'http://server/pre')).toEqual('http://server/pre/');
expect(parseLinkAndReturn($location, 'http://server/pre/')).toEqual('http://server/pre/');
expect(parseLinkAndReturn($location, 'http://server/pre/otherPath')).toEqual(
'http://server/pre/otherPath',
);
// Note: relies on the previous state!
expect(parseLinkAndReturn($location, 'someIgnoredAbsoluteHref', '#test')).toEqual(
'http://server/pre/otherPath#test',
);
});
it('should complain if the path starts with double slashes', function () {
expect(function () {
parseLinkAndReturn($location, 'http://server/pre///other/path');
}).toThrow();
expect(function () {
parseLinkAndReturn($location, 'http://server/pre/\\\\other/path');
}).toThrow();
expect(function () {
parseLinkAndReturn($location, 'http://server/pre//\\//other/path');
}).toThrow();
});
it('should support state', function () {
expect($location.state({a: 2}).state()).toEqual({a: 2});
});
}); | {
"end_byte": 5314,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/upgrade.spec.ts"
} |
angular/packages/common/upgrade/test/upgrade.spec.ts_5316_12797 | describe('NewUrl', function () {
let $location: $locationShim;
let upgradeModule: UpgradeModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
LocationUpgradeTestModule.config({useHash: false, startUrl: 'http://www.domain.com:9877'}),
],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
});
beforeEach(inject([$locationShim], (loc: $locationShim) => {
$location = loc;
}));
// Sets the default most of these tests rely on
function setupUrl(url = '/path/b?search=a&b=c&d#hash') {
$location.url(url);
}
it('should provide common getters', function () {
setupUrl();
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#hash');
expect($location.protocol()).toBe('http');
expect($location.host()).toBe('www.domain.com');
expect($location.port()).toBe(9877);
expect($location.path()).toBe('/path/b');
expect($location.search()).toEqual({search: 'a', b: 'c', d: true});
expect($location.hash()).toBe('hash');
expect($location.url()).toBe('/path/b?search=a&b=c&d#hash');
});
it('path() should change path', function () {
setupUrl();
$location.path('/new/path');
expect($location.path()).toBe('/new/path');
expect($location.absUrl()).toBe('http://www.domain.com:9877/new/path?search=a&b=c&d#hash');
});
it('path() should not break on numeric values', function () {
setupUrl();
$location.path(1);
expect($location.path()).toBe('/1');
expect($location.absUrl()).toBe('http://www.domain.com:9877/1?search=a&b=c&d#hash');
});
it('path() should allow using 0 as path', function () {
setupUrl();
$location.path(0);
expect($location.path()).toBe('/0');
expect($location.absUrl()).toBe('http://www.domain.com:9877/0?search=a&b=c&d#hash');
});
it('path() should set to empty path on null value', function () {
setupUrl();
$location.path('/foo');
expect($location.path()).toBe('/foo');
$location.path(null);
expect($location.path()).toBe('/');
});
it('search() should accept string', function () {
setupUrl();
$location.search('x=y&c');
expect($location.search()).toEqual({x: 'y', c: true});
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?x=y&c#hash');
});
it('search() should accept object', function () {
setupUrl();
$location.search({one: 1, two: true});
expect($location.search()).toEqual({one: 1, two: true});
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?one=1&two#hash');
});
it('search() should copy object', function () {
setupUrl();
let obj = {one: 1, two: true, three: null};
$location.search(obj);
expect(obj).toEqual({one: 1, two: true, three: null});
obj.one = 100; // changed value
expect($location.search()).toEqual({one: 1, two: true});
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?one=1&two#hash');
});
it('search() should change single parameter', function () {
setupUrl();
$location.search({id: 'old', preserved: true});
$location.search('id', 'new');
expect($location.search()).toEqual({id: 'new', preserved: true});
});
it('search() should remove single parameter', function () {
setupUrl();
$location.search({id: 'old', preserved: true});
$location.search('id', null);
expect($location.search()).toEqual({preserved: true});
});
it('search() should remove multiple parameters', function () {
setupUrl();
$location.search({one: 1, two: true});
expect($location.search()).toEqual({one: 1, two: true});
$location.search({one: null, two: null});
expect($location.search()).toEqual({});
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b#hash');
});
it('search() should accept numeric keys', function () {
setupUrl();
$location.search({1: 'one', 2: 'two'});
expect($location.search()).toEqual({'1': 'one', '2': 'two'});
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?1=one&2=two#hash');
});
it('search() should handle multiple value', function () {
setupUrl();
$location.search('a&b');
expect($location.search()).toEqual({a: true, b: true});
$location.search('a', null);
expect($location.search()).toEqual({b: true});
$location.search('b', undefined);
expect($location.search()).toEqual({});
});
it('search() should handle single value', function () {
setupUrl();
$location.search('ignore');
expect($location.search()).toEqual({ignore: true});
$location.search(1);
expect($location.search()).toEqual({1: true});
});
it('search() should throw error an incorrect argument', function () {
expect(() => {
$location.search(null as any);
}).toThrowError('LocationProvider.search(): First argument must be a string or an object.');
expect(function () {
$location.search(undefined as any);
}).toThrowError('LocationProvider.search(): First argument must be a string or an object.');
});
it('hash() should change hash fragment', function () {
setupUrl();
$location.hash('new-hash');
expect($location.hash()).toBe('new-hash');
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#new-hash');
});
it('hash() should accept numeric parameter', function () {
setupUrl();
$location.hash(5);
expect($location.hash()).toBe('5');
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#5');
});
it('hash() should allow using 0', function () {
setupUrl();
$location.hash(0);
expect($location.hash()).toBe('0');
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#0');
});
it('hash() should accept null parameter', function () {
setupUrl();
$location.hash(null);
expect($location.hash()).toBe('');
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d');
});
it('url() should change the path, search and hash', function () {
setupUrl();
$location.url('/some/path?a=b&c=d#hhh');
expect($location.url()).toBe('/some/path?a=b&c=d#hhh');
expect($location.absUrl()).toBe('http://www.domain.com:9877/some/path?a=b&c=d#hhh');
expect($location.path()).toBe('/some/path');
expect($location.search()).toEqual({a: 'b', c: 'd'});
expect($location.hash()).toBe('hhh');
});
it('url() should change only hash when no search and path specified', function () {
setupUrl();
$location.url('#some-hash');
expect($location.hash()).toBe('some-hash');
expect($location.url()).toBe('/path/b?search=a&b=c&d#some-hash');
expect($location.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#some-hash');
});
it('url() should change only search and hash when no path specified', function () {
setupUrl();
$location.url('?a=b');
expect($location.search()).toEqual({a: 'b'});
expect($location.hash()).toBe('');
expect($location.path()).toBe('/path/b');
});
it('url() should reset search and hash when only path specified', function () {
setupUrl();
$location.url('/new/path');
expect($location.path()).toBe('/new/path');
expect($location.search()).toEqual({});
expect($location.hash()).toBe('');
}); | {
"end_byte": 12797,
"start_byte": 5316,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/upgrade.spec.ts"
} |
angular/packages/common/upgrade/test/upgrade.spec.ts_12801_20571 | it('url() should change path when empty string specified', function () {
setupUrl();
$location.url('');
expect($location.path()).toBe('/');
expect($location.search()).toEqual({});
expect($location.hash()).toBe('');
});
it('replace should set $$replace flag and return itself', function () {
expect(($location as any).$$replace).toBe(false);
$location.replace();
expect(($location as any).$$replace).toBe(true);
expect($location.replace()).toBe($location);
});
describe('encoding', function () {
it('should encode special characters', function () {
$location.path('/a <>#');
$location.search({'i j': '<>#'});
$location.hash('<>#');
expect($location.path()).toBe('/a <>#');
expect($location.search()).toEqual({'i j': '<>#'});
expect($location.hash()).toBe('<>#');
expect($location.absUrl()).toBe(
'http://www.domain.com:9877/a%20%3C%3E%23?i%20j=%3C%3E%23#%3C%3E%23',
);
});
it('should not encode !$:@', function () {
$location.path('/!$:@');
$location.search('');
$location.hash('!$:@');
expect($location.absUrl()).toBe('http://www.domain.com:9877/!$:@#!$:@');
});
it('should decode special characters', function () {
$location.$$parse('http://www.domain.com:9877/a%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
expect($location.path()).toBe('/a <>#');
expect($location.search()).toEqual({'i j': '<>#'});
expect($location.hash()).toBe('x <>#');
});
it('should not decode encoded forward slashes in the path', function () {
$location.$$parse('http://www.domain.com:9877/a/ng2;path=%2Fsome%2Fpath');
expect($location.path()).toBe('/a/ng2;path=%2Fsome%2Fpath');
expect($location.search()).toEqual({});
expect($location.hash()).toBe('');
expect($location.url()).toBe('/a/ng2;path=%2Fsome%2Fpath');
expect($location.absUrl()).toBe('http://www.domain.com:9877/a/ng2;path=%2Fsome%2Fpath');
});
it('should decode pluses as spaces in urls', function () {
$location.$$parse('http://www.domain.com:9877/?a+b=c+d');
expect($location.search()).toEqual({'a b': 'c d'});
});
it('should retain pluses when setting search queries', function () {
$location.search({'a+b': 'c+d'});
expect($location.search()).toEqual({'a+b': 'c+d'});
});
});
it('should not preserve old properties when parsing new url', function () {
$location.$$parse('http://www.domain.com:9877/a');
expect($location.path()).toBe('/a');
expect($location.search()).toEqual({});
expect($location.hash()).toBe('');
expect($location.absUrl()).toBe('http://www.domain.com:9877/a');
});
});
describe('New URL Parsing', () => {
let $location: $locationShim;
let upgradeModule: UpgradeModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
LocationUpgradeTestModule.config({
useHash: false,
appBaseHref: '/base',
startUrl: 'http://server',
}),
],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
});
beforeEach(inject([$locationShim], (loc: $locationShim) => {
$location = loc;
}));
it('should prepend path with basePath', function () {
$location.$$parse('http://server/base/abc?a');
expect($location.path()).toBe('/abc');
expect($location.search()).toEqual({a: true});
$location.path('/new/path');
expect($location.absUrl()).toBe('http://server/base/new/path?a');
});
});
describe('New URL Parsing', () => {
let $location: $locationShim;
let upgradeModule: UpgradeModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
LocationUpgradeTestModule.config({useHash: false, startUrl: 'http://host.com/'}),
],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
});
beforeEach(inject([$locationShim], (loc: $locationShim) => {
$location = loc;
}));
it('should parse new url', function () {
$location.$$parse('http://host.com/base');
expect($location.path()).toBe('/base');
});
it('should parse new url with #', function () {
$location.$$parse('http://host.com/base#');
expect($location.path()).toBe('/base');
});
it('should prefix path with forward-slash', function () {
$location.path('b');
expect($location.path()).toBe('/b');
expect($location.absUrl()).toBe('http://host.com/b');
});
it('should set path to forward-slash when empty', function () {
$location.$$parse('http://host.com/');
expect($location.path()).toBe('/');
expect($location.absUrl()).toBe('http://host.com/');
});
it('setters should return Url object to allow chaining', function () {
expect($location.path('/any')).toBe($location);
expect($location.search('')).toBe($location);
expect($location.hash('aaa')).toBe($location);
expect($location.url('/some')).toBe($location);
});
it('should throw error when invalid server url given', function () {
expect(function () {
$location.$$parse('http://other.server.org/path#/path');
}).toThrowError(
'Invalid url "http://other.server.org/path#/path", missing path prefix "http://host.com/".',
);
});
describe('state', function () {
let mock$rootScope: $rootScopeMock;
beforeEach(inject([UpgradeModule], (ngUpgrade: UpgradeModule) => {
mock$rootScope = ngUpgrade.$injector.get('$rootScope');
}));
it('should set $$state and return itself', function () {
expect(($location as any).$$state).toEqual(null);
let returned = $location.state({a: 2});
expect(($location as any).$$state).toEqual({a: 2});
expect(returned).toBe($location);
});
it('should set state', function () {
$location.state({a: 2});
expect($location.state()).toEqual({a: 2});
});
it('should allow to set both URL and state', function () {
$location.url('/foo').state({a: 2});
expect($location.url()).toEqual('/foo');
expect($location.state()).toEqual({a: 2});
});
it('should allow to mix state and various URL functions', function () {
$location.path('/foo').hash('abcd').state({a: 2}).search('bar', 'baz');
expect($location.path()).toEqual('/foo');
expect($location.state()).toEqual({a: 2});
expect($location.search() && $location.search()['bar']).toBe('baz');
expect($location.hash()).toEqual('abcd');
});
it('should always have the same value by reference until the value is changed', function () {
expect(($location as any).$$state).toEqual(null);
expect($location.state()).toEqual(null);
const stateValue = {foo: 'bar'};
$location.state(stateValue);
expect($location.state()).toBe(stateValue);
mock$rootScope.runWatchers();
const testState = $location.state();
// $location.state() should equal by reference
expect($location.state()).toEqual(stateValue);
expect($location.state()).toBe(testState);
mock$rootScope.runWatchers();
expect($location.state()).toBe(testState);
mock$rootScope.runWatchers();
expect($location.state()).toBe(testState);
// Confirm updating other values doesn't change the value of `state`
$location.path('/new');
expect($location.state()).toBe(testState);
mock$rootScope.runWatchers();
// After watchers have been run, location should be updated and `state` should change
expect($location.state()).toBe(null);
});
});
}); | {
"end_byte": 20571,
"start_byte": 12801,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/upgrade.spec.ts"
} |
angular/packages/common/upgrade/test/upgrade.spec.ts_20573_24265 | describe('$location.onChange()', () => {
let $location: $locationShim;
let upgradeModule: UpgradeModule;
let mock$rootScope: $rootScopeMock;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
LocationUpgradeTestModule.config({useHash: false, startUrl: 'http://host.com/'}),
],
providers: [UpgradeModule],
});
upgradeModule = TestBed.inject(UpgradeModule);
upgradeModule.$injector = {get: injectorFactory()};
mock$rootScope = upgradeModule.$injector.get('$rootScope');
});
beforeEach(inject([$locationShim], (loc: $locationShim) => {
$location = loc;
}));
it('should have onChange method', () => {
expect(typeof $location.onChange).toBe('function');
});
it('should add registered functions to changeListeners', () => {
function changeListener(url: string, state: unknown) {
return undefined;
}
function errorHandler(e: Error) {}
expect(($location as any).$$changeListeners.length).toBe(0);
$location.onChange(changeListener, errorHandler);
expect(($location as any).$$changeListeners.length).toBe(1);
expect(($location as any).$$changeListeners[0][0]).toEqual(changeListener);
expect(($location as any).$$changeListeners[0][1]).toEqual(errorHandler);
});
it('should call changeListeners when URL is updated', () => {
const onChangeVals = {
url: 'url',
state: 'state' as unknown,
oldUrl: 'oldUrl',
oldState: 'oldState' as unknown,
};
function changeListener(url: string, state: unknown, oldUrl: string, oldState: unknown) {
onChangeVals.url = url;
onChangeVals.state = state;
onChangeVals.oldUrl = oldUrl;
onChangeVals.oldState = oldState;
}
$location.onChange(changeListener);
const newState = {foo: 'bar'};
$location.state(newState);
$location.path('/newUrl');
mock$rootScope.runWatchers();
expect(onChangeVals.url).toBe('/newUrl');
expect(onChangeVals.state).toEqual(newState);
expect(onChangeVals.oldUrl).toBe('http://host.com');
expect(onChangeVals.oldState).toBe(null);
});
it('should call changeListeners after $locationChangeSuccess', () => {
let changeListenerCalled = false;
let locationChangeSuccessEmitted = false;
function changeListener(url: string, state: unknown, oldUrl: string, oldState: unknown) {
changeListenerCalled = true;
}
$location.onChange(changeListener);
mock$rootScope.$on('$locationChangeSuccess', () => {
// Ensure that the changeListener hasn't been called yet
expect(changeListenerCalled).toBe(false);
locationChangeSuccessEmitted = true;
});
// Update state and run watchers
const stateValue = {foo: 'bar'};
$location.state(stateValue);
mock$rootScope.runWatchers();
// Ensure that change listeners are called and location events are emitted
expect(changeListenerCalled).toBe(true);
expect(locationChangeSuccessEmitted).toBe(true);
});
it('should call forward errors to error handler', () => {
let error!: Error;
function changeListener(url: string, state: unknown, oldUrl: string, oldState: unknown) {
throw new Error('Handle error');
}
function errorHandler(e: Error) {
error = e;
}
$location.onChange(changeListener, errorHandler);
$location.url('/newUrl');
mock$rootScope.runWatchers();
expect(error.message).toBe('Handle error');
});
});
function parseLinkAndReturn(location: $locationShim, toUrl: string, relHref?: string) {
const resetUrl = location.$$parseLinkUrl(toUrl, relHref);
return (resetUrl && location.absUrl()) || undefined;
} | {
"end_byte": 24265,
"start_byte": 20573,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/upgrade.spec.ts"
} |
angular/packages/common/upgrade/test/upgrade_location_test_module.ts_0_3109 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
APP_BASE_HREF,
CommonModule,
Location,
LocationStrategy,
PlatformLocation,
} from '@angular/common';
import {MockPlatformLocation} from '@angular/common/testing';
import {Inject, InjectionToken, ModuleWithProviders, NgModule, Optional} from '@angular/core';
import {UpgradeModule} from '@angular/upgrade/static';
import {$locationShim, $locationShimProvider} from '../src/location_shim';
import {LocationUpgradeModule} from '../src/location_upgrade_module';
import {UrlCodec} from '../src/params';
export interface LocationUpgradeTestingConfig {
useHash?: boolean;
hashPrefix?: string;
urlCodec?: typeof UrlCodec;
startUrl?: string;
appBaseHref?: string;
}
/**
* @description
*
* Is used in DI to configure the router.
*
* @publicApi
*/
export const LOC_UPGRADE_TEST_CONFIG = new InjectionToken<LocationUpgradeTestingConfig>(
'LOC_UPGRADE_TEST_CONFIG',
);
export const APP_BASE_HREF_RESOLVED = new InjectionToken<string>('APP_BASE_HREF_RESOLVED');
/**
* Module used for configuring Angular's LocationUpgradeService.
*/
@NgModule({imports: [CommonModule]})
export class LocationUpgradeTestModule {
static config(
config?: LocationUpgradeTestingConfig,
): ModuleWithProviders<LocationUpgradeTestModule> {
return {
ngModule: LocationUpgradeTestModule,
providers: [
{provide: LOC_UPGRADE_TEST_CONFIG, useValue: config || {}},
{
provide: PlatformLocation,
useFactory: (appBaseHref?: string) => {
if (config && config.appBaseHref != null) {
appBaseHref = config.appBaseHref;
}
appBaseHref ??= '';
return new MockPlatformLocation({
startUrl: config && config.startUrl,
appBaseHref: appBaseHref,
});
},
deps: [[new Inject(APP_BASE_HREF), new Optional()]],
},
{
provide: $locationShim,
useFactory: provide$location,
deps: [
UpgradeModule,
Location,
PlatformLocation,
UrlCodec,
LocationStrategy,
LOC_UPGRADE_TEST_CONFIG,
],
},
LocationUpgradeModule.config({
appBaseHref: config && config.appBaseHref,
useHash: (config && config.useHash) || false,
}).providers!,
],
};
}
}
export function provide$location(
ngUpgrade: UpgradeModule,
location: Location,
platformLocation: PlatformLocation,
urlCodec: UrlCodec,
locationStrategy: LocationStrategy,
config?: LocationUpgradeTestingConfig,
) {
const $locationProvider = new $locationShimProvider(
ngUpgrade,
location,
platformLocation,
urlCodec,
locationStrategy,
);
$locationProvider.hashPrefix(config && config.hashPrefix);
$locationProvider.html5Mode(config && !config.useHash);
return $locationProvider.$get();
}
| {
"end_byte": 3109,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/upgrade_location_test_module.ts"
} |
angular/packages/common/upgrade/test/params.spec.ts_0_2883 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AngularJSUrlCodec} from '../src/params';
describe('AngularJSUrlCodec', () => {
const codec = new AngularJSUrlCodec();
describe('parse', () => {
it('should parse a complex URL', () => {
const result = codec.parse('http://server.com:1234/foo?bar=true#heading');
expect(result.href).toBe('http://server.com:1234/foo?bar=true#heading');
expect(result.protocol).toBe('http');
expect(result.host).toBe('server.com:1234');
expect(result.search).toBe('bar=true');
expect(result.hash).toBe('heading');
expect(result.hostname).toBe('server.com');
expect(result.port).toBe('1234');
expect(result.pathname).toBe('/foo');
});
it('should parse a URL without search', () => {
const result = codec.parse('http://server.com:1234/foo#heading');
expect(result.href).toBe('http://server.com:1234/foo#heading');
expect(result.search).toBe('');
expect(result.hash).toBe('heading');
expect(result.pathname).toBe('/foo');
});
it('should parse a URL without hash', () => {
const result = codec.parse('http://server.com:1234/foo?bar=true');
expect(result.href).toBe('http://server.com:1234/foo?bar=true');
expect(result.search).toBe('bar=true');
expect(result.hash).toBe('');
expect(result.pathname).toBe('/foo');
});
it('should parse a basic URL', () => {
const result = codec.parse('http://server.com');
expect(result.href).toBe('http://server.com/');
expect(result.protocol).toBe('http');
expect(result.host).toBe('server.com');
expect(result.search).toBe('');
expect(result.hash).toBe('');
expect(result.hostname).toBe('server.com');
expect(result.port).toBe('');
expect(result.pathname).toBe('/');
});
it('should apply a base', () => {
const withoutSlash = codec.parse('foo/bar', 'http://abc.xyz');
expect(withoutSlash.href).toBe('http://abc.xyz/foo/bar');
const withSlash = codec.parse('/foo/bar', 'http://abc.xyz/');
expect(withSlash.href).toBe('http://abc.xyz/foo/bar');
});
it('should ignore an empty base', () => {
const result = codec.parse('http://abc.xyz', '');
expect(result.href).toBe('http://abc.xyz/');
});
it('should throw an error for an invalid URL', () => {
expect(() => {
codec.parse('/foo/bar');
}).toThrowError('Invalid URL (/foo/bar) with base (undefined)');
});
it('should throw an error for an invalid base', () => {
expect(() => {
codec.parse('http://foo.bar', 'abc');
}).toThrowError('Invalid URL (http://foo.bar) with base (abc)');
});
});
});
| {
"end_byte": 2883,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/params.spec.ts"
} |
angular/packages/common/upgrade/test/BUILD.bazel_0_745 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/common/upgrade/index.mjs",
deps = ["//packages/common/upgrade"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages/common",
"//packages/common/testing",
"//packages/common/upgrade",
"//packages/core",
"//packages/core/testing",
"//packages/upgrade/static",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
| {
"end_byte": 745,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/test/BUILD.bazel"
} |
angular/packages/common/upgrade/src/location_shim.ts_0_1008 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Location, LocationStrategy, PlatformLocation} from '@angular/common';
import {ɵisPromise as isPromise} from '@angular/core';
import {UpgradeModule} from '@angular/upgrade/static';
import {ReplaySubject} from 'rxjs';
import {UrlCodec} from './params';
import {deepEqual, isAnchor} from './utils';
const PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/;
const DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
const IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
const DEFAULT_PORTS: {[key: string]: number} = {
'http:': 80,
'https:': 443,
'ftp:': 21,
};
/**
* Location service that provides a drop-in replacement for the $location service
* provided in AngularJS.
*
* @see [Using the Angular Unified Location Service](guide/upgrade#using-the-unified-angular-location-service)
*
* @publicApi
*/
| {
"end_byte": 1008,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/location_shim.ts"
} |
angular/packages/common/upgrade/src/location_shim.ts_1009_9691 | xport class $locationShim {
private initializing = true;
private updateBrowser = false;
private $$absUrl: string = '';
private $$url: string = '';
private $$protocol: string;
private $$host: string = '';
private $$port: number | null;
private $$replace: boolean = false;
private $$path: string = '';
private $$search: any = '';
private $$hash: string = '';
private $$state: unknown;
private $$changeListeners: [
(
url: string,
state: unknown,
oldUrl: string,
oldState: unknown,
err?: (e: Error) => void,
) => void,
(e: Error) => void,
][] = [];
private cachedState: unknown = null;
private urlChanges = new ReplaySubject<{newUrl: string; newState: unknown}>(1);
constructor(
$injector: any,
private location: Location,
private platformLocation: PlatformLocation,
private urlCodec: UrlCodec,
private locationStrategy: LocationStrategy,
) {
const initialUrl = this.browserUrl();
let parsedUrl = this.urlCodec.parse(initialUrl);
if (typeof parsedUrl === 'string') {
throw 'Invalid URL';
}
this.$$protocol = parsedUrl.protocol;
this.$$host = parsedUrl.hostname;
this.$$port = parseInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
this.$$parseLinkUrl(initialUrl, initialUrl);
this.cacheState();
this.$$state = this.browserState();
this.location.onUrlChange((newUrl, newState) => {
this.urlChanges.next({newUrl, newState});
});
if (isPromise($injector)) {
$injector.then(($i) => this.initialize($i));
} else {
this.initialize($injector);
}
}
private initialize($injector: any) {
const $rootScope = $injector.get('$rootScope');
const $rootElement = $injector.get('$rootElement');
$rootElement.on('click', (event: any) => {
if (
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
event.which === 2 ||
event.button === 2
) {
return;
}
let elm: (Node & ParentNode) | null = event.target;
// traverse the DOM up to find first A tag
while (elm && elm.nodeName.toLowerCase() !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm === $rootElement[0] || !(elm = elm.parentNode)) {
return;
}
}
if (!isAnchor(elm)) {
return;
}
const absHref = elm.href;
const relHref = elm.getAttribute('href');
// Ignore when url is started with javascript: or mailto:
if (IGNORE_URI_REGEXP.test(absHref)) {
return;
}
if (absHref && !elm.getAttribute('target') && !event.isDefaultPrevented()) {
if (this.$$parseLinkUrl(absHref, relHref)) {
// We do a preventDefault for all urls that are part of the AngularJS application,
// in html5mode and also without, so that we are able to abort navigation without
// getting double entries in the location history.
event.preventDefault();
// update location manually
if (this.absUrl() !== this.browserUrl()) {
$rootScope.$apply();
}
}
}
});
this.urlChanges.subscribe(({newUrl, newState}) => {
const oldUrl = this.absUrl();
const oldState = this.$$state;
this.$$parse(newUrl);
newUrl = this.absUrl();
this.$$state = newState;
const defaultPrevented = $rootScope.$broadcast(
'$locationChangeStart',
newUrl,
oldUrl,
newState,
oldState,
).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if (this.absUrl() !== newUrl) return;
// If default was prevented, set back to old state. This is the state that was locally
// cached in the $location service.
if (defaultPrevented) {
this.$$parse(oldUrl);
this.state(oldState);
this.setBrowserUrlWithFallback(oldUrl, false, oldState);
this.$$notifyChangeListeners(this.url(), this.$$state, oldUrl, oldState);
} else {
this.initializing = false;
$rootScope.$broadcast('$locationChangeSuccess', newUrl, oldUrl, newState, oldState);
this.resetBrowserUpdate();
}
if (!$rootScope.$$phase) {
$rootScope.$digest();
}
});
// update browser
$rootScope.$watch(() => {
if (this.initializing || this.updateBrowser) {
this.updateBrowser = false;
const oldUrl = this.browserUrl();
const newUrl = this.absUrl();
const oldState = this.browserState();
let currentReplace = this.$$replace;
const urlOrStateChanged =
!this.urlCodec.areEqual(oldUrl, newUrl) || oldState !== this.$$state;
// Fire location changes one time to on initialization. This must be done on the
// next tick (thus inside $evalAsync()) in order for listeners to be registered
// before the event fires. Mimicing behavior from $locationWatch:
// https://github.com/angular/angular.js/blob/master/src/ng/location.js#L983
if (this.initializing || urlOrStateChanged) {
this.initializing = false;
$rootScope.$evalAsync(() => {
// Get the new URL again since it could have changed due to async update
const newUrl = this.absUrl();
const defaultPrevented = $rootScope.$broadcast(
'$locationChangeStart',
newUrl,
oldUrl,
this.$$state,
oldState,
).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if (this.absUrl() !== newUrl) return;
if (defaultPrevented) {
this.$$parse(oldUrl);
this.$$state = oldState;
} else {
// This block doesn't run when initializing because it's going to perform the update
// to the URL which shouldn't be needed when initializing.
if (urlOrStateChanged) {
this.setBrowserUrlWithFallback(
newUrl,
currentReplace,
oldState === this.$$state ? null : this.$$state,
);
this.$$replace = false;
}
$rootScope.$broadcast(
'$locationChangeSuccess',
newUrl,
oldUrl,
this.$$state,
oldState,
);
if (urlOrStateChanged) {
this.$$notifyChangeListeners(this.url(), this.$$state, oldUrl, oldState);
}
}
});
}
}
this.$$replace = false;
});
}
private resetBrowserUpdate() {
this.$$replace = false;
this.$$state = this.browserState();
this.updateBrowser = false;
this.lastBrowserUrl = this.browserUrl();
}
private lastHistoryState: unknown;
private lastBrowserUrl: string = '';
private browserUrl(): string;
private browserUrl(url: string, replace?: boolean, state?: unknown): this;
private browserUrl(url?: string, replace?: boolean, state?: unknown) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (typeof state === 'undefined') {
state = null;
}
// setter
if (url) {
let sameState = this.lastHistoryState === state;
// Normalize the inputted URL
url = this.urlCodec.parse(url).href;
// Don't change anything if previous and current URLs and states match.
if (this.lastBrowserUrl === url && sameState) {
return this;
}
this.lastBrowserUrl = url;
this.lastHistoryState = state;
// Remove server base from URL as the Angular APIs for updating URL require
// it to be the path+.
url = this.stripBaseUrl(this.getServerBase(), url) || url;
// Set the URL
if (replace) {
this.locationStrategy.replaceState(state, '', url, '');
} else {
this.locationStrategy.pushState(state, '', url, '');
}
this.cacheState();
return this;
// getter
} else {
return this.platformLocation.href;
}
}
// This variable should be used *only* inside the cacheState function.
private lastCachedState: unknown = null;
| {
"end_byte": 9691,
"start_byte": 1009,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/location_shim.ts"
} |
angular/packages/common/upgrade/src/location_shim.ts_9694_16856 | rivate cacheState() {
// This should be the only place in $browser where `history.state` is read.
this.cachedState = this.platformLocation.getState();
if (typeof this.cachedState === 'undefined') {
this.cachedState = null;
}
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (deepEqual(this.cachedState, this.lastCachedState)) {
this.cachedState = this.lastCachedState;
}
this.lastCachedState = this.cachedState;
this.lastHistoryState = this.cachedState;
}
/**
* This function emulates the $browser.state() function from AngularJS. It will cause
* history.state to be cached unless changed with deep equality check.
*/
private browserState(): unknown {
return this.cachedState;
}
private stripBaseUrl(base: string, url: string) {
if (url.startsWith(base)) {
return url.slice(base.length);
}
return undefined;
}
private getServerBase() {
const {protocol, hostname, port} = this.platformLocation;
const baseHref = this.locationStrategy.getBaseHref();
let url = `${protocol}//${hostname}${port ? ':' + port : ''}${baseHref || '/'}`;
return url.endsWith('/') ? url : url + '/';
}
private parseAppUrl(url: string) {
if (DOUBLE_SLASH_REGEX.test(url)) {
throw new Error(`Bad Path - URL cannot start with double slashes: ${url}`);
}
let prefixed = url.charAt(0) !== '/';
if (prefixed) {
url = '/' + url;
}
let match = this.urlCodec.parse(url, this.getServerBase());
if (typeof match === 'string') {
throw new Error(`Bad URL - Cannot parse URL: ${url}`);
}
let path =
prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
this.$$path = this.urlCodec.decodePath(path);
this.$$search = this.urlCodec.decodeSearch(match.search);
this.$$hash = this.urlCodec.decodeHash(match.hash);
// make sure path starts with '/';
if (this.$$path && this.$$path.charAt(0) !== '/') {
this.$$path = '/' + this.$$path;
}
}
/**
* Registers listeners for URL changes. This API is used to catch updates performed by the
* AngularJS framework. These changes are a subset of the `$locationChangeStart` and
* `$locationChangeSuccess` events which fire when AngularJS updates its internally-referenced
* version of the browser URL.
*
* It's possible for `$locationChange` events to happen, but for the browser URL
* (window.location) to remain unchanged. This `onChange` callback will fire only when AngularJS
* actually updates the browser URL (window.location).
*
* @param fn The callback function that is triggered for the listener when the URL changes.
* @param err The callback function that is triggered when an error occurs.
*/
onChange(
fn: (url: string, state: unknown, oldUrl: string, oldState: unknown) => void,
err: (e: Error) => void = (e: Error) => {},
) {
this.$$changeListeners.push([fn, err]);
}
/** @internal */
$$notifyChangeListeners(
url: string = '',
state: unknown,
oldUrl: string = '',
oldState: unknown,
) {
this.$$changeListeners.forEach(([fn, err]) => {
try {
fn(url, state, oldUrl, oldState);
} catch (e) {
err(e as Error);
}
});
}
/**
* Parses the provided URL, and sets the current URL to the parsed result.
*
* @param url The URL string.
*/
$$parse(url: string) {
let pathUrl: string | undefined;
if (url.startsWith('/')) {
pathUrl = url;
} else {
// Remove protocol & hostname if URL starts with it
pathUrl = this.stripBaseUrl(this.getServerBase(), url);
}
if (typeof pathUrl === 'undefined') {
throw new Error(`Invalid url "${url}", missing path prefix "${this.getServerBase()}".`);
}
this.parseAppUrl(pathUrl);
this.$$path ||= '/';
this.composeUrls();
}
/**
* Parses the provided URL and its relative URL.
*
* @param url The full URL string.
* @param relHref A URL string relative to the full URL string.
*/
$$parseLinkUrl(url: string, relHref?: string | null): boolean {
// When relHref is passed, it should be a hash and is handled separately
if (relHref && relHref[0] === '#') {
this.hash(relHref.slice(1));
return true;
}
let rewrittenUrl;
let appUrl = this.stripBaseUrl(this.getServerBase(), url);
if (typeof appUrl !== 'undefined') {
rewrittenUrl = this.getServerBase() + appUrl;
} else if (this.getServerBase() === url + '/') {
rewrittenUrl = this.getServerBase();
}
// Set the URL
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
}
private setBrowserUrlWithFallback(url: string, replace: boolean, state: unknown) {
const oldUrl = this.url();
const oldState = this.$$state;
try {
this.browserUrl(url, replace, state);
// Make sure $location.state() returns referentially identical (not just deeply equal)
// state object; this makes possible quick checking if the state changed in the digest
// loop. Checking deep equality would be too expensive.
this.$$state = this.browserState();
} catch (e) {
// Restore old values if pushState fails
this.url(oldUrl);
this.$$state = oldState;
throw e;
}
}
private composeUrls() {
this.$$url = this.urlCodec.normalize(this.$$path, this.$$search, this.$$hash);
this.$$absUrl = this.getServerBase() + this.$$url.slice(1); // remove '/' from front of URL
this.updateBrowser = true;
}
/**
* Retrieves the full URL representation with all segments encoded according to
* rules specified in
* [RFC 3986](https://tools.ietf.org/html/rfc3986).
*
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let absUrl = $location.absUrl();
* // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
* ```
*/
absUrl(): string {
return this.$$absUrl;
}
/**
* Retrieves the current URL, or sets a new URL. When setting a URL,
* changes the path, search, and hash, and returns a reference to its own instance.
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let url = $location.url();
* // => "/some/path?foo=bar&baz=xoxo"
* ```
*/
url(): string;
url(url: string): this;
url(url?: string): string | this {
if (typeof url === 'string') {
if (!url.length) {
url = '/';
}
const match = PATH_MATCH.exec(url);
if (!match) return this;
if (match[1] || url === '') this.path(this.urlCodec.decodePath(match[1]));
if (match[2] || match[1] || url === '') this.search(match[3] || '');
this.hash(match[5] || '');
// Chainable method
return this;
}
return this.$$url;
}
/**
* Retrieves the protocol of the current URL.
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let protocol = $location.protocol();
* // => "http"
* ```
*/
protocol(): string {
return this.$$protocol;
}
| {
"end_byte": 16856,
"start_byte": 9694,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/location_shim.ts"
} |
angular/packages/common/upgrade/src/location_shim.ts_16860_24588 | **
* Retrieves the protocol of the current URL.
*
* In contrast to the non-AngularJS version `location.host` which returns `hostname:port`, this
* returns the `hostname` portion only.
*
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let host = $location.host();
* // => "example.com"
*
* // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
* host = $location.host();
* // => "example.com"
* host = location.host;
* // => "example.com:8080"
* ```
*/
host(): string {
return this.$$host;
}
/**
* Retrieves the port of the current URL.
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let port = $location.port();
* // => 80
* ```
*/
port(): number | null {
return this.$$port;
}
/**
* Retrieves the path of the current URL, or changes the path and returns a reference to its own
* instance.
*
* Paths should always begin with forward slash (/). This method adds the forward slash
* if it is missing.
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let path = $location.path();
* // => "/some/path"
* ```
*/
path(): string;
path(path: string | number | null): this;
path(path?: string | number | null): string | this {
if (typeof path === 'undefined') {
return this.$$path;
}
// null path converts to empty string. Prepend with "/" if needed.
path = path !== null ? path.toString() : '';
path = path.charAt(0) === '/' ? path : '/' + path;
this.$$path = path;
this.composeUrls();
return this;
}
/**
* Retrieves a map of the search parameters of the current URL, or changes a search
* part and returns a reference to its own instance.
*
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
* let searchObject = $location.search();
* // => {foo: 'bar', baz: 'xoxo'}
*
* // set foo to 'yipee'
* $location.search('foo', 'yipee');
* // $location.search() => {foo: 'yipee', baz: 'xoxo'}
* ```
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
* hash object.
*
* When called with a single argument the method acts as a setter, setting the `search` component
* of `$location` to the specified value.
*
* If the argument is a hash object containing an array of values, these values will be encoded
* as duplicate search parameters in the URL.
*
* @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number,
* then `paramValue`
* will override only a single search property.
*
* If `paramValue` is an array, it will override the property of the `search` component of
* `$location` specified via the first argument.
*
* If `paramValue` is `null`, the property specified via the first argument will be deleted.
*
* If `paramValue` is `true`, the property specified via the first argument will be added with no
* value nor trailing equal sign.
*
* @return {Object} The parsed `search` object of the current URL, or the changed `search` object.
*/
search(): {[key: string]: unknown};
search(search: string | number | {[key: string]: unknown}): this;
search(
search: string | number | {[key: string]: unknown},
paramValue: null | undefined | string | number | boolean | string[],
): this;
search(
search?: string | number | {[key: string]: unknown},
paramValue?: null | undefined | string | number | boolean | string[],
): {[key: string]: unknown} | this {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (typeof search === 'string' || typeof search === 'number') {
this.$$search = this.urlCodec.decodeSearch(search.toString());
} else if (typeof search === 'object' && search !== null) {
// Copy the object so it's never mutated
search = {...search};
// remove object undefined or null properties
for (const key in search) {
if (search[key] == null) delete search[key];
}
this.$$search = search;
} else {
throw new Error(
'LocationProvider.search(): First argument must be a string or an object.',
);
}
break;
default:
if (typeof search === 'string') {
const currentSearch = this.search();
if (typeof paramValue === 'undefined' || paramValue === null) {
delete currentSearch[search];
return this.search(currentSearch);
} else {
currentSearch[search] = paramValue;
return this.search(currentSearch);
}
}
}
this.composeUrls();
return this;
}
/**
* Retrieves the current hash fragment, or changes the hash fragment and returns a reference to
* its own instance.
*
* ```js
* // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
* let hash = $location.hash();
* // => "hashValue"
* ```
*/
hash(): string;
hash(hash: string | number | null): this;
hash(hash?: string | number | null): string | this {
if (typeof hash === 'undefined') {
return this.$$hash;
}
this.$$hash = hash !== null ? hash.toString() : '';
this.composeUrls();
return this;
}
/**
* Changes to `$location` during the current `$digest` will replace the current
* history record, instead of adding a new one.
*/
replace(): this {
this.$$replace = true;
return this;
}
/**
* Retrieves the history state object when called without any parameter.
*
* Change the history state object when called with one parameter and return `$location`.
* The state object is later passed to `pushState` or `replaceState`.
*
* This method is supported only in HTML5 mode and only in browsers supporting
* the HTML5 History API methods such as `pushState` and `replaceState`. If you need to support
* older browsers (like Android < 4.0), don't use this method.
*
*/
state(): unknown;
state(state: unknown): this;
state(state?: unknown): unknown | this {
if (typeof state === 'undefined') {
return this.$$state;
}
this.$$state = state;
return this;
}
}
/**
* The factory function used to create an instance of the `$locationShim` in Angular,
* and provides an API-compatible `$locationProvider` for AngularJS.
*
* @publicApi
*/
export class $locationShimProvider {
constructor(
private ngUpgrade: UpgradeModule,
private location: Location,
private platformLocation: PlatformLocation,
private urlCodec: UrlCodec,
private locationStrategy: LocationStrategy,
) {}
/**
* Factory method that returns an instance of the $locationShim
*/
$get() {
return new $locationShim(
this.ngUpgrade.$injector,
this.location,
this.platformLocation,
this.urlCodec,
this.locationStrategy,
);
}
/**
* Stub method used to keep API compatible with AngularJS. This setting is configured through
* the LocationUpgradeModule's `config` method in your Angular app.
*/
hashPrefix(prefix?: string) {
throw new Error('Configure LocationUpgrade through LocationUpgradeModule.config method.');
}
/**
* Stub method used to keep API compatible with AngularJS. This setting is configured through
* the LocationUpgradeModule's `config` method in your Angular app.
*/
html5Mode(mode?: any) {
throw new Error('Configure LocationUpgrade through LocationUpgradeModule.config method.');
}
}
| {
"end_byte": 24588,
"start_byte": 16860,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/location_shim.ts"
} |
angular/packages/common/upgrade/src/utils.ts_0_862 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function stripPrefix(val: string, prefix: string): string {
return val.startsWith(prefix) ? val.substring(prefix.length) : val;
}
export function deepEqual(a: any, b: any): boolean {
if (a === b) {
return true;
} else if (!a || !b) {
return false;
} else {
try {
if (a.prototype !== b.prototype || (Array.isArray(a) && Array.isArray(b))) {
return false;
}
return JSON.stringify(a) === JSON.stringify(b);
} catch (e) {
return false;
}
}
}
export function isAnchor(el: (Node & ParentNode) | Element | null): el is HTMLAnchorElement {
return (<HTMLAnchorElement>el).href !== undefined;
}
| {
"end_byte": 862,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/utils.ts"
} |
angular/packages/common/upgrade/src/location_upgrade_module.ts_0_4125 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
APP_BASE_HREF,
CommonModule,
HashLocationStrategy,
Location,
LocationStrategy,
PathLocationStrategy,
PlatformLocation,
} from '@angular/common';
import {Inject, InjectionToken, ModuleWithProviders, NgModule, Optional} from '@angular/core';
import {UpgradeModule} from '@angular/upgrade/static';
import {$locationShim, $locationShimProvider} from './location_shim';
import {AngularJSUrlCodec, UrlCodec} from './params';
/**
* Configuration options for LocationUpgrade.
*
* @publicApi
*/
export interface LocationUpgradeConfig {
/**
* Configures whether the location upgrade module should use the `HashLocationStrategy`
* or the `PathLocationStrategy`
*/
useHash?: boolean;
/**
* Configures the hash prefix used in the URL when using the `HashLocationStrategy`
*/
hashPrefix?: string;
/**
* Configures the URL codec for encoding and decoding URLs. Default is the `AngularJSCodec`
*/
urlCodec?: typeof UrlCodec;
/**
* Configures the base href when used in server-side rendered applications
*/
serverBaseHref?: string;
/**
* Configures the base href when used in client-side rendered applications
*/
appBaseHref?: string;
}
/**
* A provider token used to configure the location upgrade module.
*
* @publicApi
*/
export const LOCATION_UPGRADE_CONFIGURATION = new InjectionToken<LocationUpgradeConfig>(
ngDevMode ? 'LOCATION_UPGRADE_CONFIGURATION' : '',
);
const APP_BASE_HREF_RESOLVED = new InjectionToken<string>(
ngDevMode ? 'APP_BASE_HREF_RESOLVED' : '',
);
/**
* `NgModule` used for providing and configuring Angular's Unified Location Service for upgrading.
*
* @see [Using the Unified Angular Location Service](https://angular.io/guide/upgrade#using-the-unified-angular-location-service)
*
* @publicApi
*/
@NgModule({imports: [CommonModule]})
export class LocationUpgradeModule {
static config(config?: LocationUpgradeConfig): ModuleWithProviders<LocationUpgradeModule> {
return {
ngModule: LocationUpgradeModule,
providers: [
Location,
{
provide: $locationShim,
useFactory: provide$location,
deps: [UpgradeModule, Location, PlatformLocation, UrlCodec, LocationStrategy],
},
{provide: LOCATION_UPGRADE_CONFIGURATION, useValue: config ? config : {}},
{provide: UrlCodec, useFactory: provideUrlCodec, deps: [LOCATION_UPGRADE_CONFIGURATION]},
{
provide: APP_BASE_HREF_RESOLVED,
useFactory: provideAppBaseHref,
deps: [LOCATION_UPGRADE_CONFIGURATION, [new Inject(APP_BASE_HREF), new Optional()]],
},
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [PlatformLocation, APP_BASE_HREF_RESOLVED, LOCATION_UPGRADE_CONFIGURATION],
},
],
};
}
}
export function provideAppBaseHref(config: LocationUpgradeConfig, appBaseHref?: string) {
if (config && config.appBaseHref != null) {
return config.appBaseHref;
} else if (appBaseHref != null) {
return appBaseHref;
}
return '';
}
export function provideUrlCodec(config: LocationUpgradeConfig) {
const codec = (config && config.urlCodec) || AngularJSUrlCodec;
return new (codec as any)();
}
export function provideLocationStrategy(
platformLocation: PlatformLocation,
baseHref: string,
options: LocationUpgradeConfig = {},
) {
return options.useHash
? new HashLocationStrategy(platformLocation, baseHref)
: new PathLocationStrategy(platformLocation, baseHref);
}
export function provide$location(
ngUpgrade: UpgradeModule,
location: Location,
platformLocation: PlatformLocation,
urlCodec: UrlCodec,
locationStrategy: LocationStrategy,
) {
const $locationProvider = new $locationShimProvider(
ngUpgrade,
location,
platformLocation,
urlCodec,
locationStrategy,
);
return $locationProvider.$get();
}
| {
"end_byte": 4125,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/location_upgrade_module.ts"
} |
angular/packages/common/upgrade/src/index.ts_0_457 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {$locationShim, $locationShimProvider} from './location_shim';
export {
LOCATION_UPGRADE_CONFIGURATION,
LocationUpgradeConfig,
LocationUpgradeModule,
} from './location_upgrade_module';
export {AngularJSUrlCodec, UrlCodec} from './params';
| {
"end_byte": 457,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/index.ts"
} |
angular/packages/common/upgrade/src/params.ts_0_7218 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* A codec for encoding and decoding URL parts.
*
* @publicApi
**/
export abstract class UrlCodec {
/**
* Encodes the path from the provided string
*
* @param path The path string
*/
abstract encodePath(path: string): string;
/**
* Decodes the path from the provided string
*
* @param path The path string
*/
abstract decodePath(path: string): string;
/**
* Encodes the search string from the provided string or object
*
* @param path The path string or object
*/
abstract encodeSearch(search: string | {[k: string]: unknown}): string;
/**
* Decodes the search objects from the provided string
*
* @param path The path string
*/
abstract decodeSearch(search: string): {[k: string]: unknown};
/**
* Encodes the hash from the provided string
*
* @param path The hash string
*/
abstract encodeHash(hash: string): string;
/**
* Decodes the hash from the provided string
*
* @param path The hash string
*/
abstract decodeHash(hash: string): string;
/**
* Normalizes the URL from the provided string
*
* @param path The URL string
*/
abstract normalize(href: string): string;
/**
* Normalizes the URL from the provided string, search, hash, and base URL parameters
*
* @param path The URL path
* @param search The search object
* @param hash The has string
* @param baseUrl The base URL for the URL
*/
abstract normalize(
path: string,
search: {[k: string]: unknown},
hash: string,
baseUrl?: string,
): string;
/**
* Checks whether the two strings are equal
* @param valA First string for comparison
* @param valB Second string for comparison
*/
abstract areEqual(valA: string, valB: string): boolean;
/**
* Parses the URL string based on the base URL
*
* @param url The full URL string
* @param base The base for the URL
*/
abstract parse(
url: string,
base?: string,
): {
href: string;
protocol: string;
host: string;
search: string;
hash: string;
hostname: string;
port: string;
pathname: string;
};
}
/**
* A `UrlCodec` that uses logic from AngularJS to serialize and parse URLs
* and URL parameters.
*
* @publicApi
*/
export class AngularJSUrlCodec implements UrlCodec {
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L15
encodePath(path: string): string {
const segments = path.split('/');
let i = segments.length;
while (i--) {
// decode forward slashes to prevent them from being double encoded
segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
}
path = segments.join('/');
return _stripIndexHtml(((path && path[0] !== '/' && '/') || '') + path);
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L42
encodeSearch(search: string | {[k: string]: unknown}): string {
if (typeof search === 'string') {
search = parseKeyValue(search);
}
search = toKeyValue(search);
return search ? '?' + search : '';
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L44
encodeHash(hash: string) {
hash = encodeUriSegment(hash);
return hash ? '#' + hash : '';
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L27
decodePath(path: string, html5Mode = true): string {
const segments = path.split('/');
let i = segments.length;
while (i--) {
segments[i] = decodeURIComponent(segments[i]);
if (html5Mode) {
// encode forward slashes to prevent them from being mistaken for path separators
segments[i] = segments[i].replace(/\//g, '%2F');
}
}
return segments.join('/');
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L72
decodeSearch(search: string) {
return parseKeyValue(search);
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L73
decodeHash(hash: string) {
hash = decodeURIComponent(hash);
return hash[0] === '#' ? hash.substring(1) : hash;
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L149
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L42
normalize(href: string): string;
normalize(path: string, search: {[k: string]: unknown}, hash: string, baseUrl?: string): string;
normalize(
pathOrHref: string,
search?: {[k: string]: unknown},
hash?: string,
baseUrl?: string,
): string {
if (arguments.length === 1) {
const parsed = this.parse(pathOrHref, baseUrl);
if (typeof parsed === 'string') {
return parsed;
}
const serverUrl = `${parsed.protocol}://${parsed.hostname}${
parsed.port ? ':' + parsed.port : ''
}`;
return this.normalize(
this.decodePath(parsed.pathname),
this.decodeSearch(parsed.search),
this.decodeHash(parsed.hash),
serverUrl,
);
} else {
const encPath = this.encodePath(pathOrHref);
const encSearch = (search && this.encodeSearch(search)) || '';
const encHash = (hash && this.encodeHash(hash)) || '';
let joinedPath = (baseUrl || '') + encPath;
if (!joinedPath.length || joinedPath[0] !== '/') {
joinedPath = '/' + joinedPath;
}
return joinedPath + encSearch + encHash;
}
}
areEqual(valA: string, valB: string) {
return this.normalize(valA) === this.normalize(valB);
}
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/urlUtils.js#L60
parse(url: string, base?: string) {
try {
// Safari 12 throws an error when the URL constructor is called with an undefined base.
const parsed = !base ? new URL(url) : new URL(url, base);
return {
href: parsed.href,
protocol: parsed.protocol ? parsed.protocol.replace(/:$/, '') : '',
host: parsed.host,
search: parsed.search ? parsed.search.replace(/^\?/, '') : '',
hash: parsed.hash ? parsed.hash.replace(/^#/, '') : '',
hostname: parsed.hostname,
port: parsed.port,
pathname: parsed.pathname.charAt(0) === '/' ? parsed.pathname : '/' + parsed.pathname,
};
} catch (e) {
throw new Error(`Invalid URL (${url}) with base (${base})`);
}
}
}
function _stripIndexHtml(url: string): string {
return url.replace(/\/index.html$/, '');
}
/**
* Tries to decode the URI component without throwing an exception.
*
* @param str value potential URI component to check.
* @returns the decoded URI if it can be decoded or else `undefined`.
*/
function tryDecodeURIComponent(value: string): string | undefined {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component.
return undefined;
}
}
/**
* Parses an escaped url query string into key-value pairs. Logic taken from
* https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1382
*/ | {
"end_byte": 7218,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/params.ts"
} |
angular/packages/common/upgrade/src/params.ts_7219_10516 | function parseKeyValue(keyValue: string): {[k: string]: unknown} {
const obj: {[k: string]: unknown} = {};
(keyValue || '').split('&').forEach((keyValue) => {
let splitPoint, key, val;
if (keyValue) {
key = keyValue = keyValue.replace(/\+/g, '%20');
splitPoint = keyValue.indexOf('=');
if (splitPoint !== -1) {
key = keyValue.substring(0, splitPoint);
val = keyValue.substring(splitPoint + 1);
}
key = tryDecodeURIComponent(key);
if (typeof key !== 'undefined') {
val = typeof val !== 'undefined' ? tryDecodeURIComponent(val) : true;
if (!obj.hasOwnProperty(key)) {
obj[key] = val;
} else if (Array.isArray(obj[key])) {
(obj[key] as unknown[]).push(val);
} else {
obj[key] = [obj[key], val];
}
}
}
});
return obj;
}
/**
* Serializes into key-value pairs. Logic taken from
* https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1409
*/
function toKeyValue(obj: {[k: string]: unknown}) {
const parts: unknown[] = [];
for (const key in obj) {
let value = obj[key];
if (Array.isArray(value)) {
value.forEach((arrayValue) => {
parts.push(
encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)),
);
});
} else {
parts.push(
encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value as any, true)),
);
}
}
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* https://tools.ietf.org/html/rfc3986 with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*
* Logic from https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1437
*/
function encodeUriSegment(val: string) {
return encodeUriQuery(val, true).replace(/%26/g, '&').replace(/%3D/gi, '=').replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per https://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*
* Logic from https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1456
*/
function encodeUriQuery(val: string, pctEncodeSpaces: boolean = false) {
return encodeURIComponent(val)
.replace(/%40/g, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%20/g, pctEncodeSpaces ? '%20' : '+');
} | {
"end_byte": 10516,
"start_byte": 7219,
"url": "https://github.com/angular/angular/blob/main/packages/common/upgrade/src/params.ts"
} |
angular/packages/common/locales/index.bzl_0_2065 | load("@cldr_json_data//:index.bzl", _ALL_CLDR_LOCALES = "LOCALES")
load("@build_bazel_rules_nodejs//:index.bzl", "npm_package_bin")
# List of locales the tool can generate files for.
LOCALES = _ALL_CLDR_LOCALES
# Labels resolving to the individual `generate-locale-tool` entry-points
GENERATE_LOCALES_TOOL_BIN = "//packages/common/locales/generate-locales-tool/bin"
GET_BASE_CURRENCIES_FILE_BIN = "%s:get-base-currencies-file" % GENERATE_LOCALES_TOOL_BIN
GET_BASE_LOCALE_FILE_BIN = "%s:get-base-locale-file" % GENERATE_LOCALES_TOOL_BIN
GET_CLOSURE_LOCALE_FILE_BIN = "%s:get-closure-locale-file" % GENERATE_LOCALES_TOOL_BIN
WRITE_LOCALE_FILES_TO_DIST_BIN = "%s:write-locale-files-to-dist" % GENERATE_LOCALES_TOOL_BIN
def _run_tool_with_single_output(name, output_file, tool, **kwargs):
native.genrule(
name = name,
outs = [output_file],
srcs = [],
exec_tools = [tool],
cmd = """$(location %s) > $@""" % tool,
**kwargs
)
def generate_base_currencies_file(name, output_file, **kwargs):
_run_tool_with_single_output(
name = name,
output_file = output_file,
tool = GET_BASE_CURRENCIES_FILE_BIN,
**kwargs
)
def generate_base_locale_file(name, output_file, **kwargs):
_run_tool_with_single_output(
name = name,
output_file = output_file,
tool = GET_BASE_LOCALE_FILE_BIN,
**kwargs
)
def generate_closure_locale_file(name, output_file, **kwargs):
_run_tool_with_single_output(
name = name,
output_file = output_file,
tool = GET_CLOSURE_LOCALE_FILE_BIN,
**kwargs
)
def generate_all_locale_files(name, **kwargs):
locale_files = []
for locale in LOCALES:
locale_files += [
"%s.ts" % locale,
"global/%s.js" % locale,
"extra/%s.ts" % locale,
]
npm_package_bin(
name = name,
outs = locale_files,
tool = WRITE_LOCALE_FILES_TO_DIST_BIN,
args = [
"$(@D)",
],
**kwargs
)
| {
"end_byte": 2065,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/index.bzl"
} |
angular/packages/common/locales/ff-MR.ts_0_2034 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// **Note**: Locale files are generated through Bazel and never part of the sources. This is an
// exception for backwards compatibility. With the Gulp setup we never deleted old locale files
// when updating CLDR, so older locale files which have been removed, or renamed in the CLDR
// data remained in the repository. We keep these files checked-in until the next major to avoid
// potential breaking changes. It's worth noting that the locale data for such files is outdated
// anyway. e.g. the data is missing the directionality, throwing off the indices.
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
export default [
'ff-MR',
[['subaka', 'kikiiɗe'], u, u],
u,
[
['d', 'a', 'm', 'n', 'n', 'm', 'h'],
['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'],
['dewo', 'aaɓnde', 'mawbaare', 'njeslaare', 'naasaande', 'mawnde', 'hoore-biir'],
['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'],
],
u,
[
['s', 'c', 'm', 's', 'd', 'k', 'm', 'j', 's', 'y', 'j', 'b'],
['sii', 'col', 'mbo', 'see', 'duu', 'kor', 'mor', 'juk', 'slt', 'yar', 'jol', 'bow'],
[
'siilo',
'colte',
'mbooy',
'seeɗto',
'duujal',
'korse',
'morso',
'juko',
'siilto',
'yarkomaa',
'jolal',
'bowte',
],
],
u,
[['H-I', 'C-I'], u, ['Hade Iisa', 'Caggal Iisa']],
1,
[6, 0],
['d/M/y', 'd MMM, y', 'd MMMM y', 'EEEE d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
[',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'],
'UM',
'Ugiyya Muritani',
{'JPY': ['JP¥', '¥'], 'MRU': ['UM'], 'USD': ['US$', '$']},
plural,
];
| {
"end_byte": 2034,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/ff-MR.ts"
} |
angular/packages/common/locales/ff-CM.ts_0_2021 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// **Note**: Locale files are generated through Bazel and never part of the sources. This is an
// exception for backwards compatibility. With the Gulp setup we never deleted old locale files
// when updating CLDR, so older locale files which have been removed, or renamed in the CLDR
// data remained in the repository. We keep these files checked-in until the next major to avoid
// potential breaking changes. It's worth noting that the locale data for such files is outdated
// anyway. e.g. the data is missing the directionality, throwing off the indices.
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
export default [
'ff-CM',
[['subaka', 'kikiiɗe'], u, u],
u,
[
['d', 'a', 'm', 'n', 'n', 'm', 'h'],
['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'],
['dewo', 'aaɓnde', 'mawbaare', 'njeslaare', 'naasaande', 'mawnde', 'hoore-biir'],
['dew', 'aaɓ', 'maw', 'nje', 'naa', 'mwd', 'hbi'],
],
u,
[
['s', 'c', 'm', 's', 'd', 'k', 'm', 'j', 's', 'y', 'j', 'b'],
['sii', 'col', 'mbo', 'see', 'duu', 'kor', 'mor', 'juk', 'slt', 'yar', 'jol', 'bow'],
[
'siilo',
'colte',
'mbooy',
'seeɗto',
'duujal',
'korse',
'morso',
'juko',
'siilto',
'yarkomaa',
'jolal',
'bowte',
],
],
u,
[['H-I', 'C-I'], u, ['Hade Iisa', 'Caggal Iisa']],
1,
[6, 0],
['d/M/y', 'd MMM, y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, u, u],
[',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'],
'FCFA',
'Mbuuɗi Seefaa BEAC',
{'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']},
plural,
];
| {
"end_byte": 2021,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/ff-CM.ts"
} |
angular/packages/common/locales/closure-locale.ts_0_3153 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY.
import {registerLocaleData} from '../src/i18n/locale_data';
const u = undefined;
function plural_locale_af(val: number): number {
const n = val;
if (n === 1)
return 1;
return 5;
}
export const locale_af = ["af",[["v","n"],["vm.","nm."],u],u,[["S","M","D","W","D","V","S"],["So.","Ma.","Di.","Wo.","Do.","Vr.","Sa."],["Sondag","Maandag","Dinsdag","Woensdag","Donderdag","Vrydag","Saterdag"],["So.","Ma.","Di.","Wo.","Do.","Vr.","Sa."]],u,[["J","F","M","A","M","J","J","A","S","O","N","D"],["Jan.","Feb.","Mrt.","Apr.","Mei","Jun.","Jul.","Aug.","Sep.","Okt.","Nov.","Des."],["Januarie","Februarie","Maart","April","Mei","Junie","Julie","Augustus","September","Oktober","November","Desember"]],u,[["v.C.","n.C."],u,["voor Christus","na Christus"]],0,[6,0],["y-MM-dd","dd MMM y","dd MMMM y","EEEE dd MMMM y"],["HH:mm","HH:mm:ss","HH:mm:ss z","HH:mm:ss zzzz"],["{1} {0}",u,u,u],[","," ",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0%","¤#,##0.00","#E0"],"ZAR","R","Suid-Afrikaanse rand",{"BYN":[u,"р."],"CAD":[u,"$"],"JPY":["JP¥","¥"],"MXN":[u,"$"],"PHP":[u,"₱"],"RON":[u,"leu"],"THB":["฿"],"TWD":["NT$"],"USD":[u,"$"],"ZAR":["R"]},"ltr", plural_locale_af];
export const locale_extra_af = [[["mn","o","m","a","n"],["middernag","die oggend","die middag","die aand","die nag"],u],[["mn","o","m","a","n"],["middernag","oggend","middag","aand","nag"],u],["00:00",["05:00","12:00"],["12:00","18:00"],["18:00","24:00"],["00:00","05:00"]]];
function plural_locale_am(val: number): number {
const n = val, i = Math.floor(Math.abs(val));
if (i === 0 || n === 1)
return 1;
return 5;
}
export const locale_am = ["am",[["ጠ","ከ"],["ጥዋት","ከሰዓት"],u],u,[["እ","ሰ","ማ","ረ","ሐ","ዓ","ቅ"],["እሑድ","ሰኞ","ማክሰ","ረቡዕ","ሐሙስ","ዓርብ","ቅዳሜ"],["እሑድ","ሰኞ","ማክሰኞ","ረቡዕ","ሐሙስ","ዓርብ","ቅዳሜ"],["እ","ሰ","ማ","ረ","ሐ","ዓ","ቅ"]],u,[["ጃ","ፌ","ማ","ኤ","ሜ","ጁ","ጁ","ኦ","ሴ","ኦ","ኖ","ዲ"],["ጃንዩ","ፌብሩ","ማርች","ኤፕሪ","ሜይ","ጁን","ጁላይ","ኦገስ","ሴፕቴ","ኦክቶ","ኖቬም","ዲሴም"],["ጃንዩወሪ","ፌብሩወሪ","ማርች","ኤፕሪል","ሜይ","ጁን","ጁላይ","ኦገስት","ሴፕቴምበር","ኦክቶበር","ኖቬምበር","ዲሴምበር"]],u,[["ዓ/ዓ","ዓ/ም"],u,["ዓመተ ዓለም","ዓመተ ምሕረት"]],0,[6,0],["dd/MM/y","d MMM y","d MMMM y","y MMMM d, EEEE"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1} {0}",u,u,u],[".",",",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0%","¤#,##0.00","#E0"],"ETB","ብር","የኢትዮጵያ ብር",{"AUD":["AU$","$"],"BYN":[u,"р."],"CNH":["የቻይና ዩዋን"],"ETB":["ብር"],"JPY":["JP¥","¥"],"PHP":[u,"₱"],"THB":["฿"],"TWD":["NT$"],"USD":["US$","$"]},"ltr", plural_locale_am];
export const locale_extra_am = [[["እኩለ ሌሊት","ቀ","ጥዋት1","ከሰዓት1","ማታ1","ሌሊት1"],["እኩለ ሌሊት","ቀትር","ጥዋት1","ከሰዓት 7","ማታ1","ሌሊት1"],["እኩለ ሌሊት","ቀትር","ጥዋት1","ከሰዓት 7 ሰዓት","ማታ1","ሌሊት1"]],[["እኩለ ሌሊት","ቀትር","ጥዋት","ከሰዓት በኋላ","ማታ","ሌሊት"],["እኩለ ሌሊት","ቀትር","ጥዋት1","ከሰዓት በኋላ","ማታ","ሌሊት"],u],["00:00","12:00",["06:00","12:00"],["12:00","18:00"],["18:00","24:00"],["00:00","06:00"]]];
function plural_locale_ar(val: number): number | {
"end_byte": 3153,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
angular/packages/common/locales/closure-locale.ts_3154_6779 |
const n = val;
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n % 100 === Math.floor(n % 100) && (n % 100 >= 3 && n % 100 <= 10))
return 3;
if (n % 100 === Math.floor(n % 100) && (n % 100 >= 11 && n % 100 <= 99))
return 4;
return 5;
}
export const locale_ar = ["ar",[["ص","م"],u,u],[["ص","م"],u,["صباحًا","مساءً"]],[["ح","ن","ث","ر","خ","ج","س"],["الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],u,["أحد","إثنين","ثلاثاء","أربعاء","خميس","جمعة","سبت"]],u,[["ي","ف","م","أ","و","ن","ل","غ","س","ك","ب","د"],["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],u],u,[["ق.م","م"],u,["قبل الميلاد","ميلادي"]],6,[5,6],["d/M/y","dd/MM/y","d MMMM y","EEEE، d MMMM y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1}, {0}",u,"{1} في {0}",u],[".",",",";","%","+","-","E","×","‰","∞","ليس رقمًا",":"],["#,##0.###","#,##0%","¤ #,##0.00","#E0"],"EGP","ج.م.","جنيه مصري",{"AED":["د.إ."],"ARS":[u,"AR$"],"AUD":["AU$"],"BBD":[u,"BB$"],"BHD":["د.ب."],"BMD":[u,"BM$"],"BND":[u,"BN$"],"BSD":[u,"BS$"],"BYN":[u,"р."],"BZD":[u,"BZ$"],"CAD":["CA$"],"CLP":[u,"CL$"],"CNY":["CN¥"],"COP":[u,"CO$"],"CUP":[u,"CU$"],"DOP":[u,"DO$"],"DZD":["د.ج."],"EGP":["ج.م.","E£"],"FJD":[u,"FJ$"],"GBP":["UK£"],"GYD":[u,"GY$"],"HKD":["HK$"],"IQD":["د.ع."],"IRR":["ر.إ."],"JMD":[u,"JM$"],"JOD":["د.أ."],"JPY":["JP¥"],"KWD":["د.ك."],"KYD":[u,"KY$"],"LBP":["ل.ل.","L£"],"LRD":[u,"$LR"],"LYD":["د.ل."],"MAD":["د.م."],"MRU":["أ.م."],"MXN":["MX$"],"NZD":["NZ$"],"OMR":["ر.ع."],"PHP":[u,"₱"],"QAR":["ر.ق."],"SAR":["ر.س."],"SBD":[u,"SB$"],"SDD":["د.س."],"SDG":["ج.س."],"SRD":[u,"SR$"],"SYP":["ل.س.","£"],"THB":["฿"],"TND":["د.ت."],"TTD":[u,"TT$"],"TWD":["NT$"],"USD":["US$"],"UYU":[u,"UY$"],"YER":["ر.ي."]},"rtl", plural_locale_ar];
export const locale_extra_ar = [[["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","ص","ظهرًا","بعد الظهر","مساءً","في المساء","ليلاً"],["في الصباح","صباحًا","ظهرًا","بعد الظهر","مساءً","في المساء","ليلاً"]],[["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","ص","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"]],[["03:00","06:00"],["06:00","12:00"],["12:00","13:00"],["13:00","18:00"],["18:00","24:00"],["00:00","01:00"],["01:00","03:00"]]];
function plural_locale_ar_DZ(val: number): number {
const n = val;
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n % 100 === Math.floor(n % 100) && (n % 100 >= 3 && n % 100 <= 10))
return 3;
if (n % 100 === Math.floor(n % 100) && (n % 100 >= 11 && n % 100 <= 99))
return 4;
return 5;
}
export const locale_ar_DZ = ["ar-DZ",[["ص","م"],u,u],[["ص","م"],u,["صباحًا","مساءً"]],[["ح","ن","ث","ر","خ","ج","س"],["الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],u,["أحد","إثنين","ثلاثاء","أربعاء","خميس","جمعة","سبت"]],u,[["ج","ف","م","أ","م","ج","ج","أ","س","أ","ن","د"],["جانفي","فيفري","مارس","أفريل","ماي","جوان","جويلية","أوت","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],u],u,[["ق.م","م"],u,["قبل الميلاد","ميلادي"]],6,[5,6],["d/M/y","dd/MM/y","d MMMM y","EEEE، d MMMM y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1}, {0}",u,"{1} في {0}",u],[",",".",";","%","+","-","E","×","‰","∞","ليس رقمًا",":"],["#,##0.###","#,##0%","¤ #,##0.00","#E0"],"DZD","د.ج.","دينار جزائري",{"AED":["د.إ."],"ARS":[u,"AR$"],"AUD":["AU$"],"BBD":[u,"BB$"],"BHD":["د.ب."],"BMD":[u,"BM$"],"BND":[u,"BN$"],"BSD":[u,"BS$"],"BYN":[u,"р."],"BZD":[u,"BZ$"],"CAD" | {
"end_byte": 6779,
"start_byte": 3154,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
angular/packages/common/locales/closure-locale.ts_6784_9937 | $"],"CLP":[u,"CL$"],"CNY":["CN¥"],"COP":[u,"CO$"],"CUP":[u,"CU$"],"DOP":[u,"DO$"],"DZD":["د.ج."],"EGP":["ج.م.","E£"],"FJD":[u,"FJ$"],"GBP":["UK£"],"GYD":[u,"GY$"],"HKD":["HK$"],"IQD":["د.ع."],"IRR":["ر.إ."],"JMD":[u,"JM$"],"JOD":["د.أ."],"JPY":["JP¥"],"KWD":["د.ك."],"KYD":[u,"KY$"],"LBP":["ل.ل.","L£"],"LRD":[u,"$LR"],"LYD":["د.ل."],"MAD":["د.م."],"MRU":["أ.م."],"MXN":["MX$"],"NZD":["NZ$"],"OMR":["ر.ع."],"PHP":[u,"₱"],"QAR":["ر.ق."],"SAR":["ر.س."],"SBD":[u,"SB$"],"SDD":["د.س."],"SDG":["ج.س."],"SRD":[u,"SR$"],"SYP":["ل.س.","£"],"THB":["฿"],"TND":["د.ت."],"TTD":[u,"TT$"],"TWD":["NT$"],"USD":["US$"],"UYU":[u,"UY$"],"YER":["ر.ي."]},"rtl", plural_locale_ar_DZ];
export const locale_extra_ar_DZ = [[["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","ص","ظهرًا","بعد الظهر","مساءً","في المساء","ليلاً"],["في الصباح","صباحًا","ظهرًا","بعد الظهر","مساءً","في المساء","ليلاً"]],[["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","ص","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"],["فجرًا","صباحًا","ظهرًا","بعد الظهر","مساءً","منتصف الليل","ليلاً"]],[["03:00","06:00"],["06:00","12:00"],["12:00","13:00"],["13:00","18:00"],["18:00","24:00"],["00:00","01:00"],["01:00","03:00"]]];
function plural_locale_az(val: number): number {
const n = val;
if (n === 1)
return 1;
return 5;
}
export const locale_az = ["az",[["a","p"],["AM","PM"],u],[["AM","PM"],u,u],[["7","1","2","3","4","5","6"],["B.","B.e.","Ç.a.","Ç.","C.a.","C.","Ş."],["bazar","bazar ertəsi","çərşənbə axşamı","çərşənbə","cümə axşamı","cümə","şənbə"],["B.","B.E.","Ç.A.","Ç.","C.A.","C.","Ş."]],[["7","1","2","3","4","5","6"],["B.","B.E.","Ç.A.","Ç.","C.A.","C.","Ş."],["bazar","bazar ertəsi","çərşənbə axşamı","çərşənbə","cümə axşamı","cümə","şənbə"],["B.","B.E.","Ç.A.","Ç.","C.A.","C.","Ş."]],[["1","2","3","4","5","6","7","8","9","10","11","12"],["yan","fev","mar","apr","may","iyn","iyl","avq","sen","okt","noy","dek"],["yanvar","fevral","mart","aprel","may","iyun","iyul","avqust","sentyabr","oktyabr","noyabr","dekabr"]],u,[["e.ə.","y.e."],u,["eramızdan əvvəl","yeni era"]],1,[6,0],["dd.MM.yy","d MMM y","d MMMM y","d MMMM y, EEEE"],["HH:mm","HH:mm:ss","HH:mm:ss z","HH:mm:ss zzzz"],["{1} {0}",u,u,u],[",",".",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0%","#,##0.00 ¤","#E0"],"AZN","₼","Azərbaycan Manatı",{"AZN":["₼"],"BYN":[u,"р."],"JPY":["JP¥","¥"],"PHP":[u,"₱"],"RON":[u,"ley"],"SYP":[u,"S£"],"THB":["฿"],"TWD":["NT$"],"USD":["US$","$"]},"ltr", plural_locale_az];
export const locale_extra_az = [[["gecəyarı","g","sübh","səhər","gündüz","axşamüstü","axşam","gecə"],["gecəyarı","günorta","sübh","səhər","gündüz","axşamüstü","axşam","gecə"],u],[["gecəyarı","günorta","sübh","səhər","gündüz","axşamüstü","axşam","gecə"],u,u],["00:00","12:00",["04:00","06:00"],["06:00","12:00"],["12:00","17:00"],["17:00","19:00"],["19:00","24:00"],["00:00","04:00"]]];
function plural_locale_be(val: number): number {
const n = val;
if (n % 10 === 1 && !(n % 100 === 11))
return 1;
if (n % 10 === Math.floor(n % 10) && (n % 10 >= 2 && n % 10 <= 4) && !(n % 100 >= 12 && n % 100 <= 14))
r | {
"end_byte": 9937,
"start_byte": 6784,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
angular/packages/common/locales/closure-locale.ts_9939_12040 | urn 3;
if (n % 10 === 0 || (n % 10 === Math.floor(n % 10) && (n % 10 >= 5 && n % 10 <= 9) || n % 100 === Math.floor(n % 100) && (n % 100 >= 11 && n % 100 <= 14)))
return 4;
return 5;
}
export const locale_be = ["be",[["am","pm"],["AM","PM"],u],[["AM","PM"],u,u],[["н","п","а","с","ч","п","с"],["нд","пн","аў","ср","чц","пт","сб"],["нядзеля","панядзелак","аўторак","серада","чацвер","пятніца","субота"],["нд","пн","аў","ср","чц","пт","сб"]],u,[["с","л","с","к","м","ч","л","ж","в","к","л","с"],["сту","лют","сак","кра","мая","чэр","ліп","жні","вер","кас","ліс","сне"],["студзеня","лютага","сакавіка","красавіка","мая","чэрвеня","ліпеня","жніўня","верасня","кастрычніка","лістапада","снежня"]],[["с","л","с","к","м","ч","л","ж","в","к","л","с"],["сту","лют","сак","кра","май","чэр","ліп","жні","вер","кас","ліс","сне"],["студзень","люты","сакавік","красавік","май","чэрвень","ліпень","жнівень","верасень","кастрычнік","лістапад","снежань"]],[["да н.э.","н.э."],u,["да нараджэння Хрыстова","ад нараджэння Хрыстова"]],1,[6,0],["d.MM.yy","d MMM y 'г'.","d MMMM y 'г'.","EEEE, d MMMM y 'г'."],["HH:mm","HH:mm:ss","HH:mm:ss z","HH:mm:ss, zzzz"],["{1}, {0}",u,"{1} 'у' {0}",u],[","," ",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0 %","#,##0.00 ¤","#E0"],"BYN","Br","беларускі рубель",{"AUD":["A$"],"BBD":[u,"Bds$"],"BMD":[u,"BD$"],"BRL":[u,"R$"],"BSD":[u,"B$"],"BYN":["Br"],"BZD":[u,"BZ$"],"CAD":[u,"CA$"],"CUC":[u,"CUC$"],"CUP":[u,"$MN"],"DOP":[u,"RD$"],"FJD":[u,"FJ$"],"FKP":[u,"FK£"],"GYD":[u,"G$"],"ISK":[u,"Íkr"],"JMD":[u,"J$"],"KYD":[u,"CI$"],"LRD":[u,"L$"],"MXN":["MX$"],"NAD":[u,"N$"],"NZD":[u,"NZ$"],"PHP":[u,"₱"],"RUB":["₽","руб."],"SBD":[u,"SI$"],"SGD":[u,"S$"],"TTD":[u,"TT$"],"UYU":[u,"$U"],"XCD":["EC$"]},"ltr", plural_locale_be];
export const locale_extra_be = [];
function plural_locale_bg(val: number): number {
const n = val;
if (n === 1)
return 1;
return 5;
}
export const locale_bg = ["bg",[["am","pm"],u,["пр.об.","сл.об."]],[["am","pm"],u,u],[["н","п","в","с","ч","п","с"],["нд","пн","вт","ср","чт","пт","сб"],["неделя","понеделник","вторник","сряда","че | {
"end_byte": 12040,
"start_byte": 9939,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
angular/packages/common/locales/closure-locale.ts_12042_14186 | ъртък","петък","събота"],["нд","пн","вт","ср","чт","пт","сб"]],u,[["я","ф","м","а","м","ю","ю","а","с","о","н","д"],["яну","фев","март","апр","май","юни","юли","авг","сеп","окт","ное","дек"],["януари","февруари","март","април","май","юни","юли","август","септември","октомври","ноември","декември"]],u,[["пр.Хр.","сл.Хр."],u,["преди Христа","след Христа"]],1,[6,0],["d.MM.yy 'г'.","d.MM.y 'г'.","d MMMM y 'г'.","EEEE, d MMMM y 'г'."],["H:mm 'ч'.","H:mm:ss 'ч'.","H:mm:ss 'ч'. z","H:mm:ss 'ч'. zzzz"],["{1}, {0}",u,u,u],[","," ",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0%","0.00 ¤","#E0"],"BGN","лв.","Български лев",{"AFN":[u,"Af"],"AMD":[],"ARS":[],"AUD":[],"AZN":[],"BBD":[],"BDT":[],"BGN":["лв."],"BMD":[],"BND":[],"BRL":[],"BSD":[],"BZD":[],"CAD":[],"CLP":[],"CNY":[],"COP":[],"CRC":[],"CUP":[],"DOP":[],"FJD":[],"FKP":[],"GBP":[u,"£"],"GHS":[],"GIP":[],"GYD":[],"HKD":[],"ILS":[],"INR":[],"JMD":[],"JPY":[u,"¥"],"KHR":[],"KRW":[],"KYD":[],"KZT":[],"LAK":[],"LRD":[],"MNT":[],"MXN":[],"NAD":[],"NGN":[],"NZD":[],"PHP":[],"PYG":[],"RON":[],"SBD":[],"SGD":[],"SRD":[],"SSP":[],"TRY":[],"TTD":[],"TWD":[],"UAH":[],"USD":["щ.д.","$"],"UYU":[],"VND":[],"XCD":[u,"$"]},"ltr", plural_locale_bg];
export const locale_extra_bg = [[["полунощ","сутринта","на обяд","следобед","вечерта","през нощта"],u,u],u,["00:00",["04:00","11:00"],["11:00","14:00"],["14:00","18:00"],["18:00","22:00"],["22:00","04:00"]]];
function plural_locale_bn(val: number): number {
const n = val, i = Math.floor(Math.abs(val));
if (i === 0 || n === 1)
return 1;
return 5;
}
export const locale_bn = ["bn",[["AM","PM"],u,u],u,[["র","সো","ম","বু","বৃ","শু","শ"],["রবি","সোম","মঙ্গল","বুধ","বৃহস্পতি","শুক্র","শনি"],["রবিবার","সোমবার","মঙ্গলবার","বুধবার","বৃহস্পতিবার","শুক্রবার","শনিবার"],["রঃ","সোঃ","মঃ","বুঃ","বৃঃ","শুঃ","শনি"]],u,[["জা","ফে","মা","এ","মে","জুন","জু","আ","সে","অ","ন","ডি"],["জানু","ফেব","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগস্ট","সেপ্টেম্বর","অক্টোবর","নভেম্বর","ডিসেম্বর"],["জানুয়ারী","ফেব্রুয়ারী","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগস্ট","সেপ্টেম্বর","অক্টোবর","নভেম্বর","ডিসেম্বর"]],[["জা","ফে","মা","এ","মে","জুন", | {
"end_byte": 14186,
"start_byte": 12042,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
angular/packages/common/locales/closure-locale.ts_14188_16279 | ু","আ","সে","অ","ন","ডি"],["জানুয়ারী","ফেব্রুয়ারী","মার্চ","এপ্রিল","মে","জুন","জুলাই","আগস্ট","সেপ্টেম্বর","অক্টোবর","নভেম্বর","ডিসেম্বর"],u],[["খ্রিস্টপূর্ব","খৃষ্টাব্দ"],u,["খ্রিস্টপূর্ব","খ্রীষ্টাব্দ"]],0,[6,0],["d/M/yy","d MMM, y","d MMMM, y","EEEE, d MMMM, y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1} {0}",u,u,u],[".",",",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##,##0.###","#,##,##0%","#,##,##0.00¤","#E0"],"BDT","৳","বাংলাদেশী টাকা",{"BDT":["৳"],"BYN":[u,"р."],"JPY":["JP¥","¥"],"PHP":[u,"₱"],"THB":["฿"],"TWD":["NT$"],"USD":["US$","$"]},"ltr", plural_locale_bn];
export const locale_extra_bn = [[["ভোর","সকাল","দুপুর","বিকাল","সন্ধ্যা","রাত্রি"],u,["ভোর","সকাল","দুপুর","বিকাল","সন্ধ্যা","রাত্রিতে"]],[["ভোর","সকাল","দুপুর","বিকাল","সন্ধ্যা","রাত্রি"],u,u],[["04:00","06:00"],["06:00","12:00"],["12:00","16:00"],["16:00","18:00"],["18:00","20:00"],["20:00","04:00"]]];
function plural_locale_br(val: number): number {
const n = val;
if (n % 10 === 1 && !(n % 100 === 11 || (n % 100 === 71 || n % 100 === 91)))
return 1;
if (n % 10 === 2 && !(n % 100 === 12 || (n % 100 === 72 || n % 100 === 92)))
return 2;
if (n % 10 === Math.floor(n % 10) && (n % 10 >= 3 && n % 10 <= 4 || n % 10 === 9) && !(n % 100 >= 10 && n % 100 <= 19 || (n % 100 >= 70 && n % 100 <= 79 || n % 100 >= 90 && n % 100 <= 99)))
return 3;
if (!(n === 0) && n % 1000000 === 0)
return 4;
return 5;
}
export const locale_br = ["br",[["am","gm"],["A.M.","G.M."],u],[["A.M.","G.M."],u,u],[["Su","L","Mz","Mc","Y","G","Sa"],["Sul","Lun","Meu.","Mer.","Yaou","Gwe.","Sad."],["Sul","Lun","Meurzh","Mercʼher","Yaou","Gwener","Sadorn"],["Sul","Lun","Meu.","Mer.","Yaou","Gwe.","Sad."]],u,[["01","02","03","04","05","06","07","08","09","10","11","12"],["Gen.","Cʼhwe.","Meur.","Ebr.","Mae","Mezh.","Goue.","Eost","Gwen.","Here","Du","Kzu."],["Genver","Cʼhwevrer","Meurzh","Ebrel","Mae","Mezheven","Gouere","Eost","Gwengolo","Here","Du","Kerzu"]],u,[["a-raok J.K.","goude J.K."],u,["a-raok Jezuz-Krist","goude Jezuz-Krist"]],1,[6,0],["dd/MM/y","d MMM y","d MMMM y","EEEE d MM | {
"end_byte": 16279,
"start_byte": 14188,
"url": "https://github.com/angular/angular/blob/main/packages/common/locales/closure-locale.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.