hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 10, "code_window": [ " outs = _expected_outs(ctx)\n", " return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file)\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 225 }
export class Hero { active: boolean; constructor(public name: string, public team: string[]) { } }
aio/content/examples/component-styles/src/app/hero.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017430633306503296, 0.00017430633306503296, 0.00017430633306503296, 0.00017430633306503296, 0 ]
{ "id": 10, "code_window": [ " outs = _expected_outs(ctx)\n", " return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file)\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 225 }
/** * @license * Copyright Google Inc. 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.io/license */ import {Component, Directive, ElementRef, Injectable, NgModule, Renderer} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; export function main() { platformBrowserDynamic().bootstrapModule(ExampleModule); } // A service available to the Injector, used by the HelloCmp component. @Injectable() export class GreetingService { greeting: string = 'hello'; } // Directives are light-weight. They don't allow new // expression contexts (use @Component for those needs). @Directive({selector: '[red]'}) export class RedDec { // ElementRef is always injectable and it wraps the element on which the // directive was found by the compiler. constructor(el: ElementRef, renderer: Renderer) { renderer.setElementStyle(el.nativeElement, 'color', 'red'); } } // Angular supports 2 basic types of directives: // - Component - the basic building blocks of Angular apps. Backed by // ShadowDom.(http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/) // - Directive - add behavior to existing elements. @Component({ // The Selector prop tells Angular on which elements to instantiate this // class. The syntax supported is a basic subset of CSS selectors, for example // 'element', '[attr]', [attr=foo]', etc. selector: 'hello-app', // These are services that would be created if a class in the component's // template tries to inject them. viewProviders: [GreetingService], // Expressions in the template (like {{greeting}}) are evaluated in the // context of the HelloCmp class below. template: `<div class="greeting">{{greeting}} <span red>world</span>!</div> <button class="changeButton" (click)="changeGreeting()">change greeting</button>` }) export class HelloCmp { greeting: string; constructor(service: GreetingService) { this.greeting = service.greeting; } changeGreeting(): void { this.greeting = 'howdy'; } } @NgModule({declarations: [HelloCmp, RedDec], bootstrap: [HelloCmp], imports: [BrowserModule]}) class ExampleModule { }
modules/playground/src/hello_world/index.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017642925377003849, 0.00017285451758652925, 0.00016813716501928866, 0.00017399780335836112, 0.0000028434312753233826 ]
{ "id": 11, "code_window": [ "\n", "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 227 }
# Copyright Google Inc. 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.io/license """Implementation of the ng_module rule. """ load(":rules_typescript.bzl", "tsc_wrapped_tsconfig", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "compile_ts", "DEPS_ASPECTS", "ts_providers_dict_to_struct", "json_marshal", ) def _basename_of(ctx, file): ext_len = len(".ts") if file.short_path.endswith(".ng.html"): ext_len = len(".ng.html") elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len] # Calculate the expected output of the template compiler for every source in # in the library. Most of these will be produced as empty files but it is # unknown, without parsing, which will be empty. def _expected_outs(ctx): devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: if src.short_path.endswith(".ts") and not src.short_path.endswith(".d.ts"): basename = src.short_path[len(ctx.label.package) + 1:-len(".ts")] if len(factory_basename_set) == 0 or basename in factory_basename_set: devmode_js = [ ".ngfactory.js", ".ngsummary.js", ".js", ] summaries = [".ngsummary.json"] else: devmode_js = [".js"] summaries = [] elif src.short_path.endswith(".css"): basename = src.short_path[len(ctx.label.package) + 1:-len(".css")] devmode_js = [ ".css.shim.ngstyle.js", ".css.ngstyle.js", ] summaries = [] else: continue filter_summaries = ctx.attr.filter_summaries closure_js = [f.replace(".js", ".closure.js") for f in devmode_js if not filter_summaries or not f.endswith(".ngsummary.js")] declarations = [f.replace(".js", ".d.ts") for f in devmode_js] devmode_js_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in devmode_js] closure_js_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in closure_js] declaration_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in declarations] summary_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in summaries] i18n_messages_files = [ctx.new_file(ctx.genfiles_dir, ctx.label.name + "_ngc_messages.xmb")] return struct( closure_js = closure_js_files, devmode_js = devmode_js_files, declarations = declaration_files, summaries = summary_files, i18n_messages = i18n_messages_files, ) def _ngc_tsconfig(ctx, files, srcs, **kwargs): outs = _expected_outs(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries else: expected_outs = outs.closure_js return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": { "generateCodeForLibraries": False, "allowEmptyCodegenFiles": True, "enableSummariesForJit": True, "fullTemplateTypeCheck": ctx.attr.type_check, # FIXME: wrong place to de-dupe "expectedOut": depset([o.path for o in expected_outs]).to_list() } }) def _collect_summaries_aspect_impl(target, ctx): results = depset(target.angular.summaries if hasattr(target, "angular") else []) # If we are visiting empty-srcs ts_library, this is a re-export srcs = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files of their deps if not srcs: for dep in ctx.rule.attr.deps: if (hasattr(dep, "angular")): results = depset(dep.angular.summaries, transitive = [results]) return struct(collect_summaries_aspect_result = results) _collect_summaries_aspect = aspect( implementation = _collect_summaries_aspect_impl, attr_aspects = ["deps"], ) # Extra options passed to Node when running ngc. _EXTRA_NODE_OPTIONS_FLAGS = [ # Expose the v8 garbage collection API to JS. "--node_options=--expose-gc" ] def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file, locale=None, i18n_args=[]): """Helper function to create the ngc action. This is exposed for google3 to wire up i18n replay rules, and is not intended as part of the public API. Args: ctx: skylark context label: the label of the ng_module being compiled inputs: passed to the ngc action's inputs outputs: passed to the ngc action's outputs messages_out: produced xmb files tsconfig_file: tsconfig file with settings used for the compilation locale: i18n locale, or None i18n_args: additional command-line arguments to ngc Returns: the parameters of the compilation which will be used to replay the ngc action for i18N. """ mnemonic = "AngularTemplateCompile" progress_message = "Compiling Angular templates (ngc) %s" % label if locale: mnemonic = "AngularI18NMerging" supports_workers = "0" progress_message = ("Recompiling Angular templates (ngc) %s for locale %s" % (label, locale)) else: supports_workers = str(int(ctx.attr._supports_workers)) arguments = list(_EXTRA_NODE_OPTIONS_FLAGS) # One at-sign makes this a params-file, enabling the worker strategy. # Two at-signs escapes the argument so it's passed through to ngc # rather than the contents getting expanded. if supports_workers == "1": arguments += ["@@" + tsconfig_file.path] else: arguments += ["-p", tsconfig_file.path] arguments += i18n_args ctx.action( progress_message = progress_message, mnemonic = mnemonic, inputs = inputs, outputs = outputs, arguments = arguments, executable = ctx.executable.compiler, execution_requirements = { "supports-workers": supports_workers, }, ) if messages_out != None: ctx.action(inputs = list(inputs), outputs = messages_out, executable = ctx.executable._ng_xi18n, arguments = (_EXTRA_NODE_OPTIONS_FLAGS + [tsconfig_file.path] + # The base path is bin_dir because of the way the ngc # compiler host is configured. So we need to explictily # point to genfiles/ to redirect the output. ["../genfiles/" + messages_out[0].short_path]), progress_message = "Extracting Angular 2 messages (ng_xi18n)", mnemonic = "Angular2MessageExtractor") if not locale and not ctx.attr.no_i18n: return struct( label = label, tsconfig = tsconfig_file, inputs = inputs, outputs = outputs, compiler = ctx.executable.compiler, ) return None def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) # The compiler only needs to see TypeScript sources from the npm dependencies, # but may need to look at package.json and ngsummary.json files as well. if hasattr(ctx.attr, "node_modules"): file_inputs += [f for f in ctx.files.node_modules if f.path.endswith(".ts") or f.path.endswith(".json")] # If the user supplies a tsconfig.json file, the Angular compiler needs to read it if hasattr(ctx.attr, "tsconfig") and ctx.file.tsconfig: file_inputs.append(ctx.file.tsconfig) # Collect the inputs and summary files from our deps action_inputs = depset(file_inputs, transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps if hasattr(dep, "collect_summaries_aspect_result")]) return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file) def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label _ignored = [label] return _expected_outs(ctx) def _write_bundle_index(ctx): basename = "_%s.bundle_index" % ctx.label.name tsconfig_file = ctx.actions.declare_file("%s.tsconfig.json" % basename) metadata_file = ctx.actions.declare_file("%s.metadata.json" % basename) tstyping_file = ctx.actions.declare_file("%s.d.ts" % basename) tsconfig = dict(tsc_wrapped_tsconfig(ctx, ctx.files.srcs, ctx.files.srcs), **{ "angularCompilerOptions": { "flatModuleOutFile": basename, }, }) if ctx.attr.module_name: tsconfig["angularCompilerOptions"]["flatModuleId"] = ctx.attr.module_name # createBundleIndexHost in bundle_index_host.ts will throw if the "files" has more than one entry. # We don't want to fail() here, however, because not all ng_module's will have the bundle index written. # So we make the assumption that the index.ts file in the highest parent directory is the entry point. index_file = None for f in tsconfig["files"]: if f.endswith("/index.ts"): if not index_file or len(f) < len(index_file): index_file = f tsconfig["files"] = [index_file] ctx.actions.write(tsconfig_file, json_marshal(tsconfig)) outputs = [metadata_file, tstyping_file] ctx.action( progress_message = "Producing metadata for bundle %s" % ctx.label.name, executable = ctx.executable._index_bundler, inputs = ctx.files.srcs + [tsconfig_file], outputs = outputs, arguments = ["-p", tsconfig_file.path], ) return outputs def ng_module_impl(ctx, ts_compile_actions): """Implementation function for the ng_module rule. This is exposed so that google3 can have its own entry point that re-uses this and is not meant as a public API. Args: ctx: the skylark rule context ts_compile_actions: generates all the actions to run an ngc compilation Returns: the result of the ng_module rule as a dict, suitable for conversion by ts_providers_dict_to_struct """ providers = ts_compile_actions( ctx, is_library=True, compile_action=_prodmode_compile_action, devmode_compile_action=_devmode_compile_action, tsc_wrapped_tsconfig=_ngc_tsconfig, outputs = _ts_expected_outs) outs = _expected_outs(ctx) providers["angular"] = { "summaries": _expected_outs(ctx).summaries } providers["ngc_messages"] = outs.i18n_messages # Only produces the flattened "index bundle" metadata when requested by some other rule # and only under Bazel if hasattr(ctx.executable, "_index_bundler"): bundle_index_metadata = _write_bundle_index(ctx) # note, not recursive providers["angular"]["flat_module_metadata"] = depset(bundle_index_metadata) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) NG_MODULE_ATTRIBUTES = { "srcs": attr.label_list(allow_files = [".ts"]), "deps": attr.label_list(aspects = DEPS_ASPECTS + [_collect_summaries_aspect]), "assets": attr.label_list(allow_files = [ ".css", # TODO(alexeagle): change this to ".ng.html" when usages updated ".html", ]), "factories": attr.label_list( allow_files = [".ts", ".html"], mandatory = False), "filter_summaries": attr.bool(default = False), "type_check": attr.bool(default = True), "no_i18n": attr.bool(default = False), "compiler": attr.label( default = Label("//packages/bazel/src/ngc-wrapped"), executable = True, cfg = "host", ), "_ng_xi18n": attr.label( default = Label("//packages/bazel/src/ngc-wrapped:xi18n"), executable = True, cfg = "host", ), "_supports_workers": attr.bool(default = True), } ng_module = rule( implementation = _ng_module_impl, attrs = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{ "tsconfig": attr.label(allow_files = True, single_file = True), # @// is special syntax for the "main" repository # The default assumes the user specified a target "node_modules" in their # root BUILD file. "node_modules": attr.label( default = Label("@//:node_modules") ), "_index_bundler": attr.label( executable = True, cfg = "host", default = Label("//packages/bazel/src:index_bundler")), }), outputs = COMMON_OUTPUTS, )
packages/bazel/src/ng_module.bzl
1
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.9992749094963074, 0.3487468957901001, 0.00016617911751382053, 0.011046475730836391, 0.45747917890548706 ]
{ "id": 11, "code_window": [ "\n", "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 227 }
// #docregion import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from './auth.service'; @Component({ template: ` <h2>LOGIN</h2> <p>{{message}}</p> <p> <button (click)="login()" *ngIf="!authService.isLoggedIn">Login</button> <button (click)="logout()" *ngIf="authService.isLoggedIn">Logout</button> </p>` }) export class LoginComponent { message: string; constructor(public authService: AuthService, public router: Router) { this.setMessage(); } setMessage() { this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out'); } login() { this.message = 'Trying to log in ...'; this.authService.login().subscribe(() => { this.setMessage(); if (this.authService.isLoggedIn) { // Get the redirect URL from our auth service // If no redirect has been set, use the default let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/crisis-center/admin'; // Redirect the user this.router.navigate([redirect]); } }); } logout() { this.authService.logout(); this.setMessage(); } }
aio/content/examples/router/src/app/login.component.1.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017268200463149697, 0.0001704117894405499, 0.00016494886949658394, 0.00017211258818861097, 0.0000029488562631740933 ]
{ "id": 11, "code_window": [ "\n", "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 227 }
/** * @license * Copyright Google Inc. 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.io/license */ import {ddescribe, describe, it} from '@angular/core/testing/src/testing_internal'; import {HttpHeaders} from '../src/headers'; import {HttpResponse} from '../src/response'; { describe('HttpResponse', () => { describe('constructor()', () => { it('fully constructs responses', () => { const resp = new HttpResponse({ body: 'test body', headers: new HttpHeaders({ 'Test': 'Test header', }), status: 201, statusText: 'Created', url: '/test', }); expect(resp.body).toBe('test body'); expect(resp.headers instanceof HttpHeaders).toBeTruthy(); expect(resp.headers.get('Test')).toBe('Test header'); expect(resp.status).toBe(201); expect(resp.statusText).toBe('Created'); expect(resp.url).toBe('/test'); }); it('uses defaults if no args passed', () => { const resp = new HttpResponse({}); expect(resp.headers).not.toBeNull(); expect(resp.status).toBe(200); expect(resp.statusText).toBe('OK'); expect(resp.body).toBeNull(); expect(resp.ok).toBeTruthy(); expect(resp.url).toBeNull(); }); it('accepts a falsy body', () => { expect(new HttpResponse({body: false}).body).toEqual(false); expect(new HttpResponse({body: 0}).body).toEqual(0); }); }); it('.ok is determined by status', () => { const good = new HttpResponse({status: 200}); const alsoGood = new HttpResponse({status: 299}); const badHigh = new HttpResponse({status: 300}); const badLow = new HttpResponse({status: 199}); expect(good.ok).toBe(true); expect(alsoGood.ok).toBe(true); expect(badHigh.ok).toBe(false); expect(badLow.ok).toBe(false); }); describe('.clone()', () => { it('copies the original when given no arguments', () => { const clone = new HttpResponse({body: 'test', status: 201, statusText: 'created', url: '/test'}) .clone(); expect(clone.body).toBe('test'); expect(clone.status).toBe(201); expect(clone.statusText).toBe('created'); expect(clone.url).toBe('/test'); expect(clone.headers).not.toBeNull(); }); it('overrides the original', () => { const orig = new HttpResponse({body: 'test', status: 201, statusText: 'created', url: '/test'}); const clone = orig.clone({body: {data: 'test'}, status: 200, statusText: 'Okay', url: '/bar'}); expect(clone.body).toEqual({data: 'test'}); expect(clone.status).toBe(200); expect(clone.statusText).toBe('Okay'); expect(clone.url).toBe('/bar'); expect(clone.headers).toBe(orig.headers); }); }); }); }
packages/common/http/test/response_spec.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017698697047308087, 0.00017463049152866006, 0.00017029177979566157, 0.00017521869449410588, 0.0000020618424514395883 ]
{ "id": 11, "code_window": [ "\n", "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file):\n", " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 227 }
/** * @license * Copyright Google Inc. 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.io/license */ import {ClassStmt, PartialModule, Statement, StmtModifier} from '@angular/compiler'; import * as ts from 'typescript'; import {MetadataCollector, MetadataValue, ModuleMetadata, isClassMetadata} from '../metadata/index'; import {MetadataTransformer, ValueTransform} from './metadata_cache'; export class PartialModuleMetadataTransformer implements MetadataTransformer { private moduleMap: Map<string, PartialModule>; constructor(modules: PartialModule[]) { this.moduleMap = new Map(modules.map<[string, PartialModule]>(m => [m.fileName, m])); } start(sourceFile: ts.SourceFile): ValueTransform|undefined { const partialModule = this.moduleMap.get(sourceFile.fileName); if (partialModule) { const classMap = new Map<string, ClassStmt>( partialModule.statements.filter(isClassStmt).map<[string, ClassStmt]>(s => [s.name, s])); if (classMap.size > 0) { return (value: MetadataValue, node: ts.Node): MetadataValue => { // For class metadata that is going to be transformed to have a static method ensure the // metadata contains a static declaration the new static method. if (isClassMetadata(value) && node.kind === ts.SyntaxKind.ClassDeclaration) { const classDeclaration = node as ts.ClassDeclaration; if (classDeclaration.name) { const partialClass = classMap.get(classDeclaration.name.text); if (partialClass) { for (const field of partialClass.fields) { if (field.name && field.modifiers && field.modifiers.some(modifier => modifier === StmtModifier.Static)) { value.statics = {...(value.statics || {}), [field.name]: {}}; } } } } } return value; }; } } } } function isClassStmt(v: Statement): v is ClassStmt { return v instanceof ClassStmt; }
packages/compiler-cli/src/transformers/r3_metadata_transform.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017384588136337698, 0.00017134186055045575, 0.00016817035793792456, 0.00017219761502929032, 0.0000020208469777571736 ]
{ "id": 12, "code_window": [ " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n", " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file)\n", "\n", "def _ts_expected_outs(ctx, label):\n", " # rules_typescript expects a function with two arguments, but our\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 230 }
# Copyright Google Inc. 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.io/license """Implementation of the ng_module rule. """ load(":rules_typescript.bzl", "tsc_wrapped_tsconfig", "COMMON_ATTRIBUTES", "COMMON_OUTPUTS", "compile_ts", "DEPS_ASPECTS", "ts_providers_dict_to_struct", "json_marshal", ) def _basename_of(ctx, file): ext_len = len(".ts") if file.short_path.endswith(".ng.html"): ext_len = len(".ng.html") elif file.short_path.endswith(".html"): ext_len = len(".html") return file.short_path[len(ctx.label.package) + 1:-ext_len] # Calculate the expected output of the template compiler for every source in # in the library. Most of these will be produced as empty files but it is # unknown, without parsing, which will be empty. def _expected_outs(ctx): devmode_js_files = [] closure_js_files = [] declaration_files = [] summary_files = [] factory_basename_set = depset([_basename_of(ctx, src) for src in ctx.files.factories]) for src in ctx.files.srcs + ctx.files.assets: if src.short_path.endswith(".ts") and not src.short_path.endswith(".d.ts"): basename = src.short_path[len(ctx.label.package) + 1:-len(".ts")] if len(factory_basename_set) == 0 or basename in factory_basename_set: devmode_js = [ ".ngfactory.js", ".ngsummary.js", ".js", ] summaries = [".ngsummary.json"] else: devmode_js = [".js"] summaries = [] elif src.short_path.endswith(".css"): basename = src.short_path[len(ctx.label.package) + 1:-len(".css")] devmode_js = [ ".css.shim.ngstyle.js", ".css.ngstyle.js", ] summaries = [] else: continue filter_summaries = ctx.attr.filter_summaries closure_js = [f.replace(".js", ".closure.js") for f in devmode_js if not filter_summaries or not f.endswith(".ngsummary.js")] declarations = [f.replace(".js", ".d.ts") for f in devmode_js] devmode_js_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in devmode_js] closure_js_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in closure_js] declaration_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in declarations] summary_files += [ctx.new_file(ctx.bin_dir, basename + ext) for ext in summaries] i18n_messages_files = [ctx.new_file(ctx.genfiles_dir, ctx.label.name + "_ngc_messages.xmb")] return struct( closure_js = closure_js_files, devmode_js = devmode_js_files, declarations = declaration_files, summaries = summary_files, i18n_messages = i18n_messages_files, ) def _ngc_tsconfig(ctx, files, srcs, **kwargs): outs = _expected_outs(ctx) if "devmode_manifest" in kwargs: expected_outs = outs.devmode_js + outs.declarations + outs.summaries else: expected_outs = outs.closure_js return dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{ "angularCompilerOptions": { "generateCodeForLibraries": False, "allowEmptyCodegenFiles": True, "enableSummariesForJit": True, "fullTemplateTypeCheck": ctx.attr.type_check, # FIXME: wrong place to de-dupe "expectedOut": depset([o.path for o in expected_outs]).to_list() } }) def _collect_summaries_aspect_impl(target, ctx): results = depset(target.angular.summaries if hasattr(target, "angular") else []) # If we are visiting empty-srcs ts_library, this is a re-export srcs = ctx.rule.attr.srcs if hasattr(ctx.rule.attr, "srcs") else [] # "re-export" rules should expose all the files of their deps if not srcs: for dep in ctx.rule.attr.deps: if (hasattr(dep, "angular")): results = depset(dep.angular.summaries, transitive = [results]) return struct(collect_summaries_aspect_result = results) _collect_summaries_aspect = aspect( implementation = _collect_summaries_aspect_impl, attr_aspects = ["deps"], ) # Extra options passed to Node when running ngc. _EXTRA_NODE_OPTIONS_FLAGS = [ # Expose the v8 garbage collection API to JS. "--node_options=--expose-gc" ] def ngc_compile_action(ctx, label, inputs, outputs, messages_out, tsconfig_file, locale=None, i18n_args=[]): """Helper function to create the ngc action. This is exposed for google3 to wire up i18n replay rules, and is not intended as part of the public API. Args: ctx: skylark context label: the label of the ng_module being compiled inputs: passed to the ngc action's inputs outputs: passed to the ngc action's outputs messages_out: produced xmb files tsconfig_file: tsconfig file with settings used for the compilation locale: i18n locale, or None i18n_args: additional command-line arguments to ngc Returns: the parameters of the compilation which will be used to replay the ngc action for i18N. """ mnemonic = "AngularTemplateCompile" progress_message = "Compiling Angular templates (ngc) %s" % label if locale: mnemonic = "AngularI18NMerging" supports_workers = "0" progress_message = ("Recompiling Angular templates (ngc) %s for locale %s" % (label, locale)) else: supports_workers = str(int(ctx.attr._supports_workers)) arguments = list(_EXTRA_NODE_OPTIONS_FLAGS) # One at-sign makes this a params-file, enabling the worker strategy. # Two at-signs escapes the argument so it's passed through to ngc # rather than the contents getting expanded. if supports_workers == "1": arguments += ["@@" + tsconfig_file.path] else: arguments += ["-p", tsconfig_file.path] arguments += i18n_args ctx.action( progress_message = progress_message, mnemonic = mnemonic, inputs = inputs, outputs = outputs, arguments = arguments, executable = ctx.executable.compiler, execution_requirements = { "supports-workers": supports_workers, }, ) if messages_out != None: ctx.action(inputs = list(inputs), outputs = messages_out, executable = ctx.executable._ng_xi18n, arguments = (_EXTRA_NODE_OPTIONS_FLAGS + [tsconfig_file.path] + # The base path is bin_dir because of the way the ngc # compiler host is configured. So we need to explictily # point to genfiles/ to redirect the output. ["../genfiles/" + messages_out[0].short_path]), progress_message = "Extracting Angular 2 messages (ng_xi18n)", mnemonic = "Angular2MessageExtractor") if not locale and not ctx.attr.no_i18n: return struct( label = label, tsconfig = tsconfig_file, inputs = inputs, outputs = outputs, compiler = ctx.executable.compiler, ) return None def _compile_action(ctx, inputs, outputs, messages_out, tsconfig_file): # Give the Angular compiler all the user-listed assets file_inputs = list(ctx.files.assets) # The compiler only needs to see TypeScript sources from the npm dependencies, # but may need to look at package.json and ngsummary.json files as well. if hasattr(ctx.attr, "node_modules"): file_inputs += [f for f in ctx.files.node_modules if f.path.endswith(".ts") or f.path.endswith(".json")] # If the user supplies a tsconfig.json file, the Angular compiler needs to read it if hasattr(ctx.attr, "tsconfig") and ctx.file.tsconfig: file_inputs.append(ctx.file.tsconfig) # Collect the inputs and summary files from our deps action_inputs = depset(file_inputs, transitive = [inputs] + [dep.collect_summaries_aspect_result for dep in ctx.attr.deps if hasattr(dep, "collect_summaries_aspect_result")]) return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, messages_out, tsconfig_file) def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file): outs = _expected_outs(ctx) return _compile_action(ctx, inputs, outputs + outs.closure_js, outs.i18n_messages, tsconfig_file) def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file): outs = _expected_outs(ctx) compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file) def _ts_expected_outs(ctx, label): # rules_typescript expects a function with two arguments, but our # implementation doesn't use the label _ignored = [label] return _expected_outs(ctx) def _write_bundle_index(ctx): basename = "_%s.bundle_index" % ctx.label.name tsconfig_file = ctx.actions.declare_file("%s.tsconfig.json" % basename) metadata_file = ctx.actions.declare_file("%s.metadata.json" % basename) tstyping_file = ctx.actions.declare_file("%s.d.ts" % basename) tsconfig = dict(tsc_wrapped_tsconfig(ctx, ctx.files.srcs, ctx.files.srcs), **{ "angularCompilerOptions": { "flatModuleOutFile": basename, }, }) if ctx.attr.module_name: tsconfig["angularCompilerOptions"]["flatModuleId"] = ctx.attr.module_name # createBundleIndexHost in bundle_index_host.ts will throw if the "files" has more than one entry. # We don't want to fail() here, however, because not all ng_module's will have the bundle index written. # So we make the assumption that the index.ts file in the highest parent directory is the entry point. index_file = None for f in tsconfig["files"]: if f.endswith("/index.ts"): if not index_file or len(f) < len(index_file): index_file = f tsconfig["files"] = [index_file] ctx.actions.write(tsconfig_file, json_marshal(tsconfig)) outputs = [metadata_file, tstyping_file] ctx.action( progress_message = "Producing metadata for bundle %s" % ctx.label.name, executable = ctx.executable._index_bundler, inputs = ctx.files.srcs + [tsconfig_file], outputs = outputs, arguments = ["-p", tsconfig_file.path], ) return outputs def ng_module_impl(ctx, ts_compile_actions): """Implementation function for the ng_module rule. This is exposed so that google3 can have its own entry point that re-uses this and is not meant as a public API. Args: ctx: the skylark rule context ts_compile_actions: generates all the actions to run an ngc compilation Returns: the result of the ng_module rule as a dict, suitable for conversion by ts_providers_dict_to_struct """ providers = ts_compile_actions( ctx, is_library=True, compile_action=_prodmode_compile_action, devmode_compile_action=_devmode_compile_action, tsc_wrapped_tsconfig=_ngc_tsconfig, outputs = _ts_expected_outs) outs = _expected_outs(ctx) providers["angular"] = { "summaries": _expected_outs(ctx).summaries } providers["ngc_messages"] = outs.i18n_messages # Only produces the flattened "index bundle" metadata when requested by some other rule # and only under Bazel if hasattr(ctx.executable, "_index_bundler"): bundle_index_metadata = _write_bundle_index(ctx) # note, not recursive providers["angular"]["flat_module_metadata"] = depset(bundle_index_metadata) return providers def _ng_module_impl(ctx): return ts_providers_dict_to_struct(ng_module_impl(ctx, compile_ts)) NG_MODULE_ATTRIBUTES = { "srcs": attr.label_list(allow_files = [".ts"]), "deps": attr.label_list(aspects = DEPS_ASPECTS + [_collect_summaries_aspect]), "assets": attr.label_list(allow_files = [ ".css", # TODO(alexeagle): change this to ".ng.html" when usages updated ".html", ]), "factories": attr.label_list( allow_files = [".ts", ".html"], mandatory = False), "filter_summaries": attr.bool(default = False), "type_check": attr.bool(default = True), "no_i18n": attr.bool(default = False), "compiler": attr.label( default = Label("//packages/bazel/src/ngc-wrapped"), executable = True, cfg = "host", ), "_ng_xi18n": attr.label( default = Label("//packages/bazel/src/ngc-wrapped:xi18n"), executable = True, cfg = "host", ), "_supports_workers": attr.bool(default = True), } ng_module = rule( implementation = _ng_module_impl, attrs = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{ "tsconfig": attr.label(allow_files = True, single_file = True), # @// is special syntax for the "main" repository # The default assumes the user specified a target "node_modules" in their # root BUILD file. "node_modules": attr.label( default = Label("@//:node_modules") ), "_index_bundler": attr.label( executable = True, cfg = "host", default = Label("//packages/bazel/src:index_bundler")), }), outputs = COMMON_OUTPUTS, )
packages/bazel/src/ng_module.bzl
1
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.997882068157196, 0.0637565329670906, 0.00016317333211190999, 0.0024260496720671654, 0.22469374537467957 ]
{ "id": 12, "code_window": [ " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n", " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file)\n", "\n", "def _ts_expected_outs(ctx, label):\n", " # rules_typescript expects a function with two arguments, but our\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 230 }
/** * @license * Copyright Google Inc. 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.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'so-ET', [ ['sn.', 'gn.'], , ], , [ ['A', 'I', 'T', 'A', 'Kh', 'J', 'S'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'], ['Axad', 'Isniin', 'Talaado', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'] ], , [ ['K', 'L', 'S', 'A', 'S', 'L', 'T', 'S', 'S', 'T', 'K', 'L'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [ ['CK', 'CD'], , ], 0, [6, 0], ['dd/MM/yy', 'dd-MMM-y', 'dd MMMM y', 'EEEE, MMMM dd, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], [ '{1} {0}', , , ], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'Br', 'Birta Itoobbiya', {'ETB': ['Br'], 'JPY': ['JP¥', '¥'], 'SOS': ['S'], 'USD': ['US$', '$']}, plural ];
packages/common/locales/so-ET.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017685521743260324, 0.00017473477055318654, 0.00017088190361391753, 0.00017526796727906913, 0.0000019529320525180083 ]
{ "id": 12, "code_window": [ " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n", " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file)\n", "\n", "def _ts_expected_outs(ctx, label):\n", " # rules_typescript expects a function with two arguments, but our\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 230 }
var testPackageFactory = require('../../helpers/test-package'); var Dgeni = require('dgeni'); describe('link inline-tag-def', function() { let injector, tag, getLinkInfo, log; beforeEach(() => { getLinkInfo = jasmine.createSpy('getLinkInfo'); const testPackage = testPackageFactory('links-package', true) .factory('getLinkInfo', function() { return getLinkInfo; }); getLinkInfo.disambiguators = []; const dgeni = new Dgeni([testPackage]); injector = dgeni.configureInjector(); tag = injector.get('linkInlineTagDef'); log = injector.get('log'); }); it('should be available as a service', () => { expect(tag).toBeDefined(); expect(tag.name).toEqual('link'); expect(tag.aliases).toEqual(['linkDocs']); }); it('should call getLinkInfo', () => { const doc = {}; const tagName = 'link'; const tagDescription = 'doc-id link text'; getLinkInfo.and.returnValue({ url: 'url/to/doc', title: 'link text' }); tag.handler(doc, tagName, tagDescription); expect(getLinkInfo).toHaveBeenCalledWith('doc-id', 'link text', doc); }); it('should return an HTML anchor tag', () => { const doc = {}; const tagName = 'link'; const tagDescription = 'doc-id link text'; getLinkInfo.and.returnValue({ url: 'url/to/doc', title: 'link text' }); const result = tag.handler(doc, tagName, tagDescription); expect(result).toEqual('<a href=\'url/to/doc\'>link text</a>'); }); it('should log a warning if not failOnBadLink and the link is "bad"', () => { const doc = {}; const tagName = 'link'; const tagDescription = 'doc-id link text'; getLinkInfo.and.returnValue({ valid: false, error: 'Error message', errorType: 'error' }); expect(() => tag.handler(doc, tagName, tagDescription)).not.toThrow(); expect(log.warn).toHaveBeenCalledWith('Error in {@link doc-id link text} - Error message - doc'); }); it('should throw an error if failOnBadLink and the link is "bad"', () => { const doc = {}; const tagName = 'link'; const tagDescription = 'doc-id link text'; getLinkInfo.and.returnValue({ valid: false, error: 'Error message', errorType: 'error' }); tag.failOnBadLink = true; expect(() => tag.handler(doc, tagName, tagDescription)).toThrowError('Error in {@link doc-id link text} - Error message - doc'); }); });
aio/tools/transforms/links-package/inline-tag-defs/link.spec.js
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017860323714558035, 0.00017545721493661404, 0.00017282004409935325, 0.00017526428564451635, 0.0000019563758542062715 ]
{ "id": 12, "code_window": [ " outs = _expected_outs(ctx)\n", " compile_action_outputs = outputs + outs.devmode_js + outs.declarations + outs.summaries\n", " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file)\n", "\n", "def _ts_expected_outs(ctx, label):\n", " # rules_typescript expects a function with two arguments, but our\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _compile_action(ctx, inputs, compile_action_outputs, None, tsconfig_file, node_opts)\n" ], "file_path": "packages/bazel/src/ng_module.bzl", "type": "replace", "edit_start_line_idx": 230 }
// #docregion import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .then(success => console.log(`Bootstrap success`)) .catch(err => console.error(err));
aio/content/examples/styleguide/src/02-05/main.ts
0
https://github.com/angular/angular/commit/ca06af40f4b731eda1f3f4cd5d9779505bf25a48
[ 0.00017781072529032826, 0.00017781072529032826, 0.00017781072529032826, 0.00017781072529032826, 0 ]
{ "id": 0, "code_window": [ " var series = data[i];\n", " var axis = yaxis[series.yaxis - 1];\n", " var formater = kbn.valueFormats[scope.panel.y_formats[series.yaxis - 1]];\n", " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals);\n", " if(!scope.$$phase) { scope.$digest(); }\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals+ 2);\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 108 }
define([ 'angular', 'app', 'lodash', 'kbn', 'jquery', 'jquery.flot', 'jquery.flot.time', ], function (angular, app, _, kbn, $) { 'use strict'; var module = angular.module('grafana.panels.graph'); module.directive('graphLegend', function(popoverSrv) { return { link: function(scope, elem) { var $container = $('<section class="graph-legend"></section>'); var firstRender = true; var panel = scope.panel; var data; var i; scope.$on('render', function() { data = scope.seriesList; if (data) { render(); } }); function getSeriesIndexForElement(el) { return el.parents('[data-series-index]').data('series-index'); } function openColorSelector(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; var popoverScope = scope.$new(); popoverScope.series = seriesInfo; popoverSrv.show({ element: $(':first-child', el), templateUrl: 'app/panels/graph/legend.popover.html', scope: popoverScope }); } function toggleSeries(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; scope.toggleSeries(seriesInfo, e); } function render() { if (firstRender) { elem.append($container); $container.on('click', '.graph-legend-icon', openColorSelector); $container.on('click', '.graph-legend-alias', toggleSeries); firstRender = false; } $container.empty(); $container.toggleClass('graph-legend-table', panel.legend.alignAsTable === true); if (panel.legend.alignAsTable) { var header = '<tr>'; header += '<th></th>'; header += '<th></th>'; if (panel.legend.values) { if (panel.legend.min) { header += '<th>min</div>'; } if (panel.legend.max) { header += '<th>max</div>'; } if (panel.legend.avg) { header += '<th>avg</div>'; } if (panel.legend.current) { header += '<th>current</div>'; } if (panel.legend.total) { header += '<th>total</div>'; } } header += '</tr>'; $container.append($(header)); } for (i = 0; i < data.length; i++) { var series = data[i]; var html = '<div class="graph-legend-series'; if (series.yaxis === 2) { html += ' pull-right'; } if (scope.hiddenSeries[series.alias]) { html += ' graph-legend-series-hidden'; } html += '" data-series-index="' + i + '">'; html += '<div class="graph-legend-icon">'; html += '<i class="icon-minus pointer" style="color:' + series.color + '"></i>'; html += '</div>'; html += '<div class="graph-legend-alias">'; html += '<a>' + series.label + '</a>'; html += '</div>'; var avg = series.formatValue(series.stats.avg); var current = series.formatValue(series.stats.current); var min = series.formatValue(series.stats.min); var max = series.formatValue(series.stats.max); var total = series.formatValue(series.stats.total); if (panel.legend.values) { if (panel.legend.min) { html += '<div class="graph-legend-value min">' + min + '</div>'; } if (panel.legend.max) { html += '<div class="graph-legend-value max">' + max + '</div>'; } if (panel.legend.avg) { html += '<div class="graph-legend-value avg">' + avg + '</div>'; } if (panel.legend.current) { html += '<div class="graph-legend-value">' + current + '</div>'; } if (panel.legend.total) { html += '<div class="graph-legend-value total">' + total + '</div>'; } } html += '</div>'; $container.append($(html)); } } } }; }); });
src/app/panels/graph/legend.js
1
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.9865526556968689, 0.11761970072984695, 0.00016373893595300615, 0.0010996503988280892, 0.2856462001800537 ]
{ "id": 0, "code_window": [ " var series = data[i];\n", " var axis = yaxis[series.yaxis - 1];\n", " var formater = kbn.valueFormats[scope.panel.y_formats[series.yaxis - 1]];\n", " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals);\n", " if(!scope.$$phase) { scope.$digest(); }\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals+ 2);\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 108 }
// // Pagination (multiple pages) // -------------------------------------------------- // Space out pagination from surrounding content .pagination { margin: @baseLineHeight 0; } .pagination ul { // Allow for text-based alignment display: inline-block; .ie7-inline-block(); // Reset default ul styles margin-left: 0; margin-bottom: 0; // Visuals .border-radius(@baseBorderRadius); .box-shadow(0 1px 2px rgba(0,0,0,.05)); } .pagination ul > li { display: inline; // Remove list-style and block-level defaults } .pagination ul > li > a, .pagination ul > li > span { float: left; // Collapse white-space padding: 4px 12px; line-height: @baseLineHeight; text-decoration: none; background-color: @paginationBackground; border: 1px solid @paginationBorder; border-left-width: 0; } .pagination ul > li > a:hover, .pagination ul > li > a:focus, .pagination ul > .active > a, .pagination ul > .active > span { background-color: @paginationActiveBackground; } .pagination ul > .active > a, .pagination ul > .active > span { color: @grayLight; cursor: default; } .pagination ul > .disabled > span, .pagination ul > .disabled > a, .pagination ul > .disabled > a:hover, .pagination ul > .disabled > a:focus { color: @grayLight; background-color: transparent; cursor: default; } .pagination ul > li:first-child > a, .pagination ul > li:first-child > span { border-left-width: 1px; .border-left-radius(@baseBorderRadius); } .pagination ul > li:last-child > a, .pagination ul > li:last-child > span { .border-right-radius(@baseBorderRadius); } // Alignment // -------------------------------------------------- .pagination-centered { text-align: center; } .pagination-right { text-align: right; } // Sizing // -------------------------------------------------- // Large .pagination-large { ul > li > a, ul > li > span { padding: @paddingLarge; font-size: @fontSizeLarge; } ul > li:first-child > a, ul > li:first-child > span { .border-left-radius(@borderRadiusLarge); } ul > li:last-child > a, ul > li:last-child > span { .border-right-radius(@borderRadiusLarge); } } // Small and mini .pagination-mini, .pagination-small { ul > li:first-child > a, ul > li:first-child > span { .border-left-radius(@borderRadiusSmall); } ul > li:last-child > a, ul > li:last-child > span { .border-right-radius(@borderRadiusSmall); } } // Small .pagination-small { ul > li > a, ul > li > span { padding: @paddingSmall; font-size: @fontSizeSmall; } } // Mini .pagination-mini { ul > li > a, ul > li > span { padding: @paddingMini; font-size: @fontSizeMini; } }
src/vendor/bootstrap/less/pagination.less
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.0001780964812496677, 0.00017427359125576913, 0.00016179707017727196, 0.00017485767602920532, 0.000004085647560714278 ]
{ "id": 0, "code_window": [ " var series = data[i];\n", " var axis = yaxis[series.yaxis - 1];\n", " var formater = kbn.valueFormats[scope.panel.y_formats[series.yaxis - 1]];\n", " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals);\n", " if(!scope.$$phase) { scope.$digest(); }\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals+ 2);\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 108 }
// // Accordion // -------------------------------------------------- // Parent container .accordion { margin-bottom: @baseLineHeight; } // Group == heading + body .accordion-group { margin-bottom: 2px; border: 1px solid #e5e5e5; .border-radius(@baseBorderRadius); } .accordion-heading { border-bottom: 0; } .accordion-heading .accordion-toggle { display: block; padding: 8px 15px; } // General toggle styles .accordion-toggle { cursor: pointer; } // Inner needs the styles because you can't animate properly with any styles on the element .accordion-inner { padding: 9px 15px; border-top: 1px solid #e5e5e5; }
src/vendor/bootstrap/less/accordion.less
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017553054203744978, 0.00017332764400634915, 0.00017206351913046092, 0.00017285827198065817, 0.0000013706967365578748 ]
{ "id": 0, "code_window": [ " var series = data[i];\n", " var axis = yaxis[series.yaxis - 1];\n", " var formater = kbn.valueFormats[scope.panel.y_formats[series.yaxis - 1]];\n", " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals);\n", " if(!scope.$$phase) { scope.$digest(); }\n", " }\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals+ 2);\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 108 }
// // Variables // -------------------------------------------------- // Global values // -------------------------------------------------- // Grays // ------------------------- @black: #000; @grayDarker: #222; @grayDark: #333; @gray: #555; @grayLight: #999; @grayLighter: #eee; @white: #fff; // Accent colors // ------------------------- @blue: #049cdb; @blueDark: #0064cd; @green: #46a546; @red: #9d261d; @yellow: #ffc40d; @orange: #f89406; @pink: #c3325f; @purple: #7a43b6; // Scaffolding // ------------------------- @bodyBackground: @white; @textColor: @grayDark; // Links // ------------------------- @linkColor: #08c; @linkColorHover: darken(@linkColor, 15%); // Typography // ------------------------- @sansFontFamily: "Helvetica Neue", Helvetica, Arial, sans-serif; @serifFontFamily: Georgia, "Times New Roman", Times, serif; @monoFontFamily: Monaco, Menlo, Consolas, "Courier New", monospace; @baseFontSize: 14px; @baseFontFamily: @sansFontFamily; @baseLineHeight: 20px; @altFontFamily: @serifFontFamily; @headingsFontFamily: inherit; // empty to use BS default, @baseFontFamily @headingsFontWeight: bold; // instead of browser default, bold @headingsColor: inherit; // empty to use BS default, @textColor // Component sizing // ------------------------- // Based on 14px font-size and 20px line-height @fontSizeLarge: @baseFontSize * 1.25; // ~18px @fontSizeSmall: @baseFontSize * 0.85; // ~12px @fontSizeMini: @baseFontSize * 0.75; // ~11px @paddingLarge: 11px 19px; // 44px @paddingSmall: 2px 10px; // 26px @paddingMini: 0 6px; // 22px @baseBorderRadius: 4px; @borderRadiusLarge: 6px; @borderRadiusSmall: 3px; // Tables // ------------------------- @tableBackground: transparent; // overall background-color @tableBackgroundAccent: #f9f9f9; // for striping @tableBackgroundHover: #f5f5f5; // for hover @tableBorder: #ddd; // table and cell border // Buttons // ------------------------- @btnBackground: @white; @btnBackgroundHighlight: darken(@white, 10%); @btnBorder: #ccc; @btnPrimaryBackground: @linkColor; @btnPrimaryBackgroundHighlight: spin(@btnPrimaryBackground, 20%); @btnInfoBackground: #5bc0de; @btnInfoBackgroundHighlight: #2f96b4; @btnSuccessBackground: #62c462; @btnSuccessBackgroundHighlight: #51a351; @btnWarningBackground: lighten(@orange, 15%); @btnWarningBackgroundHighlight: @orange; @btnDangerBackground: #ee5f5b; @btnDangerBackgroundHighlight: #bd362f; @btnInverseBackground: #444; @btnInverseBackgroundHighlight: @grayDarker; // Forms // ------------------------- @inputBackground: @white; @inputBorder: #ccc; @inputBorderRadius: @baseBorderRadius; @inputDisabledBackground: @grayLighter; @formActionsBackground: #f5f5f5; @inputHeight: @baseLineHeight + 10px; // base line-height + 8px vertical padding + 2px top/bottom border // Dropdowns // ------------------------- @dropdownBackground: @white; @dropdownBorder: rgba(0,0,0,.2); @dropdownDividerTop: #e5e5e5; @dropdownDividerBottom: @white; @dropdownLinkColor: @grayDark; @dropdownLinkColorHover: @white; @dropdownLinkColorActive: @white; @dropdownLinkBackgroundActive: @linkColor; @dropdownLinkBackgroundHover: @dropdownLinkBackgroundActive; // COMPONENT VARIABLES // -------------------------------------------------- // Z-index master list // ------------------------- // Used for a bird's eye view of components dependent on the z-axis // Try to avoid customizing these :) @zindexDropdown: 1000; @zindexPopover: 1010; @zindexTooltip: 1030; @zindexFixedNavbar: 1030; @zindexModalBackdrop: 1040; @zindexModal: 1050; // Sprite icons path // ------------------------- @iconSpritePath: "../img/glyphicons-halflings.png"; @iconWhiteSpritePath: "../img/glyphicons-halflings-white.png"; // Input placeholder text color // ------------------------- @placeholderText: @grayLight; // Hr border color // ------------------------- @hrBorder: @grayLighter; // Horizontal forms & lists // ------------------------- @horizontalComponentOffset: 180px; // Wells // ------------------------- @wellBackground: #f5f5f5; // Navbar // ------------------------- @navbarCollapseWidth: 979px; @navbarCollapseDesktopWidth: @navbarCollapseWidth + 1; @navbarHeight: 40px; @navbarBackgroundHighlight: #ffffff; @navbarBackground: darken(@navbarBackgroundHighlight, 5%); @navbarBorder: darken(@navbarBackground, 12%); @navbarText: #777; @navbarLinkColor: #777; @navbarLinkColorHover: @grayDark; @navbarLinkColorActive: @gray; @navbarLinkBackgroundHover: transparent; @navbarLinkBackgroundActive: darken(@navbarBackground, 5%); @navbarBrandColor: @navbarLinkColor; // Inverted navbar @navbarInverseBackground: #111111; @navbarInverseBackgroundHighlight: #222222; @navbarInverseBorder: #252525; @navbarInverseText: @grayLight; @navbarInverseLinkColor: @grayLight; @navbarInverseLinkColorHover: @white; @navbarInverseLinkColorActive: @navbarInverseLinkColorHover; @navbarInverseLinkBackgroundHover: transparent; @navbarInverseLinkBackgroundActive: @navbarInverseBackground; @navbarInverseSearchBackground: lighten(@navbarInverseBackground, 25%); @navbarInverseSearchBackgroundFocus: @white; @navbarInverseSearchBorder: @navbarInverseBackground; @navbarInverseSearchPlaceholderColor: #ccc; @navbarInverseBrandColor: @navbarInverseLinkColor; // Pagination // ------------------------- @paginationBackground: #fff; @paginationBorder: #ddd; @paginationActiveBackground: #f5f5f5; // Hero unit // ------------------------- @heroUnitBackground: @grayLighter; @heroUnitHeadingColor: inherit; @heroUnitLeadColor: inherit; // Form states and alerts // ------------------------- @warningText: #c09853; @warningBackground: #fcf8e3; @warningBorder: darken(spin(@warningBackground, -10), 3%); @errorText: #b94a48; @errorBackground: #f2dede; @errorBorder: darken(spin(@errorBackground, -10), 3%); @successText: #468847; @successBackground: #dff0d8; @successBorder: darken(spin(@successBackground, -10), 5%); @infoText: #3a87ad; @infoBackground: #d9edf7; @infoBorder: darken(spin(@infoBackground, -10), 7%); // Tooltips and popovers // ------------------------- @tooltipColor: #fff; @tooltipBackground: #000; @tooltipArrowWidth: 5px; @tooltipArrowColor: @tooltipBackground; @popoverBackground: #fff; @popoverArrowWidth: 10px; @popoverArrowColor: #fff; @popoverTitleBackground: darken(@popoverBackground, 3%); // Special enhancement for popovers @popoverArrowOuterWidth: @popoverArrowWidth + 1; @popoverArrowOuterColor: rgba(0,0,0,.25); // GRID // -------------------------------------------------- // Default 940px grid // ------------------------- @gridColumns: 12; @gridColumnWidth: 60px; @gridGutterWidth: 20px; @gridRowWidth: (@gridColumns * @gridColumnWidth) + (@gridGutterWidth * (@gridColumns - 1)); // 1200px min @gridColumnWidth1200: 70px; @gridGutterWidth1200: 30px; @gridRowWidth1200: (@gridColumns * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns - 1)); // 768px-979px @gridColumnWidth768: 42px; @gridGutterWidth768: 20px; @gridRowWidth768: (@gridColumns * @gridColumnWidth768) + (@gridGutterWidth768 * (@gridColumns - 1)); // Fluid grid // ------------------------- @fluidGridColumnWidth: percentage(@gridColumnWidth/@gridRowWidth); @fluidGridGutterWidth: percentage(@gridGutterWidth/@gridRowWidth); // 1200px min @fluidGridColumnWidth1200: percentage(@gridColumnWidth1200/@gridRowWidth1200); @fluidGridGutterWidth1200: percentage(@gridGutterWidth1200/@gridRowWidth1200); // 768px-979px @fluidGridColumnWidth768: percentage(@gridColumnWidth768/@gridRowWidth768); @fluidGridGutterWidth768: percentage(@gridGutterWidth768/@gridRowWidth768);
src/vendor/bootstrap/less/variables.less
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017876271158456802, 0.00017507898155599833, 0.00017061049584299326, 0.00017478248628322035, 0.0000018147932223655516 ]
{ "id": 1, "code_window": [ " scope.toggleSeries(seriesInfo, e);\n", " }\n", "\n", " function render() {\n", " if (firstRender) {\n", " elem.append($container);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function sortLegend(e) {\n", "\n", " }\n", "\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 55 }
define([ 'angular', 'app', 'lodash', 'kbn', 'jquery', 'jquery.flot', 'jquery.flot.time', ], function (angular, app, _, kbn, $) { 'use strict'; var module = angular.module('grafana.panels.graph'); module.directive('graphLegend', function(popoverSrv) { return { link: function(scope, elem) { var $container = $('<section class="graph-legend"></section>'); var firstRender = true; var panel = scope.panel; var data; var i; scope.$on('render', function() { data = scope.seriesList; if (data) { render(); } }); function getSeriesIndexForElement(el) { return el.parents('[data-series-index]').data('series-index'); } function openColorSelector(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; var popoverScope = scope.$new(); popoverScope.series = seriesInfo; popoverSrv.show({ element: $(':first-child', el), templateUrl: 'app/panels/graph/legend.popover.html', scope: popoverScope }); } function toggleSeries(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; scope.toggleSeries(seriesInfo, e); } function render() { if (firstRender) { elem.append($container); $container.on('click', '.graph-legend-icon', openColorSelector); $container.on('click', '.graph-legend-alias', toggleSeries); firstRender = false; } $container.empty(); $container.toggleClass('graph-legend-table', panel.legend.alignAsTable === true); if (panel.legend.alignAsTable) { var header = '<tr>'; header += '<th></th>'; header += '<th></th>'; if (panel.legend.values) { if (panel.legend.min) { header += '<th>min</div>'; } if (panel.legend.max) { header += '<th>max</div>'; } if (panel.legend.avg) { header += '<th>avg</div>'; } if (panel.legend.current) { header += '<th>current</div>'; } if (panel.legend.total) { header += '<th>total</div>'; } } header += '</tr>'; $container.append($(header)); } for (i = 0; i < data.length; i++) { var series = data[i]; var html = '<div class="graph-legend-series'; if (series.yaxis === 2) { html += ' pull-right'; } if (scope.hiddenSeries[series.alias]) { html += ' graph-legend-series-hidden'; } html += '" data-series-index="' + i + '">'; html += '<div class="graph-legend-icon">'; html += '<i class="icon-minus pointer" style="color:' + series.color + '"></i>'; html += '</div>'; html += '<div class="graph-legend-alias">'; html += '<a>' + series.label + '</a>'; html += '</div>'; var avg = series.formatValue(series.stats.avg); var current = series.formatValue(series.stats.current); var min = series.formatValue(series.stats.min); var max = series.formatValue(series.stats.max); var total = series.formatValue(series.stats.total); if (panel.legend.values) { if (panel.legend.min) { html += '<div class="graph-legend-value min">' + min + '</div>'; } if (panel.legend.max) { html += '<div class="graph-legend-value max">' + max + '</div>'; } if (panel.legend.avg) { html += '<div class="graph-legend-value avg">' + avg + '</div>'; } if (panel.legend.current) { html += '<div class="graph-legend-value">' + current + '</div>'; } if (panel.legend.total) { html += '<div class="graph-legend-value total">' + total + '</div>'; } } html += '</div>'; $container.append($(html)); } } } }; }); });
src/app/panels/graph/legend.js
1
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.9984411597251892, 0.12070977687835693, 0.00016677533858455718, 0.0011964355362579226, 0.2814275324344635 ]
{ "id": 1, "code_window": [ " scope.toggleSeries(seriesInfo, e);\n", " }\n", "\n", " function render() {\n", " if (firstRender) {\n", " elem.append($container);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function sortLegend(e) {\n", "\n", " }\n", "\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 55 }
define(['jquery'], function ($) { 'use strict'; /** * jQuery extensions */ var $win = $(window); $.fn.place_tt = (function () { var defaults = { offset: 5, }; return function (x, y, opts) { opts = $.extend(true, {}, defaults, opts); return this.each(function () { var $tooltip = $(this), width, height; $tooltip.addClass('grafana-tooltip'); $("#tooltip").remove(); $tooltip.appendTo(document.body); width = $tooltip.outerWidth(true); height = $tooltip.outerHeight(true); $tooltip.css('left', x + opts.offset + width > $win.width() ? x - opts.offset - width : x + opts.offset); $tooltip.css('top', y + opts.offset + height > $win.height() ? y - opts.offset - height : y + opts.offset); }); }; })(); return $; });
src/app/components/extend-jquery.js
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017372923321090639, 0.00017052292241714895, 0.00016902480274438858, 0.00016966881230473518, 0.000001883505319710821 ]
{ "id": 1, "code_window": [ " scope.toggleSeries(seriesInfo, e);\n", " }\n", "\n", " function render() {\n", " if (firstRender) {\n", " elem.append($container);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function sortLegend(e) {\n", "\n", " }\n", "\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 55 }
// // Grid system // -------------------------------------------------- // Fixed (940px) #grid > .core(@gridColumnWidth, @gridGutterWidth); // Fluid (940px) #grid > .fluid(@fluidGridColumnWidth, @fluidGridGutterWidth); // Reset utility classes due to specificity [class*="span"].hide, .row-fluid [class*="span"].hide { display: none; } [class*="span"].pull-right, .row-fluid [class*="span"].pull-right { float: right; }
src/vendor/bootstrap/less/grid.less
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017881745588965714, 0.0001752295793266967, 0.00017177501285914332, 0.00017509626923128963, 0.0000028766103241650853 ]
{ "id": 1, "code_window": [ " scope.toggleSeries(seriesInfo, e);\n", " }\n", "\n", " function render() {\n", " if (firstRender) {\n", " elem.append($container);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " function sortLegend(e) {\n", "\n", " }\n", "\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 55 }
/** * main app level module */ define([ 'angular', 'jquery', 'lodash', 'require', 'config', 'bootstrap', 'angular-route', 'angular-strap', 'angular-dragdrop', 'extend-jquery', 'bindonce', ], function (angular, $, _, appLevelRequire, config) { "use strict"; var app = angular.module('grafana', []), // we will keep a reference to each module defined before boot, so that we can // go back and allow it to define new features later. Once we boot, this will be false pre_boot_modules = [], // these are the functions that we need to call to register different // features if we define them after boot time register_fns = {}; // This stores the grafana version number app.constant('grafanaVersion',"@grafanaVersion@"); // Use this for cache busting partials app.constant('cacheBust',"cache-bust="+Date.now()); /** * Tells the application to watch the module, once bootstraping has completed * the modules controller, service, etc. functions will be overwritten to register directly * with this application. * @param {[type]} module [description] * @return {[type]} [description] */ app.useModule = function (module) { if (pre_boot_modules) { pre_boot_modules.push(module); } else { _.extend(module, register_fns); } return module; }; app.config(function ($routeProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) { $routeProvider.otherwise({ redirectTo: config.default_route }); // this is how the internet told me to dynamically add modules :/ register_fns.controller = $controllerProvider.register; register_fns.directive = $compileProvider.directive; register_fns.factory = $provide.factory; register_fns.service = $provide.service; register_fns.filter = $filterProvider.register; }); var apps_deps = [ 'ngRoute', '$strap.directives', 'ngDragDrop', 'grafana', 'pasvaz.bindonce' ]; var module_types = ['controllers', 'directives', 'factories', 'services', 'filters', 'routes']; _.each(module_types, function (type) { var module_name = 'grafana.'+type; // create the module app.useModule(angular.module(module_name, [])); // push it into the apps dependencies apps_deps.push(module_name); }); var preBootRequires = [ 'services/all', 'features/all', 'controllers/all', 'directives/all', 'filters/all', 'components/partials', 'routes/all', ]; _.each(config.plugins.dependencies, function(dep) { preBootRequires.push('../plugins/' + dep); }); app.boot = function() { require(preBootRequires, function () { // disable tool tip animation $.fn.tooltip.defaults.animation = false; // bootstrap the app angular .element(document) .ready(function() { angular.bootstrap(document, apps_deps) .invoke(['$rootScope', function ($rootScope) { _.each(pre_boot_modules, function (module) { _.extend(module, register_fns); }); pre_boot_modules = false; $rootScope.requireContext = appLevelRequire; $rootScope.require = function (deps, fn) { var $scope = this; $scope.requireContext(deps, function () { var deps = _.toArray(arguments); // Check that this is a valid scope. if($scope.$id) { $scope.$apply(function () { fn.apply($scope, deps); }); } }); }; }]); }); }); }; return app; });
src/app/app.js
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.0022078384645283222, 0.0003147227980662137, 0.0001647695025894791, 0.00016857426089700311, 0.0005250665126368403 ]
{ "id": 2, "code_window": [ " elem.append($container);\n", " $container.on('click', '.graph-legend-icon', openColorSelector);\n", " $container.on('click', '.graph-legend-alias', toggleSeries);\n", " firstRender = false;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $container.on('click', 'th', sortLegend);\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 60 }
define([ 'angular', 'app', 'lodash', 'kbn', 'jquery', 'jquery.flot', 'jquery.flot.time', ], function (angular, app, _, kbn, $) { 'use strict'; var module = angular.module('grafana.panels.graph'); module.directive('graphLegend', function(popoverSrv) { return { link: function(scope, elem) { var $container = $('<section class="graph-legend"></section>'); var firstRender = true; var panel = scope.panel; var data; var i; scope.$on('render', function() { data = scope.seriesList; if (data) { render(); } }); function getSeriesIndexForElement(el) { return el.parents('[data-series-index]').data('series-index'); } function openColorSelector(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; var popoverScope = scope.$new(); popoverScope.series = seriesInfo; popoverSrv.show({ element: $(':first-child', el), templateUrl: 'app/panels/graph/legend.popover.html', scope: popoverScope }); } function toggleSeries(e) { var el = $(e.currentTarget); var index = getSeriesIndexForElement(el); var seriesInfo = data[index]; scope.toggleSeries(seriesInfo, e); } function render() { if (firstRender) { elem.append($container); $container.on('click', '.graph-legend-icon', openColorSelector); $container.on('click', '.graph-legend-alias', toggleSeries); firstRender = false; } $container.empty(); $container.toggleClass('graph-legend-table', panel.legend.alignAsTable === true); if (panel.legend.alignAsTable) { var header = '<tr>'; header += '<th></th>'; header += '<th></th>'; if (panel.legend.values) { if (panel.legend.min) { header += '<th>min</div>'; } if (panel.legend.max) { header += '<th>max</div>'; } if (panel.legend.avg) { header += '<th>avg</div>'; } if (panel.legend.current) { header += '<th>current</div>'; } if (panel.legend.total) { header += '<th>total</div>'; } } header += '</tr>'; $container.append($(header)); } for (i = 0; i < data.length; i++) { var series = data[i]; var html = '<div class="graph-legend-series'; if (series.yaxis === 2) { html += ' pull-right'; } if (scope.hiddenSeries[series.alias]) { html += ' graph-legend-series-hidden'; } html += '" data-series-index="' + i + '">'; html += '<div class="graph-legend-icon">'; html += '<i class="icon-minus pointer" style="color:' + series.color + '"></i>'; html += '</div>'; html += '<div class="graph-legend-alias">'; html += '<a>' + series.label + '</a>'; html += '</div>'; var avg = series.formatValue(series.stats.avg); var current = series.formatValue(series.stats.current); var min = series.formatValue(series.stats.min); var max = series.formatValue(series.stats.max); var total = series.formatValue(series.stats.total); if (panel.legend.values) { if (panel.legend.min) { html += '<div class="graph-legend-value min">' + min + '</div>'; } if (panel.legend.max) { html += '<div class="graph-legend-value max">' + max + '</div>'; } if (panel.legend.avg) { html += '<div class="graph-legend-value avg">' + avg + '</div>'; } if (panel.legend.current) { html += '<div class="graph-legend-value">' + current + '</div>'; } if (panel.legend.total) { html += '<div class="graph-legend-value total">' + total + '</div>'; } } html += '</div>'; $container.append($(html)); } } } }; }); });
src/app/panels/graph/legend.js
1
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.997879147529602, 0.16529545187950134, 0.00016420344763901085, 0.0008038282976485789, 0.3676140010356903 ]
{ "id": 2, "code_window": [ " elem.append($container);\n", " $container.on('click', '.graph-legend-icon', openColorSelector);\n", " $container.on('click', '.graph-legend-alias', toggleSeries);\n", " firstRender = false;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $container.on('click', 'th', sortLegend);\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 60 }
module.exports = function(config) { return { source: { files: { src: ['Gruntfile.js', '<%= srcDir %>/app/**/*.js'], } }, tests: { files: { src: ['<%= srcDir %>/test/**/*.js'], } }, options: { jshintrc: true, reporter: require('jshint-stylish'), ignores: [ 'node_modules/*', 'dist/*', 'sample/*', '<%= srcDir %>/vendor/*', '<%= srcDir %>/app/panels/*/{lib,leaflet}/*', '<%= srcDir %>/app/dashboards/*' ] } }; };
tasks/options/jshint.js
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017605048196855932, 0.0001753678807290271, 0.00017427426064386964, 0.00017577892867848277, 7.812190574441047e-7 ]
{ "id": 2, "code_window": [ " elem.append($container);\n", " $container.on('click', '.graph-legend-icon', openColorSelector);\n", " $container.on('click', '.graph-legend-alias', toggleSeries);\n", " firstRender = false;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $container.on('click', 'th', sortLegend);\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 60 }
require.config({ baseUrl: 'http://localhost:9876/base/src/app', paths: { specs: '../test/specs', mocks: '../test/mocks', config: '../config.sample', kbn: 'components/kbn', store: 'components/store', settings: 'components/settings', lodash: 'components/lodash.extended', 'lodash-src': '../vendor/lodash', moment: '../vendor/moment', chromath: '../vendor/chromath', filesaver: '../vendor/filesaver', angular: '../vendor/angular/angular', 'angular-route': '../vendor/angular/angular-route', angularMocks: '../vendor/angular/angular-mocks', 'angular-dragdrop': '../vendor/angular/angular-dragdrop', 'angular-strap': '../vendor/angular/angular-strap', timepicker: '../vendor/angular/timepicker', datepicker: '../vendor/angular/datepicker', bindonce: '../vendor/angular/bindonce', crypto: '../vendor/crypto.min', spectrum: '../vendor/spectrum', jquery: '../vendor/jquery/jquery-2.1.1.min', bootstrap: '../vendor/bootstrap/bootstrap', 'bootstrap-tagsinput': '../vendor/tagsinput/bootstrap-tagsinput', 'extend-jquery': 'components/extend-jquery', 'jquery.flot': '../vendor/jquery/jquery.flot', 'jquery.flot.pie': '../vendor/jquery/jquery.flot.pie', 'jquery.flot.events': '../vendor/jquery/jquery.flot.events', 'jquery.flot.selection': '../vendor/jquery/jquery.flot.selection', 'jquery.flot.stack': '../vendor/jquery/jquery.flot.stack', 'jquery.flot.stackpercent':'../vendor/jquery/jquery.flot.stackpercent', 'jquery.flot.time': '../vendor/jquery/jquery.flot.time', 'jquery.flot.crosshair': '../vendor/jquery/jquery.flot.crosshair', 'jquery.flot.fillbelow': '../vendor/jquery/jquery.flot.fillbelow', modernizr: '../vendor/modernizr-2.6.1', }, shim: { bootstrap: { deps: ['jquery'] }, modernizr: { exports: 'Modernizr' }, angular: { deps: ['jquery', 'config'], exports: 'angular' }, angularMocks: { deps: ['angular'], }, crypto: { exports: 'Crypto' }, 'jquery.flot': ['jquery'], 'jquery.flot.pie': ['jquery', 'jquery.flot'], 'jquery.flot.events': ['jquery', 'jquery.flot'], 'jquery.flot.selection':['jquery', 'jquery.flot'], 'jquery.flot.stack': ['jquery', 'jquery.flot'], 'jquery.flot.stackpercent':['jquery', 'jquery.flot'], 'jquery.flot.time': ['jquery', 'jquery.flot'], 'jquery.flot.crosshair':['jquery', 'jquery.flot'], 'jquery.flot.fillbelow':['jquery', 'jquery.flot'], 'angular-route': ['angular'], 'angular-cookies': ['angular'], 'angular-dragdrop': ['jquery', 'angular'], 'angular-loader': ['angular'], 'angular-mocks': ['angular'], 'angular-resource': ['angular'], 'angular-touch': ['angular'], 'bindonce': ['angular'], 'angular-strap': ['angular', 'bootstrap','timepicker', 'datepicker'], 'bootstrap-tagsinput': ['jquery'], timepicker: ['jquery', 'bootstrap'], datepicker: ['jquery', 'bootstrap'], } }); require([ 'angular', 'angularMocks', 'app', ], function(angular) { 'use strict'; for (var file in window.__karma__.files) { if (/spec\.js$/.test(file)) { window.tests.push(file.replace(/^\/base\//, 'http://localhost:9876/base/')); } } angular.module('grafana', ['ngRoute']); angular.module('grafana.services', ['ngRoute', '$strap.directives']); angular.module('grafana.panels', []); angular.module('grafana.filters', []); require([ 'specs/lexer-specs', 'specs/parser-specs', 'specs/gfunc-specs', 'specs/timeSeries-specs', 'specs/row-ctrl-specs', 'specs/graphiteTargetCtrl-specs', 'specs/graphiteDatasource-specs', 'specs/influxSeries-specs', 'specs/influxQueryBuilder-specs', 'specs/influxdb-datasource-specs', 'specs/graph-ctrl-specs', 'specs/grafanaGraph-specs', 'specs/graph-tooltip-specs', 'specs/seriesOverridesCtrl-specs', 'specs/sharePanelCtrl-specs', 'specs/timeSrv-specs', 'specs/templateSrv-specs', 'specs/templateValuesSrv-specs', 'specs/kbn-format-specs', 'specs/dashboardSrv-specs', 'specs/dashboardViewStateSrv-specs' ], function () { window.__karma__.start(); }); });
src/test/test-main.js
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.0001802832557586953, 0.0001743682660162449, 0.00016402272740378976, 0.00017641276645008475, 0.000004612842531059869 ]
{ "id": 2, "code_window": [ " elem.append($container);\n", " $container.on('click', '.graph-legend-icon', openColorSelector);\n", " $container.on('click', '.graph-legend-alias', toggleSeries);\n", " firstRender = false;\n", " }\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $container.on('click', 'th', sortLegend);\n" ], "file_path": "src/app/panels/graph/legend.js", "type": "add", "edit_start_line_idx": 60 }
{ "preset" : "default", "lineBreak" : { "before" : { "VariableDeclarationWithoutInit" : 0, }, "after": { "AssignmentOperator": -1, "ArgumentListArrayExpression": ">=1" } }, "whiteSpace" : { "before" : { }, "after" : { } } }
.jsfmtrc
0
https://github.com/grafana/grafana/commit/882a477c0fc2ff4e2a900c0c082a54cdab3a75ee
[ 0.00017856850172393024, 0.00017712172120809555, 0.0001759083679644391, 0.00017688826483208686, 0.0000010984689424731187 ]
{ "id": 0, "code_window": [ " ],\n", " \"compilerOptions\": {\n", " \"sourceMap\": true\n", " },\n", " \"skipForTemplatePipeline\": true\n", " },\n", " {\n", " \"description\": \"should map default and selected projection (partial compile)\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "packages/compiler-cli/test/compliance/test_cases/source_mapping/inline_templates/TEST_CASES.json", "type": "replace", "edit_start_line_idx": 663 }
/** * @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.io/license */ import * as o from '../../../output/output_ast'; import {ParseSourceSpan} from '../../../parse_util'; import {Identifiers} from '../../../render3/r3_identifiers'; import * as ir from '../ir'; // This file contains helpers for generating calls to Ivy instructions. In particular, each // instruction type is represented as a function, which may select a specific instruction variant // depending on the exact arguments. export function element( slot: number, tag: string, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.element, slot, tag, constIndex, localRefIndex, sourceSpan); } export function elementStart( slot: number, tag: string, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementStart, slot, tag, constIndex, localRefIndex, sourceSpan); } function elementOrContainerBase( instruction: o.ExternalReference, slot: number, tag: string|null, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { const args: o.Expression[] = [o.literal(slot)]; if (tag !== null) { args.push(o.literal(tag)); } if (localRefIndex !== null) { args.push( o.literal(constIndex), // might be null, but that's okay. o.literal(localRefIndex), ); } else if (constIndex !== null) { args.push(o.literal(constIndex)); } return call(instruction, args, sourceSpan); } export function elementEnd(sourceSpan: ParseSourceSpan|null): ir.CreateOp { return call(Identifiers.elementEnd, [], sourceSpan); } export function elementContainerStart( slot: number, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementContainerStart, slot, /* tag */ null, constIndex, localRefIndex, sourceSpan); } export function elementContainer( slot: number, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementContainer, slot, /* tag */ null, constIndex, localRefIndex, sourceSpan); } export function elementContainerEnd(): ir.CreateOp { return call(Identifiers.elementContainerEnd, [], null); } export function template( slot: number, templateFnRef: o.Expression, decls: number, vars: number, tag: string|null, constIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { const args = [o.literal(slot), templateFnRef, o.literal(decls), o.literal(vars)]; if (tag !== null || constIndex !== null) { args.push(o.literal(tag)); if (constIndex !== null) { args.push(o.literal(constIndex)); } } return call(Identifiers.templateCreate, args, sourceSpan); } export function disableBindings(): ir.CreateOp { return call(Identifiers.disableBindings, [], null); } export function enableBindings(): ir.CreateOp { return call(Identifiers.enableBindings, [], null); } export function listener( name: string, handlerFn: o.Expression, sourceSpan: ParseSourceSpan): ir.CreateOp { return call( Identifiers.listener, [ o.literal(name), handlerFn, ], sourceSpan); } export function syntheticHostListener( name: string, handlerFn: o.Expression, sourceSpan: ParseSourceSpan): ir.CreateOp { return call( Identifiers.syntheticHostListener, [ o.literal(name), handlerFn, ], sourceSpan); } export function pipe(slot: number, name: string): ir.CreateOp { return call( Identifiers.pipe, [ o.literal(slot), o.literal(name), ], null); } export function namespaceHTML(): ir.CreateOp { return call(Identifiers.namespaceHTML, [], null); } export function namespaceSVG(): ir.CreateOp { return call(Identifiers.namespaceSVG, [], null); } export function namespaceMath(): ir.CreateOp { return call(Identifiers.namespaceMathML, [], null); } export function advance(delta: number, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call( Identifiers.advance, [ o.literal(delta), ], sourceSpan); } export function reference(slot: number): o.Expression { return o.importExpr(Identifiers.reference).callFn([ o.literal(slot), ]); } export function nextContext(steps: number): o.Expression { return o.importExpr(Identifiers.nextContext).callFn(steps === 1 ? [] : [o.literal(steps)]); } export function getCurrentView(): o.Expression { return o.importExpr(Identifiers.getCurrentView).callFn([]); } export function restoreView(savedView: o.Expression): o.Expression { return o.importExpr(Identifiers.restoreView).callFn([ savedView, ]); } export function resetView(returnValue: o.Expression): o.Expression { return o.importExpr(Identifiers.resetView).callFn([ returnValue, ]); } export function text( slot: number, initialValue: string, sourceSpan: ParseSourceSpan|null): ir.CreateOp { const args: o.Expression[] = [o.literal(slot, null)]; if (initialValue !== '') { args.push(o.literal(initialValue)); } return call(Identifiers.text, args, sourceSpan); } export function defer( selfSlot: number, primarySlot: number, dependencyResolverFn: null, loadingSlot: number|null, placeholderSlot: number|null, errorSlot: number|null, loadingConfigIndex: number|null, placeholderConfigIndex: number|null, sourceSpan: ParseSourceSpan|null): ir.CreateOp { const args = [ o.literal(selfSlot), o.literal(primarySlot), o.literal(dependencyResolverFn), o.literal(loadingSlot), o.literal(placeholderSlot), o.literal(errorSlot), o.literal(loadingConfigIndex), o.literal(placeholderConfigIndex), ]; while (args[args.length - 1].value === null) { args.pop(); } return call(Identifiers.defer, args, sourceSpan); } export function deferOn(sourceSpan: ParseSourceSpan|null): ir.CreateOp { return call(Identifiers.deferOnIdle, [], sourceSpan); } export function projectionDef(def: o.Expression|null): ir.CreateOp { return call(Identifiers.projectionDef, def ? [def] : [], null); } export function projection( slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp { const args: o.Expression[] = [o.literal(slot)]; if (projectionSlotIndex !== 0 || attributes.length > 0) { args.push(o.literal(projectionSlotIndex)); if (attributes.length > 0) { args.push(o.literalArr(attributes.map(attr => o.literal(attr)))); } } return call(Identifiers.projection, args, null); } export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp { const args = [o.literal(slot), o.literal(constIndex)]; if (subTemplateIndex !== null) { args.push(o.literal(subTemplateIndex)); } return call(Identifiers.i18nStart, args, null); } export function repeaterCreate( slot: number, viewFnName: string, decls: number, vars: number, trackByFn: o.Expression, trackByUsesComponentInstance: boolean, emptyViewFnName: string|null, emptyDecls: number|null, emptyVars: number|null, sourceSpan: ParseSourceSpan|null): ir.CreateOp { let args = [ o.literal(slot), o.variable(viewFnName), o.literal(decls), o.literal(vars), trackByFn, ]; if (trackByUsesComponentInstance || emptyViewFnName !== null) { args.push(o.literal(trackByUsesComponentInstance)); if (emptyViewFnName !== null) { args.push(o.variable(emptyViewFnName)); args.push(o.literal(emptyDecls)); args.push(o.literal(emptyVars)); } } return call(Identifiers.repeaterCreate, args, sourceSpan); } export function repeater( metadataSlot: number, collection: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.repeater, [o.literal(metadataSlot), collection], sourceSpan); } export function i18n(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp { const args = [o.literal(slot), o.literal(constIndex)]; if (subTemplateIndex) { args.push(o.literal(subTemplateIndex)); } return call(Identifiers.i18n, args, null); } export function i18nEnd(): ir.CreateOp { return call(Identifiers.i18nEnd, [], null); } export function property( name: string, expression: o.Expression, sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const args = [o.literal(name), expression]; if (sanitizer !== null) { args.push(sanitizer); } return call(Identifiers.property, args, sourceSpan); } export function attribute( name: string, expression: o.Expression, sanitizer: o.Expression|null): ir.UpdateOp { const args = [o.literal(name), expression]; if (sanitizer !== null) { args.push(sanitizer); } return call(Identifiers.attribute, args, null); } export function styleProp( name: string, expression: o.Expression, unit: string|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const args = [o.literal(name), expression]; if (unit !== null) { args.push(o.literal(unit)); } return call(Identifiers.styleProp, args, sourceSpan); } export function classProp( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.classProp, [o.literal(name), expression], sourceSpan); } export function styleMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.styleMap, [expression], sourceSpan); } export function classMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.classMap, [expression], sourceSpan); } const PIPE_BINDINGS: o.ExternalReference[] = [ Identifiers.pipeBind1, Identifiers.pipeBind2, Identifiers.pipeBind3, Identifiers.pipeBind4, ]; export function pipeBind(slot: number, varOffset: number, args: o.Expression[]): o.Expression { if (args.length < 1 || args.length > PIPE_BINDINGS.length) { throw new Error(`pipeBind() argument count out of bounds`); } const instruction = PIPE_BINDINGS[args.length - 1]; return o.importExpr(instruction).callFn([ o.literal(slot), o.literal(varOffset), ...args, ]); } export function pipeBindV(slot: number, varOffset: number, args: o.Expression): o.Expression { return o.importExpr(Identifiers.pipeBindV).callFn([ o.literal(slot), o.literal(varOffset), args, ]); } export function textInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { if (strings.length < 1 || expressions.length !== strings.length - 1) { throw new Error( `AssertionError: expected specific shape of args for strings/expressions in interpolation`); } const interpolationArgs: o.Expression[] = []; if (expressions.length === 1 && strings[0] === '' && strings[1] === '') { interpolationArgs.push(expressions[0]); } else { let idx: number; for (idx = 0; idx < expressions.length; idx++) { interpolationArgs.push(o.literal(strings[idx]), expressions[idx]); } // idx points at the last string. interpolationArgs.push(o.literal(strings[idx])); } return callVariadicInstruction(TEXT_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function i18nExp(expr: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.i18nExp, [expr], sourceSpan); } export function i18nApply(slot: number, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.i18nApply, [o.literal(slot)], sourceSpan); } export function propertyInterpolate( name: string, strings: string[], expressions: o.Expression[], sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs = []; if (sanitizer !== null) { extraArgs.push(sanitizer); } return callVariadicInstruction( PROPERTY_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function attributeInterpolate( name: string, strings: string[], expressions: o.Expression[], sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs = []; if (sanitizer !== null) { extraArgs.push(sanitizer); } return callVariadicInstruction( ATTRIBUTE_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function stylePropInterpolate( name: string, strings: string[], expressions: o.Expression[], unit: string|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs: o.Expression[] = []; if (unit !== null) { extraArgs.push(o.literal(unit)); } return callVariadicInstruction( STYLE_PROP_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function styleMapInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); return callVariadicInstruction( STYLE_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function classMapInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); return callVariadicInstruction( CLASS_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function hostProperty( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.hostProperty, [o.literal(name), expression], sourceSpan); } export function syntheticHostProperty( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.syntheticHostProperty, [o.literal(name), expression], sourceSpan); } export function pureFunction( varOffset: number, fn: o.Expression, args: o.Expression[]): o.Expression { return callVariadicInstructionExpr( PURE_FUNCTION_CONFIG, [ o.literal(varOffset), fn, ], args, [], null, ); } /** * Collates the string an expression arguments for an interpolation instruction. */ function collateInterpolationArgs(strings: string[], expressions: o.Expression[]): o.Expression[] { if (strings.length < 1 || expressions.length !== strings.length - 1) { throw new Error( `AssertionError: expected specific shape of args for strings/expressions in interpolation`); } const interpolationArgs: o.Expression[] = []; if (expressions.length === 1 && strings[0] === '' && strings[1] === '') { interpolationArgs.push(expressions[0]); } else { let idx: number; for (idx = 0; idx < expressions.length; idx++) { interpolationArgs.push(o.literal(strings[idx]), expressions[idx]); } // idx points at the last string. interpolationArgs.push(o.literal(strings[idx])); } return interpolationArgs; } function call<OpT extends ir.CreateOp|ir.UpdateOp>( instruction: o.ExternalReference, args: o.Expression[], sourceSpan: ParseSourceSpan|null): OpT { const expr = o.importExpr(instruction).callFn(args, sourceSpan); return ir.createStatementOp(new o.ExpressionStatement(expr, sourceSpan)) as OpT; } export function conditional( slot: number, condition: o.Expression, contextValue: o.Expression|null, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { const args = [o.literal(slot), condition]; if (contextValue !== null) { args.push(contextValue); } return call(Identifiers.conditional, args, sourceSpan); } /** * Describes a specific flavor of instruction used to represent variadic instructions, which * have some number of variants for specific argument counts. */ interface VariadicInstructionConfig { constant: o.ExternalReference[]; variable: o.ExternalReference|null; mapping: (argCount: number) => number; } /** * `InterpolationConfig` for the `textInterpolate` instruction. */ const TEXT_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.textInterpolate, Identifiers.textInterpolate1, Identifiers.textInterpolate2, Identifiers.textInterpolate3, Identifiers.textInterpolate4, Identifiers.textInterpolate5, Identifiers.textInterpolate6, Identifiers.textInterpolate7, Identifiers.textInterpolate8, ], variable: Identifiers.textInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `propertyInterpolate` instruction. */ const PROPERTY_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.propertyInterpolate, Identifiers.propertyInterpolate1, Identifiers.propertyInterpolate2, Identifiers.propertyInterpolate3, Identifiers.propertyInterpolate4, Identifiers.propertyInterpolate5, Identifiers.propertyInterpolate6, Identifiers.propertyInterpolate7, Identifiers.propertyInterpolate8, ], variable: Identifiers.propertyInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `stylePropInterpolate` instruction. */ const STYLE_PROP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.styleProp, Identifiers.stylePropInterpolate1, Identifiers.stylePropInterpolate2, Identifiers.stylePropInterpolate3, Identifiers.stylePropInterpolate4, Identifiers.stylePropInterpolate5, Identifiers.stylePropInterpolate6, Identifiers.stylePropInterpolate7, Identifiers.stylePropInterpolate8, ], variable: Identifiers.stylePropInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `attributeInterpolate` instruction. */ const ATTRIBUTE_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.attribute, Identifiers.attributeInterpolate1, Identifiers.attributeInterpolate2, Identifiers.attributeInterpolate3, Identifiers.attributeInterpolate4, Identifiers.attributeInterpolate5, Identifiers.attributeInterpolate6, Identifiers.attributeInterpolate7, Identifiers.attributeInterpolate8, ], variable: Identifiers.attributeInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `styleMapInterpolate` instruction. */ const STYLE_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.styleMap, Identifiers.styleMapInterpolate1, Identifiers.styleMapInterpolate2, Identifiers.styleMapInterpolate3, Identifiers.styleMapInterpolate4, Identifiers.styleMapInterpolate5, Identifiers.styleMapInterpolate6, Identifiers.styleMapInterpolate7, Identifiers.styleMapInterpolate8, ], variable: Identifiers.styleMapInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `classMapInterpolate` instruction. */ const CLASS_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.classMap, Identifiers.classMapInterpolate1, Identifiers.classMapInterpolate2, Identifiers.classMapInterpolate3, Identifiers.classMapInterpolate4, Identifiers.classMapInterpolate5, Identifiers.classMapInterpolate6, Identifiers.classMapInterpolate7, Identifiers.classMapInterpolate8, ], variable: Identifiers.classMapInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; const PURE_FUNCTION_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.pureFunction0, Identifiers.pureFunction1, Identifiers.pureFunction2, Identifiers.pureFunction3, Identifiers.pureFunction4, Identifiers.pureFunction5, Identifiers.pureFunction6, Identifiers.pureFunction7, Identifiers.pureFunction8, ], variable: Identifiers.pureFunctionV, mapping: n => n, }; function callVariadicInstructionExpr( config: VariadicInstructionConfig, baseArgs: o.Expression[], interpolationArgs: o.Expression[], extraArgs: o.Expression[], sourceSpan: ParseSourceSpan|null): o.Expression { const n = config.mapping(interpolationArgs.length); if (n < config.constant.length) { // Constant calling pattern. return o.importExpr(config.constant[n]) .callFn([...baseArgs, ...interpolationArgs, ...extraArgs], sourceSpan); } else if (config.variable !== null) { // Variable calling pattern. return o.importExpr(config.variable) .callFn([...baseArgs, o.literalArr(interpolationArgs), ...extraArgs], sourceSpan); } else { throw new Error(`AssertionError: unable to call variadic function`); } } function callVariadicInstruction( config: VariadicInstructionConfig, baseArgs: o.Expression[], interpolationArgs: o.Expression[], extraArgs: o.Expression[], sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return ir.createStatementOp( callVariadicInstructionExpr(config, baseArgs, interpolationArgs, extraArgs, sourceSpan) .toStmt()); }
packages/compiler/src/template/pipeline/src/instruction.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.008242261596024036, 0.0005366576369851828, 0.0001652553619351238, 0.0001713795936666429, 0.001252832473255694 ]
{ "id": 0, "code_window": [ " ],\n", " \"compilerOptions\": {\n", " \"sourceMap\": true\n", " },\n", " \"skipForTemplatePipeline\": true\n", " },\n", " {\n", " \"description\": \"should map default and selected projection (partial compile)\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "packages/compiler-cli/test/compliance/test_cases/source_mapping/inline_templates/TEST_CASES.json", "type": "replace", "edit_start_line_idx": 663 }
/** * @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.io/license */ import localeFr from '@angular/common/locales/fr'; import localeRo from '@angular/common/locales/ro'; import localeSr from '@angular/common/locales/sr'; import localeZgh from '@angular/common/locales/zgh'; import {getPluralCategory, NgLocaleLocalization, NgLocalization} from '@angular/common/src/i18n/localization'; import {LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core'; import {inject, TestBed} from '@angular/core/testing'; describe('l10n', () => { beforeAll(() => { ɵregisterLocaleData(localeRo); ɵregisterLocaleData(localeSr); ɵregisterLocaleData(localeZgh); ɵregisterLocaleData(localeFr); }); afterAll(() => ɵunregisterLocaleData()); describe('NgLocalization', () => { function roTests() { it('should return plural cases for the provided locale', inject([NgLocalization], (l10n: NgLocalization) => { expect(l10n.getPluralCategory(0)).toEqual('few'); expect(l10n.getPluralCategory(1)).toEqual('one'); expect(l10n.getPluralCategory(1212)).toEqual('few'); expect(l10n.getPluralCategory(1223)).toEqual('other'); })); } describe('ro', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: LOCALE_ID, useValue: 'ro'}], }); }); roTests(); }); function srTests() { it('should return plural cases for the provided locale', inject([NgLocalization], (l10n: NgLocalization) => { expect(l10n.getPluralCategory(1)).toEqual('one'); expect(l10n.getPluralCategory(2.1)).toEqual('one'); expect(l10n.getPluralCategory(3)).toEqual('few'); expect(l10n.getPluralCategory(0.2)).toEqual('few'); expect(l10n.getPluralCategory(2.11)).toEqual('other'); expect(l10n.getPluralCategory(2.12)).toEqual('other'); })); } describe('sr', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: LOCALE_ID, useValue: 'sr'}], }); }); srTests(); }); }); describe('NgLocaleLocalization', () => { it('should return the correct values for the "en" locale', () => { const l10n = new NgLocaleLocalization('en-US'); expect(l10n.getPluralCategory(0)).toEqual('other'); expect(l10n.getPluralCategory(1)).toEqual('one'); expect(l10n.getPluralCategory(2)).toEqual('other'); }); it('should return the correct values for the "ro" locale', () => { const l10n = new NgLocaleLocalization('ro'); expect(l10n.getPluralCategory(0)).toEqual('few'); expect(l10n.getPluralCategory(1)).toEqual('one'); expect(l10n.getPluralCategory(2)).toEqual('few'); expect(l10n.getPluralCategory(12)).toEqual('few'); expect(l10n.getPluralCategory(23)).toEqual('other'); expect(l10n.getPluralCategory(1212)).toEqual('few'); expect(l10n.getPluralCategory(1223)).toEqual('other'); }); it('should return the correct values for the "sr" locale', () => { const l10n = new NgLocaleLocalization('sr'); expect(l10n.getPluralCategory(1)).toEqual('one'); expect(l10n.getPluralCategory(31)).toEqual('one'); expect(l10n.getPluralCategory(0.1)).toEqual('one'); expect(l10n.getPluralCategory(1.1)).toEqual('one'); expect(l10n.getPluralCategory(2.1)).toEqual('one'); expect(l10n.getPluralCategory(3)).toEqual('few'); expect(l10n.getPluralCategory(33)).toEqual('few'); expect(l10n.getPluralCategory(0.2)).toEqual('few'); expect(l10n.getPluralCategory(0.3)).toEqual('few'); expect(l10n.getPluralCategory(0.4)).toEqual('few'); expect(l10n.getPluralCategory(2.2)).toEqual('few'); expect(l10n.getPluralCategory(2.11)).toEqual('other'); expect(l10n.getPluralCategory(2.12)).toEqual('other'); expect(l10n.getPluralCategory(2.13)).toEqual('other'); expect(l10n.getPluralCategory(2.14)).toEqual('other'); expect(l10n.getPluralCategory(2.15)).toEqual('other'); expect(l10n.getPluralCategory(0)).toEqual('other'); expect(l10n.getPluralCategory(5)).toEqual('other'); expect(l10n.getPluralCategory(10)).toEqual('other'); expect(l10n.getPluralCategory(35)).toEqual('other'); expect(l10n.getPluralCategory(37)).toEqual('other'); expect(l10n.getPluralCategory(40)).toEqual('other'); expect(l10n.getPluralCategory(0.0)).toEqual('other'); expect(l10n.getPluralCategory(0.5)).toEqual('other'); expect(l10n.getPluralCategory(0.6)).toEqual('other'); expect(l10n.getPluralCategory(2)).toEqual('few'); expect(l10n.getPluralCategory(2.1)).toEqual('one'); expect(l10n.getPluralCategory(2.2)).toEqual('few'); expect(l10n.getPluralCategory(2.3)).toEqual('few'); expect(l10n.getPluralCategory(2.4)).toEqual('few'); expect(l10n.getPluralCategory(2.5)).toEqual('other'); expect(l10n.getPluralCategory(20)).toEqual('other'); expect(l10n.getPluralCategory(21)).toEqual('one'); expect(l10n.getPluralCategory(22)).toEqual('few'); expect(l10n.getPluralCategory(23)).toEqual('few'); expect(l10n.getPluralCategory(24)).toEqual('few'); expect(l10n.getPluralCategory(25)).toEqual('other'); }); it('should return the default value for a locale with no rule', () => { const l10n = new NgLocaleLocalization('zgh'); expect(l10n.getPluralCategory(0)).toEqual('other'); expect(l10n.getPluralCategory(1)).toEqual('other'); expect(l10n.getPluralCategory(3)).toEqual('other'); expect(l10n.getPluralCategory(5)).toEqual('other'); expect(l10n.getPluralCategory(10)).toEqual('other'); }); }); describe('getPluralCategory', () => { it('should return plural category', () => { const l10n = new NgLocaleLocalization('fr'); expect(getPluralCategory(0, ['one', 'other'], l10n)).toEqual('one'); expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one'); expect(getPluralCategory(5, ['one', 'other'], l10n)).toEqual('other'); }); it('should return discrete cases', () => { const l10n = new NgLocaleLocalization('fr'); expect(getPluralCategory(0, ['one', 'other', '=0'], l10n)).toEqual('=0'); expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one'); expect(getPluralCategory(5, ['one', 'other', '=5'], l10n)).toEqual('=5'); expect(getPluralCategory(6, ['one', 'other', '=5'], l10n)).toEqual('other'); }); it('should fallback to other when the case is not present', () => { const l10n = new NgLocaleLocalization('ro'); expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one'); // 2 -> 'few' expect(getPluralCategory(2, ['one', 'other'], l10n)).toEqual('other'); }); describe('errors', () => { it('should report an error when the "other" category is not present', () => { expect(() => { const l10n = new NgLocaleLocalization('ro'); // 2 -> 'few' getPluralCategory(2, ['one'], l10n); }).toThrowError('No plural message found for value "2"'); }); }); }); });
packages/common/test/i18n/localization_spec.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017810666759032756, 0.00017423758981749415, 0.00016954437887761742, 0.00017380579083692282, 0.000002483673597453162 ]
{ "id": 0, "code_window": [ " ],\n", " \"compilerOptions\": {\n", " \"sourceMap\": true\n", " },\n", " \"skipForTemplatePipeline\": true\n", " },\n", " {\n", " \"description\": \"should map default and selected projection (partial compile)\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "packages/compiler-cli/test/compliance/test_cases/source_mapping/inline_templates/TEST_CASES.json", "type": "replace", "edit_start_line_idx": 663 }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
integration/trusted-types/src/app/app.module.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0001709516509436071, 0.000169902850757353, 0.00016885405057109892, 0.000169902850757353, 0.0000010488001862540841 ]
{ "id": 0, "code_window": [ " ],\n", " \"compilerOptions\": {\n", " \"sourceMap\": true\n", " },\n", " \"skipForTemplatePipeline\": true\n", " },\n", " {\n", " \"description\": \"should map default and selected projection (partial compile)\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " }\n" ], "file_path": "packages/compiler-cli/test/compliance/test_cases/source_mapping/inline_templates/TEST_CASES.json", "type": "replace", "edit_start_line_idx": 663 }
/** * @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.io/license */ import {Observable, range} from 'rxjs'; import {count} from 'rxjs/operators'; describe('Observable.count', () => { let log: any[]; const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'}); const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'}); let observable1: Observable<any>; beforeEach(() => { log = []; }); it('count func callback should run in the correct zone', () => { observable1 = constructorZone1.run(() => { return range(1, 3).pipe(count((i: number) => { expect(Zone.current.name).toEqual(constructorZone1.name); return i % 2 === 0; })); }); subscriptionZone.run(() => { observable1.subscribe( (result: any) => { log.push(result); expect(Zone.current.name).toEqual(subscriptionZone.name); }, () => { fail('should not call error'); }, () => { log.push('completed'); expect(Zone.current.name).toEqual(subscriptionZone.name); }); }); expect(log).toEqual([1, 'completed']); }); });
packages/zone.js/test/rxjs/rxjs.Observable.count.spec.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017618635320104659, 0.00017052832117769867, 0.00016581664385739714, 0.00016984986723400652, 0.0000033314065603917697 ]
{ "id": 1, "code_window": [ "\n", " sourceSpan: ParseSourceSpan;\n", "}\n", "\n", "export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp {\n", " return {\n", " kind: OpKind.Projection,\n", " xref,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createProjectionOp(\n", " xref: XrefId, selector: string, sourceSpan: ParseSourceSpan): ProjectionOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 586 }
/** * @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.io/license */ import * as i18n from '../../../../../i18n/i18n_ast'; import * as o from '../../../../../output/output_ast'; import {ParseSourceSpan} from '../../../../../parse_util'; import {BindingKind, DeferSecondaryKind, OpKind} from '../enums'; import {Op, OpList, XrefId} from '../operations'; import {ConsumesSlotOpTrait, HasConstTrait, TRAIT_CONSUMES_SLOT, TRAIT_HAS_CONST, TRAIT_USES_SLOT_INDEX, UsesSlotIndexTrait} from '../traits'; import {ListEndOp, NEW_OP, StatementOp, VariableOp} from './shared'; import type {UpdateOp} from './update'; /** * An operation usable on the creation side of the IR. */ export type CreateOp = ListEndOp<CreateOp>|StatementOp<CreateOp>|ElementOp|ElementStartOp| ElementEndOp|ContainerOp|ContainerStartOp|ContainerEndOp|TemplateOp|EnableBindingsOp| DisableBindingsOp|TextOp|ListenerOp|PipeOp|VariableOp<CreateOp>|NamespaceOp|ProjectionDefOp| ProjectionOp|ExtractedAttributeOp|DeferOp|DeferSecondaryBlockOp|DeferOnOp|RepeaterCreateOp| ExtractedMessageOp|I18nOp|I18nStartOp|I18nEndOp|IcuOp; /** * An operation representing the creation of an element or container. */ export type ElementOrContainerOps = ElementOp|ElementStartOp|ContainerOp|ContainerStartOp|TemplateOp|RepeaterCreateOp; /** * The set of OpKinds that represent the creation of an element or container */ const elementContainerOpKinds = new Set([ OpKind.Element, OpKind.ElementStart, OpKind.Container, OpKind.ContainerStart, OpKind.Template, OpKind.RepeaterCreate ]); /** * Checks whether the given operation represents the creation of an element or container. */ export function isElementOrContainerOp(op: CreateOp): op is ElementOrContainerOps { return elementContainerOpKinds.has(op.kind); } /** * Representation of a local reference on an element. */ export interface LocalRef { /** * User-defined name of the local ref variable. */ name: string; /** * Target of the local reference variable (often `''`). */ target: string; } /** * Base interface for `Element`, `ElementStart`, and `Template` operations, containing common fields * used to represent their element-like nature. */ export interface ElementOrContainerOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: ElementOrContainerOps['kind']; /** * `XrefId` allocated for this element. * * This ID is used to reference this element from other IR structures. */ xref: XrefId; /** * Attributes of various kinds on this element. Represented as a `ConstIndex` pointer into the * shared `consts` array of the component compilation. */ attributes: ConstIndex|null; /** * Local references to this element. * * Before local ref processing, this is an array of `LocalRef` declarations. * * After processing, it's a `ConstIndex` pointer into the shared `consts` array of the component * compilation. */ localRefs: LocalRef[]|ConstIndex|null; /** * Whether this container is marked `ngNonBindable`, which disabled Angular binding for itself and * all descendants. */ nonBindable: boolean; sourceSpan: ParseSourceSpan; } export interface ElementOpBase extends ElementOrContainerOpBase { kind: OpKind.Element|OpKind.ElementStart|OpKind.Template|OpKind.RepeaterCreate; /** * The HTML tag name for this element. */ tag: string|null; /** * The namespace of this element, which controls the preceding namespace instruction. */ namespace: Namespace; } /** * Logical operation representing the start of an element in the creation IR. */ export interface ElementStartOp extends ElementOpBase { kind: OpKind.ElementStart; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create an `ElementStartOp`. */ export function createElementStartOp( tag: string, xref: XrefId, namespace: Namespace, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): ElementStartOp { return { kind: OpKind.ElementStart, xref, tag, attributes: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an element with no children in the creation IR. */ export interface ElementOp extends ElementOpBase { kind: OpKind.Element; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Logical operation representing an embedded view declaration in the creation IR. */ export interface TemplateOp extends ElementOpBase { kind: OpKind.Template; /** * The number of declaration slots used by this template, or `null` if slots have not yet been * assigned. */ decls: number|null; /** * The number of binding variable slots used by this template, or `null` if binding variables have * not yet been counted. */ vars: number|null; /** * Whether or not this template was automatically created for use with block syntax (control flow * or defer). This will eventually cause the emitted template instruction to use fewer arguments, * since several of the default arguments are unnecessary for blocks. */ block: boolean; /** * The i18n placeholder data associated with this template. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create a `TemplateOp`. */ export function createTemplateOp( xref: XrefId, tag: string|null, namespace: Namespace, generatedInBlock: boolean, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): TemplateOp { return { kind: OpKind.Template, xref, attributes: null, tag, block: generatedInBlock, decls: null, vars: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * An op that creates a repeater (e.g. a for loop). */ export interface RepeaterCreateOp extends ElementOpBase { kind: OpKind.RepeaterCreate; /** * The number of declaration slots used by this repeater's template, or `null` if slots have not * yet been assigned. */ decls: number|null; /** * The number of binding variable slots used by this repeater's, or `null` if binding variables * have not yet been counted. */ vars: number|null; /** * The Xref of the empty view function. (For the primary view function, use the `xref` property). */ emptyView: XrefId|null; /** * The track expression to use while iterating. */ track: o.Expression; /** * `null` initially, then an `o.Expression`. Might be a track expression, or might be a reference * into the constant pool. */ trackByFn: o.Expression|null; /** * Context variables avaialable in this block. */ varNames: RepeaterVarNames; /** * Whether the repeater track function relies on the component instance. */ usesComponentInstance: boolean; sourceSpan: ParseSourceSpan; } // TODO: add source spans? export interface RepeaterVarNames { $index: string; $count: string; $first: string; $last: string; $even: string; $odd: string; $implicit: string; } export function createRepeaterCreateOp( primaryView: XrefId, emptyView: XrefId|null, track: o.Expression, varNames: RepeaterVarNames, sourceSpan: ParseSourceSpan): RepeaterCreateOp { return { kind: OpKind.RepeaterCreate, attributes: null, xref: primaryView, emptyView, track, trackByFn: null, tag: 'For', namespace: Namespace.HTML, nonBindable: false, localRefs: [], decls: null, vars: null, varNames, usesComponentInstance: false, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, numSlotsUsed: emptyView === null ? 2 : 3, }; } /** * Logical operation representing the end of an element structure in the creation IR. * * Pairs with an `ElementStart` operation. */ export interface ElementEndOp extends Op<CreateOp> { kind: OpKind.ElementEnd; /** * The `XrefId` of the element declared via `ElementStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan|null; } /** * Create an `ElementEndOp`. */ export function createElementEndOp(xref: XrefId, sourceSpan: ParseSourceSpan|null): ElementEndOp { return { kind: OpKind.ElementEnd, xref, sourceSpan, ...NEW_OP, }; } /** * Logical operation representing the start of a container in the creation IR. */ export interface ContainerStartOp extends ElementOrContainerOpBase { kind: OpKind.ContainerStart; } /** * Logical operation representing an empty container in the creation IR. */ export interface ContainerOp extends ElementOrContainerOpBase { kind: OpKind.Container; } /** * Logical operation representing the end of a container structure in the creation IR. * * Pairs with an `ContainerStart` operation. */ export interface ContainerEndOp extends Op<CreateOp> { kind: OpKind.ContainerEnd; /** * The `XrefId` of the element declared via `ContainerStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan; } /** * Logical operation causing binding to be disabled in descendents of a non-bindable container. */ export interface DisableBindingsOp extends Op<CreateOp> { kind: OpKind.DisableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createDisableBindingsOp(xref: XrefId): DisableBindingsOp { return { kind: OpKind.DisableBindings, xref, ...NEW_OP, }; } /** * Logical operation causing binding to be re-enabled after visiting descendants of a * non-bindable container. */ export interface EnableBindingsOp extends Op<CreateOp> { kind: OpKind.EnableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createEnableBindingsOp(xref: XrefId): EnableBindingsOp { return { kind: OpKind.EnableBindings, xref, ...NEW_OP, }; } /** * Logical operation representing a text node in the creation IR. */ export interface TextOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Text; /** * `XrefId` used to reference this text node in other IR structures. */ xref: XrefId; /** * The static initial value of the text node. */ initialValue: string; sourceSpan: ParseSourceSpan|null; } /** * Create a `TextOp`. */ export function createTextOp( xref: XrefId, initialValue: string, sourceSpan: ParseSourceSpan|null): TextOp { return { kind: OpKind.Text, xref, initialValue, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an event listener on an element in the creation IR. */ export interface ListenerOp extends Op<CreateOp>, UsesSlotIndexTrait { kind: OpKind.Listener; /** * Whether this listener is from a host binding. */ hostListener: boolean; /** * Name of the event which is being listened to. */ name: string; /** * Tag name of the element on which this listener is placed. Might be null, if this listener * belongs to a host binding. */ tag: string|null; /** * A list of `UpdateOp`s representing the body of the event listener. */ handlerOps: OpList<UpdateOp>; /** * Name of the function */ handlerFnName: string|null; /** * Whether this listener is known to consume `$event` in its body. */ consumesDollarEvent: boolean; /** * Whether the listener is listening for an animation event. */ isAnimationListener: boolean; /** * The animation phase of the listener. */ animationPhase: string|null; sourceSpan: ParseSourceSpan; } /** * Create a `ListenerOp`. Host bindings reuse all the listener logic. */ export function createListenerOp( target: XrefId, name: string, tag: string|null, animationPhase: string|null, hostListener: boolean, sourceSpan: ParseSourceSpan): ListenerOp { return { kind: OpKind.Listener, target, tag, hostListener, name, handlerOps: new OpList(), handlerFnName: null, consumesDollarEvent: false, isAnimationListener: animationPhase !== null, animationPhase: animationPhase, sourceSpan, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, }; } export interface PipeOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Pipe; xref: XrefId; name: string; } export function createPipeOp(xref: XrefId, name: string): PipeOp { return { kind: OpKind.Pipe, xref, name, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Whether the active namespace is HTML, MathML, or SVG mode. */ export enum Namespace { HTML, SVG, Math, } /** * An op corresponding to a namespace instruction, for switching between HTML, SVG, and MathML. */ export interface NamespaceOp extends Op<CreateOp> { kind: OpKind.Namespace; active: Namespace; } export function createNamespaceOp(namespace: Namespace): NamespaceOp { return { kind: OpKind.Namespace, active: namespace, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionDefOp extends Op<CreateOp> { kind: OpKind.ProjectionDef; // The parsed selector information for this projection def. def: o.Expression|null; } export function createProjectionDefOp(def: o.Expression|null): ProjectionDefOp { return { kind: OpKind.ProjectionDef, def, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Projection; xref: XrefId; slot: number|null; projectionSlotIndex: number; attributes: string[]; localRefs: string[]; selector: string; sourceSpan: ParseSourceSpan; } export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp { return { kind: OpKind.Projection, xref, selector, projectionSlotIndex: 0, attributes: [], localRefs: [], sourceSpan: null!, // TODO ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an attribute that has been extracted for inclusion in the consts array. */ export interface ExtractedAttributeOp extends Op<CreateOp> { kind: OpKind.ExtractedAttribute; /** * The `XrefId` of the template-like element the extracted attribute will belong to. */ target: XrefId; /** * The kind of binding represented by this extracted attribute. */ bindingKind: BindingKind; /** * The name of the extracted attribute. */ name: string; /** * The value expression of the extracted attribute. */ expression: o.Expression|null; } /** * Create an `ExtractedAttributeOp`. */ export function createExtractedAttributeOp( target: XrefId, bindingKind: BindingKind, name: string, expression: o.Expression|null): ExtractedAttributeOp { return { kind: OpKind.ExtractedAttribute, target, bindingKind, name, expression, ...NEW_OP, }; } export interface DeferOp extends Op<CreateOp>, ConsumesSlotOpTrait, UsesSlotIndexTrait { kind: OpKind.Defer; /** * The xref of this defer op. */ xref: XrefId; /** * The xref of the main view. This will be associated with `slot`. */ target: XrefId; /** * Secondary loading block associated with this defer op. */ loading: DeferSecondaryBlockOp|null; /** * Secondary placeholder block associated with this defer op. */ placeholder: DeferSecondaryBlockOp|null; /** * Secondary error block associated with this defer op. */ error: DeferSecondaryBlockOp|null; sourceSpan: ParseSourceSpan; } export function createDeferOp(xref: XrefId, main: XrefId, sourceSpan: ParseSourceSpan): DeferOp { return { kind: OpKind.Defer, xref, target: main, loading: null, placeholder: null, error: null, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, ...TRAIT_USES_SLOT_INDEX, }; } export interface DeferSecondaryBlockOp extends Op<CreateOp>, UsesSlotIndexTrait, HasConstTrait { kind: OpKind.DeferSecondaryBlock; /** * The xref of the corresponding defer op. */ deferOp: XrefId; /** * Which kind of secondary block this op represents. */ secondaryBlockKind: DeferSecondaryKind; /** * The xref of the secondary view. This will be associated with `slot`. */ target: XrefId; } export function createDeferSecondaryOp( deferOp: XrefId, secondaryView: XrefId, secondaryBlockKind: DeferSecondaryKind): DeferSecondaryBlockOp { return { kind: OpKind.DeferSecondaryBlock, deferOp, target: secondaryView, secondaryBlockKind, constValue: null, makeExpression: literalOrArrayLiteral, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, ...TRAIT_HAS_CONST, }; } export interface DeferOnOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.DeferOn; sourceSpan: ParseSourceSpan; } export function createDeferOnOp(xref: XrefId, sourceSpan: ParseSourceSpan): DeferOnOp { return { kind: OpKind.DeferOn, xref, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an i18n message that has been extracted for inclusion in the consts array. */ export interface ExtractedMessageOp extends Op<CreateOp> { kind: OpKind.ExtractedMessage; /** * A reference to the i18n op this message was extracted from. */ owner: XrefId; /** * The message expression. */ expression: o.Expression; /** * The statements to construct the message. */ statements: o.Statement[]; } /** * Create an `ExtractedMessageOp`. */ export function createExtractedMessageOp( owner: XrefId, expression: o.Expression, statements: o.Statement[]): ExtractedMessageOp { return { kind: OpKind.ExtractedMessage, owner, expression, statements, ...NEW_OP, }; } export interface I18nOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.I18nStart|OpKind.I18n; /** * `XrefId` allocated for this i18n block. */ xref: XrefId; /** * A reference to the root i18n block that this one belongs to. For a a root i18n block, this is * the same as xref. */ root: XrefId; /** * The i18n metadata associated with this op. */ message: i18n.Message; /** * Map of values to use for named placeholders in the i18n message. (Resolved at message creation) */ params: Map<string, o.Expression>; /** * Map of values to use for named placeholders in the i18n message. (Resolved during * post-porcessing) */ postprocessingParams: Map<string, o.Expression>; /** * The index in the consts array where the message i18n message is stored. */ messageIndex: ConstIndex|null; /** * The index of this sub-block in the i18n message. For a root i18n block, this is null. */ subTemplateIndex: number|null; /** * Whether the i18n message requires postprocessing. */ needsPostprocessing: boolean; } /** * Represents an empty i18n block. */ export interface I18nOp extends I18nOpBase { kind: OpKind.I18n; } /** * Represents the start of an i18n block. */ export interface I18nStartOp extends I18nOpBase { kind: OpKind.I18nStart; } /** * Create an `I18nStartOp`. */ export function createI18nStartOp(xref: XrefId, message: i18n.Message, root?: XrefId): I18nStartOp { return { kind: OpKind.I18nStart, xref, root: root ?? xref, message, params: new Map(), postprocessingParams: new Map(), messageIndex: null, subTemplateIndex: null, needsPostprocessing: false, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents the end of an i18n block. */ export interface I18nEndOp extends Op<CreateOp> { kind: OpKind.I18nEnd; /** * The `XrefId` of the `I18nStartOp` that created this block. */ xref: XrefId; } /** * Create an `I18nEndOp`. */ export function createI18nEndOp(xref: XrefId): I18nEndOp { return { kind: OpKind.I18nEnd, xref, ...NEW_OP, }; } /** * An op that represents an ICU expression. */ export interface IcuOp extends Op<CreateOp> { kind: OpKind.Icu; /** * The ID of the ICU. */ xref: XrefId; /** * The i18n message for this ICU. */ message: i18n.Message; sourceSpan: ParseSourceSpan; } /** * Creates an op to create an ICU expression. */ export function createIcuOp( xref: XrefId, message: i18n.Message, sourceSpan: ParseSourceSpan): IcuOp { return { kind: OpKind.Icu, xref, message, sourceSpan, ...NEW_OP, }; } /** * An index into the `consts` array which is shared across the compilation of all views in a * component. */ export type ConstIndex = number&{__brand: 'ConstIndex'}; export function literalOrArrayLiteral(value: any): o.Expression { if (Array.isArray(value)) { return o.literalArr(value.map(literalOrArrayLiteral)); } return o.literal(value, o.INFERRED_TYPE); }
packages/compiler/src/template/pipeline/ir/src/ops/create.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.9989970326423645, 0.025033963844180107, 0.000167921680258587, 0.0003842586011160165, 0.14448241889476776 ]
{ "id": 1, "code_window": [ "\n", " sourceSpan: ParseSourceSpan;\n", "}\n", "\n", "export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp {\n", " return {\n", " kind: OpKind.Projection,\n", " xref,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createProjectionOp(\n", " xref: XrefId, selector: string, sourceSpan: ParseSourceSpan): ProjectionOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 586 }
/** * @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.io/license */ // This default value is when checking the hierarchy for a token. // // It means both: // - the token is not provided by the current injector, // - only the element injectors should be checked (ie do not check module injectors // // mod1 // / // el1 mod2 // \ / // el2 // // When requesting el2.injector.get(token), we should check in the following order and return the // first found value: // - el2.injector.get(token, default) // - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module // - mod2.injector.get(token, default) export const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
packages/core/src/view/provider_flags.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017774767184164375, 0.00017565810412634164, 0.00017263804329559207, 0.0001765886408975348, 0.000002187308837164892 ]
{ "id": 1, "code_window": [ "\n", " sourceSpan: ParseSourceSpan;\n", "}\n", "\n", "export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp {\n", " return {\n", " kind: OpKind.Projection,\n", " xref,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createProjectionOp(\n", " xref: XrefId, selector: string, sourceSpan: ParseSourceSpan): ProjectionOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 586 }
/** * @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.io/license */ import * as core from '@angular/core'; // We need to something with the "core" import in order to ensure // that all symbols from core are preserved in the bundle. console.error(core);
packages/core/test/bundling/core_all/index.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017833674792200327, 0.0001780897582648322, 0.00017784276860766113, 0.0001780897582648322, 2.469896571710706e-7 ]
{ "id": 1, "code_window": [ "\n", " sourceSpan: ParseSourceSpan;\n", "}\n", "\n", "export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp {\n", " return {\n", " kind: OpKind.Projection,\n", " xref,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createProjectionOp(\n", " xref: XrefId, selector: string, sourceSpan: ParseSourceSpan): ProjectionOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 586 }
load("//tools:defaults.bzl", "ts_library") ts_library( name = "optional_chain_not_nullable", srcs = ["index.ts"], visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/BUILD.bazel
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017544235743116587, 0.00017397536430507898, 0.00017250838573090732, 0.00017397536430507898, 0.0000014669858501292765 ]
{ "id": 2, "code_window": [ " xref,\n", " selector,\n", " projectionSlotIndex: 0,\n", " attributes: [],\n", " localRefs: [],\n", " sourceSpan: null!, // TODO\n", " ...NEW_OP,\n", " ...TRAIT_CONSUMES_SLOT,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " sourceSpan,\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 594 }
/** * @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.io/license */ import * as i18n from '../../../../../i18n/i18n_ast'; import * as o from '../../../../../output/output_ast'; import {ParseSourceSpan} from '../../../../../parse_util'; import {BindingKind, DeferSecondaryKind, OpKind} from '../enums'; import {Op, OpList, XrefId} from '../operations'; import {ConsumesSlotOpTrait, HasConstTrait, TRAIT_CONSUMES_SLOT, TRAIT_HAS_CONST, TRAIT_USES_SLOT_INDEX, UsesSlotIndexTrait} from '../traits'; import {ListEndOp, NEW_OP, StatementOp, VariableOp} from './shared'; import type {UpdateOp} from './update'; /** * An operation usable on the creation side of the IR. */ export type CreateOp = ListEndOp<CreateOp>|StatementOp<CreateOp>|ElementOp|ElementStartOp| ElementEndOp|ContainerOp|ContainerStartOp|ContainerEndOp|TemplateOp|EnableBindingsOp| DisableBindingsOp|TextOp|ListenerOp|PipeOp|VariableOp<CreateOp>|NamespaceOp|ProjectionDefOp| ProjectionOp|ExtractedAttributeOp|DeferOp|DeferSecondaryBlockOp|DeferOnOp|RepeaterCreateOp| ExtractedMessageOp|I18nOp|I18nStartOp|I18nEndOp|IcuOp; /** * An operation representing the creation of an element or container. */ export type ElementOrContainerOps = ElementOp|ElementStartOp|ContainerOp|ContainerStartOp|TemplateOp|RepeaterCreateOp; /** * The set of OpKinds that represent the creation of an element or container */ const elementContainerOpKinds = new Set([ OpKind.Element, OpKind.ElementStart, OpKind.Container, OpKind.ContainerStart, OpKind.Template, OpKind.RepeaterCreate ]); /** * Checks whether the given operation represents the creation of an element or container. */ export function isElementOrContainerOp(op: CreateOp): op is ElementOrContainerOps { return elementContainerOpKinds.has(op.kind); } /** * Representation of a local reference on an element. */ export interface LocalRef { /** * User-defined name of the local ref variable. */ name: string; /** * Target of the local reference variable (often `''`). */ target: string; } /** * Base interface for `Element`, `ElementStart`, and `Template` operations, containing common fields * used to represent their element-like nature. */ export interface ElementOrContainerOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: ElementOrContainerOps['kind']; /** * `XrefId` allocated for this element. * * This ID is used to reference this element from other IR structures. */ xref: XrefId; /** * Attributes of various kinds on this element. Represented as a `ConstIndex` pointer into the * shared `consts` array of the component compilation. */ attributes: ConstIndex|null; /** * Local references to this element. * * Before local ref processing, this is an array of `LocalRef` declarations. * * After processing, it's a `ConstIndex` pointer into the shared `consts` array of the component * compilation. */ localRefs: LocalRef[]|ConstIndex|null; /** * Whether this container is marked `ngNonBindable`, which disabled Angular binding for itself and * all descendants. */ nonBindable: boolean; sourceSpan: ParseSourceSpan; } export interface ElementOpBase extends ElementOrContainerOpBase { kind: OpKind.Element|OpKind.ElementStart|OpKind.Template|OpKind.RepeaterCreate; /** * The HTML tag name for this element. */ tag: string|null; /** * The namespace of this element, which controls the preceding namespace instruction. */ namespace: Namespace; } /** * Logical operation representing the start of an element in the creation IR. */ export interface ElementStartOp extends ElementOpBase { kind: OpKind.ElementStart; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create an `ElementStartOp`. */ export function createElementStartOp( tag: string, xref: XrefId, namespace: Namespace, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): ElementStartOp { return { kind: OpKind.ElementStart, xref, tag, attributes: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an element with no children in the creation IR. */ export interface ElementOp extends ElementOpBase { kind: OpKind.Element; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Logical operation representing an embedded view declaration in the creation IR. */ export interface TemplateOp extends ElementOpBase { kind: OpKind.Template; /** * The number of declaration slots used by this template, or `null` if slots have not yet been * assigned. */ decls: number|null; /** * The number of binding variable slots used by this template, or `null` if binding variables have * not yet been counted. */ vars: number|null; /** * Whether or not this template was automatically created for use with block syntax (control flow * or defer). This will eventually cause the emitted template instruction to use fewer arguments, * since several of the default arguments are unnecessary for blocks. */ block: boolean; /** * The i18n placeholder data associated with this template. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create a `TemplateOp`. */ export function createTemplateOp( xref: XrefId, tag: string|null, namespace: Namespace, generatedInBlock: boolean, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): TemplateOp { return { kind: OpKind.Template, xref, attributes: null, tag, block: generatedInBlock, decls: null, vars: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * An op that creates a repeater (e.g. a for loop). */ export interface RepeaterCreateOp extends ElementOpBase { kind: OpKind.RepeaterCreate; /** * The number of declaration slots used by this repeater's template, or `null` if slots have not * yet been assigned. */ decls: number|null; /** * The number of binding variable slots used by this repeater's, or `null` if binding variables * have not yet been counted. */ vars: number|null; /** * The Xref of the empty view function. (For the primary view function, use the `xref` property). */ emptyView: XrefId|null; /** * The track expression to use while iterating. */ track: o.Expression; /** * `null` initially, then an `o.Expression`. Might be a track expression, or might be a reference * into the constant pool. */ trackByFn: o.Expression|null; /** * Context variables avaialable in this block. */ varNames: RepeaterVarNames; /** * Whether the repeater track function relies on the component instance. */ usesComponentInstance: boolean; sourceSpan: ParseSourceSpan; } // TODO: add source spans? export interface RepeaterVarNames { $index: string; $count: string; $first: string; $last: string; $even: string; $odd: string; $implicit: string; } export function createRepeaterCreateOp( primaryView: XrefId, emptyView: XrefId|null, track: o.Expression, varNames: RepeaterVarNames, sourceSpan: ParseSourceSpan): RepeaterCreateOp { return { kind: OpKind.RepeaterCreate, attributes: null, xref: primaryView, emptyView, track, trackByFn: null, tag: 'For', namespace: Namespace.HTML, nonBindable: false, localRefs: [], decls: null, vars: null, varNames, usesComponentInstance: false, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, numSlotsUsed: emptyView === null ? 2 : 3, }; } /** * Logical operation representing the end of an element structure in the creation IR. * * Pairs with an `ElementStart` operation. */ export interface ElementEndOp extends Op<CreateOp> { kind: OpKind.ElementEnd; /** * The `XrefId` of the element declared via `ElementStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan|null; } /** * Create an `ElementEndOp`. */ export function createElementEndOp(xref: XrefId, sourceSpan: ParseSourceSpan|null): ElementEndOp { return { kind: OpKind.ElementEnd, xref, sourceSpan, ...NEW_OP, }; } /** * Logical operation representing the start of a container in the creation IR. */ export interface ContainerStartOp extends ElementOrContainerOpBase { kind: OpKind.ContainerStart; } /** * Logical operation representing an empty container in the creation IR. */ export interface ContainerOp extends ElementOrContainerOpBase { kind: OpKind.Container; } /** * Logical operation representing the end of a container structure in the creation IR. * * Pairs with an `ContainerStart` operation. */ export interface ContainerEndOp extends Op<CreateOp> { kind: OpKind.ContainerEnd; /** * The `XrefId` of the element declared via `ContainerStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan; } /** * Logical operation causing binding to be disabled in descendents of a non-bindable container. */ export interface DisableBindingsOp extends Op<CreateOp> { kind: OpKind.DisableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createDisableBindingsOp(xref: XrefId): DisableBindingsOp { return { kind: OpKind.DisableBindings, xref, ...NEW_OP, }; } /** * Logical operation causing binding to be re-enabled after visiting descendants of a * non-bindable container. */ export interface EnableBindingsOp extends Op<CreateOp> { kind: OpKind.EnableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createEnableBindingsOp(xref: XrefId): EnableBindingsOp { return { kind: OpKind.EnableBindings, xref, ...NEW_OP, }; } /** * Logical operation representing a text node in the creation IR. */ export interface TextOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Text; /** * `XrefId` used to reference this text node in other IR structures. */ xref: XrefId; /** * The static initial value of the text node. */ initialValue: string; sourceSpan: ParseSourceSpan|null; } /** * Create a `TextOp`. */ export function createTextOp( xref: XrefId, initialValue: string, sourceSpan: ParseSourceSpan|null): TextOp { return { kind: OpKind.Text, xref, initialValue, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an event listener on an element in the creation IR. */ export interface ListenerOp extends Op<CreateOp>, UsesSlotIndexTrait { kind: OpKind.Listener; /** * Whether this listener is from a host binding. */ hostListener: boolean; /** * Name of the event which is being listened to. */ name: string; /** * Tag name of the element on which this listener is placed. Might be null, if this listener * belongs to a host binding. */ tag: string|null; /** * A list of `UpdateOp`s representing the body of the event listener. */ handlerOps: OpList<UpdateOp>; /** * Name of the function */ handlerFnName: string|null; /** * Whether this listener is known to consume `$event` in its body. */ consumesDollarEvent: boolean; /** * Whether the listener is listening for an animation event. */ isAnimationListener: boolean; /** * The animation phase of the listener. */ animationPhase: string|null; sourceSpan: ParseSourceSpan; } /** * Create a `ListenerOp`. Host bindings reuse all the listener logic. */ export function createListenerOp( target: XrefId, name: string, tag: string|null, animationPhase: string|null, hostListener: boolean, sourceSpan: ParseSourceSpan): ListenerOp { return { kind: OpKind.Listener, target, tag, hostListener, name, handlerOps: new OpList(), handlerFnName: null, consumesDollarEvent: false, isAnimationListener: animationPhase !== null, animationPhase: animationPhase, sourceSpan, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, }; } export interface PipeOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Pipe; xref: XrefId; name: string; } export function createPipeOp(xref: XrefId, name: string): PipeOp { return { kind: OpKind.Pipe, xref, name, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Whether the active namespace is HTML, MathML, or SVG mode. */ export enum Namespace { HTML, SVG, Math, } /** * An op corresponding to a namespace instruction, for switching between HTML, SVG, and MathML. */ export interface NamespaceOp extends Op<CreateOp> { kind: OpKind.Namespace; active: Namespace; } export function createNamespaceOp(namespace: Namespace): NamespaceOp { return { kind: OpKind.Namespace, active: namespace, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionDefOp extends Op<CreateOp> { kind: OpKind.ProjectionDef; // The parsed selector information for this projection def. def: o.Expression|null; } export function createProjectionDefOp(def: o.Expression|null): ProjectionDefOp { return { kind: OpKind.ProjectionDef, def, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Projection; xref: XrefId; slot: number|null; projectionSlotIndex: number; attributes: string[]; localRefs: string[]; selector: string; sourceSpan: ParseSourceSpan; } export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp { return { kind: OpKind.Projection, xref, selector, projectionSlotIndex: 0, attributes: [], localRefs: [], sourceSpan: null!, // TODO ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an attribute that has been extracted for inclusion in the consts array. */ export interface ExtractedAttributeOp extends Op<CreateOp> { kind: OpKind.ExtractedAttribute; /** * The `XrefId` of the template-like element the extracted attribute will belong to. */ target: XrefId; /** * The kind of binding represented by this extracted attribute. */ bindingKind: BindingKind; /** * The name of the extracted attribute. */ name: string; /** * The value expression of the extracted attribute. */ expression: o.Expression|null; } /** * Create an `ExtractedAttributeOp`. */ export function createExtractedAttributeOp( target: XrefId, bindingKind: BindingKind, name: string, expression: o.Expression|null): ExtractedAttributeOp { return { kind: OpKind.ExtractedAttribute, target, bindingKind, name, expression, ...NEW_OP, }; } export interface DeferOp extends Op<CreateOp>, ConsumesSlotOpTrait, UsesSlotIndexTrait { kind: OpKind.Defer; /** * The xref of this defer op. */ xref: XrefId; /** * The xref of the main view. This will be associated with `slot`. */ target: XrefId; /** * Secondary loading block associated with this defer op. */ loading: DeferSecondaryBlockOp|null; /** * Secondary placeholder block associated with this defer op. */ placeholder: DeferSecondaryBlockOp|null; /** * Secondary error block associated with this defer op. */ error: DeferSecondaryBlockOp|null; sourceSpan: ParseSourceSpan; } export function createDeferOp(xref: XrefId, main: XrefId, sourceSpan: ParseSourceSpan): DeferOp { return { kind: OpKind.Defer, xref, target: main, loading: null, placeholder: null, error: null, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, ...TRAIT_USES_SLOT_INDEX, }; } export interface DeferSecondaryBlockOp extends Op<CreateOp>, UsesSlotIndexTrait, HasConstTrait { kind: OpKind.DeferSecondaryBlock; /** * The xref of the corresponding defer op. */ deferOp: XrefId; /** * Which kind of secondary block this op represents. */ secondaryBlockKind: DeferSecondaryKind; /** * The xref of the secondary view. This will be associated with `slot`. */ target: XrefId; } export function createDeferSecondaryOp( deferOp: XrefId, secondaryView: XrefId, secondaryBlockKind: DeferSecondaryKind): DeferSecondaryBlockOp { return { kind: OpKind.DeferSecondaryBlock, deferOp, target: secondaryView, secondaryBlockKind, constValue: null, makeExpression: literalOrArrayLiteral, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, ...TRAIT_HAS_CONST, }; } export interface DeferOnOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.DeferOn; sourceSpan: ParseSourceSpan; } export function createDeferOnOp(xref: XrefId, sourceSpan: ParseSourceSpan): DeferOnOp { return { kind: OpKind.DeferOn, xref, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an i18n message that has been extracted for inclusion in the consts array. */ export interface ExtractedMessageOp extends Op<CreateOp> { kind: OpKind.ExtractedMessage; /** * A reference to the i18n op this message was extracted from. */ owner: XrefId; /** * The message expression. */ expression: o.Expression; /** * The statements to construct the message. */ statements: o.Statement[]; } /** * Create an `ExtractedMessageOp`. */ export function createExtractedMessageOp( owner: XrefId, expression: o.Expression, statements: o.Statement[]): ExtractedMessageOp { return { kind: OpKind.ExtractedMessage, owner, expression, statements, ...NEW_OP, }; } export interface I18nOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.I18nStart|OpKind.I18n; /** * `XrefId` allocated for this i18n block. */ xref: XrefId; /** * A reference to the root i18n block that this one belongs to. For a a root i18n block, this is * the same as xref. */ root: XrefId; /** * The i18n metadata associated with this op. */ message: i18n.Message; /** * Map of values to use for named placeholders in the i18n message. (Resolved at message creation) */ params: Map<string, o.Expression>; /** * Map of values to use for named placeholders in the i18n message. (Resolved during * post-porcessing) */ postprocessingParams: Map<string, o.Expression>; /** * The index in the consts array where the message i18n message is stored. */ messageIndex: ConstIndex|null; /** * The index of this sub-block in the i18n message. For a root i18n block, this is null. */ subTemplateIndex: number|null; /** * Whether the i18n message requires postprocessing. */ needsPostprocessing: boolean; } /** * Represents an empty i18n block. */ export interface I18nOp extends I18nOpBase { kind: OpKind.I18n; } /** * Represents the start of an i18n block. */ export interface I18nStartOp extends I18nOpBase { kind: OpKind.I18nStart; } /** * Create an `I18nStartOp`. */ export function createI18nStartOp(xref: XrefId, message: i18n.Message, root?: XrefId): I18nStartOp { return { kind: OpKind.I18nStart, xref, root: root ?? xref, message, params: new Map(), postprocessingParams: new Map(), messageIndex: null, subTemplateIndex: null, needsPostprocessing: false, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents the end of an i18n block. */ export interface I18nEndOp extends Op<CreateOp> { kind: OpKind.I18nEnd; /** * The `XrefId` of the `I18nStartOp` that created this block. */ xref: XrefId; } /** * Create an `I18nEndOp`. */ export function createI18nEndOp(xref: XrefId): I18nEndOp { return { kind: OpKind.I18nEnd, xref, ...NEW_OP, }; } /** * An op that represents an ICU expression. */ export interface IcuOp extends Op<CreateOp> { kind: OpKind.Icu; /** * The ID of the ICU. */ xref: XrefId; /** * The i18n message for this ICU. */ message: i18n.Message; sourceSpan: ParseSourceSpan; } /** * Creates an op to create an ICU expression. */ export function createIcuOp( xref: XrefId, message: i18n.Message, sourceSpan: ParseSourceSpan): IcuOp { return { kind: OpKind.Icu, xref, message, sourceSpan, ...NEW_OP, }; } /** * An index into the `consts` array which is shared across the compilation of all views in a * component. */ export type ConstIndex = number&{__brand: 'ConstIndex'}; export function literalOrArrayLiteral(value: any): o.Expression { if (Array.isArray(value)) { return o.literalArr(value.map(literalOrArrayLiteral)); } return o.literal(value, o.INFERRED_TYPE); }
packages/compiler/src/template/pipeline/ir/src/ops/create.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.04201984032988548, 0.0014623199822381139, 0.0001640973350731656, 0.00017578245024196804, 0.005002145189791918 ]
{ "id": 2, "code_window": [ " xref,\n", " selector,\n", " projectionSlotIndex: 0,\n", " attributes: [],\n", " localRefs: [],\n", " sourceSpan: null!, // TODO\n", " ...NEW_OP,\n", " ...TRAIT_CONSUMES_SLOT,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " sourceSpan,\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 594 }
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` <div i18n>{gender, select, single {'single quotes'} double {"double quotes"} other {other}}</div> ` }) export class MyComponent { gender = 'male'; } @NgModule({declarations: [MyComponent]}) export class MyModule { }
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_i18n/icu_logic/escape_quotes.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017704452329780906, 0.00017356761964038014, 0.00017009071598295122, 0.00017356761964038014, 0.0000034769036574289203 ]
{ "id": 2, "code_window": [ " xref,\n", " selector,\n", " projectionSlotIndex: 0,\n", " attributes: [],\n", " localRefs: [],\n", " sourceSpan: null!, // TODO\n", " ...NEW_OP,\n", " ...TRAIT_CONSUMES_SLOT,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " sourceSpan,\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 594 }
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` <ng-template *ngIf="someFlag" i18n>Content A</ng-template> <ng-container *ngIf="someFlag" i18n>Content B</ng-container> `, }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_i18n/ng-container_ng-template/structural_directives.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017704452329780906, 0.00017381043289788067, 0.00017057634249795228, 0.00017381043289788067, 0.000003234090399928391 ]
{ "id": 2, "code_window": [ " xref,\n", " selector,\n", " projectionSlotIndex: 0,\n", " attributes: [],\n", " localRefs: [],\n", " sourceSpan: null!, // TODO\n", " ...NEW_OP,\n", " ...TRAIT_CONSUMES_SLOT,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " sourceSpan,\n" ], "file_path": "packages/compiler/src/template/pipeline/ir/src/ops/create.ts", "type": "replace", "edit_start_line_idx": 594 }
// #docplaster // #docregion, preload-v1 import { NgModule } from '@angular/core'; import { RouterModule, Routes, // #enddocregion preload-v1 PreloadAllModules // #docregion preload-v1 } from '@angular/router'; import { ComposeMessageComponent } from './compose-message/compose-message.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { authGuard } from './auth/auth.guard'; const appRoutes: Routes = [ { path: 'compose', component: ComposeMessageComponent, outlet: 'popup' }, { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule), canMatch: [authGuard] }, { path: 'crisis-center', loadChildren: () => import('./crisis-center/crisis-center.module').then(m => m.CrisisCenterModule) }, { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ // #docregion forRoot RouterModule.forRoot( appRoutes, // #enddocregion preload-v1 { enableTracing: true, // <-- debugging purposes only preloadingStrategy: PreloadAllModules } // #docregion preload-v1 ) // #enddocregion forRoot ], exports: [ RouterModule ] }) export class AppRoutingModule {}
aio/content/examples/router/src/app/app-routing.module.6.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0001764304470270872, 0.00017440626106690615, 0.00016948216944001615, 0.0001755312259774655, 0.0000024359328563150484 ]
{ "id": 3, "code_window": [ "\n", "/**\n", " * Ingest a literal text node from the AST into the given `ViewCompilation`.\n", " */\n", "function ingestContent(unit: ViewCompilationUnit, content: t.Content): void {\n", " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector);\n", " for (const attr of content.attributes) {\n", " ingestBinding(\n", " unit, op.xref, attr.name, o.literal(attr.value), e.BindingType.Attribute, null,\n", " SecurityContext.NONE, attr.sourceSpan, BindingFlags.TextValue);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector, content.sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/ingest.ts", "type": "replace", "edit_start_line_idx": 225 }
/** * @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.io/license */ import * as i18n from '../../../../../i18n/i18n_ast'; import * as o from '../../../../../output/output_ast'; import {ParseSourceSpan} from '../../../../../parse_util'; import {BindingKind, DeferSecondaryKind, OpKind} from '../enums'; import {Op, OpList, XrefId} from '../operations'; import {ConsumesSlotOpTrait, HasConstTrait, TRAIT_CONSUMES_SLOT, TRAIT_HAS_CONST, TRAIT_USES_SLOT_INDEX, UsesSlotIndexTrait} from '../traits'; import {ListEndOp, NEW_OP, StatementOp, VariableOp} from './shared'; import type {UpdateOp} from './update'; /** * An operation usable on the creation side of the IR. */ export type CreateOp = ListEndOp<CreateOp>|StatementOp<CreateOp>|ElementOp|ElementStartOp| ElementEndOp|ContainerOp|ContainerStartOp|ContainerEndOp|TemplateOp|EnableBindingsOp| DisableBindingsOp|TextOp|ListenerOp|PipeOp|VariableOp<CreateOp>|NamespaceOp|ProjectionDefOp| ProjectionOp|ExtractedAttributeOp|DeferOp|DeferSecondaryBlockOp|DeferOnOp|RepeaterCreateOp| ExtractedMessageOp|I18nOp|I18nStartOp|I18nEndOp|IcuOp; /** * An operation representing the creation of an element or container. */ export type ElementOrContainerOps = ElementOp|ElementStartOp|ContainerOp|ContainerStartOp|TemplateOp|RepeaterCreateOp; /** * The set of OpKinds that represent the creation of an element or container */ const elementContainerOpKinds = new Set([ OpKind.Element, OpKind.ElementStart, OpKind.Container, OpKind.ContainerStart, OpKind.Template, OpKind.RepeaterCreate ]); /** * Checks whether the given operation represents the creation of an element or container. */ export function isElementOrContainerOp(op: CreateOp): op is ElementOrContainerOps { return elementContainerOpKinds.has(op.kind); } /** * Representation of a local reference on an element. */ export interface LocalRef { /** * User-defined name of the local ref variable. */ name: string; /** * Target of the local reference variable (often `''`). */ target: string; } /** * Base interface for `Element`, `ElementStart`, and `Template` operations, containing common fields * used to represent their element-like nature. */ export interface ElementOrContainerOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: ElementOrContainerOps['kind']; /** * `XrefId` allocated for this element. * * This ID is used to reference this element from other IR structures. */ xref: XrefId; /** * Attributes of various kinds on this element. Represented as a `ConstIndex` pointer into the * shared `consts` array of the component compilation. */ attributes: ConstIndex|null; /** * Local references to this element. * * Before local ref processing, this is an array of `LocalRef` declarations. * * After processing, it's a `ConstIndex` pointer into the shared `consts` array of the component * compilation. */ localRefs: LocalRef[]|ConstIndex|null; /** * Whether this container is marked `ngNonBindable`, which disabled Angular binding for itself and * all descendants. */ nonBindable: boolean; sourceSpan: ParseSourceSpan; } export interface ElementOpBase extends ElementOrContainerOpBase { kind: OpKind.Element|OpKind.ElementStart|OpKind.Template|OpKind.RepeaterCreate; /** * The HTML tag name for this element. */ tag: string|null; /** * The namespace of this element, which controls the preceding namespace instruction. */ namespace: Namespace; } /** * Logical operation representing the start of an element in the creation IR. */ export interface ElementStartOp extends ElementOpBase { kind: OpKind.ElementStart; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create an `ElementStartOp`. */ export function createElementStartOp( tag: string, xref: XrefId, namespace: Namespace, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): ElementStartOp { return { kind: OpKind.ElementStart, xref, tag, attributes: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an element with no children in the creation IR. */ export interface ElementOp extends ElementOpBase { kind: OpKind.Element; /** * The i18n placeholder data associated with this element. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Logical operation representing an embedded view declaration in the creation IR. */ export interface TemplateOp extends ElementOpBase { kind: OpKind.Template; /** * The number of declaration slots used by this template, or `null` if slots have not yet been * assigned. */ decls: number|null; /** * The number of binding variable slots used by this template, or `null` if binding variables have * not yet been counted. */ vars: number|null; /** * Whether or not this template was automatically created for use with block syntax (control flow * or defer). This will eventually cause the emitted template instruction to use fewer arguments, * since several of the default arguments are unnecessary for blocks. */ block: boolean; /** * The i18n placeholder data associated with this template. */ i18nPlaceholder?: i18n.TagPlaceholder; } /** * Create a `TemplateOp`. */ export function createTemplateOp( xref: XrefId, tag: string|null, namespace: Namespace, generatedInBlock: boolean, i18nPlaceholder: i18n.TagPlaceholder|undefined, sourceSpan: ParseSourceSpan): TemplateOp { return { kind: OpKind.Template, xref, attributes: null, tag, block: generatedInBlock, decls: null, vars: null, localRefs: [], nonBindable: false, namespace, i18nPlaceholder, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * An op that creates a repeater (e.g. a for loop). */ export interface RepeaterCreateOp extends ElementOpBase { kind: OpKind.RepeaterCreate; /** * The number of declaration slots used by this repeater's template, or `null` if slots have not * yet been assigned. */ decls: number|null; /** * The number of binding variable slots used by this repeater's, or `null` if binding variables * have not yet been counted. */ vars: number|null; /** * The Xref of the empty view function. (For the primary view function, use the `xref` property). */ emptyView: XrefId|null; /** * The track expression to use while iterating. */ track: o.Expression; /** * `null` initially, then an `o.Expression`. Might be a track expression, or might be a reference * into the constant pool. */ trackByFn: o.Expression|null; /** * Context variables avaialable in this block. */ varNames: RepeaterVarNames; /** * Whether the repeater track function relies on the component instance. */ usesComponentInstance: boolean; sourceSpan: ParseSourceSpan; } // TODO: add source spans? export interface RepeaterVarNames { $index: string; $count: string; $first: string; $last: string; $even: string; $odd: string; $implicit: string; } export function createRepeaterCreateOp( primaryView: XrefId, emptyView: XrefId|null, track: o.Expression, varNames: RepeaterVarNames, sourceSpan: ParseSourceSpan): RepeaterCreateOp { return { kind: OpKind.RepeaterCreate, attributes: null, xref: primaryView, emptyView, track, trackByFn: null, tag: 'For', namespace: Namespace.HTML, nonBindable: false, localRefs: [], decls: null, vars: null, varNames, usesComponentInstance: false, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, numSlotsUsed: emptyView === null ? 2 : 3, }; } /** * Logical operation representing the end of an element structure in the creation IR. * * Pairs with an `ElementStart` operation. */ export interface ElementEndOp extends Op<CreateOp> { kind: OpKind.ElementEnd; /** * The `XrefId` of the element declared via `ElementStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan|null; } /** * Create an `ElementEndOp`. */ export function createElementEndOp(xref: XrefId, sourceSpan: ParseSourceSpan|null): ElementEndOp { return { kind: OpKind.ElementEnd, xref, sourceSpan, ...NEW_OP, }; } /** * Logical operation representing the start of a container in the creation IR. */ export interface ContainerStartOp extends ElementOrContainerOpBase { kind: OpKind.ContainerStart; } /** * Logical operation representing an empty container in the creation IR. */ export interface ContainerOp extends ElementOrContainerOpBase { kind: OpKind.Container; } /** * Logical operation representing the end of a container structure in the creation IR. * * Pairs with an `ContainerStart` operation. */ export interface ContainerEndOp extends Op<CreateOp> { kind: OpKind.ContainerEnd; /** * The `XrefId` of the element declared via `ContainerStart`. */ xref: XrefId; sourceSpan: ParseSourceSpan; } /** * Logical operation causing binding to be disabled in descendents of a non-bindable container. */ export interface DisableBindingsOp extends Op<CreateOp> { kind: OpKind.DisableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createDisableBindingsOp(xref: XrefId): DisableBindingsOp { return { kind: OpKind.DisableBindings, xref, ...NEW_OP, }; } /** * Logical operation causing binding to be re-enabled after visiting descendants of a * non-bindable container. */ export interface EnableBindingsOp extends Op<CreateOp> { kind: OpKind.EnableBindings; /** * `XrefId` of the element that was marked non-bindable. */ xref: XrefId; } export function createEnableBindingsOp(xref: XrefId): EnableBindingsOp { return { kind: OpKind.EnableBindings, xref, ...NEW_OP, }; } /** * Logical operation representing a text node in the creation IR. */ export interface TextOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Text; /** * `XrefId` used to reference this text node in other IR structures. */ xref: XrefId; /** * The static initial value of the text node. */ initialValue: string; sourceSpan: ParseSourceSpan|null; } /** * Create a `TextOp`. */ export function createTextOp( xref: XrefId, initialValue: string, sourceSpan: ParseSourceSpan|null): TextOp { return { kind: OpKind.Text, xref, initialValue, sourceSpan, ...TRAIT_CONSUMES_SLOT, ...NEW_OP, }; } /** * Logical operation representing an event listener on an element in the creation IR. */ export interface ListenerOp extends Op<CreateOp>, UsesSlotIndexTrait { kind: OpKind.Listener; /** * Whether this listener is from a host binding. */ hostListener: boolean; /** * Name of the event which is being listened to. */ name: string; /** * Tag name of the element on which this listener is placed. Might be null, if this listener * belongs to a host binding. */ tag: string|null; /** * A list of `UpdateOp`s representing the body of the event listener. */ handlerOps: OpList<UpdateOp>; /** * Name of the function */ handlerFnName: string|null; /** * Whether this listener is known to consume `$event` in its body. */ consumesDollarEvent: boolean; /** * Whether the listener is listening for an animation event. */ isAnimationListener: boolean; /** * The animation phase of the listener. */ animationPhase: string|null; sourceSpan: ParseSourceSpan; } /** * Create a `ListenerOp`. Host bindings reuse all the listener logic. */ export function createListenerOp( target: XrefId, name: string, tag: string|null, animationPhase: string|null, hostListener: boolean, sourceSpan: ParseSourceSpan): ListenerOp { return { kind: OpKind.Listener, target, tag, hostListener, name, handlerOps: new OpList(), handlerFnName: null, consumesDollarEvent: false, isAnimationListener: animationPhase !== null, animationPhase: animationPhase, sourceSpan, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, }; } export interface PipeOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Pipe; xref: XrefId; name: string; } export function createPipeOp(xref: XrefId, name: string): PipeOp { return { kind: OpKind.Pipe, xref, name, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Whether the active namespace is HTML, MathML, or SVG mode. */ export enum Namespace { HTML, SVG, Math, } /** * An op corresponding to a namespace instruction, for switching between HTML, SVG, and MathML. */ export interface NamespaceOp extends Op<CreateOp> { kind: OpKind.Namespace; active: Namespace; } export function createNamespaceOp(namespace: Namespace): NamespaceOp { return { kind: OpKind.Namespace, active: namespace, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionDefOp extends Op<CreateOp> { kind: OpKind.ProjectionDef; // The parsed selector information for this projection def. def: o.Expression|null; } export function createProjectionDefOp(def: o.Expression|null): ProjectionDefOp { return { kind: OpKind.ProjectionDef, def, ...NEW_OP, }; } /** * An op that creates a content projection slot. */ export interface ProjectionOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.Projection; xref: XrefId; slot: number|null; projectionSlotIndex: number; attributes: string[]; localRefs: string[]; selector: string; sourceSpan: ParseSourceSpan; } export function createProjectionOp(xref: XrefId, selector: string): ProjectionOp { return { kind: OpKind.Projection, xref, selector, projectionSlotIndex: 0, attributes: [], localRefs: [], sourceSpan: null!, // TODO ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an attribute that has been extracted for inclusion in the consts array. */ export interface ExtractedAttributeOp extends Op<CreateOp> { kind: OpKind.ExtractedAttribute; /** * The `XrefId` of the template-like element the extracted attribute will belong to. */ target: XrefId; /** * The kind of binding represented by this extracted attribute. */ bindingKind: BindingKind; /** * The name of the extracted attribute. */ name: string; /** * The value expression of the extracted attribute. */ expression: o.Expression|null; } /** * Create an `ExtractedAttributeOp`. */ export function createExtractedAttributeOp( target: XrefId, bindingKind: BindingKind, name: string, expression: o.Expression|null): ExtractedAttributeOp { return { kind: OpKind.ExtractedAttribute, target, bindingKind, name, expression, ...NEW_OP, }; } export interface DeferOp extends Op<CreateOp>, ConsumesSlotOpTrait, UsesSlotIndexTrait { kind: OpKind.Defer; /** * The xref of this defer op. */ xref: XrefId; /** * The xref of the main view. This will be associated with `slot`. */ target: XrefId; /** * Secondary loading block associated with this defer op. */ loading: DeferSecondaryBlockOp|null; /** * Secondary placeholder block associated with this defer op. */ placeholder: DeferSecondaryBlockOp|null; /** * Secondary error block associated with this defer op. */ error: DeferSecondaryBlockOp|null; sourceSpan: ParseSourceSpan; } export function createDeferOp(xref: XrefId, main: XrefId, sourceSpan: ParseSourceSpan): DeferOp { return { kind: OpKind.Defer, xref, target: main, loading: null, placeholder: null, error: null, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, ...TRAIT_USES_SLOT_INDEX, }; } export interface DeferSecondaryBlockOp extends Op<CreateOp>, UsesSlotIndexTrait, HasConstTrait { kind: OpKind.DeferSecondaryBlock; /** * The xref of the corresponding defer op. */ deferOp: XrefId; /** * Which kind of secondary block this op represents. */ secondaryBlockKind: DeferSecondaryKind; /** * The xref of the secondary view. This will be associated with `slot`. */ target: XrefId; } export function createDeferSecondaryOp( deferOp: XrefId, secondaryView: XrefId, secondaryBlockKind: DeferSecondaryKind): DeferSecondaryBlockOp { return { kind: OpKind.DeferSecondaryBlock, deferOp, target: secondaryView, secondaryBlockKind, constValue: null, makeExpression: literalOrArrayLiteral, ...NEW_OP, ...TRAIT_USES_SLOT_INDEX, ...TRAIT_HAS_CONST, }; } export interface DeferOnOp extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.DeferOn; sourceSpan: ParseSourceSpan; } export function createDeferOnOp(xref: XrefId, sourceSpan: ParseSourceSpan): DeferOnOp { return { kind: OpKind.DeferOn, xref, sourceSpan, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents an i18n message that has been extracted for inclusion in the consts array. */ export interface ExtractedMessageOp extends Op<CreateOp> { kind: OpKind.ExtractedMessage; /** * A reference to the i18n op this message was extracted from. */ owner: XrefId; /** * The message expression. */ expression: o.Expression; /** * The statements to construct the message. */ statements: o.Statement[]; } /** * Create an `ExtractedMessageOp`. */ export function createExtractedMessageOp( owner: XrefId, expression: o.Expression, statements: o.Statement[]): ExtractedMessageOp { return { kind: OpKind.ExtractedMessage, owner, expression, statements, ...NEW_OP, }; } export interface I18nOpBase extends Op<CreateOp>, ConsumesSlotOpTrait { kind: OpKind.I18nStart|OpKind.I18n; /** * `XrefId` allocated for this i18n block. */ xref: XrefId; /** * A reference to the root i18n block that this one belongs to. For a a root i18n block, this is * the same as xref. */ root: XrefId; /** * The i18n metadata associated with this op. */ message: i18n.Message; /** * Map of values to use for named placeholders in the i18n message. (Resolved at message creation) */ params: Map<string, o.Expression>; /** * Map of values to use for named placeholders in the i18n message. (Resolved during * post-porcessing) */ postprocessingParams: Map<string, o.Expression>; /** * The index in the consts array where the message i18n message is stored. */ messageIndex: ConstIndex|null; /** * The index of this sub-block in the i18n message. For a root i18n block, this is null. */ subTemplateIndex: number|null; /** * Whether the i18n message requires postprocessing. */ needsPostprocessing: boolean; } /** * Represents an empty i18n block. */ export interface I18nOp extends I18nOpBase { kind: OpKind.I18n; } /** * Represents the start of an i18n block. */ export interface I18nStartOp extends I18nOpBase { kind: OpKind.I18nStart; } /** * Create an `I18nStartOp`. */ export function createI18nStartOp(xref: XrefId, message: i18n.Message, root?: XrefId): I18nStartOp { return { kind: OpKind.I18nStart, xref, root: root ?? xref, message, params: new Map(), postprocessingParams: new Map(), messageIndex: null, subTemplateIndex: null, needsPostprocessing: false, ...NEW_OP, ...TRAIT_CONSUMES_SLOT, }; } /** * Represents the end of an i18n block. */ export interface I18nEndOp extends Op<CreateOp> { kind: OpKind.I18nEnd; /** * The `XrefId` of the `I18nStartOp` that created this block. */ xref: XrefId; } /** * Create an `I18nEndOp`. */ export function createI18nEndOp(xref: XrefId): I18nEndOp { return { kind: OpKind.I18nEnd, xref, ...NEW_OP, }; } /** * An op that represents an ICU expression. */ export interface IcuOp extends Op<CreateOp> { kind: OpKind.Icu; /** * The ID of the ICU. */ xref: XrefId; /** * The i18n message for this ICU. */ message: i18n.Message; sourceSpan: ParseSourceSpan; } /** * Creates an op to create an ICU expression. */ export function createIcuOp( xref: XrefId, message: i18n.Message, sourceSpan: ParseSourceSpan): IcuOp { return { kind: OpKind.Icu, xref, message, sourceSpan, ...NEW_OP, }; } /** * An index into the `consts` array which is shared across the compilation of all views in a * component. */ export type ConstIndex = number&{__brand: 'ConstIndex'}; export function literalOrArrayLiteral(value: any): o.Expression { if (Array.isArray(value)) { return o.literalArr(value.map(literalOrArrayLiteral)); } return o.literal(value, o.INFERRED_TYPE); }
packages/compiler/src/template/pipeline/ir/src/ops/create.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0029133332427591085, 0.0002694941940717399, 0.00016007073281798512, 0.00016917458560783416, 0.0003825539315585047 ]
{ "id": 3, "code_window": [ "\n", "/**\n", " * Ingest a literal text node from the AST into the given `ViewCompilation`.\n", " */\n", "function ingestContent(unit: ViewCompilationUnit, content: t.Content): void {\n", " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector);\n", " for (const attr of content.attributes) {\n", " ingestBinding(\n", " unit, op.xref, attr.name, o.literal(attr.value), e.BindingType.Attribute, null,\n", " SecurityContext.NONE, attr.sourceSpan, BindingFlags.TextValue);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector, content.sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/ingest.ts", "type": "replace", "edit_start_line_idx": 225 }
/** * @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.io/license */ import {HttpHeaders} from './headers'; /** * Type enumeration for the different kinds of `HttpEvent`. * * @publicApi */ export enum HttpEventType { /** * The request was sent out over the wire. */ Sent, /** * An upload progress event was received. * * Note: The `FetchBackend` doesn't support progress report on uploads. */ UploadProgress, /** * The response status code and headers were received. */ ResponseHeader, /** * A download progress event was received. */ DownloadProgress, /** * The full response including the body was received. */ Response, /** * A custom event from an interceptor or a backend. */ User, } /** * Base interface for progress events. * * @publicApi */ export interface HttpProgressEvent { /** * Progress event type is either upload or download. */ type: HttpEventType.DownloadProgress|HttpEventType.UploadProgress; /** * Number of bytes uploaded or downloaded. */ loaded: number; /** * Total number of bytes to upload or download. Depending on the request or * response, this may not be computable and thus may not be present. */ total?: number; } /** * A download progress event. * * @publicApi */ export interface HttpDownloadProgressEvent extends HttpProgressEvent { type: HttpEventType.DownloadProgress; /** * The partial response body as downloaded so far. * * Only present if the responseType was `text`. */ partialText?: string; } /** * An upload progress event. * * Note: The `FetchBackend` doesn't support progress report on uploads. * * @publicApi */ export interface HttpUploadProgressEvent extends HttpProgressEvent { type: HttpEventType.UploadProgress; } /** * An event indicating that the request was sent to the server. Useful * when a request may be retried multiple times, to distinguish between * retries on the final event stream. * * @publicApi */ export interface HttpSentEvent { type: HttpEventType.Sent; } /** * A user-defined event. * * Grouping all custom events under this type ensures they will be handled * and forwarded by all implementations of interceptors. * * @publicApi */ export interface HttpUserEvent<T> { type: HttpEventType.User; } /** * An error that represents a failed attempt to JSON.parse text coming back * from the server. * * It bundles the Error object with the actual response body that failed to parse. * * */ export interface HttpJsonParseError { error: Error; text: string; } /** * Union type for all possible events on the response stream. * * Typed according to the expected type of the response. * * @publicApi */ export type HttpEvent<T> = HttpSentEvent|HttpHeaderResponse|HttpResponse<T>|HttpProgressEvent|HttpUserEvent<T>; /** * Base class for both `HttpResponse` and `HttpHeaderResponse`. * * @publicApi */ export abstract class HttpResponseBase { /** * All response headers. */ readonly headers: HttpHeaders; /** * Response status code. */ readonly status: number; /** * Textual description of response status code, defaults to OK. * * Do not depend on this. */ readonly statusText: string; /** * URL of the resource retrieved, or null if not available. */ readonly url: string|null; /** * Whether the status code falls in the 2xx range. */ readonly ok: boolean; /** * Type of the response, narrowed to either the full response or the header. */ // TODO(issue/24571): remove '!'. readonly type!: HttpEventType.Response|HttpEventType.ResponseHeader; /** * Super-constructor for all responses. * * The single parameter accepted is an initialization hash. Any properties * of the response passed there will override the default values. */ constructor( init: { headers?: HttpHeaders, status?: number, statusText?: string, url?: string, }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK') { // If the hash has values passed, use them to initialize the response. // Otherwise use the default values. this.headers = init.headers || new HttpHeaders(); this.status = init.status !== undefined ? init.status : defaultStatus; this.statusText = init.statusText || defaultStatusText; this.url = init.url || null; // Cache the ok value to avoid defining a getter. this.ok = this.status >= 200 && this.status < 300; } } /** * A partial HTTP response which only includes the status and header data, * but no response body. * * `HttpHeaderResponse` is a `HttpEvent` available on the response * event stream, only when progress events are requested. * * @publicApi */ export class HttpHeaderResponse extends HttpResponseBase { /** * Create a new `HttpHeaderResponse` with the given parameters. */ constructor(init: { headers?: HttpHeaders, status?: number, statusText?: string, url?: string, } = {}) { super(init); } override readonly type: HttpEventType.ResponseHeader = HttpEventType.ResponseHeader; /** * Copy this `HttpHeaderResponse`, overriding its contents with the * given parameter hash. */ clone(update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string;} = {}): HttpHeaderResponse { // Perform a straightforward initialization of the new HttpHeaderResponse, // overriding the current parameters with new ones if given. return new HttpHeaderResponse({ headers: update.headers || this.headers, status: update.status !== undefined ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A full HTTP response, including a typed response body (which may be `null` * if one was not returned). * * `HttpResponse` is a `HttpEvent` available on the response event * stream. * * @publicApi */ export class HttpResponse<T> extends HttpResponseBase { /** * The response body, or `null` if one was not returned. */ readonly body: T|null; /** * Construct a new `HttpResponse`. */ constructor(init: { body?: T|null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}) { super(init); this.body = init.body !== undefined ? init.body : null; } override readonly type: HttpEventType.Response = HttpEventType.Response; clone(): HttpResponse<T>; clone(update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string;}): HttpResponse<T>; clone<V>(update: { body?: V|null, headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }): HttpResponse<V>; clone(update: { body?: any|null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}): HttpResponse<any> { return new HttpResponse<any>({ body: (update.body !== undefined) ? update.body : this.body, headers: update.headers || this.headers, status: (update.status !== undefined) ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A response that represents an error or failure, either from a * non-successful HTTP status, an error while executing the request, * or some other failure which occurred during the parsing of the response. * * Any error returned on the `Observable` response stream will be * wrapped in an `HttpErrorResponse` to provide additional context about * the state of the HTTP layer when the error occurred. The error property * will contain either a wrapped Error object or the error response returned * from the server. * * @publicApi */ export class HttpErrorResponse extends HttpResponseBase implements Error { readonly name = 'HttpErrorResponse'; readonly message: string; readonly error: any|null; /** * Errors are never okay, even when the status code is in the 2xx success range. */ override readonly ok = false; constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }) { // Initialize with a default status of 0 / Unknown Error. super(init, 0, 'Unknown Error'); // If the response was successful, then this was a parse error. Otherwise, it was // a protocol-level failure of some sort. Either the request failed in transit // or the server returned an unsuccessful status code. if (this.status >= 200 && this.status < 300) { this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`; } else { this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${ init.statusText}`; } this.error = init.error || null; } } /** * Http status codes. * As per https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @publicApi */ export const enum HttpStatusCode { Continue = 100, SwitchingProtocols = 101, Processing = 102, EarlyHints = 103, Ok = 200, Created = 201, Accepted = 202, NonAuthoritativeInformation = 203, NoContent = 204, ResetContent = 205, PartialContent = 206, MultiStatus = 207, AlreadyReported = 208, ImUsed = 226, MultipleChoices = 300, MovedPermanently = 301, Found = 302, SeeOther = 303, NotModified = 304, UseProxy = 305, Unused = 306, TemporaryRedirect = 307, PermanentRedirect = 308, BadRequest = 400, Unauthorized = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticationRequired = 407, RequestTimeout = 408, Conflict = 409, Gone = 410, LengthRequired = 411, PreconditionFailed = 412, PayloadTooLarge = 413, UriTooLong = 414, UnsupportedMediaType = 415, RangeNotSatisfiable = 416, ExpectationFailed = 417, ImATeapot = 418, MisdirectedRequest = 421, UnprocessableEntity = 422, Locked = 423, FailedDependency = 424, TooEarly = 425, UpgradeRequired = 426, PreconditionRequired = 428, TooManyRequests = 429, RequestHeaderFieldsTooLarge = 431, UnavailableForLegalReasons = 451, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504, HttpVersionNotSupported = 505, VariantAlsoNegotiates = 506, InsufficientStorage = 507, LoopDetected = 508, NotExtended = 510, NetworkAuthenticationRequired = 511 }
packages/common/http/src/response.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0003861167933791876, 0.00017469696467742324, 0.00015912129310891032, 0.00017084101273212582, 0.00003290194217697717 ]
{ "id": 3, "code_window": [ "\n", "/**\n", " * Ingest a literal text node from the AST into the given `ViewCompilation`.\n", " */\n", "function ingestContent(unit: ViewCompilationUnit, content: t.Content): void {\n", " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector);\n", " for (const attr of content.attributes) {\n", " ingestBinding(\n", " unit, op.xref, attr.name, o.literal(attr.value), e.BindingType.Attribute, null,\n", " SecurityContext.NONE, attr.sourceSpan, BindingFlags.TextValue);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector, content.sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/ingest.ts", "type": "replace", "edit_start_line_idx": 225 }
/** * @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.io/license */ import {checkVersion} from '../src/typescript_support'; describe('checkVersion', () => { const MIN_TS_VERSION = '2.7.2'; const MAX_TS_VERSION = '2.8.0'; const versionError = (version: string) => `The Angular Compiler requires TypeScript >=${ MIN_TS_VERSION} and <${MAX_TS_VERSION} but ${version} was found instead.`; it('should not throw when a supported TypeScript version is used', () => { expect(() => checkVersion('2.7.2', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); expect(() => checkVersion('2.7.9', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); }); it('should handle a TypeScript version < the minimum supported one', () => { expect(() => checkVersion('2.4.1', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.4.1')); expect(() => checkVersion('2.7.1', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.7.1')); }); it('should handle a TypeScript version > the maximum supported one', () => { expect(() => checkVersion('2.9.0', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.9.0')); expect(() => checkVersion('2.8.0', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.8.0')); }); it('should throw when an out-of-bounds pre-release version is used', () => { expect(() => checkVersion('2.7.0-beta', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.7.0-beta')); expect(() => checkVersion('2.8.5-rc.3', MIN_TS_VERSION, MAX_TS_VERSION)) .toThrowError(versionError('2.8.5-rc.3')); }); it('should not throw when a valid pre-release version is used', () => { expect(() => checkVersion('2.7.2-beta', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); expect(() => checkVersion('2.7.9-rc.8', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); }); });
packages/compiler-cli/test/typescript_support_spec.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0001755064440658316, 0.00017471794853918254, 0.00017373089212924242, 0.0001748710055835545, 5.943971359556599e-7 ]
{ "id": 3, "code_window": [ "\n", "/**\n", " * Ingest a literal text node from the AST into the given `ViewCompilation`.\n", " */\n", "function ingestContent(unit: ViewCompilationUnit, content: t.Content): void {\n", " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector);\n", " for (const attr of content.attributes) {\n", " ingestBinding(\n", " unit, op.xref, attr.name, o.literal(attr.value), e.BindingType.Attribute, null,\n", " SecurityContext.NONE, attr.sourceSpan, BindingFlags.TextValue);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const op = ir.createProjectionOp(unit.job.allocateXrefId(), content.selector, content.sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/ingest.ts", "type": "replace", "edit_start_line_idx": 225 }
/** * @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.io/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {ReactiveRadioButtonComp} from './reactive_radio_button_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [ReactiveRadioButtonComp], bootstrap: [ReactiveRadioButtonComp] }) export class AppModule { } export {ReactiveRadioButtonComp as AppComponent};
packages/examples/forms/ts/reactiveRadioButtons/module.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017404193931724876, 0.00017085687431972474, 0.00016511487774550915, 0.00017341379134450108, 0.000004068291673320346 ]
{ "id": 4, "code_window": [ " return call(Identifiers.projectionDef, def ? [def] : [], null);\n", "}\n", "\n", "export function projection(\n", " slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp {\n", " const args: o.Expression[] = [o.literal(slot)];\n", " if (projectionSlotIndex !== 0 || attributes.length > 0) {\n", " args.push(o.literal(projectionSlotIndex));\n", " if (attributes.length > 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " slot: number, projectionSlotIndex: number, attributes: string[],\n", " sourceSpan: ParseSourceSpan): ir.CreateOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 216 }
/** * @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.io/license */ import * as o from '../../../output/output_ast'; import {ParseSourceSpan} from '../../../parse_util'; import {Identifiers} from '../../../render3/r3_identifiers'; import * as ir from '../ir'; // This file contains helpers for generating calls to Ivy instructions. In particular, each // instruction type is represented as a function, which may select a specific instruction variant // depending on the exact arguments. export function element( slot: number, tag: string, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.element, slot, tag, constIndex, localRefIndex, sourceSpan); } export function elementStart( slot: number, tag: string, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementStart, slot, tag, constIndex, localRefIndex, sourceSpan); } function elementOrContainerBase( instruction: o.ExternalReference, slot: number, tag: string|null, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { const args: o.Expression[] = [o.literal(slot)]; if (tag !== null) { args.push(o.literal(tag)); } if (localRefIndex !== null) { args.push( o.literal(constIndex), // might be null, but that's okay. o.literal(localRefIndex), ); } else if (constIndex !== null) { args.push(o.literal(constIndex)); } return call(instruction, args, sourceSpan); } export function elementEnd(sourceSpan: ParseSourceSpan|null): ir.CreateOp { return call(Identifiers.elementEnd, [], sourceSpan); } export function elementContainerStart( slot: number, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementContainerStart, slot, /* tag */ null, constIndex, localRefIndex, sourceSpan); } export function elementContainer( slot: number, constIndex: number|null, localRefIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { return elementOrContainerBase( Identifiers.elementContainer, slot, /* tag */ null, constIndex, localRefIndex, sourceSpan); } export function elementContainerEnd(): ir.CreateOp { return call(Identifiers.elementContainerEnd, [], null); } export function template( slot: number, templateFnRef: o.Expression, decls: number, vars: number, tag: string|null, constIndex: number|null, sourceSpan: ParseSourceSpan): ir.CreateOp { const args = [o.literal(slot), templateFnRef, o.literal(decls), o.literal(vars)]; if (tag !== null || constIndex !== null) { args.push(o.literal(tag)); if (constIndex !== null) { args.push(o.literal(constIndex)); } } return call(Identifiers.templateCreate, args, sourceSpan); } export function disableBindings(): ir.CreateOp { return call(Identifiers.disableBindings, [], null); } export function enableBindings(): ir.CreateOp { return call(Identifiers.enableBindings, [], null); } export function listener( name: string, handlerFn: o.Expression, sourceSpan: ParseSourceSpan): ir.CreateOp { return call( Identifiers.listener, [ o.literal(name), handlerFn, ], sourceSpan); } export function syntheticHostListener( name: string, handlerFn: o.Expression, sourceSpan: ParseSourceSpan): ir.CreateOp { return call( Identifiers.syntheticHostListener, [ o.literal(name), handlerFn, ], sourceSpan); } export function pipe(slot: number, name: string): ir.CreateOp { return call( Identifiers.pipe, [ o.literal(slot), o.literal(name), ], null); } export function namespaceHTML(): ir.CreateOp { return call(Identifiers.namespaceHTML, [], null); } export function namespaceSVG(): ir.CreateOp { return call(Identifiers.namespaceSVG, [], null); } export function namespaceMath(): ir.CreateOp { return call(Identifiers.namespaceMathML, [], null); } export function advance(delta: number, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call( Identifiers.advance, [ o.literal(delta), ], sourceSpan); } export function reference(slot: number): o.Expression { return o.importExpr(Identifiers.reference).callFn([ o.literal(slot), ]); } export function nextContext(steps: number): o.Expression { return o.importExpr(Identifiers.nextContext).callFn(steps === 1 ? [] : [o.literal(steps)]); } export function getCurrentView(): o.Expression { return o.importExpr(Identifiers.getCurrentView).callFn([]); } export function restoreView(savedView: o.Expression): o.Expression { return o.importExpr(Identifiers.restoreView).callFn([ savedView, ]); } export function resetView(returnValue: o.Expression): o.Expression { return o.importExpr(Identifiers.resetView).callFn([ returnValue, ]); } export function text( slot: number, initialValue: string, sourceSpan: ParseSourceSpan|null): ir.CreateOp { const args: o.Expression[] = [o.literal(slot, null)]; if (initialValue !== '') { args.push(o.literal(initialValue)); } return call(Identifiers.text, args, sourceSpan); } export function defer( selfSlot: number, primarySlot: number, dependencyResolverFn: null, loadingSlot: number|null, placeholderSlot: number|null, errorSlot: number|null, loadingConfigIndex: number|null, placeholderConfigIndex: number|null, sourceSpan: ParseSourceSpan|null): ir.CreateOp { const args = [ o.literal(selfSlot), o.literal(primarySlot), o.literal(dependencyResolverFn), o.literal(loadingSlot), o.literal(placeholderSlot), o.literal(errorSlot), o.literal(loadingConfigIndex), o.literal(placeholderConfigIndex), ]; while (args[args.length - 1].value === null) { args.pop(); } return call(Identifiers.defer, args, sourceSpan); } export function deferOn(sourceSpan: ParseSourceSpan|null): ir.CreateOp { return call(Identifiers.deferOnIdle, [], sourceSpan); } export function projectionDef(def: o.Expression|null): ir.CreateOp { return call(Identifiers.projectionDef, def ? [def] : [], null); } export function projection( slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp { const args: o.Expression[] = [o.literal(slot)]; if (projectionSlotIndex !== 0 || attributes.length > 0) { args.push(o.literal(projectionSlotIndex)); if (attributes.length > 0) { args.push(o.literalArr(attributes.map(attr => o.literal(attr)))); } } return call(Identifiers.projection, args, null); } export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp { const args = [o.literal(slot), o.literal(constIndex)]; if (subTemplateIndex !== null) { args.push(o.literal(subTemplateIndex)); } return call(Identifiers.i18nStart, args, null); } export function repeaterCreate( slot: number, viewFnName: string, decls: number, vars: number, trackByFn: o.Expression, trackByUsesComponentInstance: boolean, emptyViewFnName: string|null, emptyDecls: number|null, emptyVars: number|null, sourceSpan: ParseSourceSpan|null): ir.CreateOp { let args = [ o.literal(slot), o.variable(viewFnName), o.literal(decls), o.literal(vars), trackByFn, ]; if (trackByUsesComponentInstance || emptyViewFnName !== null) { args.push(o.literal(trackByUsesComponentInstance)); if (emptyViewFnName !== null) { args.push(o.variable(emptyViewFnName)); args.push(o.literal(emptyDecls)); args.push(o.literal(emptyVars)); } } return call(Identifiers.repeaterCreate, args, sourceSpan); } export function repeater( metadataSlot: number, collection: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.repeater, [o.literal(metadataSlot), collection], sourceSpan); } export function i18n(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp { const args = [o.literal(slot), o.literal(constIndex)]; if (subTemplateIndex) { args.push(o.literal(subTemplateIndex)); } return call(Identifiers.i18n, args, null); } export function i18nEnd(): ir.CreateOp { return call(Identifiers.i18nEnd, [], null); } export function property( name: string, expression: o.Expression, sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const args = [o.literal(name), expression]; if (sanitizer !== null) { args.push(sanitizer); } return call(Identifiers.property, args, sourceSpan); } export function attribute( name: string, expression: o.Expression, sanitizer: o.Expression|null): ir.UpdateOp { const args = [o.literal(name), expression]; if (sanitizer !== null) { args.push(sanitizer); } return call(Identifiers.attribute, args, null); } export function styleProp( name: string, expression: o.Expression, unit: string|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const args = [o.literal(name), expression]; if (unit !== null) { args.push(o.literal(unit)); } return call(Identifiers.styleProp, args, sourceSpan); } export function classProp( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.classProp, [o.literal(name), expression], sourceSpan); } export function styleMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.styleMap, [expression], sourceSpan); } export function classMap(expression: o.Expression, sourceSpan: ParseSourceSpan): ir.UpdateOp { return call(Identifiers.classMap, [expression], sourceSpan); } const PIPE_BINDINGS: o.ExternalReference[] = [ Identifiers.pipeBind1, Identifiers.pipeBind2, Identifiers.pipeBind3, Identifiers.pipeBind4, ]; export function pipeBind(slot: number, varOffset: number, args: o.Expression[]): o.Expression { if (args.length < 1 || args.length > PIPE_BINDINGS.length) { throw new Error(`pipeBind() argument count out of bounds`); } const instruction = PIPE_BINDINGS[args.length - 1]; return o.importExpr(instruction).callFn([ o.literal(slot), o.literal(varOffset), ...args, ]); } export function pipeBindV(slot: number, varOffset: number, args: o.Expression): o.Expression { return o.importExpr(Identifiers.pipeBindV).callFn([ o.literal(slot), o.literal(varOffset), args, ]); } export function textInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { if (strings.length < 1 || expressions.length !== strings.length - 1) { throw new Error( `AssertionError: expected specific shape of args for strings/expressions in interpolation`); } const interpolationArgs: o.Expression[] = []; if (expressions.length === 1 && strings[0] === '' && strings[1] === '') { interpolationArgs.push(expressions[0]); } else { let idx: number; for (idx = 0; idx < expressions.length; idx++) { interpolationArgs.push(o.literal(strings[idx]), expressions[idx]); } // idx points at the last string. interpolationArgs.push(o.literal(strings[idx])); } return callVariadicInstruction(TEXT_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function i18nExp(expr: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.i18nExp, [expr], sourceSpan); } export function i18nApply(slot: number, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.i18nApply, [o.literal(slot)], sourceSpan); } export function propertyInterpolate( name: string, strings: string[], expressions: o.Expression[], sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs = []; if (sanitizer !== null) { extraArgs.push(sanitizer); } return callVariadicInstruction( PROPERTY_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function attributeInterpolate( name: string, strings: string[], expressions: o.Expression[], sanitizer: o.Expression|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs = []; if (sanitizer !== null) { extraArgs.push(sanitizer); } return callVariadicInstruction( ATTRIBUTE_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function stylePropInterpolate( name: string, strings: string[], expressions: o.Expression[], unit: string|null, sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); const extraArgs: o.Expression[] = []; if (unit !== null) { extraArgs.push(o.literal(unit)); } return callVariadicInstruction( STYLE_PROP_INTERPOLATE_CONFIG, [o.literal(name)], interpolationArgs, extraArgs, sourceSpan); } export function styleMapInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); return callVariadicInstruction( STYLE_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function classMapInterpolate( strings: string[], expressions: o.Expression[], sourceSpan: ParseSourceSpan): ir.UpdateOp { const interpolationArgs = collateInterpolationArgs(strings, expressions); return callVariadicInstruction( CLASS_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan); } export function hostProperty( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.hostProperty, [o.literal(name), expression], sourceSpan); } export function syntheticHostProperty( name: string, expression: o.Expression, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return call(Identifiers.syntheticHostProperty, [o.literal(name), expression], sourceSpan); } export function pureFunction( varOffset: number, fn: o.Expression, args: o.Expression[]): o.Expression { return callVariadicInstructionExpr( PURE_FUNCTION_CONFIG, [ o.literal(varOffset), fn, ], args, [], null, ); } /** * Collates the string an expression arguments for an interpolation instruction. */ function collateInterpolationArgs(strings: string[], expressions: o.Expression[]): o.Expression[] { if (strings.length < 1 || expressions.length !== strings.length - 1) { throw new Error( `AssertionError: expected specific shape of args for strings/expressions in interpolation`); } const interpolationArgs: o.Expression[] = []; if (expressions.length === 1 && strings[0] === '' && strings[1] === '') { interpolationArgs.push(expressions[0]); } else { let idx: number; for (idx = 0; idx < expressions.length; idx++) { interpolationArgs.push(o.literal(strings[idx]), expressions[idx]); } // idx points at the last string. interpolationArgs.push(o.literal(strings[idx])); } return interpolationArgs; } function call<OpT extends ir.CreateOp|ir.UpdateOp>( instruction: o.ExternalReference, args: o.Expression[], sourceSpan: ParseSourceSpan|null): OpT { const expr = o.importExpr(instruction).callFn(args, sourceSpan); return ir.createStatementOp(new o.ExpressionStatement(expr, sourceSpan)) as OpT; } export function conditional( slot: number, condition: o.Expression, contextValue: o.Expression|null, sourceSpan: ParseSourceSpan|null): ir.UpdateOp { const args = [o.literal(slot), condition]; if (contextValue !== null) { args.push(contextValue); } return call(Identifiers.conditional, args, sourceSpan); } /** * Describes a specific flavor of instruction used to represent variadic instructions, which * have some number of variants for specific argument counts. */ interface VariadicInstructionConfig { constant: o.ExternalReference[]; variable: o.ExternalReference|null; mapping: (argCount: number) => number; } /** * `InterpolationConfig` for the `textInterpolate` instruction. */ const TEXT_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.textInterpolate, Identifiers.textInterpolate1, Identifiers.textInterpolate2, Identifiers.textInterpolate3, Identifiers.textInterpolate4, Identifiers.textInterpolate5, Identifiers.textInterpolate6, Identifiers.textInterpolate7, Identifiers.textInterpolate8, ], variable: Identifiers.textInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `propertyInterpolate` instruction. */ const PROPERTY_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.propertyInterpolate, Identifiers.propertyInterpolate1, Identifiers.propertyInterpolate2, Identifiers.propertyInterpolate3, Identifiers.propertyInterpolate4, Identifiers.propertyInterpolate5, Identifiers.propertyInterpolate6, Identifiers.propertyInterpolate7, Identifiers.propertyInterpolate8, ], variable: Identifiers.propertyInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `stylePropInterpolate` instruction. */ const STYLE_PROP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.styleProp, Identifiers.stylePropInterpolate1, Identifiers.stylePropInterpolate2, Identifiers.stylePropInterpolate3, Identifiers.stylePropInterpolate4, Identifiers.stylePropInterpolate5, Identifiers.stylePropInterpolate6, Identifiers.stylePropInterpolate7, Identifiers.stylePropInterpolate8, ], variable: Identifiers.stylePropInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `attributeInterpolate` instruction. */ const ATTRIBUTE_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.attribute, Identifiers.attributeInterpolate1, Identifiers.attributeInterpolate2, Identifiers.attributeInterpolate3, Identifiers.attributeInterpolate4, Identifiers.attributeInterpolate5, Identifiers.attributeInterpolate6, Identifiers.attributeInterpolate7, Identifiers.attributeInterpolate8, ], variable: Identifiers.attributeInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `styleMapInterpolate` instruction. */ const STYLE_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.styleMap, Identifiers.styleMapInterpolate1, Identifiers.styleMapInterpolate2, Identifiers.styleMapInterpolate3, Identifiers.styleMapInterpolate4, Identifiers.styleMapInterpolate5, Identifiers.styleMapInterpolate6, Identifiers.styleMapInterpolate7, Identifiers.styleMapInterpolate8, ], variable: Identifiers.styleMapInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; /** * `InterpolationConfig` for the `classMapInterpolate` instruction. */ const CLASS_MAP_INTERPOLATE_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.classMap, Identifiers.classMapInterpolate1, Identifiers.classMapInterpolate2, Identifiers.classMapInterpolate3, Identifiers.classMapInterpolate4, Identifiers.classMapInterpolate5, Identifiers.classMapInterpolate6, Identifiers.classMapInterpolate7, Identifiers.classMapInterpolate8, ], variable: Identifiers.classMapInterpolateV, mapping: n => { if (n % 2 === 0) { throw new Error(`Expected odd number of arguments`); } return (n - 1) / 2; }, }; const PURE_FUNCTION_CONFIG: VariadicInstructionConfig = { constant: [ Identifiers.pureFunction0, Identifiers.pureFunction1, Identifiers.pureFunction2, Identifiers.pureFunction3, Identifiers.pureFunction4, Identifiers.pureFunction5, Identifiers.pureFunction6, Identifiers.pureFunction7, Identifiers.pureFunction8, ], variable: Identifiers.pureFunctionV, mapping: n => n, }; function callVariadicInstructionExpr( config: VariadicInstructionConfig, baseArgs: o.Expression[], interpolationArgs: o.Expression[], extraArgs: o.Expression[], sourceSpan: ParseSourceSpan|null): o.Expression { const n = config.mapping(interpolationArgs.length); if (n < config.constant.length) { // Constant calling pattern. return o.importExpr(config.constant[n]) .callFn([...baseArgs, ...interpolationArgs, ...extraArgs], sourceSpan); } else if (config.variable !== null) { // Variable calling pattern. return o.importExpr(config.variable) .callFn([...baseArgs, o.literalArr(interpolationArgs), ...extraArgs], sourceSpan); } else { throw new Error(`AssertionError: unable to call variadic function`); } } function callVariadicInstruction( config: VariadicInstructionConfig, baseArgs: o.Expression[], interpolationArgs: o.Expression[], extraArgs: o.Expression[], sourceSpan: ParseSourceSpan|null): ir.UpdateOp { return ir.createStatementOp( callVariadicInstructionExpr(config, baseArgs, interpolationArgs, extraArgs, sourceSpan) .toStmt()); }
packages/compiler/src/template/pipeline/src/instruction.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.9981194138526917, 0.37351250648498535, 0.00016754343232605606, 0.018122395500540733, 0.4508473575115204 ]
{ "id": 4, "code_window": [ " return call(Identifiers.projectionDef, def ? [def] : [], null);\n", "}\n", "\n", "export function projection(\n", " slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp {\n", " const args: o.Expression[] = [o.literal(slot)];\n", " if (projectionSlotIndex !== 0 || attributes.length > 0) {\n", " args.push(o.literal(projectionSlotIndex));\n", " if (attributes.length > 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " slot: number, projectionSlotIndex: number, attributes: string[],\n", " sourceSpan: ParseSourceSpan): ir.CreateOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 216 }
import { NgIf } from '@angular/common'; import { Component } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { NameEditorComponent } from './name-editor/name-editor.component'; import { ProfileEditorComponent } from './profile-editor/profile-editor.component'; export type EditorType = 'name' | 'profile'; @Component({ standalone: true, selector: 'app-root', template: ` <h1>Reactive Forms</h1> <nav> <button type="button" (click)="toggleEditor('name')">Name Editor</button> <button type="button" (click)="toggleEditor('profile')"> Profile Editor </button> </nav> <app-name-editor *ngIf="showNameEditor"></app-name-editor> <app-profile-editor *ngIf="showProfileEditor"></app-profile-editor> `, styles: [ ` nav button { padding: 1rem; font-size: inherit; } `, ], imports: [ NameEditorComponent, ProfileEditorComponent, NgIf, ReactiveFormsModule, ], }) export class AppComponent { editor: EditorType = 'name'; get showNameEditor() { return this.editor === 'name'; } get showProfileEditor() { return this.editor === 'profile'; } toggleEditor(type: EditorType) { this.editor = type; } }
aio/content/examples/reactive-forms/src/app/app.component.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017433475295547396, 0.0001707039336906746, 0.000168060083524324, 0.00017022609245032072, 0.0000020233776467648568 ]
{ "id": 4, "code_window": [ " return call(Identifiers.projectionDef, def ? [def] : [], null);\n", "}\n", "\n", "export function projection(\n", " slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp {\n", " const args: o.Expression[] = [o.literal(slot)];\n", " if (projectionSlotIndex !== 0 || attributes.length > 0) {\n", " args.push(o.literal(projectionSlotIndex));\n", " if (attributes.length > 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " slot: number, projectionSlotIndex: number, attributes: string[],\n", " sourceSpan: ParseSourceSpan): ir.CreateOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 216 }
/** * @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.io/license */ import {ASTWithSource, Binary, BindingPipe, Conditional, Interpolation, PropertyRead, TmplAstBoundAttribute, TmplAstBoundText, TmplAstElement, TmplAstNode, TmplAstReference, TmplAstTemplate} from '@angular/compiler'; import {AST, LiteralArray, LiteralMap} from '@angular/compiler/src/compiler'; import ts from 'typescript'; import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {ClassDeclaration} from '../../reflection'; import {DirectiveSymbol, DomBindingSymbol, ElementSymbol, ExpressionSymbol, InputBindingSymbol, OutputBindingSymbol, PipeSymbol, ReferenceSymbol, Symbol, SymbolKind, TemplateSymbol, TemplateTypeChecker, TypeCheckingConfig, VariableSymbol} from '../api'; import {getClass, ngForDeclaration, ngForTypeCheckTarget, setup as baseTestSetup, TypeCheckingTarget} from '../testing'; runInEachFileSystem(() => { describe('TemplateTypeChecker.getSymbolOfNode', () => { it('should get a symbol for regular attributes', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div id="helloWorld"></div>`; const {templateTypeChecker, program} = setup( [ { fileName, templates: {'Cmp': templateString}, source: `export class Cmp {}`, }, ], ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); describe('should get a symbol for text attributes corresponding with a directive input', () => { let fileName: AbsoluteFsPath; let targets: TypeCheckingTarget[]; beforeEach(() => { fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div name="helloWorld"></div>`; targets = [ { fileName, templates: {'Cmp': templateString} as {[key: string]: string}, declarations: [{ name: 'NameDiv', selector: 'div[name]', file: dirFile, type: 'directive' as const, inputs: {name: 'name'}, }] }, { fileName: dirFile, source: `export class NameDiv {name!: string;}`, templates: {}, } ]; }); it('checkTypeOfAttributes = true', () => { const {templateTypeChecker, program} = setup(targets, {checkTypeOfAttributes: true}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertInputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('name'); // Ensure we can go back to the original location using the shim location const mapping = templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.bindings[0].tcbLocation)!; expect(mapping.span.toString()).toEqual('name'); }); it('checkTypeOfAttributes = false', () => { const {templateTypeChecker, program} = setup(targets, {checkTypeOfAttributes: false}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertInputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('name'); }); }); describe('templates', () => { describe('ng-templates', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let templateNode: TmplAstTemplate; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <ng-template dir #ref0 #ref1="dir" let-contextFoo="bar"> <div [input0]="contextFoo" [input1]="ref0" [input2]="ref1"></div> </ng-template>`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { }`, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', exportAs: ['dir'], }] }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, } ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); templateNode = getAstTemplates(templateTypeChecker, cmp)[0]; }); it('should get symbol for variables at the declaration', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.variables[0], cmp)!; assertVariableSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toEqual('any'); expect(symbol.declaration.name).toEqual('contextFoo'); }); it('should get symbol for variables when used', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[0].value, cmp)!; assertVariableSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toEqual('any'); expect(symbol.declaration.name).toEqual('contextFoo'); // Ensure we can map the shim locations back to the template const initializerMapping = templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.initializerLocation)!; expect(initializerMapping.span.toString()).toEqual('bar'); const localVarMapping = templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.localVarLocation)!; expect(localVarMapping.span.toString()).toEqual('contextFoo'); }); it('should get a symbol for local ref which refers to a directive', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.references[1], cmp)!; assertReferenceSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol)).toEqual('TestDir'); assertDirectiveReference(symbol); }); it('should get a symbol for usage local ref which refers to a directive', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[2].value, cmp)!; assertReferenceSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol)).toEqual('TestDir'); assertDirectiveReference(symbol); // Ensure we can map the var shim location back to the template const localVarMapping = templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.referenceVarLocation); expect(localVarMapping!.span.toString()).toEqual('ref1'); }); function assertDirectiveReference(symbol: ReferenceSymbol) { expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('TestDir'); expect((symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect(symbol.declaration.name).toEqual('ref1'); } it('should get a symbol for local ref which refers to the template', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.references[0], cmp)!; assertReferenceSymbol(symbol); assertTemplateReference(symbol); }); it('should get a symbol for usage local ref which refers to a template', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[1].value, cmp)!; assertReferenceSymbol(symbol); assertTemplateReference(symbol); }); function assertTemplateReference(symbol: ReferenceSymbol) { expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('TemplateRef<any>'); expect((symbol.target as TmplAstTemplate).tagName).toEqual('ng-template'); expect(symbol.declaration.name).toEqual('ref0'); } it('should get symbol for the template itself', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode, cmp)!; assertTemplateSymbol(symbol); expect(symbol.directives.length).toBe(1); assertDirectiveSymbol(symbol.directives[0]); expect(symbol.directives[0].tsSymbol.getName()).toBe('TestDir'); }); }); describe('structural directives', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let templateNode: TmplAstTemplate; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <div *ngFor="let user of users; let i = index;" dir> {{user.name}} {{user.streetNumber}} <div [tabIndex]="i"></div> </div>`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export interface User { name: string; streetNumber: number; } export class Cmp { users: User[]; } `, declarations: [ ngForDeclaration(), { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {name: 'name'} }, ], }, ngForTypeCheckTarget(), { fileName: dirFile, source: `export class TestDir {name:string}`, templates: {}, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); templateNode = getAstTemplates(templateTypeChecker, cmp)[0]; }); it('should retrieve a symbol for a directive on a microsyntax template', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode, cmp); const testDir = symbol?.directives.find(dir => dir.selector === '[dir]'); expect(testDir).toBeDefined(); expect(program.getTypeChecker().symbolToString(testDir!.tsSymbol)).toEqual('TestDir'); }); it('should retrieve a symbol for an expression inside structural binding', () => { const ngForOfBinding = templateNode.templateAttrs.find(a => a.name === 'ngForOf')! as TmplAstBoundAttribute; const symbol = templateTypeChecker.getSymbolOfNode(ngForOfBinding.value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('users'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Array<User>'); }); it('should retrieve a symbol for property reads of implicit variable inside structural binding', () => { const boundText = (templateNode.children[0] as TmplAstElement).children[0] as TmplAstBoundText; const interpolation = (boundText.value as ASTWithSource).ast as Interpolation; const namePropRead = interpolation.expressions[0] as PropertyRead; const streetNumberPropRead = interpolation.expressions[1] as PropertyRead; const nameSymbol = templateTypeChecker.getSymbolOfNode(namePropRead, cmp)!; assertExpressionSymbol(nameSymbol); expect(program.getTypeChecker().symbolToString(nameSymbol.tsSymbol!)).toEqual('name'); expect(program.getTypeChecker().typeToString(nameSymbol.tsType)).toEqual('string'); const streetSymbol = templateTypeChecker.getSymbolOfNode(streetNumberPropRead, cmp)!; assertExpressionSymbol(streetSymbol); expect(program.getTypeChecker().symbolToString(streetSymbol.tsSymbol!)) .toEqual('streetNumber'); expect(program.getTypeChecker().typeToString(streetSymbol.tsType)).toEqual('number'); const userSymbol = templateTypeChecker.getSymbolOfNode(namePropRead.receiver, cmp)!; expectUserSymbol(userSymbol); }); it('finds symbols for variables', () => { const userVar = templateNode.variables.find(v => v.name === 'user')!; const userSymbol = templateTypeChecker.getSymbolOfNode(userVar, cmp)!; expectUserSymbol(userSymbol); const iVar = templateNode.variables.find(v => v.name === 'i')!; const iSymbol = templateTypeChecker.getSymbolOfNode(iVar, cmp)!; expectIndexSymbol(iSymbol); }); it('finds symbol when using a template variable', () => { const innerElementNodes = onlyAstElements((templateNode.children[0] as TmplAstElement).children); const indexSymbol = templateTypeChecker.getSymbolOfNode(innerElementNodes[0].inputs[0].value, cmp)!; expectIndexSymbol(indexSymbol); }); function expectUserSymbol(userSymbol: Symbol) { assertVariableSymbol(userSymbol); expect(userSymbol.tsSymbol!.escapedName).toContain('$implicit'); expect(userSymbol.tsSymbol!.declarations![0].parent!.getText()) .toContain('NgForOfContext'); expect(program.getTypeChecker().typeToString(userSymbol.tsType!)).toEqual('User'); expect((userSymbol).declaration).toEqual(templateNode.variables[0]); } function expectIndexSymbol(indexSymbol: Symbol) { assertVariableSymbol(indexSymbol); expect(indexSymbol.tsSymbol!.escapedName).toContain('index'); expect(indexSymbol.tsSymbol!.declarations![0].parent!.getText()) .toContain('NgForOfContext'); expect(program.getTypeChecker().typeToString(indexSymbol.tsType!)).toEqual('number'); expect((indexSymbol).declaration).toEqual(templateNode.variables[1]); } }); }); describe('for expressions', () => { it('should get a symbol for a component property used in an input binding', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="helloWorld"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: `export class Cmp {helloWorld?: boolean;}`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const symbol = templateTypeChecker.getSymbolOfNode(nodes[0].inputs[0].value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('helloWorld'); expect(program.getTypeChecker().typeToString(symbol.tsType)) .toEqual('false | true | undefined'); }); it('should get a symbol for properties several levels deep', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="person.address.street"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` interface Address { street: string; } interface Person { address: Address; } export class Cmp {person?: Person;} `, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const inputNode = nodes[0].inputs[0].value as ASTWithSource; const symbol = templateTypeChecker.getSymbolOfNode(inputNode, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('street'); expect((symbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name!.getText()) .toEqual('Address'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('string'); const personSymbol = templateTypeChecker.getSymbolOfNode( ((inputNode.ast as PropertyRead).receiver as PropertyRead).receiver, cmp)!; assertExpressionSymbol(personSymbol); expect(program.getTypeChecker().symbolToString(personSymbol.tsSymbol!)).toEqual('person'); expect(program.getTypeChecker().typeToString(personSymbol.tsType)) .toEqual('Person | undefined'); }); describe('should get symbols for conditionals', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let program: ts.Program; let templateString: string; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); templateString = ` <div [inputA]="person?.address?.street"></div> <div [inputA]="person ? person.address : noPersonError"></div> <div [inputA]="person?.speak()"></div> <div [inputA]="person?.cars?.[1].engine"></div> `; const testValues = setup( [ { fileName, templates: {'Cmp': templateString}, source: ` interface Address { street: string; } interface Car { engine: string; } interface Person { address: Address; speak(): string; cars?: Car[]; } export class Cmp {person?: Person; noPersonError = 'no person'} `, }, ], ); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(program, fileName); cmp = getClass(sf, 'Cmp'); }); it('safe property reads', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safePropertyRead = nodes[0].inputs[0].value as ASTWithSource; const propReadSymbol = templateTypeChecker.getSymbolOfNode(safePropertyRead, cmp)!; assertExpressionSymbol(propReadSymbol); expect(program.getTypeChecker().symbolToString(propReadSymbol.tsSymbol!)) .toEqual('street'); expect((propReadSymbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name!.getText()) .toEqual('Address'); expect(program.getTypeChecker().typeToString(propReadSymbol.tsType)) .toEqual('string | undefined'); }); it('safe method calls', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safeMethodCall = nodes[2].inputs[0].value as ASTWithSource; const methodCallSymbol = templateTypeChecker.getSymbolOfNode(safeMethodCall, cmp)!; assertExpressionSymbol(methodCallSymbol); // Note that the symbol returned is for the return value of the safe method call. expect(methodCallSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(methodCallSymbol.tsType)) .toBe('string | undefined'); }); it('safe keyed reads', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safeKeyedRead = nodes[3].inputs[0].value as ASTWithSource; const keyedReadSymbol = templateTypeChecker.getSymbolOfNode(safeKeyedRead, cmp)!; assertExpressionSymbol(keyedReadSymbol); expect(program.getTypeChecker().symbolToString(keyedReadSymbol.tsSymbol!)) .toEqual('engine'); expect((keyedReadSymbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name!.getText()) .toEqual('Car'); expect(program.getTypeChecker().typeToString(keyedReadSymbol.tsType)).toEqual('string'); }); it('ternary expressions', () => { const nodes = getAstElements(templateTypeChecker, cmp); const ternary = (nodes[1].inputs[0].value as ASTWithSource).ast as Conditional; const ternarySymbol = templateTypeChecker.getSymbolOfNode(ternary, cmp)!; assertExpressionSymbol(ternarySymbol); expect(ternarySymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(ternarySymbol.tsType)) .toEqual('string | Address'); const addrSymbol = templateTypeChecker.getSymbolOfNode(ternary.trueExp, cmp)!; assertExpressionSymbol(addrSymbol); expect(program.getTypeChecker().symbolToString(addrSymbol.tsSymbol!)).toEqual('address'); expect(program.getTypeChecker().typeToString(addrSymbol.tsType)).toEqual('Address'); const noPersonSymbol = templateTypeChecker.getSymbolOfNode(ternary.falseExp, cmp)!; assertExpressionSymbol(noPersonSymbol); expect(program.getTypeChecker().symbolToString(noPersonSymbol.tsSymbol!)) .toEqual('noPersonError'); expect(program.getTypeChecker().typeToString(noPersonSymbol.tsType)).toEqual('string'); }); }); it('should get a symbol for function on a component used in an input binding', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="helloWorld"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { helloWorld() { return ''; } }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const symbol = templateTypeChecker.getSymbolOfNode(nodes[0].inputs[0].value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('helloWorld'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('() => string'); }); it('should get a symbol for binary expressions', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="a + b"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { a!: string; b!: number; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const valueAssignment = nodes[0].inputs[0].value as ASTWithSource; const wholeExprSymbol = templateTypeChecker.getSymbolOfNode(valueAssignment, cmp)!; assertExpressionSymbol(wholeExprSymbol); expect(wholeExprSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(wholeExprSymbol.tsType)).toEqual('string'); const aSymbol = templateTypeChecker.getSymbolOfNode((valueAssignment.ast as Binary).left, cmp)!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toBe('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode((valueAssignment.ast as Binary).right, cmp)!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toBe('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); }); describe('local reference of an Element', () => { it('checkTypeOfDomReferences = true', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: { 'Cmp': ` <input #myRef> <div [input]="myRef"></div>` }, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const refSymbol = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp)!; assertReferenceSymbol(refSymbol); expect((refSymbol.target as TmplAstElement).name).toEqual('input'); expect((refSymbol.declaration as TmplAstReference).name).toEqual('myRef'); const myRefUsage = templateTypeChecker.getSymbolOfNode(nodes[1].inputs[0].value, cmp)!; assertReferenceSymbol(myRefUsage); expect((myRefUsage.target as TmplAstElement).name).toEqual('input'); expect((myRefUsage.declaration as TmplAstReference).name).toEqual('myRef'); }); it('checkTypeOfDomReferences = false', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup( [ { fileName, templates: { 'Cmp': ` <input #myRef> <div [input]="myRef"></div>` }, }, ], {checkTypeOfDomReferences: false}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const refSymbol = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp); // Our desired behavior here is to honor the user's compiler settings and not produce a // symbol for the reference when `checkTypeOfDomReferences` is false. expect(refSymbol).toBeNull(); }); }); it('should get symbols for references which refer to directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <div dir #myDir1="dir"></div> <div dir #myDir2="dir"></div> <div [inputA]="myDir1.dirValue" [inputB]="myDir1"></div> <div [inputA]="myDir2.dirValue" [inputB]="myDir2"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', exportAs: ['dir'], }] }, { fileName: dirFile, source: `export class TestDir { dirValue = 'helloWorld' }`, templates: {} } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const ref1Declaration = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp)!; assertReferenceSymbol(ref1Declaration); expect((ref1Declaration.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((ref1Declaration.declaration as TmplAstReference).name).toEqual('myDir1'); const ref2Declaration = templateTypeChecker.getSymbolOfNode(nodes[1].references[0], cmp)!; assertReferenceSymbol(ref2Declaration); expect((ref2Declaration.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((ref2Declaration.declaration as TmplAstReference).name).toEqual('myDir2'); const dirValueSymbol = templateTypeChecker.getSymbolOfNode(nodes[2].inputs[0].value, cmp)!; assertExpressionSymbol(dirValueSymbol); expect(program.getTypeChecker().symbolToString(dirValueSymbol.tsSymbol!)).toBe('dirValue'); expect(program.getTypeChecker().typeToString(dirValueSymbol.tsType)).toEqual('string'); const dir1Symbol = templateTypeChecker.getSymbolOfNode(nodes[2].inputs[1].value, cmp)!; assertReferenceSymbol(dir1Symbol); expect((dir1Symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((dir1Symbol.declaration as TmplAstReference).name).toEqual('myDir1'); const dir2Symbol = templateTypeChecker.getSymbolOfNode(nodes[3].inputs[1].value, cmp)!; assertReferenceSymbol(dir2Symbol); expect((dir2Symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((dir2Symbol.declaration as TmplAstReference).name).toEqual('myDir2'); }); describe('literals', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let interpolation: Interpolation; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const templateString = ` {{ [1, 2, 3] }} {{ { hello: "world" } }} {{ { foo } }}`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` type Foo {name: string;} export class Cmp {foo: Foo;} `, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); interpolation = ((templateTypeChecker.getTemplate(cmp)![0] as TmplAstBoundText).value as ASTWithSource) .ast as Interpolation; }); it('literal array', () => { const literalArray = interpolation.expressions[0] as LiteralArray; const symbol = templateTypeChecker.getSymbolOfNode(literalArray, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('Array'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Array<number>'); }); it('literal map', () => { const literalMap = interpolation.expressions[1] as LiteralMap; const symbol = templateTypeChecker.getSymbolOfNode(literalMap, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('__object'); expect(program.getTypeChecker().typeToString(symbol.tsType)) .toEqual('{ hello: string; }'); }); it('literal map shorthand property', () => { const shorthandProp = (interpolation.expressions[2] as LiteralMap).values[0] as PropertyRead; const symbol = templateTypeChecker.getSymbolOfNode(shorthandProp, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('foo'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Foo'); }); }); describe('pipes', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let binding: BindingPipe; let program: ts.Program; function setupPipesTest(checkTypeOfPipes = true) { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="a | test:b:c"></div>`; const testValues = setup( [ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { a: string; b: number; c: boolean } export class TestPipe { transform(value: string, repeat: number, commaSeparate: boolean): string[] { } } `, declarations: [{ type: 'pipe', name: 'TestPipe', pipeName: 'test', }], }, ], {checkTypeOfPipes}); program = testValues.program; templateTypeChecker = testValues.templateTypeChecker; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); binding = (getAstElements(templateTypeChecker, cmp)[0].inputs[0].value as ASTWithSource).ast as BindingPipe; } for (const checkTypeOfPipes of [true, false]) { it(`should get symbol for pipe, checkTypeOfPipes: ${checkTypeOfPipes}`, () => { setupPipesTest(checkTypeOfPipes); const pipeSymbol = templateTypeChecker.getSymbolOfNode(binding, cmp)!; assertPipeSymbol(pipeSymbol); expect(program.getTypeChecker().symbolToString(pipeSymbol.tsSymbol!)) .toEqual('transform'); expect(program.getTypeChecker().symbolToString(pipeSymbol.classSymbol.tsSymbol)) .toEqual('TestPipe'); expect(program.getTypeChecker().typeToString(pipeSymbol.tsType!)) .toEqual('(value: string, repeat: number, commaSeparate: boolean) => string[]'); }); } it('should get symbols for pipe expression and args', () => { setupPipesTest(false); const aSymbol = templateTypeChecker.getSymbolOfNode(binding.exp, cmp)!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toEqual('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode(binding.args[0] as AST, cmp)!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toEqual('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); const cSymbol = templateTypeChecker.getSymbolOfNode(binding.args[1] as AST, cmp)!; assertExpressionSymbol(cSymbol); expect(program.getTypeChecker().symbolToString(cSymbol.tsSymbol!)).toEqual('c'); expect(program.getTypeChecker().typeToString(cSymbol.tsType)).toEqual('boolean'); }); for (const checkTypeOfPipes of [true, false]) { describe(`checkTypeOfPipes: ${checkTypeOfPipes}`, () => { // Because the args are property reads, we still need information about them. it(`should get symbols for pipe expression and args`, () => { setupPipesTest(checkTypeOfPipes); const aSymbol = templateTypeChecker.getSymbolOfNode(binding.exp, cmp)!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toEqual('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode(binding.args[0] as AST, cmp)!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toEqual('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); const cSymbol = templateTypeChecker.getSymbolOfNode(binding.args[1] as AST, cmp)!; assertExpressionSymbol(cSymbol); expect(program.getTypeChecker().symbolToString(cSymbol.tsSymbol!)).toEqual('c'); expect(program.getTypeChecker().typeToString(cSymbol.tsType)).toEqual('boolean'); }); }); } }); it('should get a symbol for PropertyWrite expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': '<div (output)="lastEvent = $event"></div>'}, source: `export class Cmp { lastEvent: any; }` }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const writeSymbol = templateTypeChecker.getSymbolOfNode(node.outputs[0].handler, cmp)!; assertExpressionSymbol(writeSymbol); // Note that the symbol returned is for the RHS of the PropertyWrite. The AST // does not support specific designation for the RHS so we assume that's what // is wanted in this case. We don't support retrieving a symbol for the whole // expression and if you want to get a symbol for the '$event', you can // use the `value` AST of the `PropertyWrite`. expect(program.getTypeChecker().symbolToString(writeSymbol.tsSymbol!)).toEqual('lastEvent'); expect(program.getTypeChecker().typeToString(writeSymbol.tsType)).toEqual('any'); }); it('should get a symbol for Call expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': '<div [input]="toString(123)"></div>'}, source: `export class Cmp { toString(v: any): string { return String(v); } }` }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const callSymbol = templateTypeChecker.getSymbolOfNode(node.inputs[0].value, cmp)!; assertExpressionSymbol(callSymbol); // Note that the symbol returned is for the return value of the Call. expect(callSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(callSymbol.tsType)).toBe('string'); }); it('should get a symbol for SafeCall expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': '<div [input]="toString?.(123)"></div>'}, source: `export class Cmp { toString?: (value: number) => string; }` }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const safeCallSymbol = templateTypeChecker.getSymbolOfNode(node.inputs[0].value, cmp)!; assertExpressionSymbol(safeCallSymbol); // Note that the symbol returned is for the return value of the SafeCall. expect(safeCallSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(safeCallSymbol.tsType)) .toBe('string | undefined'); }); }); describe('input bindings', () => { it('can get a symbol for empty binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [inputA]=""></div>`}, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }] }, { fileName: dirFile, source: `export class TestDir {inputA?: string; }`, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(aSymbol); expect((aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('inputA'); }); it('can retrieve a symbol for an input binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'" [inputBRenamed]="'my inputB'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA', inputB: 'inputBRenamed'}, }] }, { fileName: dirFile, source: `export class TestDir {inputA!: string; inputB!: string}`, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(aSymbol); expect((aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('inputA'); const inputBbinding = (nodes[0] as TmplAstElement).inputs[1]; const bSymbol = templateTypeChecker.getSymbolOfNode(inputBbinding, cmp)!; assertInputBindingSymbol(bSymbol); expect((bSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('inputB'); }); it('does not retrieve a symbol for an input when undeclared', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }] }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; expect(aSymbol).toBeNull(); }); it('can retrieve a symbol for an input of structural directive', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div *ngFor="let user of users"></div>`; const {program, templateTypeChecker} = setup([ {fileName, templates: {'Cmp': templateString}, declarations: [ngForDeclaration()]}, ngForTypeCheckTarget(), ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const ngForOfBinding = (nodes[0] as TmplAstTemplate).templateAttrs.find(a => a.name === 'ngForOf')! as TmplAstBoundAttribute; const symbol = templateTypeChecker.getSymbolOfNode(ngForOfBinding, cmp)!; assertInputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('ngForOf'); }); it('returns dom binding input binds only to the dom element', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [name]="'my input'"></div>`; const {program, templateTypeChecker} = setup([ {fileName, templates: {'Cmp': templateString}, declarations: []}, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const binding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(binding, cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); it('returns dom binding when directive members do not match the input', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [{ name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {}, }] }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); it('can match binding when there are two directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir otherDir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, { name: 'OtherDir', selector: '[otherDir]', file: dirFile, type: 'directive', inputs: {}, } ] }, { fileName: dirFile, source: ` export class TestDir {inputA!: string;} export class OtherDir {} `, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('inputA'); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name?.text) .toEqual('TestDir'); }); it('returns the first field match when directive maps same input to two fields', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [inputA]="'my input A'"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA', otherInputA: 'inputA'}, }, ] }, { fileName: dirFile, source: ` export class TestDir {inputA!: string; otherInputA!: string;} `, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('otherInputA'); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name?.text) .toEqual('TestDir'); }); it('returns the all inputs when two directives have the same input', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir otherDir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, { name: 'OtherDir', selector: '[otherDir]', file: dirFile, type: 'directive', inputs: {otherDirInputA: 'inputA'}, } ] }, { fileName: dirFile, source: ` export class TestDir {inputA!: string;} export class OtherDir {otherDirInputA!: string;} `, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect(new Set(symbol.bindings.map( b => (b.tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText()))) .toEqual(new Set(['inputA', 'otherDirInputA'])); expect( new Set(symbol.bindings.map( b => (b.tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name?.text))) .toEqual(new Set(['TestDir', 'OtherDir'])); }); }); describe('output bindings', () => { it('should find symbol for output binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir (outputA)="handle($event)" (renamedOutputB)="handle($event)"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA', outputB: 'renamedOutputB'}, }, ] }, { fileName: dirFile, source: ` export class TestDir {outputA!: EventEmitter<string>; outputB!: EventEmitter<string>} `, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(aSymbol); expect((aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('outputA'); const outputBBinding = (nodes[0] as TmplAstElement).outputs[1]; const bSymbol = templateTypeChecker.getSymbolOfNode(outputBBinding, cmp)!; assertOutputBindingSymbol(bSymbol); expect((bSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('outputB'); }); it('should find symbol for output binding when there are multiple directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir otherdir (outputA)="handle($event)"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA'}, }, { name: 'OtherDir', selector: '[otherdir]', file: dirFile, type: 'directive', outputs: {unusedOutput: 'unusedOutput'}, }, ] }, { fileName: dirFile, source: ` export class TestDir {outputA!: EventEmitter<string>;} export class OtherDir {unusedOutput!: EventEmitter<string>;} `, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('outputA'); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name?.text) .toEqual('TestDir'); }); it('returns addEventListener binding to native element when no match to any directive output', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div (click)="handle($event)"></div>`}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.bindings[0].tsSymbol!)) .toEqual('addEventListener'); const eventSymbol = templateTypeChecker.getSymbolOfNode(outputABinding.handler, cmp)!; assertExpressionSymbol(eventSymbol); }); it('still returns binding when checkTypeOfOutputEvents is false', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': `<div dir (outputA)="handle($event)"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA'}, }, ] }, { fileName: dirFile, source: `export class TestDir {outputA!: EventEmitter<string>;}`, templates: {}, } ], {checkTypeOfOutputEvents: false}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('outputA'); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name?.text) .toEqual('TestDir'); }); it('returns output symbol for two way binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [(ngModel)]="value"></div>`}, source: ` export class Cmp { value = ''; }`, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {ngModel: 'ngModel'}, outputs: {ngModelChange: 'ngModelChange'}, }, ] }, { fileName: dirFile, source: ` export class TestDir { ngModel!: string; ngModelChange!: EventEmitter<string>; }`, templates: {}, } ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .name.getText()) .toEqual('ngModelChange'); expect((symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration) .parent.name?.text) .toEqual('TestDir'); }); }); describe('for elements', () => { it('for elements that are components with no inputs', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': `<child-component></child-component>`}, declarations: [ { name: 'ChildComponent', selector: 'child-component', isComponent: true, file: dirFile, type: 'directive', }, ] }, { fileName: dirFile, source: ` export class ChildComponent {} `, templates: {'ChildComponent': ''}, } ], ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(1); assertDirectiveSymbol(symbol.directives[0]); expect(program.getTypeChecker().typeToString(symbol.directives[0].tsType)) .toEqual('ChildComponent'); expect(symbol.directives[0].isComponent).toBe(true); }); it('element with directive matches', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': `<div dir dir2></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', }, { name: 'TestDir2', selector: '[dir2]', file: dirFile, type: 'directive', }, { name: 'TestDirAllDivs', selector: 'div', file: dirFile, type: 'directive', }, ] }, { fileName: dirFile, source: ` export class TestDir {} // Allow the fake ComponentScopeReader to return a module for TestDir export class TestDirModule {} export class TestDir2 {} // Allow the fake ComponentScopeReader to return a module for TestDir2 export class TestDir2Module {} export class TestDirAllDivs {} `, templates: {}, } ], ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(3); const expectedDirectives = ['TestDir', 'TestDir2', 'TestDirAllDivs'].sort(); const actualDirectives = symbol.directives.map(dir => program.getTypeChecker().typeToString(dir.tsType)).sort(); expect(actualDirectives).toEqual(expectedDirectives); const expectedSelectors = ['[dir]', '[dir2]', 'div'].sort(); const actualSelectors = symbol.directives.map(dir => dir.selector).sort(); expect(actualSelectors).toEqual(expectedSelectors); // Testing this fully requires an integration test with a real `NgCompiler` (like in the // Language Service, which uses the ngModule name for quick info). However, this path does // assert that we are able to handle when the scope reader returns `null` or a class from // the fake implementation. const expectedModules = new Set([null, 'TestDirModule', 'TestDir2Module']); const actualModules = new Set(symbol.directives.map(dir => dir.ngModule?.name.getText() ?? null)); expect(actualModules).toEqual(expectedModules); }); }); it('elements with generic directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': `<div genericDir></div>`}, declarations: [ { name: 'GenericDir', selector: '[genericDir]', file: dirFile, type: 'directive', isGeneric: true }, ] }, { fileName: dirFile, source: ` export class GenericDir<T>{} `, templates: {}, } ], ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(1); const actualDirectives = symbol.directives.map(dir => program.getTypeChecker().typeToString(dir.tsType)).sort(); expect(actualDirectives).toEqual(['GenericDir<any>']); }); it('has correct tcb location for components with inline TCBs', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = baseTestSetup( [ { fileName, templates: {'Cmp': '<div></div>'}, // Force an inline TCB by using a non-exported component class source: `class Cmp {}`, }, ], {inlining: true, config: {enableTemplateTypeChecker: true}}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.tcbLocation.tcbPath).toBe(sf.fileName); expect(symbol.tcbLocation.isShimFile).toBe(false); }); it('has correct tcb location for components with TCBs in a type-checking shim file', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': '<div></div>'}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.tcbLocation.tcbPath).not.toBe(sf.fileName); expect(symbol.tcbLocation.isShimFile).toBe(true); }); }); }); function onlyAstTemplates(nodes: TmplAstNode[]): TmplAstTemplate[] { return nodes.filter((n): n is TmplAstTemplate => n instanceof TmplAstTemplate); } function onlyAstElements(nodes: TmplAstNode[]): TmplAstElement[] { return nodes.filter((n): n is TmplAstElement => n instanceof TmplAstElement); } function getAstElements( templateTypeChecker: TemplateTypeChecker, cmp: ts.ClassDeclaration&{name: ts.Identifier}) { return onlyAstElements(templateTypeChecker.getTemplate(cmp)!); } function getAstTemplates( templateTypeChecker: TemplateTypeChecker, cmp: ts.ClassDeclaration&{name: ts.Identifier}) { return onlyAstTemplates(templateTypeChecker.getTemplate(cmp)!); } function assertDirectiveSymbol(tSymbol: Symbol): asserts tSymbol is DirectiveSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Directive); } function assertInputBindingSymbol(tSymbol: Symbol): asserts tSymbol is InputBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Input); } function assertOutputBindingSymbol(tSymbol: Symbol): asserts tSymbol is OutputBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Output); } function assertVariableSymbol(tSymbol: Symbol): asserts tSymbol is VariableSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Variable); } function assertTemplateSymbol(tSymbol: Symbol): asserts tSymbol is TemplateSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Template); } function assertReferenceSymbol(tSymbol: Symbol): asserts tSymbol is ReferenceSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Reference); } function assertExpressionSymbol(tSymbol: Symbol): asserts tSymbol is ExpressionSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Expression); } function assertPipeSymbol(tSymbol: Symbol): asserts tSymbol is PipeSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Pipe); } function assertElementSymbol(tSymbol: Symbol): asserts tSymbol is ElementSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Element); } function assertDomBindingSymbol(tSymbol: Symbol): asserts tSymbol is DomBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.DomBinding); } export function setup(targets: TypeCheckingTarget[], config?: Partial<TypeCheckingConfig>) { return baseTestSetup(targets, { inlining: false, config: {...config, enableTemplateTypeChecker: true, useInlineTypeConstructors: false} }); }
packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0007228755857795477, 0.0001851436245488003, 0.00016709481133148074, 0.000170093058841303, 0.00006270337325986475 ]
{ "id": 4, "code_window": [ " return call(Identifiers.projectionDef, def ? [def] : [], null);\n", "}\n", "\n", "export function projection(\n", " slot: number, projectionSlotIndex: number, attributes: string[]): ir.CreateOp {\n", " const args: o.Expression[] = [o.literal(slot)];\n", " if (projectionSlotIndex !== 0 || attributes.length > 0) {\n", " args.push(o.literal(projectionSlotIndex));\n", " if (attributes.length > 0) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " slot: number, projectionSlotIndex: number, attributes: string[],\n", " sourceSpan: ParseSourceSpan): ir.CreateOp {\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 216 }
/** * @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.io/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/upgrade'; // This file only reexports content of the `src` folder. Keep it that way.
packages/router/upgrade/public_api.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017544638831168413, 0.0001704019377939403, 0.0001653575018281117, 0.0001704019377939403, 0.000005044443241786212 ]
{ "id": 5, "code_window": [ " args.push(o.literalArr(attributes.map(attr => o.literal(attr))));\n", " }\n", " }\n", " return call(Identifiers.projection, args, null);\n", "}\n", "\n", "export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp {\n", " const args = [o.literal(slot), o.literal(constIndex)];\n", " if (subTemplateIndex !== null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return call(Identifiers.projection, args, sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 224 }
{ "$schema": "../../test_case_schema.json", "cases": [ { "description": "should map simple element with content (full compile)", "inputFiles": [ "simple_element.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map simple element with content (partial compile)", "inputFiles": [ "simple_element.ts" ], "expectations": [ { "files": [ { "generated": "simple_element.js", "expected": "simple_element_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map void element (full compile)", "inputFiles": [ "void_element.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map void element (partial compile)", "inputFiles": [ "void_element.ts" ], "expectations": [ { "files": [ { "generated": "void_element.js", "expected": "void_element_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a mix of interpolated and static content (full compile)", "inputFiles": [ "interpolation_basic.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a mix of interpolated and static content (partial compile)", "inputFiles": [ "interpolation_basic.ts" ], "expectations": [ { "files": [ { "generated": "interpolation_basic.js", "expected": "interpolation_basic_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex interpolated expression (full compile)", "inputFiles": [ "interpolation_complex.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex interpolated expression (partial compile)", "inputFiles": [ "interpolation_complex.ts" ], "expectations": [ { "files": [ { "generated": "interpolation_complex.js", "expected": "interpolation_complex_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map interpolated properties (full compile)", "inputFiles": [ "interpolation_properties.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map interpolated properties (partial compile)", "inputFiles": [ "interpolation_properties.ts" ], "expectations": [ { "files": [ { "generated": "interpolation_properties.js", "expected": "interpolation_properties_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map interpolation with pipe (full compile)", "inputFiles": [ "interpolation_with_pipe.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map interpolation with pipe (partial compile)", "inputFiles": [ "interpolation_with_pipe.ts" ], "expectations": [ { "files": [ { "generated": "interpolation_with_pipe.js", "expected": "interpolation_with_pipe_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a simple input binding expression (full compile)", "inputFiles": [ "input_binding_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a simple input binding expression (partial compile)", "inputFiles": [ "input_binding_simple.ts" ], "expectations": [ { "files": [ { "generated": "input_binding_simple.js", "expected": "input_binding_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex input binding expression (full compile)", "inputFiles": [ "input_binding_complex.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex input binding expression (partial compile)", "inputFiles": [ "input_binding_complex.ts" ], "expectations": [ { "files": [ { "generated": "input_binding_complex.js", "expected": "input_binding_complex_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a longhand input binding expression (full compile)", "inputFiles": [ "input_binding_longhand.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a longhand input binding expression (partial compile)", "inputFiles": [ "input_binding_longhand.ts" ], "expectations": [ { "files": [ { "generated": "input_binding_longhand.js", "expected": "input_binding_longhand_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a simple output binding expression (full compile)", "inputFiles": [ "output_binding_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a simple output binding expression (partial compile)", "inputFiles": [ "output_binding_simple.ts" ], "expectations": [ { "files": [ { "generated": "output_binding_simple.js", "expected": "output_binding_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex output binding expression (full compile)", "inputFiles": [ "output_binding_complex.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a complex output binding expression (partial compile)", "inputFiles": [ "output_binding_complex.ts" ], "expectations": [ { "files": [ { "generated": "output_binding_complex.js", "expected": "output_binding_complex_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a longhand output binding expression (full compile)", "inputFiles": [ "output_binding_longhand.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a longhand output binding expression (partial compile)", "inputFiles": [ "output_binding_longhand.ts" ], "expectations": [ { "files": [ { "generated": "output_binding_longhand.js", "expected": "output_binding_longhand_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a two-way binding expression (full compile)", "inputFiles": [ "two_way_binding_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should map a two-way binding expression (partial compile)", "inputFiles": [ "two_way_binding_simple.ts" ], "expectations": [ { "files": [ { "generated": "two_way_binding_simple.js", "expected": "two_way_binding_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a longhand two-way binding expression (full compile)", "inputFiles": [ "two_way_binding_longhand.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should map a longhand two-way binding expression (partial compile)", "inputFiles": [ "two_way_binding_longhand.ts" ], "expectations": [ { "files": [ { "generated": "two_way_binding_longhand.js", "expected": "two_way_binding_longhand_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a class input binding (full compile)", "inputFiles": [ "input_binding_class.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map a class input binding (partial compile)", "inputFiles": [ "input_binding_class.ts" ], "expectations": [ { "files": [ { "generated": "input_binding_class.js", "expected": "input_binding_class_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map *ngIf scenario (full compile)", "inputFiles": [ "ng_if_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map *ngIf scenario (partial compile)", "inputFiles": [ "ng_if_simple.ts" ], "expectations": [ { "files": [ { "generated": "ng_if_simple.js", "expected": "ng_if_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map ng-template [ngIf] scenario (full compile)", "inputFiles": [ "ng_if_templated.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map ng-template [ngIf] scenario (partial compile)", "inputFiles": [ "ng_if_templated.ts" ], "expectations": [ { "files": [ { "generated": "ng_if_templated.js", "expected": "ng_if_templated_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map *ngFor scenario (full compile)", "inputFiles": [ "ng_for_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should map *ngFor scenario (partial compile)", "inputFiles": [ "ng_for_simple.ts" ], "expectations": [ { "files": [ { "generated": "ng_for_simple.js", "expected": "ng_for_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map ng-template [ngFor] scenario (full compile)", "inputFiles": [ "ng_for_templated.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should map ng-template [ngFor] scenario (partial compile)", "inputFiles": [ "ng_for_templated.ts" ], "expectations": [ { "files": [ { "generated": "ng_for_templated.js", "expected": "ng_for_templated_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should map default and selected projection (full compile)", "inputFiles": [ "projection.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should map default and selected projection (partial compile)", "inputFiles": [ "projection.ts" ], "expectations": [ { "files": [ { "generated": "projection.js", "expected": "projection_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create simple i18n message source-mapping (full compile)", "inputFiles": [ "i18n_message_simple.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should create simple i18n message source-mapping (partial compile)", "inputFiles": [ "i18n_message_simple.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_simple.js", "expected": "i18n_message_simple_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create placeholder i18n message source-mappings (full compile)", "inputFiles": [ "i18n_message_placeholder.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should create placeholder i18n message source-mappings (partial compile)", "inputFiles": [ "i18n_message_placeholder.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_placeholder.js", "expected": "i18n_message_placeholder_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should handle encoded entities in i18n message source-mappings (full compile)", "inputFiles": [ "i18n_message_placeholder_entities.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should handle encoded entities in i18n message source-mappings (partial compile)", "inputFiles": [ "i18n_message_placeholder_entities.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_placeholder_entities.js", "expected": "i18n_message_placeholder_entities_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should correctly handle collapsed whitespace in interpolation placeholder i18n message source-mappings (full compile)", "inputFiles": [ "i18n_message_interpolation_whitespace.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should correctly handle collapsed whitespace in interpolation placeholder i18n message source-mappings (partial compile)", "inputFiles": [ "i18n_message_interpolation_whitespace.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_interpolation_whitespace.js", "expected": "i18n_message_interpolation_whitespace_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should correctly handle collapsed whitespace in element placeholder i18n message source-mappings (full compile)", "inputFiles": [ "i18n_message_element_whitespace.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should correctly handle collapsed whitespace in element placeholder i18n message source-mappings (partial compile)", "inputFiles": [ "i18n_message_element_whitespace.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_element_whitespace.js", "expected": "i18n_message_element_whitespace_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create tag (container) placeholder i18n message source-mappings (full compile)", "inputFiles": [ "i18n_message_container_tag.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true }, "skipForTemplatePipeline": true }, { "description": "should create tag (container) placeholder i18n message source-mappings (partial compile)", "inputFiles": [ "i18n_message_container_tag.ts" ], "expectations": [ { "files": [ { "generated": "i18n_message_container_tag.js", "expected": "i18n_message_container_tag_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create (simple string) inline template source-mapping (full compile)", "inputFiles": [ "update_mode.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create (simple string) inline template source-mapping (partial compile)", "inputFiles": [ "update_mode.ts" ], "expectations": [ { "files": [ { "generated": "update_mode.js", "expected": "update_mode_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create correct inline template source-mapping when the source contains escape sequences (full compile)", "inputFiles": [ "escape_sequences.ts" ], "compilationModeFilter": [ "full compile" ], "compilerOptions": { "sourceMap": true } }, { "description": "should create correct inline template source-mapping when the source contains escape sequences (partial compile)", "inputFiles": [ "escape_sequences.ts" ], "expectations": [ { "files": [ { "generated": "escape_sequences.js", "expected": "escape_sequences_partial.js" } ] } ], "compilationModeFilter": [ "linked compile" ], "compilerOptions": { "sourceMap": true } } ] }
packages/compiler-cli/test/compliance/test_cases/source_mapping/inline_templates/TEST_CASES.json
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0003876148839481175, 0.00018505699699744582, 0.00016611478349659592, 0.00017131488129962236, 0.00003796941746259108 ]
{ "id": 5, "code_window": [ " args.push(o.literalArr(attributes.map(attr => o.literal(attr))));\n", " }\n", " }\n", " return call(Identifiers.projection, args, null);\n", "}\n", "\n", "export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp {\n", " const args = [o.literal(slot), o.literal(constIndex)];\n", " if (subTemplateIndex !== null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return call(Identifiers.projection, args, sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 224 }
aio/content/examples/attribute-directives/example-config.json
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017163452866952866, 0.00017163452866952866, 0.00017163452866952866, 0.00017163452866952866, 0 ]
{ "id": 5, "code_window": [ " args.push(o.literalArr(attributes.map(attr => o.literal(attr))));\n", " }\n", " }\n", " return call(Identifiers.projection, args, null);\n", "}\n", "\n", "export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp {\n", " const args = [o.literal(slot), o.literal(constIndex)];\n", " if (subTemplateIndex !== null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return call(Identifiers.projection, args, sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 224 }
import {Directive} from '@angular/core'; @Directive({selector: 'loading-dep', standalone: true}) export class LoadingDep { }
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_deferred/deferred_with_external_deps_loading.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0001666087773628533, 0.0001666087773628533, 0.0001666087773628533, 0.0001666087773628533, 0 ]
{ "id": 5, "code_window": [ " args.push(o.literalArr(attributes.map(attr => o.literal(attr))));\n", " }\n", " }\n", " return call(Identifiers.projection, args, null);\n", "}\n", "\n", "export function i18nStart(slot: number, constIndex: number, subTemplateIndex: number): ir.CreateOp {\n", " const args = [o.literal(slot), o.literal(constIndex)];\n", " if (subTemplateIndex !== null) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return call(Identifiers.projection, args, sourceSpan);\n" ], "file_path": "packages/compiler/src/template/pipeline/src/instruction.ts", "type": "replace", "edit_start_line_idx": 224 }
/** * @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.io/license */ import {Expression} from '@angular/compiler'; import ts from 'typescript'; import {identifierOfNode} from '../../util/src/typescript'; export interface OwningModule { specifier: string; resolutionContext: string; } /** * A `ts.Node` plus the context in which it was discovered. * * A `Reference` is a pointer to a `ts.Node` that was extracted from the program somehow. It * contains not only the node itself, but the information regarding how the node was located. In * particular, it might track different identifiers by which the node is exposed, as well as * potentially a module specifier which might expose the node. * * The Angular compiler uses `Reference`s instead of `ts.Node`s when tracking classes or generating * imports. */ export class Reference<T extends ts.Node = ts.Node> { /** * The compiler's best guess at an absolute module specifier which owns this `Reference`. * * This is usually determined by tracking the import statements which led the compiler to a given * node. If any of these imports are absolute, it's an indication that the node being imported * might come from that module. * * It is not _guaranteed_ that the node in question is exported from its `bestGuessOwningModule` - * that is mostly a convention that applies in certain package formats. * * If `bestGuessOwningModule` is `null`, then it's likely the node came from the current program. */ readonly bestGuessOwningModule: OwningModule|null; private identifiers: ts.Identifier[] = []; /** * Indicates that the Reference was created synthetically, not as a result of natural value * resolution. * * This is used to avoid misinterpreting the Reference in certain contexts. */ synthetic = false; private _alias: Expression|null = null; constructor(readonly node: T, bestGuessOwningModule: OwningModule|null = null) { this.bestGuessOwningModule = bestGuessOwningModule; const id = identifierOfNode(node); if (id !== null) { this.identifiers.push(id); } } /** * The best guess at which module specifier owns this particular reference, or `null` if there * isn't one. */ get ownedByModuleGuess(): string|null { if (this.bestGuessOwningModule !== null) { return this.bestGuessOwningModule.specifier; } else { return null; } } /** * Whether this reference has a potential owning module or not. * * See `bestGuessOwningModule`. */ get hasOwningModuleGuess(): boolean { return this.bestGuessOwningModule !== null; } /** * A name for the node, if one is available. * * This is only suited for debugging. Any actual references to this node should be made with * `ts.Identifier`s (see `getIdentityIn`). */ get debugName(): string|null { const id = identifierOfNode(this.node); return id !== null ? id.text : null; } get alias(): Expression|null { return this._alias; } /** * Record a `ts.Identifier` by which it's valid to refer to this node, within the context of this * `Reference`. */ addIdentifier(identifier: ts.Identifier): void { this.identifiers.push(identifier); } /** * Get a `ts.Identifier` within this `Reference` that can be used to refer within the context of a * given `ts.SourceFile`, if any. */ getIdentityIn(context: ts.SourceFile): ts.Identifier|null { return this.identifiers.find(id => id.getSourceFile() === context) || null; } /** * Get a `ts.Identifier` for this `Reference` that exists within the given expression. * * This is very useful for producing `ts.Diagnostic`s that reference `Reference`s that were * extracted from some larger expression, as it can be used to pinpoint the `ts.Identifier` within * the expression from which the `Reference` originated. */ getIdentityInExpression(expr: ts.Expression): ts.Identifier|null { const sf = expr.getSourceFile(); return this.identifiers.find(id => { if (id.getSourceFile() !== sf) { return false; } // This identifier is a match if its position lies within the given expression. return id.pos >= expr.pos && id.end <= expr.end; }) || null; } /** * Given the 'container' expression from which this `Reference` was extracted, produce a * `ts.Expression` to use in a diagnostic which best indicates the position within the container * expression that generated the `Reference`. * * For example, given a `Reference` to the class 'Bar' and the containing expression: * `[Foo, Bar, Baz]`, this function would attempt to return the `ts.Identifier` for `Bar` within * the array. This could be used to produce a nice diagnostic context: * * ```text * [Foo, Bar, Baz] * ~~~ * ``` * * If no specific node can be found, then the `fallback` expression is used, which defaults to the * entire containing expression. */ getOriginForDiagnostics(container: ts.Expression, fallback: ts.Expression = container): ts.Expression { const id = this.getIdentityInExpression(container); return id !== null ? id : fallback; } cloneWithAlias(alias: Expression): Reference<T> { const ref = new Reference(this.node, this.bestGuessOwningModule); ref.identifiers = [...this.identifiers]; ref._alias = alias; return ref; } cloneWithNoIdentifiers(): Reference<T> { const ref = new Reference(this.node, this.bestGuessOwningModule); ref._alias = this._alias; ref.identifiers = []; return ref; } }
packages/compiler-cli/src/ngtsc/imports/src/references.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0007831405964680016, 0.00020355878223199397, 0.00016217409574892372, 0.0001672219659667462, 0.00014085409929975867 ]
{ "id": 6, "code_window": [ " if (op.slot === null) {\n", " throw new Error('No slot was assigned for project instruction');\n", " }\n", " ir.OpList.replace<ir.CreateOp>(\n", " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes));\n", " break;\n", " case ir.OpKind.RepeaterCreate:\n", " if (op.slot === null) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes, op.sourceSpan));\n" ], "file_path": "packages/compiler/src/template/pipeline/src/phases/reify.ts", "type": "replace", "edit_start_line_idx": 164 }
/** * @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.io/license */ import * as o from '../../../../output/output_ast'; import {Identifiers} from '../../../../render3/r3_identifiers'; import * as ir from '../../ir'; import {ViewCompilationUnit, type CompilationJob, type CompilationUnit} from '../compilation'; import * as ng from '../instruction'; /** * Map of sanitizers to their identifier. */ const sanitizerIdentifierMap = new Map<ir.SanitizerFn, o.ExternalReference>([ [ir.SanitizerFn.Html, Identifiers.sanitizeHtml], [ir.SanitizerFn.IframeAttribute, Identifiers.validateIframeAttribute], [ir.SanitizerFn.ResourceUrl, Identifiers.sanitizeResourceUrl], [ir.SanitizerFn.Script, Identifiers.sanitizeScript], [ir.SanitizerFn.Style, Identifiers.sanitizeStyle], [ir.SanitizerFn.Url, Identifiers.sanitizeUrl] ]); /** * Compiles semantic operations across all views and generates output `o.Statement`s with actual * runtime calls in their place. * * Reification replaces semantic operations with selected Ivy instructions and other generated code * structures. After reification, the create/update operation lists of all views should only contain * `ir.StatementOp`s (which wrap generated `o.Statement`s). */ export function phaseReify(cpl: CompilationJob): void { for (const unit of cpl.units) { reifyCreateOperations(unit, unit.create); reifyUpdateOperations(unit, unit.update); } } function reifyCreateOperations(unit: CompilationUnit, ops: ir.OpList<ir.CreateOp>): void { for (const op of ops) { ir.transformExpressionsInOp(op, reifyIrExpression, ir.VisitorContextFlag.None); switch (op.kind) { case ir.OpKind.Text: ir.OpList.replace(op, ng.text(op.slot!, op.initialValue, op.sourceSpan)); break; case ir.OpKind.ElementStart: ir.OpList.replace( op, ng.elementStart( op.slot!, op.tag!, op.attributes as number | null, op.localRefs as number | null, op.sourceSpan)); break; case ir.OpKind.Element: ir.OpList.replace( op, ng.element( op.slot!, op.tag!, op.attributes as number | null, op.localRefs as number | null, op.sourceSpan)); break; case ir.OpKind.ElementEnd: ir.OpList.replace(op, ng.elementEnd(op.sourceSpan)); break; case ir.OpKind.ContainerStart: ir.OpList.replace( op, ng.elementContainerStart( op.slot!, op.attributes as number | null, op.localRefs as number | null, op.sourceSpan)); break; case ir.OpKind.Container: ir.OpList.replace( op, ng.elementContainer( op.slot!, op.attributes as number | null, op.localRefs as number | null, op.sourceSpan)); break; case ir.OpKind.ContainerEnd: ir.OpList.replace(op, ng.elementContainerEnd()); break; case ir.OpKind.I18nStart: ir.OpList.replace(op, ng.i18nStart(op.slot!, op.messageIndex!, op.subTemplateIndex!)); break; case ir.OpKind.I18nEnd: ir.OpList.replace(op, ng.i18nEnd()); break; case ir.OpKind.I18n: ir.OpList.replace(op, ng.i18n(op.slot!, op.messageIndex!, op.subTemplateIndex!)); break; case ir.OpKind.Template: if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } const childView = unit.job.views.get(op.xref)!; ir.OpList.replace( op, ng.template( op.slot!, o.variable(childView.fnName!), childView.decls!, childView.vars!, op.block ? null : op.tag, op.attributes, op.sourceSpan), ); break; case ir.OpKind.DisableBindings: ir.OpList.replace(op, ng.disableBindings()); break; case ir.OpKind.EnableBindings: ir.OpList.replace(op, ng.enableBindings()); break; case ir.OpKind.Pipe: ir.OpList.replace(op, ng.pipe(op.slot!, op.name)); break; case ir.OpKind.Listener: const listenerFn = reifyListenerHandler(unit, op.handlerFnName!, op.handlerOps, op.consumesDollarEvent); const reified = op.hostListener && op.isAnimationListener ? ng.syntheticHostListener(op.name, listenerFn, op.sourceSpan) : ng.listener(op.name, listenerFn, op.sourceSpan); ir.OpList.replace(op, reified); break; case ir.OpKind.Variable: if (op.variable.name === null) { throw new Error(`AssertionError: unnamed variable ${op.xref}`); } ir.OpList.replace<ir.CreateOp>( op, ir.createStatementOp(new o.DeclareVarStmt( op.variable.name, op.initializer, undefined, o.StmtModifier.Final))); break; case ir.OpKind.Namespace: switch (op.active) { case ir.Namespace.HTML: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceHTML()); break; case ir.Namespace.SVG: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceSVG()); break; case ir.Namespace.Math: ir.OpList.replace<ir.CreateOp>(op, ng.namespaceMath()); break; } break; case ir.OpKind.Defer: ir.OpList.replace( op, ng.defer( op.slot!, op.targetSlot!, null, op.loading && op.loading.targetSlot, op.placeholder && op.placeholder.targetSlot, op.error && op.error.targetSlot, op.loading?.constIndex ?? null, op.placeholder?.constIndex ?? null, op.sourceSpan)); break; case ir.OpKind.DeferSecondaryBlock: ir.OpList.remove<ir.CreateOp>(op); break; case ir.OpKind.DeferOn: ir.OpList.replace(op, ng.deferOn(op.sourceSpan)); break; case ir.OpKind.ProjectionDef: ir.OpList.replace<ir.CreateOp>(op, ng.projectionDef(op.def)); break; case ir.OpKind.Projection: if (op.slot === null) { throw new Error('No slot was assigned for project instruction'); } ir.OpList.replace<ir.CreateOp>( op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes)); break; case ir.OpKind.RepeaterCreate: if (op.slot === null) { throw new Error('No slot was assigned for repeater instruction'); } if (!(unit instanceof ViewCompilationUnit)) { throw new Error(`AssertionError: must be compiling a component`); } const repeaterView = unit.job.views.get(op.xref)!; if (repeaterView.fnName === null) { throw new Error(`AssertionError: expected repeater primary view to have been named`); } let emptyViewFnName: string|null = null; let emptyDecls: number|null = null; let emptyVars: number|null = null; if (op.emptyView !== null) { const emptyView = unit.job.views.get(op.emptyView); if (emptyView === undefined) { throw new Error( 'AssertionError: repeater had empty view xref, but empty view was not found'); } if (emptyView.fnName === null || emptyView.decls === null || emptyView.vars === null) { throw new Error( `AssertionError: expected repeater empty view to have been named and counted`); } emptyViewFnName = emptyView.fnName; emptyDecls = emptyView.decls; emptyVars = emptyView.vars; } ir.OpList.replace( op, ng.repeaterCreate( op.slot, repeaterView.fnName, op.decls!, op.vars!, op.trackByFn!, op.usesComponentInstance, emptyViewFnName, emptyDecls, emptyVars, op.sourceSpan)); break; case ir.OpKind.Statement: // Pass statement operations directly through. break; default: throw new Error( `AssertionError: Unsupported reification of create op ${ir.OpKind[op.kind]}`); } } } function reifyUpdateOperations(_unit: CompilationUnit, ops: ir.OpList<ir.UpdateOp>): void { for (const op of ops) { ir.transformExpressionsInOp(op, reifyIrExpression, ir.VisitorContextFlag.None); switch (op.kind) { case ir.OpKind.Advance: ir.OpList.replace(op, ng.advance(op.delta, op.sourceSpan)); break; case ir.OpKind.Property: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.propertyInterpolate( op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan)); } else { ir.OpList.replace(op, ng.property(op.name, op.expression, op.sanitizer, op.sourceSpan)); } break; case ir.OpKind.StyleProp: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.stylePropInterpolate( op.name, op.expression.strings, op.expression.expressions, op.unit, op.sourceSpan)); } else { ir.OpList.replace(op, ng.styleProp(op.name, op.expression, op.unit, op.sourceSpan)); } break; case ir.OpKind.ClassProp: ir.OpList.replace(op, ng.classProp(op.name, op.expression, op.sourceSpan)); break; case ir.OpKind.StyleMap: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.styleMapInterpolate( op.expression.strings, op.expression.expressions, op.sourceSpan)); } else { ir.OpList.replace(op, ng.styleMap(op.expression, op.sourceSpan)); } break; case ir.OpKind.ClassMap: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.classMapInterpolate( op.expression.strings, op.expression.expressions, op.sourceSpan)); } else { ir.OpList.replace(op, ng.classMap(op.expression, op.sourceSpan)); } break; case ir.OpKind.I18nExpression: ir.OpList.replace(op, ng.i18nExp(op.expression, op.sourceSpan)); break; case ir.OpKind.I18nApply: ir.OpList.replace(op, ng.i18nApply(op.targetSlot!, op.sourceSpan)); break; case ir.OpKind.InterpolateText: ir.OpList.replace( op, ng.textInterpolate( op.interpolation.strings, op.interpolation.expressions, op.sourceSpan)); break; case ir.OpKind.Attribute: if (op.expression instanceof ir.Interpolation) { ir.OpList.replace( op, ng.attributeInterpolate( op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan)); } else { ir.OpList.replace(op, ng.attribute(op.name, op.expression, op.sanitizer)); } break; case ir.OpKind.HostProperty: if (op.expression instanceof ir.Interpolation) { throw new Error('not yet handled'); } else { if (op.isAnimationTrigger) { ir.OpList.replace(op, ng.syntheticHostProperty(op.name, op.expression, op.sourceSpan)); } else { ir.OpList.replace(op, ng.hostProperty(op.name, op.expression, op.sourceSpan)); } } break; case ir.OpKind.Variable: if (op.variable.name === null) { throw new Error(`AssertionError: unnamed variable ${op.xref}`); } ir.OpList.replace<ir.UpdateOp>( op, ir.createStatementOp(new o.DeclareVarStmt( op.variable.name, op.initializer, undefined, o.StmtModifier.Final))); break; case ir.OpKind.Conditional: if (op.processed === null) { throw new Error(`Conditional test was not set.`); } if (op.targetSlot === null) { throw new Error(`Conditional slot was not set.`); } ir.OpList.replace( op, ng.conditional(op.targetSlot, op.processed, op.contextValue, op.sourceSpan)); break; case ir.OpKind.Repeater: ir.OpList.replace(op, ng.repeater(op.targetSlot!, op.collection, op.sourceSpan)); break; case ir.OpKind.Statement: // Pass statement operations directly through. break; default: throw new Error( `AssertionError: Unsupported reification of update op ${ir.OpKind[op.kind]}`); } } } function reifyIrExpression(expr: o.Expression): o.Expression { if (!ir.isIrExpression(expr)) { return expr; } switch (expr.kind) { case ir.ExpressionKind.NextContext: return ng.nextContext(expr.steps); case ir.ExpressionKind.Reference: return ng.reference(expr.targetSlot! + 1 + expr.offset); case ir.ExpressionKind.LexicalRead: throw new Error(`AssertionError: unresolved LexicalRead of ${expr.name}`); case ir.ExpressionKind.RestoreView: if (typeof expr.view === 'number') { throw new Error(`AssertionError: unresolved RestoreView`); } return ng.restoreView(expr.view); case ir.ExpressionKind.ResetView: return ng.resetView(expr.expr); case ir.ExpressionKind.GetCurrentView: return ng.getCurrentView(); case ir.ExpressionKind.ReadVariable: if (expr.name === null) { throw new Error(`Read of unnamed variable ${expr.xref}`); } return o.variable(expr.name); case ir.ExpressionKind.ReadTemporaryExpr: if (expr.name === null) { throw new Error(`Read of unnamed temporary ${expr.xref}`); } return o.variable(expr.name); case ir.ExpressionKind.AssignTemporaryExpr: if (expr.name === null) { throw new Error(`Assign of unnamed temporary ${expr.xref}`); } return o.variable(expr.name).set(expr.expr); case ir.ExpressionKind.PureFunctionExpr: if (expr.fn === null) { throw new Error(`AssertionError: expected PureFunctions to have been extracted`); } return ng.pureFunction(expr.varOffset!, expr.fn, expr.args); case ir.ExpressionKind.PureFunctionParameterExpr: throw new Error(`AssertionError: expected PureFunctionParameterExpr to have been extracted`); case ir.ExpressionKind.PipeBinding: return ng.pipeBind(expr.targetSlot!, expr.varOffset!, expr.args); case ir.ExpressionKind.PipeBindingVariadic: return ng.pipeBindV(expr.targetSlot!, expr.varOffset!, expr.args); case ir.ExpressionKind.SanitizerExpr: return o.importExpr(sanitizerIdentifierMap.get(expr.fn)!); case ir.ExpressionKind.SlotLiteralExpr: return o.literal(expr.targetSlot); default: throw new Error(`AssertionError: Unsupported reification of ir.Expression kind: ${ ir.ExpressionKind[(expr as ir.Expression).kind]}`); } } /** * Listeners get turned into a function expression, which may or may not have the `$event` * parameter defined. */ function reifyListenerHandler( unit: CompilationUnit, name: string, handlerOps: ir.OpList<ir.UpdateOp>, consumesDollarEvent: boolean): o.FunctionExpr { // First, reify all instruction calls within `handlerOps`. reifyUpdateOperations(unit, handlerOps); // Next, extract all the `o.Statement`s from the reified operations. We can expect that at this // point, all operations have been converted to statements. const handlerStmts: o.Statement[] = []; for (const op of handlerOps) { if (op.kind !== ir.OpKind.Statement) { throw new Error( `AssertionError: expected reified statements, but found op ${ir.OpKind[op.kind]}`); } handlerStmts.push(op.statement); } // If `$event` is referenced, we need to generate it as a parameter. const params: o.FnParam[] = []; if (consumesDollarEvent) { // We need the `$event` parameter. params.push(new o.FnParam('$event')); } return o.fn(params, handlerStmts, undefined, undefined, name); }
packages/compiler/src/template/pipeline/src/phases/reify.ts
1
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.998085618019104, 0.032346077263355255, 0.00016076456813607365, 0.004303520545363426, 0.15120652318000793 ]
{ "id": 6, "code_window": [ " if (op.slot === null) {\n", " throw new Error('No slot was assigned for project instruction');\n", " }\n", " ir.OpList.replace<ir.CreateOp>(\n", " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes));\n", " break;\n", " case ir.OpKind.RepeaterCreate:\n", " if (op.slot === null) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes, op.sourceSpan));\n" ], "file_path": "packages/compiler/src/template/pipeline/src/phases/reify.ts", "type": "replace", "edit_start_line_idx": 164 }
<!doctype html> <html> <head> <title>Benchpress test</title> </head> <body> <button onclick="pleaseLog()">Click me</button> <div id="log"></div> <script type="text/javascript"> function pleaseLog() { document.getElementById("log").innerHTML = "hi"; } </script> </body> </html>
modules/playground/src/benchpress/index.html
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017209026555065066, 0.00017181283328682184, 0.0001715353864710778, 0.00017181283328682184, 2.774395397864282e-7 ]
{ "id": 6, "code_window": [ " if (op.slot === null) {\n", " throw new Error('No slot was assigned for project instruction');\n", " }\n", " ir.OpList.replace<ir.CreateOp>(\n", " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes));\n", " break;\n", " case ir.OpKind.RepeaterCreate:\n", " if (op.slot === null) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes, op.sourceSpan));\n" ], "file_path": "packages/compiler/src/template/pipeline/src/phases/reify.ts", "type": "replace", "edit_start_line_idx": 164 }
/** * @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.io/license */ import {invalidSkipHydrationHost, validateMatchingNode, validateNodeExists} from '../../hydration/error_handling'; import {locateNextRNode} from '../../hydration/node_lookup_utils'; import {hasSkipHydrationAttrOnRElement, hasSkipHydrationAttrOnTNode} from '../../hydration/skip_hydration'; import {getSerializedContainerViews, isDisconnectedNode, markRNodeAsClaimedByHydration, setSegmentHead} from '../../hydration/utils'; import {assertDefined, assertEqual, assertIndexInRange} from '../../util/assert'; import {assertFirstCreatePass, assertHasParent} from '../assert'; import {attachPatchData} from '../context_discovery'; import {registerPostOrderHooks} from '../hooks'; import {hasClassInput, hasStyleInput, TAttributes, TElementNode, TNode, TNodeFlags, TNodeType} from '../interfaces/node'; import {Renderer} from '../interfaces/renderer'; import {RElement} from '../interfaces/renderer_dom'; import {hasI18n, isComponentHost, isContentQueryHost, isDirectiveHost} from '../interfaces/type_checks'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view'; import {assertTNodeType} from '../node_assert'; import {appendChild, clearElementContents, createElementNode, setupStaticAttributes} from '../node_manipulation'; import {decreaseElementDepthCount, enterSkipHydrationBlock, getBindingIndex, getCurrentTNode, getElementDepthCount, getLView, getNamespace, getTView, increaseElementDepthCount, isCurrentTNodeParent, isInSkipHydrationBlock, isSkipHydrationRootTNode, lastNodeWasCreated, leaveSkipHydrationBlock, setCurrentTNode, setCurrentTNodeAsNotParent, wasLastNodeCreated} from '../state'; import {computeStaticStyling} from '../styling/static_styling'; import {getConstant} from '../util/view_utils'; import {validateElementIsKnown} from './element_validation'; import {setDirectiveInputsWhichShadowsStyling} from './property'; import {createDirectivesInstances, executeContentQueries, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData} from './shared'; function elementStartFirstCreatePass( index: number, tView: TView, lView: LView, name: string, attrsIndex?: number|null, localRefsIndex?: number): TElementNode { ngDevMode && assertFirstCreatePass(tView); ngDevMode && ngDevMode.firstCreatePass++; const tViewConsts = tView.consts; const attrs = getConstant<TAttributes>(tViewConsts, attrsIndex); const tNode = getOrCreateTNode(tView, index, TNodeType.Element, name, attrs); resolveDirectives(tView, lView, tNode, getConstant<string[]>(tViewConsts, localRefsIndex)); if (tNode.attrs !== null) { computeStaticStyling(tNode, tNode.attrs, false); } if (tNode.mergedAttrs !== null) { computeStaticStyling(tNode, tNode.mergedAttrs, true); } if (tView.queries !== null) { tView.queries.elementStart(tView, tNode); } return tNode; } /** * Create DOM element. The instruction must later be followed by `elementEnd()` call. * * @param index Index of the element in the LView array * @param name Name of the DOM Node * @param attrsIndex Index of the element's attributes in the `consts` array. * @param localRefsIndex Index of the element's local references in the `consts` array. * @returns This function returns itself so that it may be chained. * * Attributes and localRefs are passed as an array of strings where elements with an even index * hold an attribute name and elements with an odd index hold an attribute value, ex.: * ['id', 'warning5', 'class', 'alert'] * * @codeGenApi */ export function ɵɵelementStart( index: number, name: string, attrsIndex?: number|null, localRefsIndex?: number): typeof ɵɵelementStart { const lView = getLView(); const tView = getTView(); const adjustedIndex = HEADER_OFFSET + index; ngDevMode && assertEqual( getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings'); ngDevMode && assertIndexInRange(lView, adjustedIndex); const renderer = lView[RENDERER]; const tNode = tView.firstCreatePass ? elementStartFirstCreatePass(adjustedIndex, tView, lView, name, attrsIndex, localRefsIndex) : tView.data[adjustedIndex] as TElementNode; const native = _locateOrCreateElementNode(tView, lView, tNode, renderer, name, index); lView[adjustedIndex] = native; const hasDirectives = isDirectiveHost(tNode); if (ngDevMode && tView.firstCreatePass) { validateElementIsKnown(native, lView, tNode.value, tView.schemas, hasDirectives); } setCurrentTNode(tNode, true); setupStaticAttributes(renderer, native, tNode); if ((tNode.flags & TNodeFlags.isDetached) !== TNodeFlags.isDetached && wasLastNodeCreated()) { // In the i18n case, the translation may have removed this element, so only add it if it is not // detached. See `TNodeType.Placeholder` and `LFrame.inI18n` for more context. appendChild(tView, lView, native, tNode); } // any immediate children of a component or template container must be pre-emptively // monkey-patched with the component view data so that the element can be inspected // later on using any element discovery utility methods (see `element_discovery.ts`) if (getElementDepthCount() === 0) { attachPatchData(native, lView); } increaseElementDepthCount(); if (hasDirectives) { createDirectivesInstances(tView, lView, tNode); executeContentQueries(tView, tNode, lView); } if (localRefsIndex !== null) { saveResolvedLocalsInData(lView, tNode); } return ɵɵelementStart; } /** * Mark the end of the element. * @returns This function returns itself so that it may be chained. * * @codeGenApi */ export function ɵɵelementEnd(): typeof ɵɵelementEnd { let currentTNode = getCurrentTNode()!; ngDevMode && assertDefined(currentTNode, 'No parent node to close.'); if (isCurrentTNodeParent()) { setCurrentTNodeAsNotParent(); } else { ngDevMode && assertHasParent(getCurrentTNode()); currentTNode = currentTNode.parent!; setCurrentTNode(currentTNode, false); } const tNode = currentTNode; ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode); if (isSkipHydrationRootTNode(tNode)) { leaveSkipHydrationBlock(); } decreaseElementDepthCount(); const tView = getTView(); if (tView.firstCreatePass) { registerPostOrderHooks(tView, currentTNode); if (isContentQueryHost(currentTNode)) { tView.queries!.elementEnd(currentTNode); } } if (tNode.classesWithoutHost != null && hasClassInput(tNode)) { setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true); } if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) { setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false); } return ɵɵelementEnd; } /** * Creates an empty element using {@link elementStart} and {@link elementEnd} * * @param index Index of the element in the data array * @param name Name of the DOM Node * @param attrsIndex Index of the element's attributes in the `consts` array. * @param localRefsIndex Index of the element's local references in the `consts` array. * @returns This function returns itself so that it may be chained. * * @codeGenApi */ export function ɵɵelement( index: number, name: string, attrsIndex?: number|null, localRefsIndex?: number): typeof ɵɵelement { ɵɵelementStart(index, name, attrsIndex, localRefsIndex); ɵɵelementEnd(); return ɵɵelement; } let _locateOrCreateElementNode: typeof locateOrCreateElementNodeImpl = (tView: TView, lView: LView, tNode: TNode, renderer: Renderer, name: string, index: number) => { lastNodeWasCreated(true); return createElementNode(renderer, name, getNamespace()); }; /** * Enables hydration code path (to lookup existing elements in DOM) * in addition to the regular creation mode of element nodes. */ function locateOrCreateElementNodeImpl( tView: TView, lView: LView, tNode: TNode, renderer: Renderer, name: string, index: number): RElement { const hydrationInfo = lView[HYDRATION]; const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock() || isDisconnectedNode(hydrationInfo, index); lastNodeWasCreated(isNodeCreationMode); // Regular creation mode. if (isNodeCreationMode) { return createElementNode(renderer, name, getNamespace()); } // Hydration mode, looking up an existing element in DOM. const native = locateNextRNode<RElement>(hydrationInfo, tView, lView, tNode)!; ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode); ngDevMode && markRNodeAsClaimedByHydration(native); // This element might also be an anchor of a view container. if (getSerializedContainerViews(hydrationInfo, index)) { // Important note: this element acts as an anchor, but it's **not** a part // of the embedded view, so we start the segment **after** this element, taking // a reference to the next sibling. For example, the following template: // `<div #vcrTarget>` is represented in the DOM as `<div></div>...<!--container-->`, // so while processing a `<div>` instruction, point to the next sibling as a // start of a segment. ngDevMode && validateNodeExists(native.nextSibling, lView, tNode); setSegmentHead(hydrationInfo, index, native.nextSibling); } // Checks if the skip hydration attribute is present during hydration so we know to // skip attempting to hydrate this block. We check both TNode and RElement for an // attribute: the RElement case is needed for i18n cases, when we add it to host // elements during the annotation phase (after all internal data structures are setup). if (hydrationInfo && (hasSkipHydrationAttrOnTNode(tNode) || hasSkipHydrationAttrOnRElement(native))) { if (isComponentHost(tNode)) { enterSkipHydrationBlock(tNode); // Since this isn't hydratable, we need to empty the node // so there's no duplicate content after render clearElementContents(native); ngDevMode && ngDevMode.componentsSkippedHydration++; } else if (ngDevMode) { // If this is not a component host, throw an error. // Hydration can be skipped on per-component basis only. throw invalidSkipHydrationHost(native); } } return native; } export function enableLocateOrCreateElementNodeImpl() { _locateOrCreateElementNode = locateOrCreateElementNodeImpl; }
packages/core/src/render3/instructions/element.ts
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.0001772392715793103, 0.00017097599629778415, 0.0001599938259460032, 0.00017111236229538918, 0.000004203499884170014 ]
{ "id": 6, "code_window": [ " if (op.slot === null) {\n", " throw new Error('No slot was assigned for project instruction');\n", " }\n", " ir.OpList.replace<ir.CreateOp>(\n", " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes));\n", " break;\n", " case ir.OpKind.RepeaterCreate:\n", " if (op.slot === null) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " op, ng.projection(op.slot, op.projectionSlotIndex, op.attributes, op.sourceSpan));\n" ], "file_path": "packages/compiler/src/template/pipeline/src/phases/reify.ts", "type": "replace", "edit_start_line_idx": 164 }
/** * @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.io/license * * @externs */ /** * @suppress {duplicate} */ var getAngularTestability; /** * @suppress {duplicate} */ var getAllAngularTestabilities; /** * @suppress {duplicate} */ var getAllAngularRootElements; /** * @suppress {duplicate} */ var frameworkStabilizers;
packages/platform-browser/src/platform-browser.externs.js
0
https://github.com/angular/angular/commit/17be1a8aca2b3e0cac67a853727a446207238549
[ 0.00017562379071023315, 0.00017515818763058633, 0.0001747626520227641, 0.00017508807650301605, 3.5503529716152116e-7 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n", "\n", "/**\n", " * @publicApi\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @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.io/license */ import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core'; /** * @publicApi */ export class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> { constructor(public $implicit: T, public ngForOf: U, public index: number, public count: number) {} get first(): boolean { return this.index === 0; } get last(): boolean { return this.index === this.count - 1; } get even(): boolean { return this.index % 2 === 0; } get odd(): boolean { return !this.even; } } /** * A [structural directive](guide/structural-directives) that renders * a template for each item in a collection. * The directive is placed on an element, which becomes the parent * of the cloned templates. * * The `ngForOf` directive is generally used in the * [shorthand form](guide/structural-directives#the-asterisk--prefix) `*ngFor`. * In this form, the template to be rendered for each iteration is the content * of an anchor element containing the directive. * * The following example shows the shorthand syntax with some options, * contained in an `<li>` element. * * ``` * <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> * ``` * * The shorthand form expands into a long form that uses the `ngForOf` selector * on an `<ng-template>` element. * The content of the `<ng-template>` element is the `<li>` element that held the * short-form directive. * * Here is the expanded version of the short-form example. * * ``` * <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> * <li>...</li> * </ng-template> * ``` * * Angular automatically expands the shorthand syntax as it compiles the template. * The context for each embedded view is logically merged to the current component * context according to its lexical position. * * When using the shorthand syntax, Angular allows only [one structural directive * on an element](guide/structural-directives#one-structural-directive-per-host-element). * If you want to iterate conditionally, for example, * put the `*ngIf` on a container element that wraps the `*ngFor` element. * For futher discussion, see * [Structural Directives](guide/structural-directives#one-per-element). * * @usageNotes * * ### Local variables * * `NgForOf` provides exported values that can be aliased to local variables. * For example: * * ``` * <li *ngFor="let user of users; index as i; first as isFirst"> * {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> * </li> * ``` * * The following exported values can be aliased to local variables: * * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`). * - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe (`userStreams | * async`). * - `index: number`: The index of the current item in the iterable. * - `count: number`: The length of the iterable. * - `first: boolean`: True when the item is the first item in the iterable. * - `last: boolean`: True when the item is the last item in the iterable. * - `even: boolean`: True when the item has an even index in the iterable. * - `odd: boolean`: True when the item has an odd index in the iterable. * * ### Change propagation * * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * Angular uses object identity to track insertions and deletions within the iterator and reproduce * those changes in the DOM. This has important implications for animations and any stateful * controls that are present, such as `<input>` elements that accept user input. Inserted rows can * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state * such as user input. * For more on animations, see [Transitions and Triggers](guide/transition-and-triggers). * * The identities of elements in the iterator can change while the data does not. * This can happen, for example, if the iterator is produced from an RPC to the server, and that * RPC is re-run. Even if the data hasn't changed, the second response produces objects with * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old * elements were deleted and all new elements inserted). * * To avoid this expensive operation, you can customize the default tracking algorithm. * by supplying the `trackBy` option to `NgForOf`. * `trackBy` takes a function that has two arguments: `index` and `item`. * If `trackBy` is given, Angular tracks changes by the return value of the function. * * @see [Structural Directives](guide/structural-directives) * @ngModule CommonModule * @publicApi */ @Directive({selector: '[ngFor][ngForOf]'}) export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck { /** * The value of the iterable expression, which can be used as a * [template input variable](guide/structural-directives#template-input-variable). */ @Input() set ngForOf(ngForOf: U&NgIterable<T>|undefined|null) { this._ngForOf = ngForOf; this._ngForOfDirty = true; } /** * A function that defines how to track changes for items in the iterable. * * When items are added, moved, or removed in the iterable, * the directive must re-render the appropriate DOM nodes. * To minimize churn in the DOM, only nodes that have changed * are re-rendered. * * By default, the change detector assumes that * the object instance identifies the node in the iterable. * When this function is supplied, the directive uses * the result of calling this function to identify the item node, * rather than the identity of the object itself. * * The function receives two inputs, * the iteration index and the associated node data. */ @Input() set ngForTrackBy(fn: TrackByFunction<T>) { if (isDevMode() && fn != null && typeof fn !== 'function') { // TODO(vicb): use a log service once there is a public one available if (<any>console && <any>console.warn) { console.warn( `trackBy must be a function, but received ${JSON.stringify(fn)}. ` + `See https://angular.io/api/common/NgForOf#change-propagation for more information.`); } } this._trackByFn = fn; } get ngForTrackBy(): TrackByFunction<T> { return this._trackByFn; } private _ngForOf: U|undefined|null = null; private _ngForOfDirty: boolean = true; private _differ: IterableDiffer<T>|null = null; // TODO(issue/24571): remove '!'. private _trackByFn!: TrackByFunction<T>; constructor( private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForOfContext<T, U>>, private _differs: IterableDiffers) {} /** * A reference to the template that is stamped out for each item in the iterable. * @see [template reference variable](guide/template-reference-variables) */ @Input() set ngForTemplate(value: TemplateRef<NgForOfContext<T, U>>) { // TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1 // The current type is too restrictive; a template that just uses index, for example, // should be acceptable. if (value) { this._template = value; } } /** * Applies the changes when needed. */ ngDoCheck(): void { if (this._ngForOfDirty) { this._ngForOfDirty = false; // React on ngForOf changes only once all inputs have been initialized const value = this._ngForOf; if (!this._differ && value) { try { this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch { throw new Error(`Cannot find a differ supporting object '${value}' of type '${ getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`); } } } if (this._differ) { const changes = this._differ.diff(this._ngForOf); if (changes) this._applyChanges(changes); } } private _applyChanges(changes: IterableChanges<T>) { const insertTuples: RecordViewTuple<T, U>[] = []; changes.forEachOperation( (item: IterableChangeRecord<any>, adjustedPreviousIndex: number|null, currentIndex: number|null) => { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". const view = this._viewContainer.createEmbeddedView( this._template, new NgForOfContext<T, U>(null!, this._ngForOf!, -1, -1), currentIndex === null ? undefined : currentIndex); const tuple = new RecordViewTuple<T, U>(item, view); insertTuples.push(tuple); } else if (currentIndex == null) { this._viewContainer.remove( adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { const view = this._viewContainer.get(adjustedPreviousIndex)!; this._viewContainer.move(view, currentIndex); const tuple = new RecordViewTuple(item, <EmbeddedViewRef<NgForOfContext<T, U>>>view); insertTuples.push(tuple); } }); for (let i = 0; i < insertTuples.length; i++) { this._perViewChange(insertTuples[i].view, insertTuples[i].record); } for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>this._viewContainer.get(i); viewRef.context.index = i; viewRef.context.count = ilen; viewRef.context.ngForOf = this._ngForOf!; } changes.forEachIdentityChange((record: any) => { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>this._viewContainer.get(record.currentIndex); viewRef.context.$implicit = record.item; }); } private _perViewChange( view: EmbeddedViewRef<NgForOfContext<T, U>>, record: IterableChangeRecord<any>) { view.context.$implicit = record.item; } /** * Asserts the correct type of the context for the template that `NgForOf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgForOf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard<T, U extends NgIterable<T>>(dir: NgForOf<T, U>, ctx: any): ctx is NgForOfContext<T, U> { return true; } } class RecordViewTuple<T, U extends NgIterable<T>> { constructor(public record: any, public view: EmbeddedViewRef<NgForOfContext<T, U>>) {} } function getTypeName(type: any): string { return type['name'] || typeof type; }
packages/common/src/directives/ng_for_of.ts
1
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.007003990933299065, 0.0005651137907989323, 0.00016119220526888967, 0.0001690516364760697, 0.0014502762351185083 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n", "\n", "/**\n", " * @publicApi\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @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.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'fo', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'T', 'M', 'H', 'F', 'L'], ['sun.', 'mán.', 'týs.', 'mik.', 'hós.', 'frí.', 'ley.'], ['sunnudagur', 'mánadagur', 'týsdagur', 'mikudagur', 'hósdagur', 'fríggjadagur', 'leygardagur'], ['su.', 'má.', 'tý.', 'mi.', 'hó.', 'fr.', 'le.'] ], [ ['S', 'M', 'T', 'M', 'H', 'F', 'L'], ['sun', 'mán', 'týs', 'mik', 'hós', 'frí', 'ley'], ['sunnudagur', 'mánadagur', 'týsdagur', 'mikudagur', 'hósdagur', 'fríggjadagur', 'leygardagur'], ['su', 'má', 'tý', 'mi', 'hó', 'fr', 'le'] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['jan.', 'feb.', 'mar.', 'apr.', 'mai', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'des.'], [ 'januar', 'februar', 'mars', 'apríl', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'], [ 'januar', 'februar', 'mars', 'apríl', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ] ], [['fKr', 'eKr'], ['f.Kr.', 'e.Kr.'], ['fyri Krist', 'eftir Krist']], 1, [6, 0], ['dd.MM.yy', 'dd.MM.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} \'kl\'. {0}', u], [',', '.', ';', '%', '+', '−', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'DKK', 'kr', 'donsk króna', {'DKK': ['kr'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural ];
packages/common/locales/fo.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017769225814845413, 0.00017497055523563176, 0.00016750908980611712, 0.0001756544370437041, 0.000003312087983431411 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n", "\n", "/**\n", " * @publicApi\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 8 }
/** * @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.io/license */ import * as ts from 'typescript'; import {Evaluator} from '../../src/metadata/evaluator'; import {Symbols} from '../../src/metadata/symbols'; import {Directory, expectNoDiagnostics, findVar, findVarInitializer, Host} from './typescript.mocks'; describe('Evaluator', () => { const documentRegistry = ts.createDocumentRegistry(); let host: ts.LanguageServiceHost; let service: ts.LanguageService; let program: ts.Program; let typeChecker: ts.TypeChecker; let symbols: Symbols; let evaluator: Evaluator; beforeEach(() => { host = new Host(FILES, [ 'expressions.ts', 'consts.ts', 'const_expr.ts', 'forwardRef.ts', 'classes.ts', 'newExpression.ts', 'errors.ts', 'declared.ts' ]); service = ts.createLanguageService(host, documentRegistry); program = service.getProgram()!; typeChecker = program.getTypeChecker(); symbols = new Symbols(null as any as ts.SourceFile); evaluator = new Evaluator(symbols, new Map()); }); it('should not have typescript errors in test data', () => { expectNoDiagnostics(service.getCompilerOptionsDiagnostics()); for (const sourceFile of program.getSourceFiles()) { expectNoDiagnostics(service.getSyntacticDiagnostics(sourceFile.fileName)); if (sourceFile.fileName != 'errors.ts') { // Skip errors.ts because we it has intentional semantic errors that we are testing for. expectNoDiagnostics(service.getSemanticDiagnostics(sourceFile.fileName)); } } }); it('should be able to fold literal expressions', () => { const consts = program.getSourceFile('consts.ts')!; expect(evaluator.isFoldable(findVarInitializer(consts, 'someName'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(consts, 'someBool'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(consts, 'one'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(consts, 'two'))).toBeTruthy(); }); it('should be able to fold expressions with foldable references', () => { const expressions = program.getSourceFile('expressions.ts')!; symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); symbols.define('two', 2); expect(evaluator.isFoldable(findVarInitializer(expressions, 'three'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(expressions, 'four'))).toBeTruthy(); symbols.define('three', 3); symbols.define('four', 4); expect(evaluator.isFoldable(findVarInitializer(expressions, 'obj'))).toBeTruthy(); expect(evaluator.isFoldable(findVarInitializer(expressions, 'arr'))).toBeTruthy(); }); it('should be able to evaluate literal expressions', () => { const consts = program.getSourceFile('consts.ts')!; expect(evaluator.evaluateNode(findVarInitializer(consts, 'someName'))).toBe('some-name'); expect(evaluator.evaluateNode(findVarInitializer(consts, 'someBool'))).toBe(true); expect(evaluator.evaluateNode(findVarInitializer(consts, 'one'))).toBe(1); expect(evaluator.evaluateNode(findVarInitializer(consts, 'two'))).toBe(2); }); it('should be able to evaluate expressions', () => { const expressions = program.getSourceFile('expressions.ts')!; symbols.define('someName', 'some-name'); symbols.define('someBool', true); symbols.define('one', 1); symbols.define('two', 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'three'))).toBe(3); symbols.define('three', 3); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'four'))).toBe(4); symbols.define('four', 4); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'obj'))) .toEqual({one: 1, two: 2, three: 3, four: 4}); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'arr'))).toEqual([1, 2, 3, 4]); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bTrue'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bFalse'))).toEqual(false); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bAnd'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bOr'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'nDiv'))).toEqual(2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'nMod'))).toEqual(1); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bLOr'))).toEqual(false || true); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bLAnd'))).toEqual(true && true); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bBOr'))).toEqual(0x11 | 0x22); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bBAnd'))).toEqual(0x11 & 0x03); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bXor'))).toEqual(0x11 ^ 0x21); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bEqual'))) .toEqual(1 == <any>'1'); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bNotEqual'))) .toEqual(1 != <any>'1'); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bIdentical'))) .toEqual(1 === <any>'1'); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bNotIdentical'))) .toEqual(1 !== <any>'1'); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bLessThan'))).toEqual(1 < 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bGreaterThan'))).toEqual(1 > 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bLessThanEqual'))) .toEqual(1 <= 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bGreaterThanEqual'))) .toEqual(1 >= 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bShiftLeft'))).toEqual(1 << 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bShiftRight'))).toEqual(-1 >> 2); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'bShiftRightU'))) .toEqual(-1 >>> 2); }); it('should report recursive references as symbolic', () => { const expressions = program.getSourceFile('expressions.ts')!; expect(evaluator.evaluateNode(findVarInitializer(expressions, 'recursiveA'))) .toEqual({__symbolic: 'reference', name: 'recursiveB'}); expect(evaluator.evaluateNode(findVarInitializer(expressions, 'recursiveB'))) .toEqual({__symbolic: 'reference', name: 'recursiveA'}); }); it('should correctly handle special cases for CONST_EXPR', () => { const const_expr = program.getSourceFile('const_expr.ts')!; expect(evaluator.evaluateNode(findVarInitializer(const_expr, 'bTrue'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(const_expr, 'bFalse'))).toEqual(false); }); it('should resolve a forwardRef', () => { const forwardRef = program.getSourceFile('forwardRef.ts')!; expect(evaluator.evaluateNode(findVarInitializer(forwardRef, 'bTrue'))).toEqual(true); expect(evaluator.evaluateNode(findVarInitializer(forwardRef, 'bFalse'))).toEqual(false); }); it('should return new expressions', () => { symbols.define('Value', {__symbolic: 'reference', module: './classes', name: 'Value'}); evaluator = new Evaluator(symbols, new Map()); const newExpression = program.getSourceFile('newExpression.ts')!; expect(evaluator.evaluateNode(findVarInitializer(newExpression, 'someValue'))).toEqual({ __symbolic: 'new', expression: {__symbolic: 'reference', name: 'Value', module: './classes', line: 4, character: 33}, arguments: ['name', 12] }); expect(evaluator.evaluateNode(findVarInitializer(newExpression, 'complex'))).toEqual({ __symbolic: 'new', expression: {__symbolic: 'reference', name: 'Value', module: './classes', line: 5, character: 42}, arguments: ['name', 12] }); }); it('should support reference to a declared module type', () => { const declared = program.getSourceFile('declared.ts')!; const aDecl = findVar(declared, 'a')!; expect(evaluator.evaluateNode(aDecl.type!)).toEqual({ __symbolic: 'select', expression: {__symbolic: 'reference', name: 'Foo'}, member: 'A' }); }); it('should return errors for unsupported expressions', () => { const errors = program.getSourceFile('errors.ts')!; const fDecl = findVar(errors, 'f')!; expect(evaluator.evaluateNode(fDecl.initializer!)) .toEqual({__symbolic: 'error', message: 'Lambda not supported', line: 1, character: 12}); const eDecl = findVar(errors, 'e')!; expect(evaluator.evaluateNode(eDecl.type!)).toEqual({ __symbolic: 'error', message: 'Could not resolve type', line: 2, character: 11, context: {typeName: 'NotFound'} }); const sDecl = findVar(errors, 's')!; expect(evaluator.evaluateNode(sDecl.initializer!)).toEqual({ __symbolic: 'error', message: 'Name expected', line: 3, character: 14, context: {received: '1'} }); const tDecl = findVar(errors, 't')!; expect(evaluator.evaluateNode(tDecl.initializer!)).toEqual({ __symbolic: 'error', message: 'Expression form not supported', line: 4, character: 12 }); }); it('should be able to fold an array spread', () => { const expressions = program.getSourceFile('expressions.ts')!; symbols.define('arr', [1, 2, 3, 4]); const arrSpread = findVar(expressions, 'arrSpread')!; expect(evaluator.evaluateNode(arrSpread.initializer!)).toEqual([0, 1, 2, 3, 4, 5]); }); it('should be able to produce a spread expression', () => { const expressions = program.getSourceFile('expressions.ts')!; const arrSpreadRef = findVar(expressions, 'arrSpreadRef')!; expect(evaluator.evaluateNode(arrSpreadRef.initializer!)).toEqual([ 0, {__symbolic: 'spread', expression: {__symbolic: 'reference', name: 'arrImport'}}, 5 ]); }); it('should be able to handle a new expression with no arguments', () => { const source = sourceFileOf(` export var a = new f; `); const expr = findVar(source, 'a')!; expect(evaluator.evaluateNode(expr.initializer!)) .toEqual({__symbolic: 'new', expression: {__symbolic: 'reference', name: 'f'}}); }); describe('with substitution', () => { let evaluator: Evaluator; const lambdaTemp = 'lambdaTemp'; beforeEach(() => { evaluator = new Evaluator(symbols, new Map(), { substituteExpression: (value, node) => { if (node.kind == ts.SyntaxKind.ArrowFunction) { return {__symbolic: 'reference', name: lambdaTemp}; } return value; } }); }); it('should be able to substitute a lambda with a reference', () => { const source = sourceFileOf(` var b = 1; export var a = () => b; `); const expr = findVar(source, 'a'); expect(evaluator.evaluateNode(expr!.initializer!)) .toEqual({__symbolic: 'reference', name: lambdaTemp}); }); it('should be able to substitute a lambda in an expression', () => { const source = sourceFileOf(` var b = 1; export var a = [ { provide: 'someValue': useFactory: () => b } ]; `); const expr = findVar(source, 'a'); expect(evaluator.evaluateNode(expr!.initializer!)).toEqual([ {provide: 'someValue', useFactory: {__symbolic: 'reference', name: lambdaTemp}} ]); }); }); }); function sourceFileOf(text: string): ts.SourceFile { return ts.createSourceFile('test.ts', text, ts.ScriptTarget.Latest, true); } const FILES: Directory = { 'directives.ts': ` export function Pipe(options: { name?: string, pure?: boolean}) { return function(fn: Function) { } } `, 'classes.ts': ` export class Value { constructor(public name: string, public value: any) {} } `, 'consts.ts': ` export var someName = 'some-name'; export var someBool = true; export var one = 1; export var two = 2; export var arrImport = [1, 2, 3, 4]; `, 'expressions.ts': ` import {arrImport} from './consts'; export var someName = 'some-name'; export var someBool = true; export var one = 1; export var two = 2; export var three = one + two; export var four = two * two; export var obj = { one: one, two: two, three: three, four: four }; export var arr = [one, two, three, four]; export var bTrue = someBool; export var bFalse = !someBool; export var bAnd = someBool && someBool; export var bOr = someBool || someBool; export var nDiv = four / two; export var nMod = (four + one) % two; export var bLOr = false || true; // true export var bLAnd = true && true; // true export var bBOr = 0x11 | 0x22; // 0x33 export var bBAnd = 0x11 & 0x03; // 0x01 export var bXor = 0x11 ^ 0x21; // 0x20 export var bEqual = 1 == <any>"1"; // true export var bNotEqual = 1 != <any>"1"; // false export var bIdentical = 1 === <any>"1"; // false export var bNotIdentical = 1 !== <any>"1"; // true export var bLessThan = 1 < 2; // true export var bGreaterThan = 1 > 2; // false export var bLessThanEqual = 1 <= 2; // true export var bGreaterThanEqual = 1 >= 2; // false export var bShiftLeft = 1 << 2; // 0x04 export var bShiftRight = -1 >> 2; // -1 export var bShiftRightU = -1 >>> 2; // 0x3fffffff export var arrSpread = [0, ...arr, 5]; export var arrSpreadRef = [0, ...arrImport, 5]; export var recursiveA = recursiveB; export var recursiveB = recursiveA; `, 'A.ts': ` import {Pipe} from './directives'; @Pipe({name: 'A', pure: false}) export class A {}`, 'B.ts': ` import {Pipe} from './directives'; import {someName, someBool} from './consts'; @Pipe({name: someName, pure: someBool}) export class B {}`, 'const_expr.ts': ` function CONST_EXPR(value: any) { return value; } export var bTrue = CONST_EXPR(true); export var bFalse = CONST_EXPR(false); `, 'forwardRef.ts': ` function forwardRef(value: any) { return value; } export var bTrue = forwardRef(() => true); export var bFalse = forwardRef(() => false); `, 'newExpression.ts': ` import {Value} from './classes'; function CONST_EXPR(value: any) { return value; } function forwardRef(value: any) { return value; } export const someValue = new Value("name", 12); export const complex = CONST_EXPR(new Value("name", forwardRef(() => 12))); `, 'errors.ts': ` let f = () => 1; let e: NotFound; let s = { 1: 1, 2: 2 }; let t = typeof 12; `, 'declared.ts': ` declare namespace Foo { type A = string; } let a: Foo.A = 'some value'; ` };
packages/compiler-cli/test/metadata/evaluator_spec.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00031320948619395494, 0.00018025557801593095, 0.00016502561629749835, 0.000177120411535725, 0.00002205447708547581 ]
{ "id": 0, "code_window": [ " * found in the LICENSE file at https://angular.io/license\n", " */\n", "\n", "import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n", "\n", "/**\n", " * @publicApi\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import {Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core';\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 8 }
// Classes export class ChangedPrVisibilityEvent { // Properties - Public, Static public static type = 'pr.changedVisibility'; // Constructor constructor(public pr: number, public shas: string[], public isPublic: boolean) {} } export class CreatedBuildEvent { // Properties - Public, Static public static type = 'build.created'; // Constructor constructor(public pr: number, public sha: string, public isPublic: boolean) {} }
aio/aio-builds-setup/dockerbuild/scripts-js/lib/preview-server/build-events.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017649437359068543, 0.00017546711023896933, 0.00017443984688725322, 0.00017546711023896933, 0.0000010272633517161012 ]
{ "id": 1, "code_window": [ " * the iteration index and the associated node data.\n", " */\n", " @Input()\n", " set ngForTrackBy(fn: TrackByFunction<T>) {\n", " if (isDevMode() && fn != null && typeof fn !== 'function') {\n", " // TODO(vicb): use a log service once there is a public one available\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 161 }
/** * @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.io/license */ import {DEFAULT_CURRENCY_CODE, Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; import {formatCurrency, formatNumber, formatPercent} from '../i18n/format_number'; import {getCurrencySymbol} from '../i18n/locale_data_api'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * @ngModule CommonModule * @description * * Transforms a number into a string, * formatted according to locale rules that determine group sizing and * separator, decimal-point character, and other locale-specific * configurations. * * If no parameters are specified, the function rounds off to the nearest value using this * [rounding method](https://en.wikibooks.org/wiki/Arithmetic/Rounding). * The behavior differs from that of the JavaScript ```Math.round()``` function. * In the following case for example, the pipe rounds down where * ```Math.round()``` rounds up: * * ```html * -2.5 | number:'1.0-0' * > -3 * Math.round(-2.5) * > -2 * ``` * * @see `formatNumber()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * ### Example * * <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example> * * @publicApi */ @Pipe({name: 'number'}) export class DecimalPipe implements PipeTransform { constructor(@Inject(LOCALE_ID) private _locale: string) {} /** * @param value The number to be formatted. * @param digitsInfo Decimal representation options, specified by a string * in the following format:<br> * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `0`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `3`. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). */ transform(value: number|string, digitsInfo?: string, locale?: string): string|null; transform(value: null|undefined, digitsInfo?: string, locale?: string): null; transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string|null; transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string |null { if (!isValue(value)) return null; locale = locale || this._locale; try { const num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(DecimalPipe, error.message); } } } /** * @ngModule CommonModule * @description * * Transforms a number to a percentage * string, formatted according to locale rules that determine group sizing and * separator, decimal-point character, and other locale-specific * configurations. * * @see `formatPercent()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example> * * @publicApi */ @Pipe({name: 'percent'}) export class PercentPipe implements PipeTransform { constructor(@Inject(LOCALE_ID) private _locale: string) {} /** * * @param value The number to be formatted as a percentage. * @param digitsInfo Decimal representation options, specified by a string * in the following format:<br> * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `0`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `0`. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). */ transform(value: number|string, digitsInfo?: string, locale?: string): string|null; transform(value: null|undefined, digitsInfo?: string, locale?: string): null; transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string|null; transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string |null { if (!isValue(value)) return null; locale = locale || this._locale; try { const num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(PercentPipe, error.message); } } } /** * @ngModule CommonModule * @description * * Transforms a number to a currency string, formatted according to locale rules * that determine group sizing and separator, decimal-point character, * and other locale-specific configurations. * * {@a currency-code-deprecation} * <div class="alert is-helpful"> * * **Deprecation notice:** * * The default currency code is currently always `USD` but this is deprecated from v9. * * **In v11 the default currency code will be taken from the current locale identified by * the `LOCAL_ID` token. See the [i18n guide](guide/i18n#setting-up-the-locale-of-your-app) for * more information.** * * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in * your application `NgModule`: * * ```ts * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'} * ``` * * </div> * * @see `getCurrencySymbol()` * @see `formatCurrency()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example> * * @publicApi */ @Pipe({name: 'currency'}) export class CurrencyPipe implements PipeTransform { constructor( @Inject(LOCALE_ID) private _locale: string, @Inject(DEFAULT_CURRENCY_CODE) private _defaultCurrencyCode: string = 'USD') {} /** * * @param value The number to be formatted as currency. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, * such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be * configured using the `DEFAULT_CURRENCY_CODE` injection token. * @param display The format for the currency indicator. One of the following: * - `code`: Show the code (such as `USD`). * - `symbol`(default): Show the symbol (such as `$`). * - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their * currency. * For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the * locale has no narrow symbol, uses the standard symbol for the locale. * - String: Use the given string value instead of a code or a symbol. * For example, an empty string will suppress the currency & symbol. * - Boolean (marked deprecated in v5): `true` for symbol and false for `code`. * * @param digitsInfo Decimal representation options, specified by a string * in the following format:<br> * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `2`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `2`. * If not provided, the number will be formatted with the proper amount of digits, * depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies. * For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). */ transform( value: number|string, currencyCode?: string, display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string, locale?: string): string|null; transform( value: null|undefined, currencyCode?: string, display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string, locale?: string): null; transform( value: number|string|null|undefined, currencyCode?: string, display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string, locale?: string): string|null; transform( value: number|string|null|undefined, currencyCode?: string, display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string, locale?: string): string|null { if (!isValue(value)) return null; locale = locale || this._locale; if (typeof display === 'boolean') { if (<any>console && <any>console.warn) { console.warn( `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`); } display = display ? 'symbol' : 'code'; } let currency: string = currencyCode || this._defaultCurrencyCode; if (display !== 'code') { if (display === 'symbol' || display === 'symbol-narrow') { currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale); } else { currency = display; } } try { const num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { throw invalidPipeArgumentError(CurrencyPipe, error.message); } } } function isValue(value: number|string|null|undefined): value is number|string { return !(value == null || value === '' || value !== value); } /** * Transforms a string into a number (if needed). */ function strToNumber(value: number|string): number { // Convert strings to numbers if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) { return Number(value); } if (typeof value !== 'number') { throw new Error(`${value} is not a number`); } return value; }
packages/common/src/pipes/number_pipe.ts
1
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.0006208878476172686, 0.0001908067788463086, 0.0001621261762920767, 0.00017038403893820941, 0.00008646085188956931 ]
{ "id": 1, "code_window": [ " * the iteration index and the associated node data.\n", " */\n", " @Input()\n", " set ngForTrackBy(fn: TrackByFunction<T>) {\n", " if (isDevMode() && fn != null && typeof fn !== 'function') {\n", " // TODO(vicb): use a log service once there is a public one available\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 161 }
/** * @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.io/license */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <select formControlName="state"> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ form.value | json }}</p> <!-- {state: {name: 'New York', abbrev: 'NY'} } --> `, }) export class ReactiveSelectComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; form = new FormGroup({ state: new FormControl(this.states[3]), }); } // #enddocregion
packages/examples/forms/ts/reactiveSelectControl/reactive_select_control_example.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017755762382876128, 0.00017513327475171536, 0.00017189346544910222, 0.0001749067014316097, 0.0000020372692688397365 ]
{ "id": 1, "code_window": [ " * the iteration index and the associated node data.\n", " */\n", " @Input()\n", " set ngForTrackBy(fn: TrackByFunction<T>) {\n", " if (isDevMode() && fn != null && typeof fn !== 'function') {\n", " // TODO(vicb): use a log service once there is a public one available\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 161 }
// #docplaster // #docregion import-http import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; // #enddocregion import-http @Injectable({ providedIn: 'root' }) // #docregion props, methods, inject-http, get-shipping export class CartService { items = []; // #enddocregion props, methods constructor( private http: HttpClient ) {} // #enddocregion inject-http // #docregion methods addToCart(product) { this.items.push(product); } getItems() { return this.items; } clearCart() { this.items = []; return this.items; } // #enddocregion methods getShippingPrices() { return this.http.get('/assets/shipping.json'); } // #docregion props, methods, inject-http }
aio/content/examples/getting-started/src/app/cart.service.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017685808415990323, 0.00017220953304786235, 0.00016584589320700616, 0.00017306706286035478, 0.000004061329946125625 ]
{ "id": 1, "code_window": [ " * the iteration index and the associated node data.\n", " */\n", " @Input()\n", " set ngForTrackBy(fn: TrackByFunction<T>) {\n", " if (isDevMode() && fn != null && typeof fn !== 'function') {\n", " // TODO(vicb): use a log service once there is a public one available\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {\n" ], "file_path": "packages/common/src/directives/ng_for_of.ts", "type": "replace", "edit_start_line_idx": 161 }
/** * @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.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { 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 default [ 'ar-SS', [['ص', 'م'], u, u], [['ص', 'م'], u, ['صباحًا', 'مساءً']], [ ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'], ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], u, ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'] ], u, [ ['ي', 'ف', 'م', 'أ', 'و', 'ن', 'ل', 'غ', 'س', 'ك', 'ب', 'د'], [ 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر' ], u ], u, [['ق.م', 'م'], u, ['قبل الميلاد', 'ميلادي']], 1, [6, 0], ['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/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], ['.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'ليس رقمًا', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'SSP', '£', 'جنيه جنوب السودان', { 'AED': ['د.إ.\u200f'], 'ARS': [u, 'AR$'], 'AUD': ['AU$'], 'BBD': [u, 'BB$'], 'BHD': ['د.ب.\u200f'], 'BMD': [u, 'BM$'], 'BND': [u, 'BN$'], 'BSD': [u, 'BS$'], 'BZD': [u, 'BZ$'], 'CAD': ['CA$'], 'CLP': [u, 'CL$'], 'CNY': ['CN¥'], 'COP': [u, 'CO$'], 'CUP': [u, 'CU$'], 'DOP': [u, 'DO$'], 'DZD': ['د.ج.\u200f'], 'EGP': ['ج.م.\u200f', 'E£'], 'FJD': [u, 'FJ$'], 'GBP': ['GB£', 'UK£'], 'GYD': [u, 'GY$'], 'HKD': ['HK$'], 'IQD': ['د.ع.\u200f'], 'IRR': ['ر.إ.'], 'JMD': [u, 'JM$'], 'JOD': ['د.أ.\u200f'], 'JPY': ['JP¥'], 'KWD': ['د.ك.\u200f'], 'KYD': [u, 'KY$'], 'LBP': ['ل.ل.\u200f', 'L£'], 'LRD': [u, '$LR'], 'LYD': ['د.ل.\u200f'], 'MAD': ['د.م.\u200f'], 'MRU': ['أ.م.'], 'MXN': ['MX$'], 'NZD': ['NZ$'], 'OMR': ['ر.ع.\u200f'], 'QAR': ['ر.ق.\u200f'], 'SAR': ['ر.س.\u200f'], 'SBD': [u, 'SB$'], 'SDD': ['د.س.\u200f'], 'SDG': ['ج.س.'], 'SRD': [u, 'SR$'], 'SSP': ['£'], 'SYP': ['ل.س.\u200f', '£'], 'THB': ['฿'], 'TND': ['د.ت.\u200f'], 'TTD': [u, 'TT$'], 'TWD': ['NT$'], 'USD': ['US$'], 'UYU': [u, 'UY$'], 'XXX': ['***'], 'YER': ['ر.ي.\u200f'] }, 'rtl', plural ];
packages/common/locales/ar-SS.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017680160817690194, 0.00017284184286836535, 0.00016533260350115597, 0.00017492320330347866, 0.000003946385731978808 ]
{ "id": 2, "code_window": [ " if (!isValue(value)) return null;\n", "\n", " locale = locale || this._locale;\n", "\n", " if (typeof display === 'boolean') {\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n", " `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".`);\n", " }\n", " display = display ? 'symbol' : 'code';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {\n" ], "file_path": "packages/common/src/pipes/number_pipe.ts", "type": "replace", "edit_start_line_idx": 243 }
/** * @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.io/license */ import {Directive, DoCheck, EmbeddedViewRef, Input, isDevMode, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef} from '@angular/core'; /** * @publicApi */ export class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> { constructor(public $implicit: T, public ngForOf: U, public index: number, public count: number) {} get first(): boolean { return this.index === 0; } get last(): boolean { return this.index === this.count - 1; } get even(): boolean { return this.index % 2 === 0; } get odd(): boolean { return !this.even; } } /** * A [structural directive](guide/structural-directives) that renders * a template for each item in a collection. * The directive is placed on an element, which becomes the parent * of the cloned templates. * * The `ngForOf` directive is generally used in the * [shorthand form](guide/structural-directives#the-asterisk--prefix) `*ngFor`. * In this form, the template to be rendered for each iteration is the content * of an anchor element containing the directive. * * The following example shows the shorthand syntax with some options, * contained in an `<li>` element. * * ``` * <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> * ``` * * The shorthand form expands into a long form that uses the `ngForOf` selector * on an `<ng-template>` element. * The content of the `<ng-template>` element is the `<li>` element that held the * short-form directive. * * Here is the expanded version of the short-form example. * * ``` * <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> * <li>...</li> * </ng-template> * ``` * * Angular automatically expands the shorthand syntax as it compiles the template. * The context for each embedded view is logically merged to the current component * context according to its lexical position. * * When using the shorthand syntax, Angular allows only [one structural directive * on an element](guide/structural-directives#one-structural-directive-per-host-element). * If you want to iterate conditionally, for example, * put the `*ngIf` on a container element that wraps the `*ngFor` element. * For futher discussion, see * [Structural Directives](guide/structural-directives#one-per-element). * * @usageNotes * * ### Local variables * * `NgForOf` provides exported values that can be aliased to local variables. * For example: * * ``` * <li *ngFor="let user of users; index as i; first as isFirst"> * {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> * </li> * ``` * * The following exported values can be aliased to local variables: * * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`). * - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe (`userStreams | * async`). * - `index: number`: The index of the current item in the iterable. * - `count: number`: The length of the iterable. * - `first: boolean`: True when the item is the first item in the iterable. * - `last: boolean`: True when the item is the last item in the iterable. * - `even: boolean`: True when the item has an even index in the iterable. * - `odd: boolean`: True when the item has an odd index in the iterable. * * ### Change propagation * * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * Angular uses object identity to track insertions and deletions within the iterator and reproduce * those changes in the DOM. This has important implications for animations and any stateful * controls that are present, such as `<input>` elements that accept user input. Inserted rows can * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state * such as user input. * For more on animations, see [Transitions and Triggers](guide/transition-and-triggers). * * The identities of elements in the iterator can change while the data does not. * This can happen, for example, if the iterator is produced from an RPC to the server, and that * RPC is re-run. Even if the data hasn't changed, the second response produces objects with * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old * elements were deleted and all new elements inserted). * * To avoid this expensive operation, you can customize the default tracking algorithm. * by supplying the `trackBy` option to `NgForOf`. * `trackBy` takes a function that has two arguments: `index` and `item`. * If `trackBy` is given, Angular tracks changes by the return value of the function. * * @see [Structural Directives](guide/structural-directives) * @ngModule CommonModule * @publicApi */ @Directive({selector: '[ngFor][ngForOf]'}) export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck { /** * The value of the iterable expression, which can be used as a * [template input variable](guide/structural-directives#template-input-variable). */ @Input() set ngForOf(ngForOf: U&NgIterable<T>|undefined|null) { this._ngForOf = ngForOf; this._ngForOfDirty = true; } /** * A function that defines how to track changes for items in the iterable. * * When items are added, moved, or removed in the iterable, * the directive must re-render the appropriate DOM nodes. * To minimize churn in the DOM, only nodes that have changed * are re-rendered. * * By default, the change detector assumes that * the object instance identifies the node in the iterable. * When this function is supplied, the directive uses * the result of calling this function to identify the item node, * rather than the identity of the object itself. * * The function receives two inputs, * the iteration index and the associated node data. */ @Input() set ngForTrackBy(fn: TrackByFunction<T>) { if (isDevMode() && fn != null && typeof fn !== 'function') { // TODO(vicb): use a log service once there is a public one available if (<any>console && <any>console.warn) { console.warn( `trackBy must be a function, but received ${JSON.stringify(fn)}. ` + `See https://angular.io/api/common/NgForOf#change-propagation for more information.`); } } this._trackByFn = fn; } get ngForTrackBy(): TrackByFunction<T> { return this._trackByFn; } private _ngForOf: U|undefined|null = null; private _ngForOfDirty: boolean = true; private _differ: IterableDiffer<T>|null = null; // TODO(issue/24571): remove '!'. private _trackByFn!: TrackByFunction<T>; constructor( private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForOfContext<T, U>>, private _differs: IterableDiffers) {} /** * A reference to the template that is stamped out for each item in the iterable. * @see [template reference variable](guide/template-reference-variables) */ @Input() set ngForTemplate(value: TemplateRef<NgForOfContext<T, U>>) { // TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1 // The current type is too restrictive; a template that just uses index, for example, // should be acceptable. if (value) { this._template = value; } } /** * Applies the changes when needed. */ ngDoCheck(): void { if (this._ngForOfDirty) { this._ngForOfDirty = false; // React on ngForOf changes only once all inputs have been initialized const value = this._ngForOf; if (!this._differ && value) { try { this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch { throw new Error(`Cannot find a differ supporting object '${value}' of type '${ getTypeName(value)}'. NgFor only supports binding to Iterables such as Arrays.`); } } } if (this._differ) { const changes = this._differ.diff(this._ngForOf); if (changes) this._applyChanges(changes); } } private _applyChanges(changes: IterableChanges<T>) { const insertTuples: RecordViewTuple<T, U>[] = []; changes.forEachOperation( (item: IterableChangeRecord<any>, adjustedPreviousIndex: number|null, currentIndex: number|null) => { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". const view = this._viewContainer.createEmbeddedView( this._template, new NgForOfContext<T, U>(null!, this._ngForOf!, -1, -1), currentIndex === null ? undefined : currentIndex); const tuple = new RecordViewTuple<T, U>(item, view); insertTuples.push(tuple); } else if (currentIndex == null) { this._viewContainer.remove( adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { const view = this._viewContainer.get(adjustedPreviousIndex)!; this._viewContainer.move(view, currentIndex); const tuple = new RecordViewTuple(item, <EmbeddedViewRef<NgForOfContext<T, U>>>view); insertTuples.push(tuple); } }); for (let i = 0; i < insertTuples.length; i++) { this._perViewChange(insertTuples[i].view, insertTuples[i].record); } for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>this._viewContainer.get(i); viewRef.context.index = i; viewRef.context.count = ilen; viewRef.context.ngForOf = this._ngForOf!; } changes.forEachIdentityChange((record: any) => { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>this._viewContainer.get(record.currentIndex); viewRef.context.$implicit = record.item; }); } private _perViewChange( view: EmbeddedViewRef<NgForOfContext<T, U>>, record: IterableChangeRecord<any>) { view.context.$implicit = record.item; } /** * Asserts the correct type of the context for the template that `NgForOf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgForOf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard<T, U extends NgIterable<T>>(dir: NgForOf<T, U>, ctx: any): ctx is NgForOfContext<T, U> { return true; } } class RecordViewTuple<T, U extends NgIterable<T>> { constructor(public record: any, public view: EmbeddedViewRef<NgForOfContext<T, U>>) {} } function getTypeName(type: any): string { return type['name'] || typeof type; }
packages/common/src/directives/ng_for_of.ts
1
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.0013096611946821213, 0.0002056312223430723, 0.00015937168791424483, 0.00016777170822024345, 0.0002050523180514574 ]
{ "id": 2, "code_window": [ " if (!isValue(value)) return null;\n", "\n", " locale = locale || this._locale;\n", "\n", " if (typeof display === 'boolean') {\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n", " `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".`);\n", " }\n", " display = display ? 'symbol' : 'code';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {\n" ], "file_path": "packages/common/src/pipes/number_pipe.ts", "type": "replace", "edit_start_line_idx": 243 }
import { browser, by, element } from 'protractor'; describe('Component Communication Cookbook Tests', () => { beforeEach(() => browser.get(browser.baseUrl)); describe('Parent-to-child communication', () => { // #docregion parent-to-child // ... const heroNames = ['Dr IQ', 'Magneta', 'Bombasto']; const masterName = 'Master'; it('should pass properties to children properly', async () => { const parent = element(by.tagName('app-hero-parent')); const heroes = parent.all(by.tagName('app-hero-child')); for (let i = 0; i < heroNames.length; i++) { const childTitle = await heroes.get(i).element(by.tagName('h3')).getText(); const childDetail = await heroes.get(i).element(by.tagName('p')).getText(); expect(childTitle).toEqual(heroNames[i] + ' says:'); expect(childDetail).toContain(masterName); } }); // ... // #enddocregion parent-to-child }); describe('Parent-to-child communication with setter', () => { // #docregion parent-to-child-setter // ... it('should display trimmed, non-empty names', async () => { const nonEmptyNameIndex = 0; const nonEmptyName = '"Dr IQ"'; const parent = element(by.tagName('app-name-parent')); const hero = parent.all(by.tagName('app-name-child')).get(nonEmptyNameIndex); const displayName = await hero.element(by.tagName('h3')).getText(); expect(displayName).toEqual(nonEmptyName); }); it('should replace empty name with default name', async () => { const emptyNameIndex = 1; const defaultName = '"<no name set>"'; const parent = element(by.tagName('app-name-parent')); const hero = parent.all(by.tagName('app-name-child')).get(emptyNameIndex); const displayName = await hero.element(by.tagName('h3')).getText(); expect(displayName).toEqual(defaultName); }); // ... // #enddocregion parent-to-child-setter }); describe('Parent-to-child communication with ngOnChanges', () => { // #docregion parent-to-child-onchanges // ... // Test must all execute in this exact order it('should set expected initial values', async () => { const actual = await getActual(); const initialLabel = 'Version 1.23'; const initialLog = 'Initial value of major set to 1, Initial value of minor set to 23'; expect(actual.label).toBe(initialLabel); expect(actual.count).toBe(1); expect(await actual.logs.get(0).getText()).toBe(initialLog); }); it('should set expected values after clicking \'Minor\' twice', async () => { const repoTag = element(by.tagName('app-version-parent')); const newMinorButton = repoTag.all(by.tagName('button')).get(0); await newMinorButton.click(); await newMinorButton.click(); const actual = await getActual(); const labelAfter2Minor = 'Version 1.25'; const logAfter2Minor = 'minor changed from 24 to 25'; expect(actual.label).toBe(labelAfter2Minor); expect(actual.count).toBe(3); expect(await actual.logs.get(2).getText()).toBe(logAfter2Minor); }); it('should set expected values after clicking \'Major\' once', async () => { const repoTag = element(by.tagName('app-version-parent')); const newMajorButton = repoTag.all(by.tagName('button')).get(1); await newMajorButton.click(); const actual = await getActual(); const labelAfterMajor = 'Version 2.0'; const logAfterMajor = 'major changed from 1 to 2, minor changed from 23 to 0'; expect(actual.label).toBe(labelAfterMajor); expect(actual.count).toBe(2); expect(await actual.logs.get(1).getText()).toBe(logAfterMajor); }); async function getActual() { const versionTag = element(by.tagName('app-version-child')); const label = await versionTag.element(by.tagName('h3')).getText(); const ul = versionTag.element((by.tagName('ul'))); const logs = ul.all(by.tagName('li')); return { label, logs, count: await logs.count(), }; } // ... // #enddocregion parent-to-child-onchanges }); describe('Child-to-parent communication', () => { // #docregion child-to-parent // ... it('should not emit the event initially', async () => { const voteLabel = element(by.tagName('app-vote-taker')).element(by.tagName('h3')); expect(await voteLabel.getText()).toBe('Agree: 0, Disagree: 0'); }); it('should process Agree vote', async () => { const voteLabel = element(by.tagName('app-vote-taker')).element(by.tagName('h3')); const agreeButton1 = element.all(by.tagName('app-voter')).get(0) .all(by.tagName('button')).get(0); await agreeButton1.click(); expect(await voteLabel.getText()).toBe('Agree: 1, Disagree: 0'); }); it('should process Disagree vote', async () => { const voteLabel = element(by.tagName('app-vote-taker')).element(by.tagName('h3')); const agreeButton1 = element.all(by.tagName('app-voter')).get(1) .all(by.tagName('button')).get(1); await agreeButton1.click(); expect(await voteLabel.getText()).toBe('Agree: 0, Disagree: 1'); }); // ... // #enddocregion child-to-parent }); describe('Parent calls child via local var', () => { countDownTimerTests('app-countdown-parent-lv'); }); describe('Parent calls ViewChild', () => { countDownTimerTests('app-countdown-parent-vc'); }); function countDownTimerTests(parentTag: string) { // #docregion countdown-timer-tests // ... // The tests trigger periodic asynchronous operations (via `setInterval()`), which will prevent // the app from stabilizing. See https://angular.io/api/core/ApplicationRef#is-stable-examples // for more details. // To allow the tests to complete, we will disable automatically waiting for the Angular app to // stabilize. beforeEach(() => browser.waitForAngularEnabled(false)); afterEach(() => browser.waitForAngularEnabled(true)); it('timer and parent seconds should match', async () => { const parent = element(by.tagName(parentTag)); const startButton = parent.element(by.buttonText('Start')); const seconds = parent.element(by.className('seconds')); const timer = parent.element(by.tagName('app-countdown-timer')); await startButton.click(); // Wait for `<app-countdown-timer>` to be populated with any text. await browser.wait(() => timer.getText(), 2000); expect(await timer.getText()).toContain(await seconds.getText()); }); it('should stop the countdown', async () => { const parent = element(by.tagName(parentTag)); const startButton = parent.element(by.buttonText('Start')); const stopButton = parent.element(by.buttonText('Stop')); const timer = parent.element(by.tagName('app-countdown-timer')); await startButton.click(); expect(await timer.getText()).not.toContain('Holding'); await stopButton.click(); expect(await timer.getText()).toContain('Holding'); }); // ... // #enddocregion countdown-timer-tests } describe('Parent and children communicate via a service', () => { // #docregion bidirectional-service // ... it('should announce a mission', async () => { const missionControl = element(by.tagName('app-mission-control')); const announceButton = missionControl.all(by.tagName('button')).get(0); const history = missionControl.all(by.tagName('li')); await announceButton.click(); expect(await history.count()).toBe(1); expect(await history.get(0).getText()).toMatch(/Mission.* announced/); }); it('should confirm the mission by Lovell', async () => { await testConfirmMission(1, 'Lovell'); }); it('should confirm the mission by Haise', async () => { await testConfirmMission(3, 'Haise'); }); it('should confirm the mission by Swigert', async () => { await testConfirmMission(2, 'Swigert'); }); async function testConfirmMission(buttonIndex: number, astronaut: string) { const missionControl = element(by.tagName('app-mission-control')); const announceButton = missionControl.all(by.tagName('button')).get(0); const confirmButton = missionControl.all(by.tagName('button')).get(buttonIndex); const history = missionControl.all(by.tagName('li')); await announceButton.click(); await confirmButton.click(); expect(await history.count()).toBe(2); expect(await history.get(1).getText()).toBe(`${astronaut} confirmed the mission`); } // ... // #enddocregion bidirectional-service }); });
aio/content/examples/component-interaction/e2e/src/app.e2e-spec.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.0001770656235748902, 0.0001733903045533225, 0.00016737465921323746, 0.00017340967315249145, 0.0000021334419670893112 ]
{ "id": 2, "code_window": [ " if (!isValue(value)) return null;\n", "\n", " locale = locale || this._locale;\n", "\n", " if (typeof display === 'boolean') {\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n", " `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".`);\n", " }\n", " display = display ? 'symbol' : 'code';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {\n" ], "file_path": "packages/common/src/pipes/number_pipe.ts", "type": "replace", "edit_start_line_idx": 243 }
import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[dir]'}) class WithInput { @Input() dir: string = ''; } @Component({ selector: 'my-app', template: '<ng-template *ngIf="true" dir="{{ message }}"></ng-template>', }) export class TestComp { message = 'Hello'; }
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_template_interpolated_prop_with_structural_directive.ts
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00017418786592315882, 0.00017305205983575433, 0.00017191625374834985, 0.00017305205983575433, 0.0000011358060874044895 ]
{ "id": 2, "code_window": [ " if (!isValue(value)) return null;\n", "\n", " locale = locale || this._locale;\n", "\n", " if (typeof display === 'boolean') {\n", " if (<any>console && <any>console.warn) {\n", " console.warn(\n", " `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".`);\n", " }\n", " display = display ? 'symbol' : 'code';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {\n" ], "file_path": "packages/common/src/pipes/number_pipe.ts", "type": "replace", "edit_start_line_idx": 243 }
Provides infrastructure for the rendering of animations in supported browsers.
packages/platform-browser/animations/PACKAGE.md
0
https://github.com/angular/angular/commit/f022efa06f0ef3379d7bcdb5ecadf44daa366818
[ 0.00015943279140628874, 0.00015943279140628874, 0.00015943279140628874, 0.00015943279140628874, 0 ]
{ "id": 0, "code_window": [ " }\n", " }\n", "};\n", "\n", "const browserNameMap = {\n", " android: \"android\",\n", " chrome: \"chrome\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " and_chr: \"chrome\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 32 }
// @flow import browserslist from "browserslist"; import invariant from "invariant"; import semver from "semver"; import { semverify, isUnreleasedVersion, getLowestUnreleased, getValues, findSuggestion, } from "./utils"; import { objectToBrowserslist } from "./normalize-options"; import browserModulesData from "../data/built-in-modules.json"; import { TargetNames } from "./options"; import type { Targets } from "./types"; const browserslistDefaults = browserslist.defaults; const validateTargetNames = (validTargets, targets) => { for (const target in targets) { if (!TargetNames[target]) { const validOptions = getValues(TargetNames); throw new Error( `Invalid Option: '${target}' is not a valid target Maybe you meant to use '${findSuggestion(validOptions, target)}'?`, ); } } }; const browserNameMap = { android: "android", chrome: "chrome", and_chr: "chrome", edge: "edge", firefox: "firefox", ie: "ie", ios_saf: "ios", safari: "safari", node: "node", }; export const isBrowsersQueryValid = ( browsers: string | Array<string> | Targets, ): boolean => typeof browsers === "string" || Array.isArray(browsers); const validateBrowsers = browsers => { invariant( typeof browsers === "undefined" || isBrowsersQueryValid(browsers), `Invalid Option: '${browsers}' is not a valid browserslist query`, ); return browsers; }; export const semverMin = (first: ?string, second: string): string => { return first && semver.lt(first, second) ? first : second; }; const mergeBrowsers = (fromQuery: Targets, fromTarget: Targets) => { return Object.keys(fromTarget).reduce((queryObj, targKey) => { if (targKey !== TargetNames.browsers) { queryObj[targKey] = fromTarget[targKey]; } return queryObj; }, fromQuery); }; const getLowestVersions = (browsers: Array<string>): Targets => { return browsers.reduce((all: Object, browser: string): Object => { const [browserName, browserVersion] = browser.split(" "); const normalizedBrowserName = browserNameMap[browserName]; if (!normalizedBrowserName) { return all; } try { // Browser version can return as "10.0-10.2" const splitVersion = browserVersion.split("-")[0].toLowerCase(); const isSplitUnreleased = isUnreleasedVersion(splitVersion, browserName); if (!all[normalizedBrowserName]) { all[normalizedBrowserName] = isSplitUnreleased ? splitVersion : semverify(splitVersion); return all; } const version = all[normalizedBrowserName]; const isUnreleased = isUnreleasedVersion(version, browserName); if (isUnreleased && isSplitUnreleased) { all[normalizedBrowserName] = getLowestUnreleased( version, splitVersion, browserName, ); } else if (isUnreleased) { all[normalizedBrowserName] = semverify(splitVersion); } else if (!isUnreleased && !isSplitUnreleased) { const parsedBrowserVersion = semverify(splitVersion); all[normalizedBrowserName] = semverMin(version, parsedBrowserVersion); } } catch (e) {} return all; }, {}); }; const outputDecimalWarning = (decimalTargets: Array<Object>): void => { if (!decimalTargets || !decimalTargets.length) { return; } console.log("Warning, the following targets are using a decimal version:"); console.log(""); decimalTargets.forEach(({ target, value }) => console.log(` ${target}: ${value}`), ); console.log(""); console.log( "We recommend using a string for minor/patch versions to avoid numbers like 6.10", ); console.log("getting parsed as 6.1, which can lead to unexpected behavior."); console.log(""); }; const semverifyTarget = (target, value) => { try { return semverify(value); } catch (error) { throw new Error( `Invalid Option: '${value}' is not a valid value for 'targets.${target}'.`, ); } }; const targetParserMap = { __default: (target, value) => { const version = isUnreleasedVersion(value, target) ? value.toLowerCase() : semverifyTarget(target, value); return [target, version]; }, // Parse `node: true` and `node: "current"` to version node: (target, value) => { const parsed = value === true || value === "current" ? process.versions.node : semverifyTarget(target, value); return [target, parsed]; }, }; type ParsedResult = { targets: Targets, decimalWarnings: Array<Object>, }; const getTargets = (targets: Object = {}, options: Object = {}): Targets => { const targetOpts: Targets = {}; validateTargetNames(targets); // `esmodules` as a target indicates the specific set of browsers supporting ES Modules. // These values OVERRIDE the `browsers` field. if (targets.esmodules) { const supportsESModules = browserModulesData["es6.module"]; targets.browsers = Object.keys(supportsESModules) .map(browser => `${browser} ${supportsESModules[browser]}`) .join(", "); } // Parse browsers target via browserslist const browsersquery = validateBrowsers(targets.browsers); const shouldParseBrowsers = !!targets.browsers; const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !Object.keys(targets).length; if (shouldParseBrowsers || shouldSearchForConfig) { browserslist.defaults = objectToBrowserslist(targets); const browsers = browserslist(browsersquery, { path: options.configPath, }); const queryBrowsers = getLowestVersions(browsers); targets = mergeBrowsers(queryBrowsers, targets); // Reset browserslist defaults browserslist.defaults = browserslistDefaults; } // Parse remaining targets const parsed = Object.keys(targets) .filter(value => value !== TargetNames.esmodules) .sort() .reduce( (results: ParsedResult, target: string): ParsedResult => { if (target !== TargetNames.browsers) { const value = targets[target]; // Warn when specifying minor/patch as a decimal if (typeof value === "number" && value % 1 !== 0) { results.decimalWarnings.push({ target, value }); } // Check if we have a target parser? const parser = targetParserMap[target] || targetParserMap.__default; const [parsedTarget, parsedValue] = parser(target, value); if (parsedValue) { // Merge (lowest wins) results.targets[parsedTarget] = parsedValue; } } return results; }, { targets: targetOpts, decimalWarnings: [], }, ); outputDecimalWarning(parsed.decimalWarnings); return parsed.targets; }; export default getTargets;
packages/babel-preset-env/src/targets-parser.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.9991257786750793, 0.08360567688941956, 0.00016727573529351503, 0.00021952764654997736, 0.27585530281066895 ]
{ "id": 0, "code_window": [ " }\n", " }\n", "};\n", "\n", "const browserNameMap = {\n", " android: \"android\",\n", " chrome: \"chrome\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " and_chr: \"chrome\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 32 }
{ "throws": "Invalid or unexpected token (1:3)" }
packages/babel-parser/test/fixtures/experimental/numeric-separator/invalid-138/options.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00016774564574006945, 0.00016774564574006945, 0.00016774564574006945, 0.00016774564574006945, 0 ]
{ "id": 0, "code_window": [ " }\n", " }\n", "};\n", "\n", "const browserNameMap = {\n", " android: \"android\",\n", " chrome: \"chrome\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " and_chr: \"chrome\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 32 }
var obj = { ["x" + foo]: "heh" };
packages/babel-plugin-transform-computed-properties/test/fixtures/loose/single/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017657365242484957, 0.00017657365242484957, 0.00017657365242484957, 0.00017657365242484957, 0 ]
{ "id": 0, "code_window": [ " }\n", " }\n", "};\n", "\n", "const browserNameMap = {\n", " android: \"android\",\n", " chrome: \"chrome\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " and_chr: \"chrome\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 32 }
function pushElement(e) { return function (c) { c.elements.push(e); return c }; } var value = {}; @pushElement({ kind: "field", placement: "prototype", key: "foo", descriptor: { enumerable: true, configurable: true, writable: true, }, initializer() { return value; } }) class A {} expect(A).not.toHaveProperty("foo"); expect(Object.getOwnPropertyDescriptor(A.prototype, "foo")).toEqual({ enumerable: true, configurable: true, writable: true, value: value, });
packages/babel-plugin-proposal-decorators/test/fixtures/element-descriptors/created-prototype-field/exec.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00018147916125599295, 0.00017397241026628762, 0.0001684457529336214, 0.00017199234571307898, 0.000005501996838574996 ]
{ "id": 1, "code_window": [ " android: \"android\",\n", " chrome: \"chrome\",\n", " and_chr: \"chrome\",\n", " edge: \"edge\",\n", " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 34 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0002409744047326967, 0.00017637173004914075, 0.00016376299026887864, 0.00017139510600827634, 0.000016314803360728547 ]
{ "id": 1, "code_window": [ " android: \"android\",\n", " chrome: \"chrome\",\n", " and_chr: \"chrome\",\n", " edge: \"edge\",\n", " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 34 }
sampleTag`\u{`
packages/babel-parser/test/fixtures/experimental/template-literal-invalid-escapes-tagged/45/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017486317665316164, 0.00017486317665316164, 0.00017486317665316164, 0.00017486317665316164, 0 ]
{ "id": 1, "code_window": [ " android: \"android\",\n", " chrome: \"chrome\",\n", " and_chr: \"chrome\",\n", " edge: \"edge\",\n", " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 34 }
src test *.log
packages/babel-plugin-transform-flow-strip-types/.npmignore
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001748515060171485, 0.0001748515060171485, 0.0001748515060171485, 0.0001748515060171485, 0 ]
{ "id": 1, "code_window": [ " android: \"android\",\n", " chrome: \"chrome\",\n", " and_chr: \"chrome\",\n", " edge: \"edge\",\n", " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 34 }
{ "throws": "Unexpected token, expected \";\" (1:6)" }
packages/babel-parser/test/fixtures/es2015/yield/in-global-scope/options.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001724419416859746, 0.0001724419416859746, 0.0001724419416859746, 0.0001724419416859746, 0 ]
{ "id": 2, "code_window": [ " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n", " safari: \"safari\",\n", " node: \"node\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 39 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00066632084781304, 0.00026107949088327587, 0.00016553892055526376, 0.00018327620637137443, 0.00015066523337736726 ]
{ "id": 2, "code_window": [ " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n", " safari: \"safari\",\n", " node: \"node\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 39 }
opaque type ID = string; opaque type Foo<T> = Bar<T>; opaque type Maybe<T> = _Maybe<T, *>; export opaque type Foo = number; opaque type union = | {type: "A"} | {type: "B"} ; opaque type overloads = & ((x: string) => number) & ((x: number) => string) ;
packages/babel-generator/test/fixtures/flow/opaque-type-alias/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017191821825690567, 0.00017155450768768787, 0.00017119078256655484, 0.00017155450768768787, 3.637178451754153e-7 ]
{ "id": 2, "code_window": [ " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n", " safari: \"safari\",\n", " node: \"node\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 39 }
{ "throws": "Invalid escape sequence in template (1:10)" }
packages/babel-parser/test/fixtures/experimental/template-literal-invalid-escapes-untagged/52/options.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017288200615439564, 0.00017288200615439564, 0.00017288200615439564, 0.00017288200615439564, 0 ]
{ "id": 2, "code_window": [ " firefox: \"firefox\",\n", " ie: \"ie\",\n", " ios_saf: \"ios\",\n", " safari: \"safari\",\n", " node: \"node\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "replace", "edit_start_line_idx": 39 }
//index.js file import { form } from "./export"; function ParentComponent() { return <form.TestComponent />; }
packages/babel-plugin-transform-react-inline-elements/test/fixtures/inline-elements/lowercase-member-expression/input.mjs
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001770651142578572, 0.0001770651142578572, 0.0001770651142578572, 0.0001770651142578572, 0 ]
{ "id": 3, "code_window": [ " node: \"node\",\n", "};\n", "\n", "export const isBrowsersQueryValid = (\n", " browsers: string | Array<string> | Targets,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"opera\",\n", " safari: \"safari\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 41 }
// @flow import browserslist from "browserslist"; import invariant from "invariant"; import semver from "semver"; import { semverify, isUnreleasedVersion, getLowestUnreleased, getValues, findSuggestion, } from "./utils"; import { objectToBrowserslist } from "./normalize-options"; import browserModulesData from "../data/built-in-modules.json"; import { TargetNames } from "./options"; import type { Targets } from "./types"; const browserslistDefaults = browserslist.defaults; const validateTargetNames = (validTargets, targets) => { for (const target in targets) { if (!TargetNames[target]) { const validOptions = getValues(TargetNames); throw new Error( `Invalid Option: '${target}' is not a valid target Maybe you meant to use '${findSuggestion(validOptions, target)}'?`, ); } } }; const browserNameMap = { android: "android", chrome: "chrome", and_chr: "chrome", edge: "edge", firefox: "firefox", ie: "ie", ios_saf: "ios", safari: "safari", node: "node", }; export const isBrowsersQueryValid = ( browsers: string | Array<string> | Targets, ): boolean => typeof browsers === "string" || Array.isArray(browsers); const validateBrowsers = browsers => { invariant( typeof browsers === "undefined" || isBrowsersQueryValid(browsers), `Invalid Option: '${browsers}' is not a valid browserslist query`, ); return browsers; }; export const semverMin = (first: ?string, second: string): string => { return first && semver.lt(first, second) ? first : second; }; const mergeBrowsers = (fromQuery: Targets, fromTarget: Targets) => { return Object.keys(fromTarget).reduce((queryObj, targKey) => { if (targKey !== TargetNames.browsers) { queryObj[targKey] = fromTarget[targKey]; } return queryObj; }, fromQuery); }; const getLowestVersions = (browsers: Array<string>): Targets => { return browsers.reduce((all: Object, browser: string): Object => { const [browserName, browserVersion] = browser.split(" "); const normalizedBrowserName = browserNameMap[browserName]; if (!normalizedBrowserName) { return all; } try { // Browser version can return as "10.0-10.2" const splitVersion = browserVersion.split("-")[0].toLowerCase(); const isSplitUnreleased = isUnreleasedVersion(splitVersion, browserName); if (!all[normalizedBrowserName]) { all[normalizedBrowserName] = isSplitUnreleased ? splitVersion : semverify(splitVersion); return all; } const version = all[normalizedBrowserName]; const isUnreleased = isUnreleasedVersion(version, browserName); if (isUnreleased && isSplitUnreleased) { all[normalizedBrowserName] = getLowestUnreleased( version, splitVersion, browserName, ); } else if (isUnreleased) { all[normalizedBrowserName] = semverify(splitVersion); } else if (!isUnreleased && !isSplitUnreleased) { const parsedBrowserVersion = semverify(splitVersion); all[normalizedBrowserName] = semverMin(version, parsedBrowserVersion); } } catch (e) {} return all; }, {}); }; const outputDecimalWarning = (decimalTargets: Array<Object>): void => { if (!decimalTargets || !decimalTargets.length) { return; } console.log("Warning, the following targets are using a decimal version:"); console.log(""); decimalTargets.forEach(({ target, value }) => console.log(` ${target}: ${value}`), ); console.log(""); console.log( "We recommend using a string for minor/patch versions to avoid numbers like 6.10", ); console.log("getting parsed as 6.1, which can lead to unexpected behavior."); console.log(""); }; const semverifyTarget = (target, value) => { try { return semverify(value); } catch (error) { throw new Error( `Invalid Option: '${value}' is not a valid value for 'targets.${target}'.`, ); } }; const targetParserMap = { __default: (target, value) => { const version = isUnreleasedVersion(value, target) ? value.toLowerCase() : semverifyTarget(target, value); return [target, version]; }, // Parse `node: true` and `node: "current"` to version node: (target, value) => { const parsed = value === true || value === "current" ? process.versions.node : semverifyTarget(target, value); return [target, parsed]; }, }; type ParsedResult = { targets: Targets, decimalWarnings: Array<Object>, }; const getTargets = (targets: Object = {}, options: Object = {}): Targets => { const targetOpts: Targets = {}; validateTargetNames(targets); // `esmodules` as a target indicates the specific set of browsers supporting ES Modules. // These values OVERRIDE the `browsers` field. if (targets.esmodules) { const supportsESModules = browserModulesData["es6.module"]; targets.browsers = Object.keys(supportsESModules) .map(browser => `${browser} ${supportsESModules[browser]}`) .join(", "); } // Parse browsers target via browserslist const browsersquery = validateBrowsers(targets.browsers); const shouldParseBrowsers = !!targets.browsers; const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !Object.keys(targets).length; if (shouldParseBrowsers || shouldSearchForConfig) { browserslist.defaults = objectToBrowserslist(targets); const browsers = browserslist(browsersquery, { path: options.configPath, }); const queryBrowsers = getLowestVersions(browsers); targets = mergeBrowsers(queryBrowsers, targets); // Reset browserslist defaults browserslist.defaults = browserslistDefaults; } // Parse remaining targets const parsed = Object.keys(targets) .filter(value => value !== TargetNames.esmodules) .sort() .reduce( (results: ParsedResult, target: string): ParsedResult => { if (target !== TargetNames.browsers) { const value = targets[target]; // Warn when specifying minor/patch as a decimal if (typeof value === "number" && value % 1 !== 0) { results.decimalWarnings.push({ target, value }); } // Check if we have a target parser? const parser = targetParserMap[target] || targetParserMap.__default; const [parsedTarget, parsedValue] = parser(target, value); if (parsedValue) { // Merge (lowest wins) results.targets[parsedTarget] = parsedValue; } } return results; }, { targets: targetOpts, decimalWarnings: [], }, ); outputDecimalWarning(parsed.decimalWarnings); return parsed.targets; }; export default getTargets;
packages/babel-preset-env/src/targets-parser.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.9982550740242004, 0.04807911813259125, 0.00016600773960817605, 0.0003774679498746991, 0.19840940833091736 ]
{ "id": 3, "code_window": [ " node: \"node\",\n", "};\n", "\n", "export const isBrowsersQueryValid = (\n", " browsers: string | Array<string> | Targets,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"opera\",\n", " safari: \"safari\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 41 }
{ "type": "File", "start": 0, "end": 23, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 23 } }, "program": { "type": "Program", "start": 0, "end": 23, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 23 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "VariableDeclaration", "start": 0, "end": 23, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 23 } }, "declarations": [ { "type": "VariableDeclarator", "start": 4, "end": 22, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 22 } }, "id": { "type": "Identifier", "start": 4, "end": 10, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 10 }, "identifierName": "source" }, "name": "source" }, "init": { "type": "StringLiteral", "start": 13, "end": 22, "loc": { "start": { "line": 1, "column": 13 }, "end": { "line": 1, "column": 22 } }, "extra": { "rawValue": "\\u0061", "raw": "'\\\\u0061'" }, "value": "\\u0061" } } ], "kind": "var" } ], "directives": [] } }
packages/babel-parser/test/fixtures/esprima/statement-expression/migrated_0002/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017389431013725698, 0.00017064731218852103, 0.00016771189984865487, 0.00017023835971485823, 0.0000018831927945939242 ]
{ "id": 3, "code_window": [ " node: \"node\",\n", "};\n", "\n", "export const isBrowsersQueryValid = (\n", " browsers: string | Array<string> | Targets,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"opera\",\n", " safari: \"safari\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 41 }
{ "type": "File", "start": 0, "end": 22, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 22 } }, "program": { "type": "Program", "start": 0, "end": 22, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 22 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "WithStatement", "start": 0, "end": 22, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 22 } }, "object": { "type": "Identifier", "start": 6, "end": 7, "loc": { "start": { "line": 1, "column": 6 }, "end": { "line": 1, "column": 7 }, "identifierName": "x" }, "name": "x" }, "body": { "type": "BlockStatement", "start": 9, "end": 22, "loc": { "start": { "line": 1, "column": 9 }, "end": { "line": 1, "column": 22 } }, "body": [ { "type": "ExpressionStatement", "start": 11, "end": 20, "loc": { "start": { "line": 1, "column": 11 }, "end": { "line": 1, "column": 20 } }, "expression": { "type": "AssignmentExpression", "start": 11, "end": 20, "loc": { "start": { "line": 1, "column": 11 }, "end": { "line": 1, "column": 20 } }, "operator": "=", "left": { "type": "Identifier", "start": 11, "end": 14, "loc": { "start": { "line": 1, "column": 11 }, "end": { "line": 1, "column": 14 }, "identifierName": "foo" }, "name": "foo" }, "right": { "type": "Identifier", "start": 17, "end": 20, "loc": { "start": { "line": 1, "column": 17 }, "end": { "line": 1, "column": 20 }, "identifierName": "bar" }, "name": "bar" } } } ], "directives": [] } } ], "directives": [] } }
packages/babel-parser/test/fixtures/esprima/statement-with/migrated_0002/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001771678071236238, 0.00017039920203387737, 0.00016750652866903692, 0.0001697350962786004, 0.0000024257910808955785 ]
{ "id": 3, "code_window": [ " node: \"node\",\n", "};\n", "\n", "export const isBrowsersQueryValid = (\n", " browsers: string | Array<string> | Targets,\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"opera\",\n", " safari: \"safari\",\n" ], "file_path": "packages/babel-preset-env/src/targets-parser.js", "type": "add", "edit_start_line_idx": 41 }
class C { static f(); public static f(); protected static f(); private static f(); }
packages/babel-generator/test/fixtures/typescript/class-static/output.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017056218348443508, 0.00017056218348443508, 0.00017056218348443508, 0.00017056218348443508, 0 ]
{ "id": 4, "code_window": [ "\n", " it(\"works with current node version and string type browsers\", () => {\n", " expect(\n", " getTargets({\n", " browsers: \"current node, chrome 55\",\n", " }),\n", " ).toEqual({\n", " node: process.versions.node,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " browsers: \"current node, chrome 55, opera 42\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "replace", "edit_start_line_idx": 101 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.09572205692529678, 0.0051862625405192375, 0.0001665283925831318, 0.000346871092915535, 0.017978748306632042 ]
{ "id": 4, "code_window": [ "\n", " it(\"works with current node version and string type browsers\", () => {\n", " expect(\n", " getTargets({\n", " browsers: \"current node, chrome 55\",\n", " }),\n", " ).toEqual({\n", " node: process.versions.node,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " browsers: \"current node, chrome 55, opera 42\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "replace", "edit_start_line_idx": 101 }
"use strict"; var _a = _interopRequireDefault(require("a")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
packages/babel-preset-env/test/fixtures/preset-options/modules-cjs/output.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00016771302034612745, 0.00016771302034612745, 0.00016771302034612745, 0.00016771302034612745, 0 ]
{ "id": 4, "code_window": [ "\n", " it(\"works with current node version and string type browsers\", () => {\n", " expect(\n", " getTargets({\n", " browsers: \"current node, chrome 55\",\n", " }),\n", " ).toEqual({\n", " node: process.versions.node,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " browsers: \"current node, chrome 55, opera 42\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "replace", "edit_start_line_idx": 101 }
function foo() { arr.map(x => x * x); var f = (x, y) => x * y; (function () { return () => this; })(); return { g: () => this } }
packages/babel-plugin-transform-arrow-functions/test/fixtures/arrow-functions/spec/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017809307610150427, 0.00017768426914699376, 0.00017727544764056802, 0.00017768426914699376, 4.0881423046812415e-7 ]
{ "id": 4, "code_window": [ "\n", " it(\"works with current node version and string type browsers\", () => {\n", " expect(\n", " getTargets({\n", " browsers: \"current node, chrome 55\",\n", " }),\n", " ).toEqual({\n", " node: process.versions.node,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " browsers: \"current node, chrome 55, opera 42\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "replace", "edit_start_line_idx": 101 }
{ "throws": "Unexpected token (1:6)" }
packages/babel-parser/test/fixtures/esprima/invalid-syntax/migrated_0117/options.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017298408783972263, 0.00017298408783972263, 0.00017298408783972263, 0.00017298408783972263, 0 ]
{ "id": 5, "code_window": [ " }),\n", " ).toEqual({\n", " node: process.versions.node,\n", " chrome: \"55.0.0\",\n", " });\n", " });\n", "\n", " it(\"does throws on unsupported versions\", () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"42.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 106 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.9938700199127197, 0.04371698573231697, 0.0001628514437470585, 0.00017777751781977713, 0.18931396305561066 ]
{ "id": 5, "code_window": [ " }),\n", " ).toEqual({\n", " node: process.versions.node,\n", " chrome: \"55.0.0\",\n", " });\n", " });\n", "\n", " it(\"does throws on unsupported versions\", () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"42.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 106 }
function fn(){} var args = [1, 2, 3]; var obj = {obj: {fn}}; switch (true){ case true: obj.obj.fn(...args); break; }
packages/babel-plugin-transform-spread/test/fixtures/regression/T6761/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017111195484176278, 0.00017078846576623619, 0.00017046496213879436, 0.00017078846576623619, 3.234963514842093e-7 ]
{ "id": 5, "code_window": [ " }),\n", " ).toEqual({\n", " node: process.versions.node,\n", " chrome: \"55.0.0\",\n", " });\n", " });\n", "\n", " it(\"does throws on unsupported versions\", () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"42.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 106 }
export * from "foo";
packages/babel-generator/test/fixtures/types/ExportSpecifier/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017103235586546361, 0.00017103235586546361, 0.00017103235586546361, 0.00017103235586546361, 0 ]
{ "id": 5, "code_window": [ " }),\n", " ).toEqual({\n", " node: process.versions.node,\n", " chrome: \"55.0.0\",\n", " });\n", " });\n", "\n", " it(\"does throws on unsupported versions\", () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"42.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 106 }
let a = 1; function b() { return a + 1; } expect(b()).toBe(2);
packages/babel-plugin-transform-block-scoping/test/fixtures/pass/call.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00015905106556601822, 0.00015905106556601822, 0.00015905106556601822, 0.00015905106556601822, 0 ]
{ "id": 6, "code_window": [ " }),\n", " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 180 }
// @flow import browserslist from "browserslist"; import invariant from "invariant"; import semver from "semver"; import { semverify, isUnreleasedVersion, getLowestUnreleased, getValues, findSuggestion, } from "./utils"; import { objectToBrowserslist } from "./normalize-options"; import browserModulesData from "../data/built-in-modules.json"; import { TargetNames } from "./options"; import type { Targets } from "./types"; const browserslistDefaults = browserslist.defaults; const validateTargetNames = (validTargets, targets) => { for (const target in targets) { if (!TargetNames[target]) { const validOptions = getValues(TargetNames); throw new Error( `Invalid Option: '${target}' is not a valid target Maybe you meant to use '${findSuggestion(validOptions, target)}'?`, ); } } }; const browserNameMap = { android: "android", chrome: "chrome", and_chr: "chrome", edge: "edge", firefox: "firefox", ie: "ie", ios_saf: "ios", safari: "safari", node: "node", }; export const isBrowsersQueryValid = ( browsers: string | Array<string> | Targets, ): boolean => typeof browsers === "string" || Array.isArray(browsers); const validateBrowsers = browsers => { invariant( typeof browsers === "undefined" || isBrowsersQueryValid(browsers), `Invalid Option: '${browsers}' is not a valid browserslist query`, ); return browsers; }; export const semverMin = (first: ?string, second: string): string => { return first && semver.lt(first, second) ? first : second; }; const mergeBrowsers = (fromQuery: Targets, fromTarget: Targets) => { return Object.keys(fromTarget).reduce((queryObj, targKey) => { if (targKey !== TargetNames.browsers) { queryObj[targKey] = fromTarget[targKey]; } return queryObj; }, fromQuery); }; const getLowestVersions = (browsers: Array<string>): Targets => { return browsers.reduce((all: Object, browser: string): Object => { const [browserName, browserVersion] = browser.split(" "); const normalizedBrowserName = browserNameMap[browserName]; if (!normalizedBrowserName) { return all; } try { // Browser version can return as "10.0-10.2" const splitVersion = browserVersion.split("-")[0].toLowerCase(); const isSplitUnreleased = isUnreleasedVersion(splitVersion, browserName); if (!all[normalizedBrowserName]) { all[normalizedBrowserName] = isSplitUnreleased ? splitVersion : semverify(splitVersion); return all; } const version = all[normalizedBrowserName]; const isUnreleased = isUnreleasedVersion(version, browserName); if (isUnreleased && isSplitUnreleased) { all[normalizedBrowserName] = getLowestUnreleased( version, splitVersion, browserName, ); } else if (isUnreleased) { all[normalizedBrowserName] = semverify(splitVersion); } else if (!isUnreleased && !isSplitUnreleased) { const parsedBrowserVersion = semverify(splitVersion); all[normalizedBrowserName] = semverMin(version, parsedBrowserVersion); } } catch (e) {} return all; }, {}); }; const outputDecimalWarning = (decimalTargets: Array<Object>): void => { if (!decimalTargets || !decimalTargets.length) { return; } console.log("Warning, the following targets are using a decimal version:"); console.log(""); decimalTargets.forEach(({ target, value }) => console.log(` ${target}: ${value}`), ); console.log(""); console.log( "We recommend using a string for minor/patch versions to avoid numbers like 6.10", ); console.log("getting parsed as 6.1, which can lead to unexpected behavior."); console.log(""); }; const semverifyTarget = (target, value) => { try { return semverify(value); } catch (error) { throw new Error( `Invalid Option: '${value}' is not a valid value for 'targets.${target}'.`, ); } }; const targetParserMap = { __default: (target, value) => { const version = isUnreleasedVersion(value, target) ? value.toLowerCase() : semverifyTarget(target, value); return [target, version]; }, // Parse `node: true` and `node: "current"` to version node: (target, value) => { const parsed = value === true || value === "current" ? process.versions.node : semverifyTarget(target, value); return [target, parsed]; }, }; type ParsedResult = { targets: Targets, decimalWarnings: Array<Object>, }; const getTargets = (targets: Object = {}, options: Object = {}): Targets => { const targetOpts: Targets = {}; validateTargetNames(targets); // `esmodules` as a target indicates the specific set of browsers supporting ES Modules. // These values OVERRIDE the `browsers` field. if (targets.esmodules) { const supportsESModules = browserModulesData["es6.module"]; targets.browsers = Object.keys(supportsESModules) .map(browser => `${browser} ${supportsESModules[browser]}`) .join(", "); } // Parse browsers target via browserslist const browsersquery = validateBrowsers(targets.browsers); const shouldParseBrowsers = !!targets.browsers; const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !Object.keys(targets).length; if (shouldParseBrowsers || shouldSearchForConfig) { browserslist.defaults = objectToBrowserslist(targets); const browsers = browserslist(browsersquery, { path: options.configPath, }); const queryBrowsers = getLowestVersions(browsers); targets = mergeBrowsers(queryBrowsers, targets); // Reset browserslist defaults browserslist.defaults = browserslistDefaults; } // Parse remaining targets const parsed = Object.keys(targets) .filter(value => value !== TargetNames.esmodules) .sort() .reduce( (results: ParsedResult, target: string): ParsedResult => { if (target !== TargetNames.browsers) { const value = targets[target]; // Warn when specifying minor/patch as a decimal if (typeof value === "number" && value % 1 !== 0) { results.decimalWarnings.push({ target, value }); } // Check if we have a target parser? const parser = targetParserMap[target] || targetParserMap.__default; const [parsedTarget, parsedValue] = parser(target, value); if (parsedValue) { // Merge (lowest wins) results.targets[parsedTarget] = parsedValue; } } return results; }, { targets: targetOpts, decimalWarnings: [], }, ); outputDecimalWarning(parsed.decimalWarnings); return parsed.targets; }; export default getTargets;
packages/babel-preset-env/src/targets-parser.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0005342529620975256, 0.00018690740398596972, 0.00016611700993962586, 0.00017213067621923983, 0.00007246391760418192 ]
{ "id": 6, "code_window": [ " }),\n", " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 180 }
{ "type": "File", "start": 0, "end": 62, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 62 } }, "program": { "type": "Program", "start": 0, "end": 62, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 62 } }, "sourceType": "module", "interpreter": null, "body": [ { "type": "DeclareModule", "start": 0, "end": 62, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 62 } }, "id": { "type": "StringLiteral", "start": 15, "end": 20, "loc": { "start": { "line": 1, "column": 15 }, "end": { "line": 1, "column": 20 } }, "extra": { "rawValue": "foo", "raw": "\"foo\"" }, "value": "foo" }, "body": { "type": "BlockStatement", "start": 21, "end": 62, "loc": { "start": { "line": 1, "column": 21 }, "end": { "line": 1, "column": 62 } }, "body": [ { "type": "DeclareExportDeclaration", "start": 23, "end": 60, "loc": { "start": { "line": 1, "column": 23 }, "end": { "line": 1, "column": 60 } }, "declaration": { "type": "UnionTypeAnnotation", "start": 46, "end": 59, "loc": { "start": { "line": 1, "column": 46 }, "end": { "line": 1, "column": 59 } }, "types": [ { "type": "NumberTypeAnnotation", "start": 46, "end": 52, "loc": { "start": { "line": 1, "column": 46 }, "end": { "line": 1, "column": 52 } } }, { "type": "StringTypeAnnotation", "start": 53, "end": 59, "loc": { "start": { "line": 1, "column": 53 }, "end": { "line": 1, "column": 59 } } } ] }, "default": true } ] }, "kind": "ES" } ], "directives": [] } }
packages/babel-parser/test/fixtures/flow/declare-export/export-default-union/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017390857101418078, 0.00016961718210950494, 0.00016612255421932787, 0.0001693226513452828, 0.0000027036030587623827 ]
{ "id": 6, "code_window": [ " }),\n", " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 180 }
{ "type": "File", "start": 0, "end": 13, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 13 } }, "program": { "type": "Program", "start": 0, "end": 13, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 13 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 13, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 13 } }, "expression": { "type": "BinaryExpression", "start": 0, "end": 13, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 13 } }, "left": { "type": "BinaryExpression", "start": 1, "end": 8, "loc": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 8 } }, "left": { "type": "NumericLiteral", "start": 1, "end": 2, "loc": { "start": { "line": 1, "column": 1 }, "end": { "line": 1, "column": 2 } }, "extra": { "rawValue": 2, "raw": "2" }, "value": 2 }, "operator": "**", "right": { "type": "UnaryExpression", "start": 6, "end": 8, "loc": { "start": { "line": 1, "column": 6 }, "end": { "line": 1, "column": 8 } }, "operator": "-", "prefix": true, "argument": { "type": "NumericLiteral", "start": 7, "end": 8, "loc": { "start": { "line": 1, "column": 7 }, "end": { "line": 1, "column": 8 } }, "extra": { "rawValue": 1, "raw": "1" }, "value": 1 } }, "extra": { "parenthesized": true, "parenStart": 0 } }, "operator": "*", "right": { "type": "NumericLiteral", "start": 12, "end": 13, "loc": { "start": { "line": 1, "column": 12 }, "end": { "line": 1, "column": 13 } }, "extra": { "rawValue": 2, "raw": "2" }, "value": 2 } } } ], "directives": [] } }
packages/babel-parser/test/fixtures/es2016/exponentiation-operator/7/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001751886011334136, 0.00017202162416651845, 0.00017016306810546666, 0.0001716621918603778, 0.0000014087889894653927 ]
{ "id": 6, "code_window": [ " }),\n", " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 180 }
{ "type": "File", "start": 0, "end": 5, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 5 } }, "program": { "type": "Program", "start": 0, "end": 5, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 5 } }, "sourceType": "script", "interpreter": null, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 5, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 5 } }, "expression": { "type": "NumericLiteral", "start": 0, "end": 5, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 5 } }, "extra": { "rawValue": 161, "raw": "0xa_1" }, "value": 161 } } ], "directives": [] } }
packages/babel-parser/test/fixtures/experimental/numeric-separator/valid-6/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017483567353338003, 0.00017285355716012418, 0.00017112516798079014, 0.000172838888829574, 0.0000011603519851632882 ]
{ "id": 7, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 195 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.9505265951156616, 0.08433274924755096, 0.0001636292290640995, 0.0001712913508526981, 0.2486981749534607 ]
{ "id": 7, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 195 }
import "core-js/modules/web.dom.iterable"; Array.from; // static function Map; // top level built-in // instance methods may have false positives (which is ok) a.includes(); // method call b['find']; // computed string? c.prototype.findIndex(); // .prototype d.fill.bind(); //.bind e.padStart.apply(); // .apply f.padEnd.call(); // .call String.prototype.startsWith.call; // prototype.call var { codePointAt, endsWith } = k; // destructuring
packages/babel-preset-env/test/fixtures/preset-options-add-used-built-ins/builtins-used-instance-methods-native-support/output.mjs
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017365273379255086, 0.00017022836254909635, 0.00016497292381245643, 0.00017205941549036652, 0.000003772652007683064 ]
{ "id": 7, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 195 }
{ "throws": "Octal literal in strict mode (1:38)" }
packages/babel-parser/test/fixtures/esprima/invalid-syntax/migrated_0219/options.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017367606051266193, 0.00017367606051266193, 0.00017367606051266193, 0.00017367606051266193, 0 ]
{ "id": 7, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 195 }
x = { f(a=1) {} }
packages/babel-parser/test/fixtures/es2015/uncategorised/162/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017114492948167026, 0.00017114492948167026, 0.00017114492948167026, 0.00017114492948167026, 0 ]
{ "id": 8, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 210 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.9788170456886292, 0.07985951006412506, 0.00016418421000707895, 0.00016956702165771276, 0.2534884512424469 ]
{ "id": 8, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 210 }
0x
packages/babel-parser/test/fixtures/core/uncategorised/354/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017332567949779332, 0.00017332567949779332, 0.00017332567949779332, 0.00017332567949779332, 0 ]
{ "id": 8, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 210 }
{ "type": "AssignmentExpression", "start": 0, "end": 9, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 9 } }, "operator": ">>>=", "left": { "type": "Identifier", "start": 0, "end": 1, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 1 }, "identifierName": "x" }, "name": "x" }, "right": { "type": "NumericLiteral", "start": 7, "end": 9, "loc": { "start": { "line": 1, "column": 7 }, "end": { "line": 1, "column": 9 } }, "extra": { "rawValue": 42, "raw": "42" }, "value": 42 } }
packages/babel-parser/test/expressions/esprima/expression-assignment/migrated_0010/output.json
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.0001734678662614897, 0.0001724265021039173, 0.0001712297962512821, 0.00017252369434572756, 7.063094926706981e-7 ]
{ "id": 8, "code_window": [ " ).toEqual({\n", " chrome: \"61.0.0\",\n", " safari: \"10.1.0\",\n", " firefox: \"60.0.0\",\n", " ios: \"10.3.0\",\n", " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " });\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 210 }
"use strict"; void 0;
packages/babel-plugin-transform-modules-commonjs/test/fixtures/misc/undefined-this-root-reference/output.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00016708603652659804, 0.00016708603652659804, 0.00016708603652659804, 0.00016708603652659804, 0 ]
{ "id": 9, "code_window": [ " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " firefox: \"60.0.0\",\n", " });\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 230 }
import browserslist from "browserslist"; import getTargets from "../lib/targets-parser"; describe("getTargets", () => { it("parses", () => { expect( getTargets({ chrome: 49, firefox: "55", ie: "9", node: "6.10", electron: "1.6", }), ).toEqual({ chrome: "49.0.0", electron: "1.6.0", firefox: "55.0.0", ie: "9.0.0", node: "6.10.0", }); }); it("does not clobber browserslists defaults", () => { const browserslistDefaults = browserslist.defaults; getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", }); expect(browserslist.defaults).toEqual(browserslistDefaults); }); describe("validation", () => { it("throws on invalid target name", () => { const invalidTargetName = () => { getTargets({ unknown: "unknown", }); }; expect(invalidTargetName).toThrow(); }); it("throws on invalid browsers target", () => { const invalidBrowsersTarget = () => { getTargets({ browsers: 59, }); }; expect(invalidBrowsersTarget).toThrow(); }); it("throws on invalid target version", () => { const invalidTargetVersion = () => { getTargets({ chrome: "unknown", }); }; expect(invalidTargetVersion).toThrow(); }); }); describe("browser", () => { it("merges browser key targets", () => { expect( getTargets({ browsers: "chrome 56, ie 11, firefox 51, safari 9", chrome: "49", firefox: "55", ie: "9", }), ).toEqual({ chrome: "49.0.0", firefox: "55.0.0", ie: "9.0.0", safari: "9.0.0", }); }); it("works with TP versions", () => { expect( getTargets({ browsers: "safari tp", }), ).toEqual({ safari: "tp", }); }); it("works with node versions", () => { expect( getTargets({ browsers: "node 8.5", }), ).toEqual({ node: "8.5.0", }); }); it("works with current node version and string type browsers", () => { expect( getTargets({ browsers: "current node, chrome 55", }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", }); }); it("does throws on unsupported versions", () => { expect(() => { getTargets({ browsers: "node 15.0.0, chrome 1000", }); }).toThrow(); }); it("works with current node version and array type browsers", () => { expect( getTargets({ browsers: ["ie 11", "current node", "chrome 55"], }), ).toEqual({ node: process.versions.node, chrome: "55.0.0", ie: "11.0.0", }); }); it("prefers released version over TP", () => { expect( getTargets({ browsers: "safari tp, safari 11", }), ).toEqual({ safari: "11.0.0", }); }); it("returns TP version in lower case", () => { expect( getTargets({ safari: "TP", }), ).toEqual({ safari: "tp", }); }); it("works with android", () => { expect( getTargets({ browsers: "Android 4", }), ).toEqual({ android: "4.0.0", }); }); it("works with inequalities", () => { expect( getTargets({ browsers: "Android >= 4", }), ).toEqual({ android: "4.0.0", }); }); }); describe("esmodules", () => { it("returns browsers supporting modules", () => { expect( getTargets({ esmodules: true, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browsers supporting modules, ignoring browsers key", () => { expect( getTargets({ esmodules: true, browsers: "ie 8", }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides", () => { expect( getTargets({ esmodules: true, ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", firefox: "60.0.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", }); }); it("returns browser supporting modules and keyed browser overrides, ignoring browsers field", () => { expect( getTargets({ esmodules: true, browsers: "ie 10", ie: 11, }), ).toEqual({ chrome: "61.0.0", safari: "10.1.0", ios: "10.3.0", ie: "11.0.0", edge: "16.0.0", firefox: "60.0.0", }); }); }); describe("node", () => { it("should return the current node version with option 'current'", () => { expect( getTargets({ node: true, }), ).toEqual({ node: process.versions.node, }); }); }); describe("electron", () => { it("should be its own target", () => { expect( getTargets({ chrome: "46", electron: "0.34", }), ).toEqual({ chrome: "46.0.0", electron: "0.34.0", }); }); }); });
packages/babel-preset-env/test/targets-parser.spec.js
1
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.8731855750083923, 0.03258289396762848, 0.00016616421635262668, 0.0001714918907964602, 0.16485615074634552 ]
{ "id": 9, "code_window": [ " ie: \"11.0.0\",\n", " edge: \"16.0.0\",\n", " firefox: \"60.0.0\",\n", " });\n", " });\n", " });\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " opera: \"48.0.0\",\n" ], "file_path": "packages/babel-preset-env/test/targets-parser.spec.js", "type": "add", "edit_start_line_idx": 230 }
import { null as nil } from "bar"
packages/babel-parser/test/fixtures/es2015/uncategorised/97/input.js
0
https://github.com/babel/babel/commit/7b54ab620bd0ca6ca40680631285e3a89c72a628
[ 0.00017357326578348875, 0.00017357326578348875, 0.00017357326578348875, 0.00017357326578348875, 0 ]